Random Fun and Games: Go Ahead, Take a Chance! 123
import random
faces = ["two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "jack", "queen", "king", "ace"]
my_face = random.choice(faces)
your_face = random.choice(faces)
if faces.index(my_face) > faces.index(your_face):
print("I win!")
elif faces.index(my_face) < faces.index(your_face):
print("You win!")
We use random.choice() twice to pull two random values out
of the faces array, and then we store the values in my_face and
your_face. We use faces.index(my_face) to find the index of my_face in
faces, and we use faces.index(your_face) to get the index of your_face.
If the index of my_face is higher, my card has a higher face value,
and the program prints I win!. Otherwise, if the index of my_face is
lower than the index of your_face, your card’s face value is higher,
and the program prints You win!. Because of the way we ordered
our list, a higher card will always correspond to a higher index.
With this handy tool, we’ve got almost everything we need to build
a “high card” game like War. (We haven’t added the ability to test
for a tie game yet, but we’ll add that as part of the complete pro-
gram in “Putting It All Together” on page 125.)
k eping It Goinge
The final tool we need is a loop so the user can keep playing as
long as they want. We’re going to build this loop a little differently
so that we can reuse it in other games.
First, we need to decide which kind of loop to use. Remember
that a for loop usually means we know exactly the number of
times we want to do something. Because we can’t always predict
how many times someone will want to play our game, a for loop is
not the right fit. A while loop can keep going until some condition
becomes false—for example, when the user presses a key to end
the program. The while loop is what we’ll use for our game loop.
The while loop needs a condition to check, so we’re going to
create a variable that we’ll use as our flag, or signal, to end the
program. Let’s call our flag variable keep_going and set it equal to
True to start:
keep_going = True