-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhangman.cpp
More file actions
95 lines (94 loc) · 2.89 KB
/
Copy pathhangman.cpp
File metadata and controls
95 lines (94 loc) · 2.89 KB
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
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <vector>
// Find all indexes of an instance of `c` in a word
std::vector<int> findCharIndexesInString(const std::string& str, const char c) {
std::vector<int> results = {};
int i = 0;
for (auto& ch : str) {
if (ch == c) {
results.push_back(i);
}
i++;
}
return results;
}
// Get every line of the file
std::vector<std::string> readFileLines(const char* fileName) {
std::ifstream ifs(fileName);
if (!ifs.is_open()) {
return {};
}
std::vector<std::string> lines;
for (std::string s; getline(ifs, s);) {
lines.push_back(s);
}
ifs.close();
return lines;
}
int main()
{
std::vector<std::string> words = readFileLines("static/words.txt");
if (words.size() == 0) {
std::cout << "Cannot play without file static/words.txt!";
return 1;
}
srand(time(NULL));
int mistakes = 0;
int index = rand() % words.size();
std::string wordToGuess = words[index];
bool guessed = false;
bool run = true;
while(mistakes < 10 && run)
{
int decision;
std::string wordGuess;
char letterGuess;
std::cout << "Enter 0 to guess the word, 1 to guess a letter:\n";
std::cin >> decision;
switch(decision)
{
default:
std::cout << "That's not a valid choice.\n";
break;
case 0:
std::cout << "You have decided to guess the word.\n";
std::cout << "Enter a word: \n";
std::cin >> wordGuess;
if(wordGuess == wordToGuess){
std::cout << "You have guessed the word!\n";
guessed = true;
run = false;
} else {
std::cout << "Try Again.\n";
mistakes++;
}
break;
case 1:
std::cout << "You have decided to guess a letter.\n";
std::cout << "Enter a letter: \n";
std::cin >> letterGuess;
auto indexes = findCharIndexesInString(wordToGuess, letterGuess);
if (indexes.size() > 0) {
for (auto index : indexes) {
std::cout << "Position #" << index + 1 << std::endl;
}
} else {
std::cout << "That letter doesn't exist.\n";
mistakes++;
}
break;
}
}
if (guessed == false) {
std::cout << "You lost!" << std::endl;
std::cout << "Actual word: " << wordToGuess << std::endl;
} else {
std::cout << "Congratulations! You guessed the word!" << std::endl;
std::cout << "Mistakes: " << mistakes << std::endl;
}
return 0;
}