11 Chapter 11: Making Computer Games

MAKING COMPUTER GAMES

0s and 1s in a hypnotic arrangement.

 

Topics Covered:

  • Random numbers
  • Guess the number game
  • Paper rock scissors game

In this chapter, we are going to discuss creating computer games. Of course, playing computer games is fun and entertaining. Many computer games also have skill-building and educational aspects, too. Before we create our first computer game, we must first talk about random numbers.

 

Random Numbers

If you are playing a dice game, you wouldn’t want the same dice rolls to show up every game. In a card game, you don’t want to be dealt the same hand every game. If you’re chasing zombies, you wouldn’t want them to follow the same path every time. To make games more fun, interesting and challenging, you need random, unpredictable events to occur. Most programming languages include a random number generation module that provides one or more functions for producing random numbers. Not only do random numbers play an important role in computer-based game programs, they are also widely used to create programs that simulate real-world situations, including business and scientific applications.

Python provides a module named random that you can use to create random events. To be clear, a computer’s random number generator is not truly random. It is simply a mathematical algorithm that will produce numbers or events that appear to be random. Because of this face, we often call one of these functions a pseudorandom number generator (PRNG). To use the random number features, your first must import the random module.

Although the reference random.random() may initially seem awkward, we are just calling the random() method from the random module. The random method will generate a floating point number in the range [0..1), which means a number greater than or equal to 0 but less than 1. In the example below, we make three calls to the random method:

Numbers between 0 and 1 found with the random.random command.

Most programming languages will use the computer’s clock to initialize, or seed, the random number generator. This gives you different random numbers every time you run your program, which is usually what you want. Occasionally, you want to reproduce the same random numbers. In this case, you can manually give the random number generator a seed, which is an integer, to initialize the PRNG. Below, we seed the PRNG with the value of 100 and call the random method twice. Then, we again seed the function with 100 and call the random method two more times. As you can see, the numbers generated are identical.

Numbers between 0 and 1 found with the random.seed(100) command.

If you want random integers generated instead of floating point numbers, you can call the randint() method. It accepts two parameters, a and b, and generates an integer in the range [a..b]. In the example below, we make three calls of randint(10,20) to generate integers in the range [10..20]. Since this range is in square brackets [], that means the end points are included. It’s possible that the value 10 or 20 could be generated.

Finding a random number between 10 and 20 with the command random.randint(10,20).

The randrange() method will generate random integers using three parameters, ab, and step. It will generate numbers in the range [a..b) such that each number is a+k*step, where k is a non-negative integer, and the number is less than b. Below, we generate four multiples of 10 that are less than 50:

Finding a random number using the command random.randrange(0,50,10).

Here we generate three random odd numbers between 1 and 99, inclusive:

Finding a random number using the command random.randrange(1,100,2).

 

Guess the Number Game

We know enough about random numbers at this point to develop our first game. In the “Guess the Number” game, the computer will generate a random number between 1 and 100 and the user’s job is to guess it. Each time the user guesses, the program will notify the user if his guess was “too high”, “too low”, or if he guessed it correctly. Before looking at the code, first we will check out a flowchart modeling the solution:

Flowchart Modeling the Guess the Number Game.

 

Flowchart Modeling the Guess the Number Game

We will use a Boolean variable named done as the condition of our while loop. The program should continue looping until the user successfully guesses the number. Our loop first asks the user for his guess. It increments a guess count variable. It then goes through a series of if statements that compare the user guess to the number. When the guess is correct, done is set to True, the program exits the loop and lets the user know how many guesses he took. The code for the program is shown here:

Code for the Guess the Number Game (Version 1).

Here is a sample run of the program:

Output of the code for the Guess the Number Game (Version 1) in the previous image.
Code for the Guess the Number Game (Version 2).

 

Allowing Multiple Turns

Now that we have a working game, we can play all day and put your guessing skills to the test. Each time we want to play, though, we have to run the program again. In version 2 of the guessing game, we will allow the user to play as many games as they wish with just a single run of the program.

