11 Chapter 11: Making Computer Games
MAKING COMPUTER GAMES
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:
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.
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.
The randrange() method will generate random integers using three parameters, a, b, 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:
Here we generate three random odd numbers between 1 and 99, inclusive:
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
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:
Here is a sample run of the program:
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.
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:
The sample() method can be used to randomly pick k unique items from a list, where the list itself and the value of k 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 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:
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.
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”]?