I feel that this implementation can still be simplified. I've tried to keep variable scopes low and have used as much of the standard library as I could.
It currently works with a hard-coded word or phrase, but I eventually plan on having it work with random words or phrases from a file.
My main concern is in regards to my functions. Am I using too few or too many of them? I still feel that main()
is doing a little too much.
Note: I have not tagged this as c++11 because there's no utilization of it here, but I am open to any recommendations from C++11.
#include <iostream>
#include <string>
bool isCorrectGuess(const char guess, std::string const& word)
{
return (word.find(guess) != std::string::npos);
}
std::string updateWrongGuesses(const char guess, std::string const& word, std::string wrongGuesses)
{
return wrongGuesses += guess;
}
std::string updateCorrectGuesses(const char guess, std::string const& word, std::string correctGuesses)
{
for (std::string::size_type i = 0; i != word.size(); ++i)
{
if (word[i] == guess)
{
correctGuesses[i] = guess;
}
}
return correctGuesses;
}
void displayStatus(const unsigned int triesLeft, std::string const& guessedWord, std::string const& wrongGuesses)
{
std::cout << "\n\nRemaining Tries: " << triesLeft;
std::cout << "\nWrong Guesses : " << wrongGuesses;
std::cout << "\n\n" << guessedWord << "\n\n";
}
int main()
{
const std::string word = "rabbit rabbit";
std::string guessedWord;
// set up placeholders for word to be guessed
for (std::string::size_type i = 0; i != word.size(); ++i)
{
guessedWord += (isspace(word[i])) ? ' ' : '*';
}
unsigned int triesLeft = 8;
std::string wrongGuesses;
displayStatus(triesLeft, guessedWord, wrongGuesses);
std::string attemptedGuesses;
while (triesLeft > 0 && guessedWord != word)
{
std::cout << "\nGuess a letter: ";
char guess;
std::cin >> guess;
guess = tolower(guess);
attemptedGuesses += guess;
if (isCorrectGuess(guess, word))
{
guessedWord = updateCorrectGuesses(guess, word, guessedWord);
}
else
{
wrongGuesses = updateWrongGuesses(guess, word, wrongGuesses);
triesLeft--;
}
displayStatus(triesLeft, guessedWord, wrongGuesses);
}
if (guessedWord == word)
{
std::cout << "\n\nYou've guessed the word/phrase!\n\n";
}
else
{
std::cout << "\n\nYou've been hanged...\n\n";
std::cout << "The word/phrase is: " << word;
}
}