1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
string word = "";
char knownLetters[15]; // The word could be of any length
int lives = 7; // Our hangman has 7 stages, so the player starts with 7 lives
bool running = 0;
string GenerateWord();
void PrintLetters();
void PrintMan();
void PlayerLose();
void PlayerWin();
int main() {
char userGuess;
word = GenerateWord(); // Pick a random word
while(running) {
cout << "Guess a letter: ";
cin >> userGuess;
bool correct = 0;
for(int pos = 0; pos < 15; pos++) {
if(userGuess == word[pos]) {
knownLetters[pos] = userGuess; // If the letter is in the word, mark it as guessed
correct = 1;
}
}
if(correct == 0) lives--; // If the letter was wrong, subtract a life
correct = 0;
PrintMan();
PrintLetters();
if(lives <= 0) PlayerLose();
if(knownLetters == word) PlayerWin();
}
return 0;
}
string GenerateWord() {
srand(time(NULL)); // Use the system time as a seed
int wordID = rand() % 31;
string wordList[30] = { "computer", "ascii", "games", "danger", "riverside", "america", "calculator", "archemedes", "california", "lightbulb","telephone","delta","epsilon","alpha","beta","gamma","granulous","incredible","tomorrow","loquacious","residual","sincerely","accoutrements","concupiscent","unencumbered","perspicacious","magnanimous","penultimate","idiosyncratic","done" };
string word = wordList[wordID];
return word;
}
void PrintLetters() {
for(int pos = 0; pos < word.length(); pos++) {
if(knownLetters[pos] == word[pos]) cout << word[pos];
else cout << "_";
}
cout << "\n";
return;
}
void PrintMan() {
switch(lives) {
case 7:
cout << "\n\n\n\n\n";
break;
case 6:
cout << "\n\n\n\n______";
break;
case 5:
cout << "\n |\n |\n |\n |\n____|_";
break;
case 4:
cout << " ___\n | \\|\n |\n |\n |\n____|_";
break;
case 3:
cout << " ___\n | \\|\n O |\n |\n |\n____|_";
break;
case 2:
cout << " ___\n | \\|\n O |\n | |\n |\n____|_";
break;
case 1:
cout << " ___\n | \\|\n O |\n/|\\ |\n |\n____|_";
break;
case 0:
cout << " ___\n | \\|\n O |\n/|\\ |\n/ \\ |\n____|_";
cout << "\n";
return;
}
}
void PlayerWin() {
cout << "Congratulations, you guessed the word correctly!";
cout << "Press ENTER to quit\n";
cin.get();
running = 0;
return;
}
void PlayerLose() {
cout << "You lose! The word was: " << word << "\n";
cout << "Press ENTER to quit\n";
cin.get();
running = 0;
return;
}
|