我创造了一个刽子手游戏。我想知道是否有一种强大的方法来实现这个功能,如果没有,我可以使用标准库函数吗?我正在使用该函数替换guessed_word中的空格,只要它们的猜测与random_word的一部分相匹配。
功能实施
std::pair<std::string&, std::size_t> replace_if_match(
std::string& write,
const std::string& read,
const std::string& match
)
{
assert( write.length() >= read.length() );
int occurrences{0};
for(
int search_pos{0};
(search_pos = read.find( match, search_pos )) != -1;
++search_pos, ++occurrences){
write.replace( search_pos, match.length(), match );
}
return {write, occurrences};
}
使用功能
// I have not yet implemented the random word
std::string random_word{"timeless"};
// set number of guesses
int guesses{5};
// set guessed word to length of random word in underscores
std::string guessed_word{
std::string().append(random_word.length(),'_')
};
// enter guessing loop as long as
// guesses is greater than or equal to zero
while( guesses > 0 && random_word != guessed_word )
{
// display guessed word in progress
std::cout << guessed_word << '\n';
// display number of guesses left
std::cout << "Number of Guesses Left: " << guesses << '\n';
// prompt user to enter a guess
std::cout << "Enter a string as guess." << '\n';
static std::string guess;
std::cin >> guess;
// the guessed word will be modified in the if statement via function; therefore, the value must be stored to look back on
static std::string prev_word;
prev_word = guessed_word;
// guess fails to succeed if the guessed word does not change
if( prev_word == replace_if_match( guessed_word, random_word, guess ).first )
{
guesses--;
}
}
if( guessed_word == random_word )
{
std::cout << "You winza!!!! ";
}
else
{
std::cout << "Game over yeah!!!! ";
}