Most hangman implementations I have seen keep a list of characters the player has already guessed and compares them to the players current guess each time to see if they have already made the same guess. My implementation checks if the word was changed after replacing any matches. Is my implementation easier to understand as well as more efficient than this one Hangman game logicistics and cleanliness?
Side Question: Should I use static variables in loops?
Hangman
#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <random>
#include <string>
std::string replace_if_match(std::string& write, const std::string& read, const std::string& match)
{
assert( write.length() >= read.length() );
for( int search_pos{0}; (search_pos = read.find( match, search_pos )) != -1; ++search_pos){
write.replace( search_pos, match.length(), match );
}
return write;
}
int main()
{
std::ifstream file("word_list");
assert( file.is_open() );
std::vector<std::string> word_list;
while( !file.eof() ){
static std::string word;
file >> word;
word_list.push_back( word );
}
file.close();
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0, word_list.size() - 1);
std::string unknown_word;
std::string previous_word;
std::string guessed_word;
std::string guess;
int num_of_guesses;
int in_game{true};
while( in_game )
{
unknown_word = word_list[dist(mt)];
guessed_word = std::string().append( unknown_word.length(), '_' );
num_of_guesses = 5;
while( num_of_guesses > 0 && unknown_word != guessed_word )
{
std::cout << guessed_word << '\n';
std::cout << "Number of Guesses Left: " << num_of_guesses << '\n';
std::cout << "Enter a string as guess.\n";
std::cin >> guess;
previous_word = guessed_word;
if( previous_word == replace_if_match( guessed_word, unknown_word, guess ) ){
num_of_guesses--;
}
}
if( guessed_word == unknown_word ){
std::cout << "We did not have a noose for you any way.\n";
}
else{
std::cout << "You loser, the word was " << unknown_word << "!\n";
}
std::cout << "Would you like to try another? <Yes: 1, No: 0>\n";
std::cin >> in_game;
}
}