/* GuessAWord.c (c) Kari Laitinen http://www.naturalprogramming.com/ 2013-11-22 File created. 2013-11-22 Last modification. This program is a simple computer game in which the player has to guess the characters of a word, or the player may also try to guess the whole word. This program demonstrates, among other things, various string operations. */ #include #include #include /* Definitions for bool, true, and false */ int main() { printf( "\n This is a GUESS-A-WORD game. \n" ) ; char word_to_be_guessed[] = "VIENNA" ; char guessed_characters[] = "________________________________________" ; guessed_characters[ strlen( word_to_be_guessed ) ] = 0 ; // Now guessed_characters refers to a string that has as many // underscore characters as the word to be guessed. bool game_is_over = false ; while ( game_is_over == false ) { printf( " %s Give a character or word: ", guessed_characters ) ; char player_input[ 30 ] ; gets( player_input ) ; // The following loop uses to bit operator & to convert the // player input to uppercase letters. (Note that this program may // not work with non-English letters.) int character_index ; for ( character_index = 0 ; character_index < strlen( player_input ) ; character_index ++ ) { player_input[ character_index ] = player_input[ character_index ] & 0xDF ; } if ( strlen( player_input ) == 1 ) { // The player gave a single character for ( character_index = 0 ; character_index < strlen( word_to_be_guessed ) ; character_index ++ ) { if ( word_to_be_guessed[ character_index ] == player_input[ 0 ] ) { guessed_characters[ character_index ] = player_input[ 0 ] ; } } if ( strstr( guessed_characters, "_" ) == 0 ) { // "_" is not a substring in guessed characters. // This means that all characters have been guessed. game_is_over = true ; printf( " %s Congratulations! \n\n", guessed_characters ) ; } } else if ( strlen( player_input ) > 1 ) { // The player tried to guess the whole word. if ( strcmp( player_input, word_to_be_guessed ) == 0 ) { // The player made a correct guess. game_is_over = true ; printf( "\n Congratulations! \n\n" ) ; } } else { game_is_over = true ; printf( " \n Game over. \n\n" ) ; } } }