[homework]C# Console Hangman Game
class Program
{
static void Main(string[] args)
{
string[] wordBank = { "banana", "elephant", "xylophone", "alligator", "pharmacy", "stereo", "leopard", "keyboard" };
Random random = new Random();
string wordToGuess = wordBank[random.Next(0, wordBank.Length)];
StringBuilder display = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
display.Append('*');
WriteLine("\t\tWelcome to Guess A Word!");
WriteLine("\t****************************************");
Write("\nWord is: " + display);
char[] guess = new char[wordToGuess.Length];
Write("\nGuess a letter: ");
for (int p = 0; p < wordToGuess.Length; p++)
guess[p] = '*';
while (true)
{
char playerGuess = char.Parse(ReadLine());
for (int j = 0; j < wordToGuess.Length; j++)
{
if (playerGuess == wordToGuess[j])
guess[j] = playerGuess;
}
Write("Correct! Word is: ");
WriteLine(guess);
Write("Guess a letter: ");
}
}
}
I have gotten this far but am unable to figure out what kind of loop statements I need to return for incorrect guesses and when a user completes the word.
Would it be new if/else statements within the while (true) loop? OR would I need new if/else outside of the while loop?
Any guidance is appreciated!
Posted Oct 8, 2017, 11:49 PM UTC
Actually you can keep the loop and if that you have. Just store if they guess right somewhere.
Before your for loop you could have a boolean if they got a letter correct, set it to false. In your for loop if the playerGuess is in the wordToGuess, you can set it to true. If you come out of the loop and its still false, they didn't guess a letter. Now we know if at some point they got a correct letter.
You could keep track of number of incorrect guesses/number of correct guesses. When incorrect guesses = Max number (whatever that may be), you can print they lost and break. If the number of correct guesses equals the number of UNIQUE characters in the word, you could print they won and break the loop.
edit: you would still have to handle repeating guesses, maybe have another String of the letters they guessed and check that at some point
Thank you for the feedback!
I guess we haven't gone over lists yet so I'm trying to figure that out. Will keep trying at it. I think using a boolean for correct/incorrect will help and just need to figure out how to nest my loops properly.
Why would you need a list? Also the way you nested your loops should be fine. Just one more for loop before (not inside) the for loop you have now, to check if the guess was already guessed.