How to Build a Game & Learn C#

Self-Paced Workshop – Part 3

By Former Tech Elevator Instructor Matt Eland

In our last two tutorials we discussed creating a new C# project and the concepts of variables and expressions as we moved towards programming our first application: a Guess the Number Game.

In this tutorial, we’ll expand our bag of tools to get text from the user, interpret it as a number and perform some basic mathematics with it. We’ll close by introducing if statements, an extremely powerful tool in our toolbelts as programmers.

Note: This series is based loosely on some of the content from the 1st week of Tech Elevator‘s 14 week C# curriculum

Let’s get started.

Cleaning the Slate

In our last article we wrote some basic code to illustrate string and int variables. That was good as a learning exercise, but it won’t be useful for our final application, a game where the user can guess a number from one to one hundred and be told if their guess was high, low, or correct.

Let’s clear out the existing Main method and replace it with this:

Here we have a mostly empty method that has major comments for the logic we’ll need to do in this tutorial and the next one in order to get the game working properly.We also have a secretNumber integer variable that is set to 42 for now, but we’ll have the program generate a random number next tutorial.This secretNumber represents the number that the player has to guess. By the end of this tutorial, you’ll be able to enter a number into the console and be told if it is less than, greater than, or exactly the “secret” number. Note: We’re declaring our guess variable here to save us some time and confusion later on. Don’t worry about why this line is here yet.

Getting User Input

Let’s expand the // Let the player enter a number comment to include the following code:

Before we talk about the code, let’s run the program with these changes. You should now be able to enter some text and see the result in the console as shown below:

Click Next to continue.

This works because Console.ReadLine() causes the program to wait for the user to type in some text and type enter. The program then takes that value and assigns it into the guessText variable.

So, if the user typed in “I’m Batman” (remember, ReadLine allows the user to type in any text), guessText would store that string and the following line: Console.WriteLine(“You guessed: ” + guessText); would evaluate to Console.WriteLine(“You guessed: I’m Batman”); and display that message.

Next, let’s look at how we can interpret the user’s input as a number.

Parsing Strings to Integers

While we can’t change Console.ReadLine to have it return an int instead of a string or require a numeric input, we can try to interpret the string the user typed in as a number.

We do this via the int.Parse method.

Add the following code below the code you wrote earlier:

Click Create when ready and your project will be created.

There’s a decent amount going on here, so let’s take it a line at a time.

guess = int.Parse(guessText); sets the guess variable we declared earlier to be the result of int.Parse on the user’s text. int.Parse is a method provided by .NET’s base class libraries that takes in a string and attempts to convert it to an integer.

Note: There are ways of handling cases where the user types in random text instead of something that is a number. However, for the purposes of keeping this tutorial focused, we’ll assume that the user is providing valid input.

Revisiting Expressions

Next let’s talk about that Console.WriteLine(“2 x ” + guess + ” = ” + (guess * 2)); line.

This is similar to what we’ve seen before, but a bit more complicated. We have a few new things that we’ve not seen before in the (guess * 2) expression.

The * operator means multiplication, so this will multiply the current value of guess by 2.

When this line runs and guess is 5, it will first evaluate to

This simplifies down to:

This is a lot more familiar and simplifies to

Which is exactly what is displayed on the screen.

Getting Ready for Conditions

Okay, now that we’ve demonstrated that integer parsing works, let’s remove the last two Console.WriteLine statements. Your code should now look like this:

We should now be in a good place to start looking at interpreting the user’s guess.

If Statements

Now, let’s look at some new syntax for conditionally doing things in code: the if statement.

If statements let us do specific logic if an expression evaluates to true.

Below the int guess = … line, add the following code:

Now when we run the application, if you type in “42” you should see the console message indicating you guessed the number:

So let’s look at how this works. We’ll start at that first line: if (guess == secretNumber)

The if statement requires parentheses. Inside these parentheses, C# needs an expression that evaluates to either true or false. If the expression evaluates to true, any code inside of the { }’s will be executed.

The code inside the {}’s can be any C# code you can write – variable declarations, Console calls, etc. The key here is that it only is executed if the expression in the if statement is true.

Let’s look a bit more at that expression: guess == secretNumber. We’ve not seen == before. The “double equals” operator is a way to compare the left side to the right side. If the two sides are equal, the expression will evaluate to true, otherwise the expression will evaluate to false.

As an example, if the current value of guess is 35, the line becomes if (35 == 42) which evaluates to if (false). Since this value is false, the code inside the { }’s will not execute.

Conversely, if guess was 42, the line becomes if (42 == 42) or if (true) and the code inside the {}’s will work.

If / Else Blocks

So, if statements are powerful, but they can do a bit more than we just did. We can add an else statement after our if as shown below:

Here one of these two { } blocks will always be executed. If the expression in the if statement is true, the first block will execute as before. Otherwise, the else block will execute and the user will see the message indicating that they guessed incorrectly.

Chaining If / Else Blocks

But wait, there’s more!

Remember that the app we’re building will tell the user if their guess was exactly correct, too high, or too low. Right now we only give the user information on whether their guess was correct or incorrect.

We can take advantage of else blocks to chain together if statements by replacing that second { } (and its code) with another if statement as shown below:

Here we go directly from the else statement into another if statement. This is entirely legal C# code and will only execute if the guess is not the secretNumber.

C# will then evaluate that second if statement and check if (guess > secretNumber).

We haven’t looked at > before, but this is a comparison operator that evaluates to true if the left side is greater than the right side and false otherwise. Similarly, there is also a < operator for less than as well as >= and <= for greater than or equal to and less than or equal to.

Now, if we run and guess 50, we’ll see a message indicating that our guess was too high.

Accounting for All Possibilities

Our code is still missing something, however. If the user guesses a number below the secret number, they won’t see a message. Let’s add an else to the end of our logic as shown below:

This finalized if / else chain handles cases where:

  • guess is exactly equal to secretNumber
  • guess is greater than secretNumber
  • All other cases (less than secretNumber)

Now, no matter what the user enters, they should see a message letting them know how close their guess was.

Next Steps

As you can see, we’re starting to get to a workable application, but we’re still missing a few key pieces.

In the final tutorial of the series, we’ll introduce random number generation, loops, and tie everything together into a single application.

Continue the workshop in the next session.

Matt Eland

Matt has worked on services, desktop applications, single page JavaScript applications, mobile apps, and web applications in various .NET, Java, and JavaScript technologies for 30+ years. He loves mentoring and writing about software development. He leads instruction at Tech Elevator Columbus.