beanz Magazine

Code Hangman Game in C#

Jeremy Tarling on Flickr

Learn how to code the hangman game in C#. Includes link to full code.

If you’ve ever operated a game of hangman for someone to play, you may have noticed that it’s easy to run. You simply think of a word, give a visual cue on the letters revealed, then reveal them one by one as the player guesses them.

Because it’s so simple, Hangman makes for a great way to learn how to program in C#. In this article, we’ll take a look at how to code Hangman using the C# Console in Visual Studio Community 2015, which is a free download. If you get lost, don’t worry; simply check the pastebin link at the end of this article to see (and even copy!) all the code as one.

Once Visual Studio is running, you can make a console project by clicking File->New->Project…, then Templates->Visual C#->Windows and clicking Console Application on the right.

Visual Studio with Console App

So, how do you code Hangman in C#? Before we dive right into the main body code, we’ll need to do some setup first. Within the main function of our new project, we’ll add these:

Random random = new Random(); 
 
            string ThisAnswer;
            string Input;
 
            bool HasWon = false;
 
            List<string> GameAnswers = new List<string> { "Apple", "Pear", "Banana", "Mango", "Apricot", "Plum" };
            ThisAnswer = GameAnswers[random.Next(GameAnswers.Count)].ToUpper();
 
            int length = ThisAnswer.Length;
 
            Console.WriteLine("Welcome to Hangman!");
            Console.WriteLine("Discover the word in 5 attempts by guessing using letters.");
            string TellLength = "This word has: " + length + " letters. Good luck!";
            Console.WriteLine(TellLength);
 
            List<string> GuessDisplay = new List<string>(ThisAnswer.Length);
 
   for (int i = 0; i < ThisAnswer.Length; i++)
            {
                GuessDisplay.Add("_");
            }
 

The Random called ‘random’ is our random number generation, so we can select a random answer every time we play. We declare this early so the computer has time to select a good seed; if you declare it very soon before using it, you may see it repeat answers a lot!

We have two strings called ‘ThisAnswer’ and ‘Input’. ThisAnswer will store the answer for the game, while Input will store what the user types.

We have a bool called ‘HasWon’ which is set to false. This tells the program if the player has won or not, and used to keep the player in the game until they win. We’ll set this to true when the player wins.

The next part is quite confusing. We start a List of strings called ‘GameAnswers’, which will store the answers that our game of Hangman can choose from. We declare it as a new List, then fill it with six answers, all of which are fruit. If you want to add more answers, just add them using speech marks within the curly brackets and a comma separating each. Lists are great for people learning to code, as they’re easy to imagine — just think of them as a literal list starting at 0 and then listing each element one by one.

Now we have a list of possible answers, it’s time to pick one. We pick a random answer from GameAnswers and hand it to ThisAnswer to keep. We use the random tool we created to make a random number between 0 and the amount of answers within GameAnswers (defined by GameAnswers.Count), then use that number to pick out an answer from the list.

For instance, with the answers currently defined, it’ll pick a number between 0 and 5. Let’s say it picked 2 — the answer at spot 2 of the list is “Banana” (remember that the first entry of a list is at spot 0, so spot 2 is the third item!). So, Banana will be our answer. ‘ToUpper’ is to make the answer all upper case, which comes in handy later.

Then we quickly grab the character length of the answer using ThisAnswer.length(). This is used in both setting up the game and telling the player how many letters are in the word.

Then we talk to the player using Console.WriteLine(). We let them know how to play, as well as how many letters are in the answer by using the length of the answer. Then, we set up a list called GuessDisplay, which we’ll use to show the player which letters they’ve guessed and which remain. There’s a lot of different ways we can code the display, from a char array to a StringBuilder, but a list makes things a little easier to understand.

We fill the list full of underscores so we can show the player how many letters they have to guess. You can use an underscore and a space afterward if you like a gapped display, but either works fine. Just remember which you use for the win check we’ll code in later.

Now we’ve set up the game; let’s code it!

First, let’s put the main game logic into a while loop. Write ‘while (HasWon == false)’ then add two curly brackets. We’re going to store all our game in these brackets, so the player continues to play the game until they win it.

The first thing we code in this HasWon loop is this:

foreach (string letter in GuessDisplay)
                {
                    Console.Write(letter);
                }
 
                Console.WriteLine();
 
                Input = Console.ReadLine().ToUpper();

The foreach loop goes through each letter within GuessDisplay and prints them on the screen. This is the first thing we do when a new round begins, so the player can see what there’s left to do. We use Console.Write instead of WriteLine so it displays all on one line.

We then do a WriteLine to put the cursor down a line, then wait for user input. Do you see that ToUpper makes an appearance here? We make both the answer detection and the inputs upper case, so that people aren’t told they’re wrong when using a difference case (i.e. guessing ‘P’ when the word contains ‘p’ and the computer saying it’s incorrect).

