-
Notifications
You must be signed in to change notification settings - Fork 0
/
Software.cpp
110 lines (97 loc) · 2.55 KB
/
Software.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
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
104
105
106
107
108
109
110
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <list>
class HangmanGame
{
private:
std::string secretWord;
std::string guessedWord;
int maxAttempts;
int remainingAttempts;
std::list<char> guessedLetters;
public:
HangmanGame(const std::string& word, int attempts) : secretWord(word), maxAttempts(attempts), remainingAttempts(attempts)
{
guessedWord = std::string(secretWord.length(), '_');
}
void play() {
while (remainingAttempts > 0 && guessedWord != secretWord)
{
displayStatus();
char guess = getGuess();
updateGuessedWord(guess);
if (secretWord.find(guess) == std::string::npos)
{
remainingAttempts--;
std::cout << "Incorrect guess! " << remainingAttempts << " attempts left.\n";
}
}
if (guessedWord == secretWord)
{
std::cout << "Congratulations! You guessed the word: " << secretWord << std::endl;
} else
{
std::cout << "Out of attempts! The word was: " << secretWord << std::endl;
}
}
private:
void displayStatus()
{
std::cout << "Guessed word: " << guessedWord << std::endl;
std::cout << "Guessed letters: ";
for (char letter : guessedLetters)
{
std::cout << letter << " ";
}
std::cout << std::endl;
}
char getGuess()
{
char guess;
std::cout << "Enter your guess: ";
std::cin >> guess;
guessedLetters.push_back(guess);
return guess;
}
void updateGuessedWord(char guess)
{
for (size_t i = 0; i < secretWord.length(); ++i)
{
if (secretWord[i] == guess)
{
guessedWord[i] = guess;
}
}
}
};
int main()
{
std::ifstream file("C:/Users/ACER/Desktop/Codes/C++ Sftw/words.txt");
if (!file.is_open())
{
std::cerr << "Error opening file." << std::endl;
return 1;
}
std::list<std::string> words;
std::string word;
while (file >> word)
{
words.push_back(word);
}
file.close();
if (words.empty())
{
std::cerr << "No words found in file." << std::endl;
return 1;
}
srand(time(nullptr));
int randomIndex = rand() % words.size();
auto it = std::next(words.begin(), randomIndex);
std::string secretWord = *it;
HangmanGame game(secretWord, 6);
game.play();
return 0;
}