CODE CREATIVE
GUESSING GAME
A classic programming exercise
A Rite of Passage
The “Guessing Game” is a classic computer science exercise that is considered by programmers to be a rite of passage. The computer generates a random number and the user needs to guess what the number is. If the user’s guess is too low, the computer will say “Higher”. If the user’s guess is too high, the computer will say “Lower”. The goal is to guess the random number in the least amount of guesses.

We will be programming the above functionality along with a few more bells and whistles. Every 1000 mile journey begins with a single step, so let’s get started!

Now Try

  • Create a variable that contains a randomly generated number.
  • Create a menu that displays a welcome message and asks the user to enter a number between 1-10.
  • Take in the input from the user.

  • Now, that we have the front-end of the “Guessing Game”, let’s start programming the guts of the game. What we need to do now is check if the number that the user entered in is higher, lower or equal to the randomly generated number. Remember that every time you need your program to check some condition, it’s always going to be done using a branch statement.

    Now Try

  • Create a branch that checks if the user’s input is lower, higher or equal to the randomly generated number.
  • In the case the number is lower, print out the message “The number you entered is too low.”
  • In the case the number is higher, print out the message “The number you entered is too high.”
  • In the case the number is equal, print out the message “Congratulations you got it!”

  • Fantastic, now we have a program that generates a random number and allows the user to make one guess. Based on the user’s guess, the computer let’s them know if the random number is higher, lower or equal. This is all fine and good if the user guesses the number on the first try, but what if they don’t? Our program should let the user continue guessing until they guess correctly.

    Not All Loops Are Created Equal
    When you first thought about accomplishing the task above, you must have asked yourself what kind of loop you should use, a for loop or a while loop? When considering which type of loop to use, you must remember that not all loops are created equal. Although it is true that any for loop can be written as a while loop and every while loop can be written as a for loop, each has situations that they were specifically built for. You would use the for loop if you know exactly how many iterations you want the loop to repeat.

    A clear example would be if you wanted to add all the numbers between 1-100. To accomplish this task, you would need to repeat an instruction 100 times and in this case you would use a for loop. If you wanted to add the digits of pi, assuming you had an infinite amount of time, you would use a while loop.

    This brings us back to the question at hand, which type of loop should we use to allow the user to enter in guesses repeatedly? You probably guessed that we would use a while loop. This is because it is within the realm of possibility that the user will enter the wrong number infinitely. If this is the case, the “Guessing Game” should continue allowing the user to enter in numbers. Since this means we don’t know how many iterations of the loop we need, we need a while loop.

    Now Try

  • Create a while loop around your algorithm to allow the user to enter numbers repeatedly. Remember that the command that generates the random number should not be in the loop.

  • Break
    Test your program and you will see that your program allows the user to guess repeatedly and tells whether the number is higher, lower, or equal. Great, however, we still need to make our program stop when the user enters the correct number. This will require using the ‘break’ command. The ‘break’ command stops the surrounding loop. Take a look at the following code:

    while(True){
       ...
      
       if(random_num == user_num):
           println("Great job! You got it!");
           break;
      
       …
    }
    
    If you add the ‘break’ command in your branch statement, it will stop the surrounding loop. This is exactly what we need our algorithm to do because if the user guesses the number correctly, we want a success message to be displayed and the game to end.

    A Menu
    Now that we have the basic version of the “Guessing Game” completed, let’s add a menu to our program that asks the user if they would like to play a hard, medium or easy game.

    Now Try

  • After the welcome message, display a menu that asks the user to enter a 1(Easy), 2(Medium) or 3(Hard).
  • Take in the user’s input and create a branch statement. Remember that an “Easy” game generates a random number from 1-10, “Medium” generates a random number between 1-20 and “Hard” generates a random number between 1-100.

  • Would You Like to Play Again?
    Our game is now basically complete. The last element we want to add is a choice that is given to the user which allows them to quit or re-run the game. Take a look at the example output below to get an idea of how this works.
    # Game ends
    …
    
    
    Would you like to play again?(Y/N)
    Please enter your choice: y
    
    …
    
    Now Try

  • Output the repeat prompt at the end of the game.
  • Take in the user’s input.

  • Great, now we have our programs asking the user if they would like to play again and taking in their choice. Now we need to program our game to repeat itself if the user entered a ‘Y’. To accomplish this, we need to understand how to get while loops to repeat code based on a user input. Take a look at the algorithm below:
    int num = 5
    
    while(num != 0):
    	println("num is not equal to 0");
    	num = raw_input("Enter the new value for num: ");
    
    Following the control flow, we can see that num is initialized to the value 5. Next, the condition for the while loop is checked and found to be True. The while loop is entered and a message is printed. Before exiting the loop, the user is asked to input another value for the ‘num’ variable. After the user enters another value for num, the condition for the while loop is checked and the body of the loop is executed if the expression is evaluated to True.

    Now, how can we apply this technique to get our “Guessing Game” to repeat itself based on the user’s input? What we need to do create a while loop around our program like so:
    while(play == True){
    	#Guessing Game code
    	…
    }
    
    If you make the above adjustment and try running your code, you will see that the program won’t run. This is because the Python interpreter is searching for a variable called ‘play’ to evaluate whether it is equal to “True”, but a variable called ‘play’ doesn’t exist because we haven’t created it yet. Let’s do that now.

    Now Try

  • Create a variable called ‘play’ and be sure that you initialize it to a value that will be evaluated to ‘True’.
  • Change the name of the variable that contains the input the user enters at the end of the “Guessing Game” to ‘play’.


  • Project

    1. Create a 2 player "Human vs Human" game in which each player takes turns playing a full game with a different random number.
    2. Keep track of the number of guesses each player makes and determine the winner/loser of the round based on the first to reach 10 guesses for easy, 15 for medium, and 30 for hard.
    3. Make the winner based on the first player to win 3 rounds.
    4. Extra Credit - Create a “vs Computer” mode in which the 2nd player is a ‘smart’ computer algorithm. A "dumb" algorithm will choose a random number every time. A "smart" algorithm will play exactly like you do.
    5. Extra Credit - Implement a betting system in which each player starts with $100 and the goal is to win $150.
    Add-Ons
    Take a look at the videos below to get a blueprint on how to add additional elements to your project.

    Clarification on Rounds
    Examples
    Take a look below to see examples of the project in an outstanding range.