Now we code what happens when a user inputs something. This is quite long, so hold on!

                    if (ThisAnswer.Contains(Input) == true)
                    {
                        Console.WriteLine("Correct!");
                        char guess = Input[0];
 
                        for (int i = 0; i < ThisAnswer.Length; i++)
                        {
                            if (ThisAnswer[i].Equals(guess) == true)
                            {
                                GuessDisplay[i] = Input;
                            }
                        }
 
                        HasWon = true;
 
             
if (GuessDisplay.Contains("_") == false)
                    {
                        HasWon = true;
                    }
 
                    }
                    else
                    {
                        Console.WriteLine("Incorrect!");
                    }

Okay — so what’s going on here?

We start with an if clause that says: if (ThisAnswer.Contains(Input) == true). What this means in English is ‘If the answer to the puzzle contains the letter the user guessed’. This is done by using the Contains function that strings have, and passing in the user’s Input into the function. Unfortunately, Contains only tells us if it contains the letter, not where the letter is. We want to know where the letters are, so we can reveal them to the player through GuessDisplay.

You may already know that “if (boolean == true)” can also be written as “if (boolean)” and “if (boolean == false)” can be written as “if (!boolean)”. However, for the sakes of simplicity and ease of reading, we’ll be typing it out in full. Feel free to use the shorthand version if you like!

If the answer does contain the letter, that means the player is correct. First, we tell the player they got the right answer. Then we turn the input into a char, so we can easily use it for the function coming up.

For this part:

               for (int i = 0; i < ThisAnswer.Length; i++)
                        {
                            if (ThisAnswer[i].Equals(guess) == true)
                            {
                                GuessDisplay[i] = Input;
                            }
                        }

We use a for loop to go through each letter of the answer list and check it against the input. The loop starts at zero, keeps going until it hits the answer’s character length, and increases by 1 each time. If the input matches the current letter being inspected, it updates the GuessDisplay to let the player know where the letters are.

Under this, we put an if statement that reads like this:

if (GuessDisplay.Contains("_") == false)
                    {
                        HasWon = true;
                    }
 

This states that if the GuessDisplay does not contain underscores, the player has successfully guessed every letter in the puzzle. This means they’ve won, so we allow the player to escape the game loop to victory!

At the end, we close out the if statement for when the player gets a correct answer, and starts an else statement. Of course, if the player wasn’t correct, it has to be incorrect! We tell the user that they’re wrong and leave it there.

So that’s the base game now coded. If you played it now, you should be able to guess all the letters, but when you get the correct answer, the game just stops working. So, let’s code up something to finish the game properly, just under our HasWon loop:

            if (HasWon == true)
            {
                Console.WriteLine("YOU WON! Press any key to quit.");
                Console.ReadKey();
                System.Environment.Exit(0);
            }

After the HasWon loop, we check to see if the player won. If they did, we let them know, then wait for a key press. When a key is pressed, we safely close out the software. Now we’re finished!

Where To Go From Here

So now we have a game of hangman that’s functional. It plays through, loops around until the player gets the word right, then congratulates the player when they win and closes on key press. While fun to play by itself, there’s still some features you can add to make it even better. Have a think about how you’d implement the following:

Lose Clause

We have a way for the player to win the game, but they currently can’t lose at all! Implement a way for the computer to keep track of the amount of incorrect guesses the player makes, then ends the game and reveals the answer when they run out.

One method to implement this is to add a lives counter that decreases when we tell the player they’re incorrect, then breaks out of the loop when their lives run out. You’ll want to add an or clause to the game loop (if HasWon == false || HasLost == false) then add a separate ‘if HasLost == true’ clause afterward, like we did with HasWon.

Avoid Similar Guesses

You may be wondering why we check GuessDisplay for underscores to determine if the player has won, rather than simply counting the amount of letters correctly guessed. The reason for this is because, in its current state, if you had a counter that incremented up every time you got a letter correct, you’d win very easily by simply guessing the same correct letter over and over!

Think about how you’d tackle this problem and stop similar guesses. You might want to create a list of guessed letters is checked against when a guess is made. If there’s a match, the game tells the player they can’t guess it. If there isn’t, it adds it to the list and continues as normal.

Full Guess Capabilities

What if the player thinks they know the word and wants to make a full guess? Think about how to implement a way for the player to do that. Perhaps the player can type a special phrase or symbol that triggers ‘guess mode’, or perhaps the game can handle any guesses longer than a single character as a full guess. You choose!

Learn More

Source Code

https://pastebin.com/RaC5Ki16

Visual Studio Community

https://www.visualstudio.com/free-developer-offers/

C# Lists

http://www.learncs.org/en/Lists

C# For Loops

http://www.learncs.org/en/For_loops

Also In The June 2017 Issue

Can we measure the time and steps required for things to happen?

This Canadian experiment used a robot to explore how people respond to robots and technology.

An amazing new book turns math problems into shapes and illustrations.

This pen and paper project helps organize ideas into stories with a finite state machine.

While you can't use soap and water on your code, you can keep your code as sparkly clean as any dish or silverware.

This project explores the basics of using Google's Static Map software to display your own maps.

Most people love cookies. But these cookies are the kind that make the internet possible.

Links from the bottom of all the June 2017 articles, collected in one place for you to print, share, or bookmark.

Interesting stories about computer science, software programming, and technology for June 2017.

Software languages don't magically appear. They're created by design. First in a series.