-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHangmanGame.cpp
58 lines (51 loc) · 1.23 KB
/
HangmanGame.cpp
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
#include <iostream>
#include <string>
using namespace std;
class Hangman {
private:
string word;
string guessedWord;
int attempts;
public:
Hangman() : attempts(6) { // Default constructor
word = "hangman";
guessedWord = string(word.length(), '_');
}
~Hangman() {} // Destructor
void guessLetter(char letter) {
bool found = false;
for (int i = 0; i < word.length(); i++) {
if (word[i] == letter) {
guessedWord[i] = letter;
found = true;
}
}
if (!found) {
attempts--;
cout << "Wrong guess! Attempts left: " << attempts << endl;
} else {
cout << "Good guess! " << guessedWord << endl;
}
}
bool isGameOver() {
return (guessedWord == word || attempts == 0);
}
bool isWin() {
return (guessedWord == word);
}
};
int main() {
Hangman game;
char guess;
while (!game.isGameOver()) {
cout << "Guess a letter: ";
cin >> guess;
game.guessLetter(guess);
}
if (game.isWin()) {
cout << "You win!" << endl;
} else {
cout << "Game Over! The word was: hangman" << endl;
}
return 0;
}