Question

In: Computer Science

For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...

For a C program hangman game:

Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do)

setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and puts that into g->hidden_word. It sets the number of wrong guesses to zero, and initialises the guesses array to be empty (all zeroes). To select a random word, just pick a random number between 0 and numwords-1, and copy that element of wordlist into the hidden word part of the structure.

    // Data that is in g (Game)

    // g->wrong_guesses

    // g->guesses

    // g->hidden_word

int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords )

{

    g->wrong_guesses = 0 ;

    // next, have to set what the hidden_word is

    // pick a random number between 0 and numwords-1

    // now copy that index of the wordlist into hidden_word

    // next, initialise the entire guesses array to be all 0s

    // DONE

}

The exist code

/* Hangman game!

Author: 1305ENG students
Date: 13/7/2020

A simple hangman game
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <math.h>
// include all OUR function declarations and constants
#include "hangman.h"


// The main function!
int main( int argc, char **argv )
{
char wordfile[256], option, temp[256] ;
char wordlist[MAX_WORDS][MAX_WORD_LENGTH] ;
int num_words, result ;
Game g ;

// seed the rand() function first
srand ( time(NULL));

// check to see if command line argument was given, if so use it as the filename for the words
if ( argc > 1 ){
strcpy ( wordfile, argv[1] ) ;
} else {
strcpy ( wordfile, "wordlist.txt" ) ;
}

// now read word file
num_words = read_words ( wordfile, wordlist ) ;

if ( num_words == 0 ){
printf ( "No words were read from file, exiting\n") ;
exit ( -1 ) ;
}
printf ( "Read %d words from file\n", num_words ) ;

setup_game ( &g, wordlist, num_words ) ;
result = play_game ( &g ) ;
printf ( "Would you like to play again (y/n)? " ) ;
fgets ( temp, 256, stdin ) ; // read the rest of the line to get rid of it from stdin
while ( option == 'y' || option == 'Y' ) ;
return 0 ;
}

// Functions used in the program here!

// WEEK 1 FUNCTIONS
// Replace the call to the library function with your own code

// draw_man()
// Draws the hangman picture for the specified wrong number of moves.
// There is no need to exactly copy the example program, but it should progress from almost nothing
// at zero wrong moves to the man being "hanged" at MAX_WRONG_GUESSES
int draw_man ( int misses ){
return draw_man_lib(int misses);

}

// display_guesses
// Displays a representation of the guessed letters from the guesses array.
// Each letter is displayed in all caps, separated by a space. If the array is '1', that letter is display,
// otherwise if it is '0' it is not. For example if elements 0, 9, and 19 are '1' and the others are 0, then
// "A J T" would be displayed. No newline should be displayed after the list of letters.
int display_guesses( unsigned char guesses[])
{
printf("Guesses so far:");
for(int i=0;i<26;i++)
{
if(guesses[i]==1)//checking the array of guesses if the its there or not
{
printf("%c",i+65);
}
printf("\t");
}
return 0;
}

// read_guess()
// Reads a guess from the user. Uses the guesses array to make sure that the player has not
// already guessed that letter. If an invalid character is entered or they have already guessed
// the letter, they are asked to continue guessing until they enter a valid input.
// Returns the character that was read.
// Note that it is usually better to read an entire line of text rather than a single character, and taking the first
// character of the line as the input. This way, the entire line is removed from the input buffer and won't interfere
// with future input calls.
char read_guess(unsigned char guesses[])
{
return read_guess_lib(guesses);
}
//Week 2 Functions

// add_guess()
// Adds the given guess to the guesses array, making the relevant entry 1. For exmpale, if guess is 'a' or 'A',
// element 0 of the guesses array is set to 1. If 'z' or 'Z' is input, then element 25 is set to 1. Your function
// should check that the character is a valid letter and return -1 if it is not.
// Returns 0 if successful, or -1 if an invalid character is entered.
int add_guess(char guess, unsigned char guesses[26])
{
if ((guess >= 'a' && guess <= 'z') || (guess >= 'A' && guess <= 'Z'))
{
if (guess >= 'a' && guess <= 'z')
{
guesses[guess - 'a'] = 1;
}
else
{
guesses[guess - 'A'] = 1;
}
return 0;
}
return -1;
}
// check_guess()
// Checks if the given character 'guess' is contained within the string 'word'.
// Returns 1 if it is, 0 otherwise
int check_guess ( char word[], char guess )
{
int i;
while(word[i] != '\0')
{
if(guess == word[i])
return 1;
}
return 0;
}
// hidden_word()

// Creates the word that is displayed to the user, with all the correctly guessed letters
// shown, and the rest displayed as underscores. Any non-letters (punctuation, etc) are displayed.
// The function takes two strings as inputs. word[] is the word that the player is trying to guess,
// and display_word[] is the output string to be displayed to the player. The guesses array is a binary
// array of size 26 indicating whether each letter (a-z) has been guessed yet or not.
// Returns 0 if successful, -1 otherwise.
int hidden_word ( char display_word[], char word[], unsigned char guesses[])
{

return hidden_word_lib (display_word, word, guesses);
}
// WEEK 3 FUNCTIONS

// read_words()
// takes a filename as input as well as the wordlist to populate
// Reads from the give file and stores each word (line of text) into a new row of the array.
// A maximum of MAX_WORDS is read, and the wordlist array should be this big (at least).
// Each word read from the file should be a maximum of MAX_wORD_LENGTH characters long.
// Returns the total number of words read. If the file cannot be opened, 0 is returned.
int read_words ( char input[], char wordlist[][MAX_WORD_LENGTH])
{
int count= 0;
FILE*fp = fopen(input, "r");
if(fp == NULL)
return 0;

char buf[MAX_WORD_LENGTH];
while (fscanf(fp, "%s", buf) != EOF && count < MAX_WORDS)
{
strcpy(wordlist[count], buf);
count++;
}
fclose(fp);
return count;
}

// display_game()
// Displays the entire game to the screen. This includes the picture of the hangman, the hidden word,
// and the guesses so far.
int display_game ( Game *g )
{
return display_game_lib (g);
}

// WEEK 4-5 FUNCTIONS


// check_win()
// Checks to see whether all letters in the word have been guessed already.
// The hidden word and guesses inside the Game structure should be used to check this
// Returns 1 if so, 0 otherwise
int check_win ( Game *g ){

return check_win_lib ( g ) ;
}

// setup_game()
// Initialises the given game structure by chooseing a random word from the supplied wordlist.
// The number of words in the wordlist is also passed to the function.
// As well as doing this, the number of incorrect guesses is set to 0, and the guesses array is
// initialised to be all zeros.
int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords ){

return setup_game_lib ( g, wordlist, numwords ) ;

}

// play_game()
// Runs one complete game of hangman with the supplied Game structure.
// The usual hangman rules are followed - the player guesses letters one at a time until either
// the entire word is guessed or the maximum number of incorrect guesses MAX_WRONG_GUESSES is
// reached. If the player wins, 1 is returned, otherwise 0.
int play_game ( Game *g ){

return play_game_lib ( g );
}

Solutions

Expert Solution

Change the function name as per your requirement.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <string.h>

//Global Strings

char word [50];

char guessed_letters[20];

char user_guess[] = "";

char blank[1] = "-";

//Global Integers

int random_number;

int word_len;

int user_input;

int attempts = 10;

//Function Declarations

void start_game();

void get_input();

void print_blanks();

void draw_platform();

void get_word();

int main(void)

{

//Game Loop

while(1)

{

start_game();

while(attempts > 0)

{

system("cls");

//If they have guessed all the letters they win

if(strlen(guessed_letters) == word_len - 1)

{

print_blanks();

break;

}

//Else, decr attempts and try again

else

{

printf("Attempts Remaining: %i\n", attempts);

print_blanks();

get_input();

}

}

system("cls");

//If they won

if(attempts > 0)

{

print_blanks();

printf("You Won! Play again?\n");

}

//If they lost

else

{

draw_platform();

printf("You Lost! The word was %s, Play again?\n", word);

}

scanf("%i", &user_input);

switch(user_input)

{

case 0:

return 0;

default:

continue;

}

}

}

void start_game()

{

//Initializes Game

get_word();

word_len = strlen(word);

memset(guessed_letters, 0, sizeof guessed_letters);

attempts = 10;

}

void get_input()

{

//Gets guess from user and checks

//To see if that letter is in the word

int i;

int letter_hit = 0; //Used to tell if the guess letter is in the word

printf("\nYour guess: \n");

scanf(" %c", user_guess);

for(i=0; i < word_len; i++)

{

if(user_guess[0] == word[i])

{

guessed_letters[i] = user_guess[0];

letter_hit ++;

}

}

if(letter_hit > 0)

{

return;

}

else

{

attempts --;

}

}

void print_blanks()

{

/////////////////////////////////////////////////

/// Prints out a number of blanks equal to the

/// Length of the word

/// Then fills the blanks with the guessed letters

/////////////////////////////////////////////////

int i, j;

draw_platform();

for(i=0; i<word_len; i++)

{

printf("%c", guessed_letters[i]);

printf(" ");

}

printf("\n");

for(j=0; j<word_len - 1; j++)

{

printf("%s", blank);

printf(" ");

}

printf("\n");

}

void draw_platform()

{

/////////////////////////////////////////////////

/// Draws a new segment onto

/// The platform every time

/// The user gets a wrong guess

/////////////////////////////////////////////////

char *platform[]={

" ===\n",

" |\n"

" |\n"

" |\n"

" ===\n",

" =====|\n"

" |\n"

" |\n"

" |\n"

" ===\n",

" |=====|\n"

" |\n"

" |\n"

" |\n"

" ===\n",

" |=====|\n"

" O |\n"

" |\n"

" |\n"

" ===\n",

" |=====|\n"

" O |\n"

" | |\n"

" |\n"

" ===\n",

" |=====|\n"

" O |\n"

" |- |\n"

" |\n"

" ===\n",

" |=====|\n"

" O |\n"

" -|- |\n"

" |\n"

" ===\n",

" |=====|\n"

" O |\n"

" -|- |\n"

" | |\n"

" ===\n",

" |=====|\n"

" O |\n"

" -|- |\n"

" // |\n"

" ===\n"

};

switch(attempts)

{

case 9:

printf("\n\n%s\n", platform[0]);

break;

case 8:

printf("\n\n%s\n", platform[1]);

break;

case 7:

printf("\n\n%s\n", platform[2]);

break;

case 6:

printf("\n\n%s\n", platform[3]);

break;

case 5:

printf("\n\n%s\n", platform[4]);

break;

case 4:

printf("\n\n%s\n", platform[5]);

break;

case 3:

printf("\n\n%s\n", platform[6]);

break;

case 2:

printf("\n\n%s\n", platform[7]);

break;

case 1:

printf("\n\n%s\n", platform[8]);

break;

case 0:

printf("\n\n%s\n", platform[9]);

break;

}

}

void get_word()

{

/////////////////////////////////////////////////

/// Scans a file to get the total number of lines

/// The line total is then used as a max range

/// For the random number

/// The word that is on the random line is the word

/// That will be used for the game

/////////////////////////////////////////////////

FILE *fp;

int line_number = 0;

char current_word[50];

fp = fopen("dictionary.txt","r");

if(fp == NULL)

{

perror("Error in opening file");

}

//While not end of file, incr line number

while(fgets(current_word, 50, fp) != NULL)

{

line_number++;

}

random_number = rand() % line_number;

//Start from top of file

rewind(fp);

//Goes to whatever line the random number equals to find the

//Random word

for(line_number = 0; line_number != random_number; line_number++)

{

fgets(current_word, 50, fp);

}

strcpy(word, current_word);

fclose(fp);

}


Related Solutions

Write a hangman program in c++.The game is played as follows: 1. The program selects a...
Write a hangman program in c++.The game is played as follows: 1. The program selects a random word for the user to guess (Read words for the user to guess into an array of strings from a file. The words are: revolutionary, meaning, recovery, compartment, trainer, pursuit, harm, platform, error, confusion) 2. User guesses one letter at a time until either they guess the word, or they run out of guesses. 3. Select a random word from the array of...
Please create a Hangman game in Java language. For this game a random word will be...
Please create a Hangman game in Java language. For this game a random word will be selected from the following list (abstract, cemetery, nurse, pharmacy, climbing). You should keep a running tab of the user’s score and display it on screen; the user begins with 100 points possible if they correctly guess the word without any mistakes. For every incorrect letter which is guessed, 10 points should be taken away from what is left of their total possible points. For...
C++ language You will create a Hangman class. Possible private member variables: int numOfCharacters; //for the...
C++ language You will create a Hangman class. Possible private member variables: int numOfCharacters; //for the secret word char * secretWord; char *guessedWord; public: //please create related constructors, getters, setters,constructor() constructor() You will need to initialize all member variables including the two dynamic variables. destructor() Please deallocate/freeup(delete) the two dynamic arrays memories. guessALetter(char letter) 1.the function will check if the letter guessed is included in the word. 2. display the guessed word with related field(s) filled if the letter guessed...
Create a Hangman game using C++ by QT creator. please separate each code that will insert...
Create a Hangman game using C++ by QT creator. please separate each code that will insert in hider files and cpp files and use an accurate screeshoots if needed. Thanks in advance.
Write a program to allow a user to play the game Hangman. DO NOT USE AN...
Write a program to allow a user to play the game Hangman. DO NOT USE AN ARRAY The program will generate a random number (between 1 and 4581) to pick a word from the file - this is the word you then have to guess. Note: if the random number you generate is 42, you need the 42nd word - so loop 41 times picking up the word from the file and not doing anything with it, it is the...
C PROGRAMMING Create the int delete(int key) function so that it deletes the LAST occurrence of...
C PROGRAMMING Create the int delete(int key) function so that it deletes the LAST occurrence of a given number in the linked list Make sure the parameter for this delete function is (int key). Also, use these variables and global Nodes BELOW as this is a DOUBLY LINKED LIST!!! #include #include typedef struct node {             int data;             struct node *next;             struct node *prev; } Node; Node *head; Node *tail; ----------------------- So, the function has to look like...
How would I create a Hangman game that chooses  a random word and the player needs to...
How would I create a Hangman game that chooses  a random word and the player needs to guess it, letter by letter using  JavaScript and jQuery to allow user interaction. The content and the style of the page must be updated based on user’s input.
For this assignment, you will create a command-line version of the game ​Hangman. You should work...
For this assignment, you will create a command-line version of the game ​Hangman. You should work in a group of two on the project and not view Hangman code of other students or found on-line. Submit this project-- your .java file-- here on Canvas. For this assignment you will research on StringBuilder Class (​Use this link​) and use it in your code. Functional requirements (rubric) ● Your game should have a list of at least ten phrases of your choosing...
In JAVA Create a simple guessing game, similar to Hangman, in which the user guesses letters...
In JAVA Create a simple guessing game, similar to Hangman, in which the user guesses letters and then attempts to guess a partially hidden phrase. Display a phrase in which some of the letters are replaced by asterisks: for example, G* T*** (for Go Team). Each time the user guesses a letter, either place the letter in the correct spot (or spots) in the phrase and display it again or tell the user the guessed letter is not in the...
Hangman We're going to write a game of hangman. Don't worry, this assignment is not nearly...
Hangman We're going to write a game of hangman. Don't worry, this assignment is not nearly as difficult as it may appear. The way hangman works (for this assignment - we are doing a simplified game) is as follows: the computer will choose a word. (For this version, a word is selected from a static list encoded into the program -- so the words are pretty limited). Let's say the word is "cocoa". the computer shows the user how many...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT