[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

05
rjvalenti•

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

2
brightboyOP•

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.

1
rjvalenti•

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.

1
davedontmind•
    StringBuilder display = new StringBuilder(wordToGuess.Length);
    for (int i = 0; i < wordToGuess.Length; i++)
        display.Append('*');
    ...
    Write("\nWord is: " + display);

You can simplify that code.

The String class has this constructor which takes a character and count and creates a string consisting of the given character repeated that many times.

So your code above could simply be:

    string display = new String( '*', wordToGuess.Length );
    Write("\nWord is: " + display );

or even just:

    Write("\nWord is: " + new String( '*', wordToGuess.Length ) );

And likewise this bit:

    char[] guess = new char[wordToGuess.Length];
    ...
    for (int p = 0; p < wordToGuess.Length; p++)
        guess[p] = '*';

Could just be:

string guess =  new String( '*', wordToGuess.Length );

In fact you don't need both display and guess - those 2 blocks of code could both use the same variable, since they both contain the same thing.

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.

Well you have this code for detecting a correct guess:

        for (int j = 0; j < wordToGuess.Length; j++)
        {
            if (playerGuess == wordToGuess[j])
                guess[j] = playerGuess;
        }

So if the user's guess is correct, it will execute the body of that if statement at least once, right? So to detect an invalid guess have a bool variable that indicates if the user's guess is correct or not - set it to false before that for loop (because we've not yet determined it the user has guessed anything correct) and set it to true inside that if, where we know that they actually do have a correct guess. Then after that for loop, once you've checked all the letters, you can inspect your boolvariable - if it'sfalse` they didn't guess correctly.

And for the full word, just compary guess with wordToGuess - if they match then the user has guessed the whole word.

1
Soulcraver•

This should work for this scenario to check when the word is finished decrypting or if it exceeds the maximum number of guesses.

using System;
using System.Collections.Generic;
using System.Text;

namespace Hangman
{
    public class Program
    {
        public static void Main(string[] args)
        {
            const int MAXGUESSES = 6;
            List<string> wordBank = new List<string>() { "banana", "elephant", "xylophone", "alligator", "pharmacy", "stereo", "leopard", "keyboard" };
            Random rand = new Random();
            bool wordDecrypted = false;           

            string wordToGuess = wordBank[rand.Next(0, wordBank.Count)];
            StringBuilder encodedWord = GetEncodedString(wordToGuess);
            int numGuesses = 0;
            
            while (!wordDecrypted && numGuesses < MAXGUESSES)
            {
                Console.WriteLine(encodedWord);
                char inputKey = Console.ReadKey().KeyChar;
                Console.WriteLine();
                CheckInput(inputKey, wordToGuess, encodedWord, numGuesses, wordDecrypted);                
            }
        }

        private static void CheckInput(char inputKey, string wordToGuess, StringBuilder encodedWord, int numGuesses, bool wordDecrypted)
        {
            bool correctGuess = false;

            for (int i = 0; i < wordToGuess.Length; i++)
            {
                if (wordToGuess[i] == inputKey)
                {
                    DecodeCharacter(i, inputKey, encodedWord);
                    correctGuess = true;
                }
            }

            for (int i = 0; i < encodedWord.Length; i++)
            {
                wordDecrypted = true;
                if (encodedWord[i] == '*')
                {
                    wordDecrypted = false;
                    break;
                }
            }

            if (correctGuess)
            {
                correctGuess = false;
            }
            else
            {
                numGuesses++;
            }
        }

        private static StringBuilder GetEncodedString(string word)
        {
            StringBuilder encodedString = new StringBuilder(new string('*', word.Length));
            return encodedString;
        }

        private static void DecodeCharacter(int index, char key, StringBuilder encodedWord)
        {
            encodedWord[index] = key;     
        }

    }
}
1