Created
January 3, 2013 02:30
-
-
Save anonymous/4440269 to your computer and use it in GitHub Desktop.
aman's hangman C++ code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstring> | |
using namespace std; | |
const int MAX_WORD_LEN = 100; | |
const int TOTAL_LIVES = 10; | |
int find_len( const char word[] ); | |
void clear_screen(); | |
void create_hidden( const char word[] ,char hidden[] , int len ); | |
int main(){ | |
cout << "Welcome to Hangman\n" << | |
"Please enter your word and then press enter: "; | |
char word[MAX_WORD_LEN + 1] = {'\0'}; | |
cin.getline( word , 100 ); | |
int len = find_len(word); | |
int lives = TOTAL_LIVES; | |
cout << len << endl; | |
char hidden[MAX_WORD_LEN + 1]; | |
create_hidden( word , hidden , len ); | |
cout << hidden; | |
char used[ MAX_WORD_LEN ] = {'\0'}; | |
while( lives > 0 and strncmp( word , hidden , len ) != 0 ){ | |
clear_screen(); | |
cout << hidden << endl << | |
"You have guessed the following: " << | |
used << endl << | |
"Please enter your guess: "; | |
char guess; | |
cin >> guess; | |
bool changed = false; | |
for(int i = 0 ; i < len ; i++ ){ | |
if( guess == word[i]){ | |
hidden[i] = guess; | |
changed = true; | |
} | |
} | |
if( changed == false ){ | |
used[TOTAL_LIVES - lives] = guess; | |
lives--; | |
} | |
} | |
if( lives == 0 ){ | |
cout << endl << endl << "Sorry, you lost, the word was: " << | |
word << endl; | |
} | |
else | |
cout << endl << endl << "Congratulations on guessing: " << | |
word << endl; | |
} | |
int find_len( const char word[] ){ | |
int i = 0; | |
while( word[i] != '\0' ) | |
i++; | |
return i; | |
} | |
void clear_screen(){ | |
for( int i = 0 ; i < 100 ; i++ ){ | |
cout << endl; | |
} | |
} | |
void create_hidden( const char word[] , char hidden[] , int len ){ | |
for(int i = 0 ; i < len ; i++ ){ | |
if( isspace( word[i])) | |
hidden[i] = ' '; | |
else | |
hidden[i] = '-'; | |
} | |
hidden[len] = '\0'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment