Guessing Number Game with C#

Guessing Game Number

Guessing Number Game is not a famous or fun game but still widely used by instructors as an example or as an assignment.

In this tutorial, we will create a simple number guessing game with C#, using Visual Basic. The game is console base only – not UI.

Following are some rules for the game:


  • Giving a user 7 chances to guess a randomly generated whole number between 1 and 100

  • The program begins by randomly generating a number between 1 and 100

  • The random number is winning number used to compare against users input

  • The Game prompts user for input

Create a Solution

We start with creating Solution in Visual Basic. Open Visual Basic, create new Solution and name it: GuessingGame. Visual Basic automatically creates project structure including program.cs file which contains the following code by default:

program.cs

 

Welcome Users and Create Variables

Let’s start with the editing program.cs file to add required code for making the game. All code goes inside the Main method.

Add the following line of code inside the Main method to welcome user:

Console.WriteLine(); is a method which prints on a screen. It accepts content as parameter.

We will create four properties/ variables as following:

The first variable generates a random number between 1 and 100.
The second variable store user’s input which is an integer.
The third variable keeps track of guesses. (How many times user guess?)
The last variable is a Boolean and by default the value is false. This is a flag for ending the game.

Creating playGame() Method

We create playGame() method which has while loop. The while loop runs until a user attempt is more than 7 or the game is won. The method has Console.ReadLine() which ask a user for input and then evaluate it with validateInput() method to make sure user entered the right option. It also calls evaluateAnswer() to determine a win, guess too low or guess too high.

playGame()

playGame() method is void, and we run it by calling it.

Validate User Input

It is important to check user’s input to make sure it’s an integer. validateInput() method returns Boolean after checking user’s input. It returns true if a user entered an integer, else false.

validateInput()

Determine Win or Lost

Create evaluateAnswer() method which returns string base on win or loses situation. If a user wins: userWin value is changed to true and the game ends. The method also determines too low or too high guess and return strings to print on a screen.

Create resetGame() Method and Loop Game

The last method is resetGame() which asks a user if want to play again or quit and reset variables with Y option.

resetGame()

The last line is looping resetGame() method until a user chooses to quit the game.

Source Code

The complete source code is available on GitHub: GuessingNumber on GitHub