You might be thinking that all we need to do is enclose another loop around the code that plays the game. This will work, but our code is starting to get cluttered. A cleaner and more structured way to do this is to convert our game code into a function. In chapter 8, we talked about how many Python programmers will include their main program in a main() function. By doing this, we can separate the loop that allows multiple turns from the game itself. The only thing left to do is make a call to main(). Be careful that you do not indent this line since it will be the first instruction that will get executed. You can see the code listing of this version below. After each game concludes, the user will now enter either “yes” or “no”, depending on if they would like to play again or not.

 

INTERACTIVE – Playing the lottery

Suppose we wanted to generate a random 3-digit number. Take a look at the program below. That should do the trick! Make sure you examine the code closely and understand how it works. Also, run the program multiple times. Does it produce the same output each time? Now, see if you can modify the program so that the user will first input an integer, then the program will generate and print a random number with that many digits.

 

Generating Random Strings

Often times, we would like to generate a random string. The choice() method will randomly pick an item from a list. To simulate flipping a coin three times, we create a list named coins with the strings “Heads” and “Tails”, and then call the choice() method passing coins as an argument.

Random choice that flips a coin.

Maybe you have a game that needs to pick a random superhero. You could store superheroes in a list and use the choice() method to randomly pick one. In the example below, we illustrate the choice() method by calling it three times:

Choosing a random superhero through the random.choice(superHeroes) command.

The sample() method can be used to randomly pick unique items from a list, where the list itself and the value of are provided as parameters to the method. The sample() method returns a list, which can be stored as a variable. In the example below, we first show a list of 3 randomly chosen superheroes. We also call sample and store the list to a variable heroes. To access the individual items from the heroes list, you could use a for loop:

Another method that comes in handy with programs that include PRNG of lists is shuffle(). This method mixes up the order of the list items, similar to shuffling a deck of cards. Below, we print the superHeroes list, both before and after the shuffle() call:

The list of superheros being randomly shuffled.

 

The Paper-Rock-Scissors Game

Problem: Your friend Leo really loves to play the “Paper-Rock-Scissors” game, but he is currently isolated and has no opponent to play. Your job is to write a game so that Leo can play “Paper-Rock-Scissors.” Specifically, you need to:

– Create a user-defined function named game() that will play the game:

  • Your Python program should generate and store to a variable named computer either “paper”, “rock”, or “scissors”.
  • The program should ask the user to type in either “paper”, “rock”, or “scissors” as keyboard input and store it to a variable named player.
  • The program should use if statements to output either “Computer wins”, “Player wins”, or “It was a tie”.

– A main() function should be created that will call the game function. Once the game is over, the program should ask the user if they would like to play again (yes/no). The main() function should continue looping until the user says “no”.

– The interaction of the program should be case-insensitive and look like this:

Rock Paper Scissors Game output.

The code that implements this game is shown below. The first thing you notice is the main() function looks the same as the one from the Guess the Number program. The lower() method is used on both strings that the user inputs in order to make the logic case-insensitive. The choice method is used to randomly select the computer’s picks. To check for a tie, we look to see if player and computer are the same. There are three ways a player can win this game, so a compound condition was created to test those three cases. Finally, we can use the else statement to conclude a loss since the player did not win or tie.

Code for the Paper Rock Scissors Game

 

Chapter Review Exercises:

11.1. What Python function could generate numbers from a random sequence such as 10, 15, 20…45, 50?

11.2. What Python function will select one item out of a list such as [“cat”, “dog”, “fish”, “horse”, “monkey”, “snake”]?

11.3. What Python function will generate a random floating point number between 0 and 1?

11.4. What Python function will select multiple items out of a list such as [“cat”, “dog”, “fish”, “horse”, “monkey”, “snake”]?

11.5. What Python function, when you give it minimum and maximum values like 3 and 10, will generate a random integer in that range [3..10]?

11.6. What Python function will take a list like [“cat”, “dog”, “fish”, “horse”, “monkey”, “snake”] and turn it into a new list that looks like [“horse”, “snake”, “monkey”, “cat”, “fish”, “dog”]?

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Python Textbook Copyright © 2022 by Dr. Mark Terwilliger is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book