Random Fun and Games: Go Ahead, Take a Chance! 125
Here we add the while statement, so our loop will continue as
long as keep_going evaluates to True. In the final program, we will
“wrap” this while loop around the code to play a single hand. We’ll
do this by putting the while statement before the code that chooses
the cards, and by putting the prompt to hit a key after the code
that tells who wins. Remember to indent the code inside the loop!
Putting It All Together
Putting all those components together, we can build a War-like
game that we’ll call HighCard.py. The computer draws a card for
itself and a card for the player, checks to see which card is higher,
and declares the winner. Type the code for HighCard.py into a
new IDLE window or go to http://www.nostarch.com/teachkids/
to download it and play.
HighCard.py
import random
suits = ["clubs", "diamonds", "hearts", "spades"]
faces = ["two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "jack", "queen", "king", "ace"]
keep_going = True
while keep_going:
my_face = random.choice(faces)
my_suit = random.choice(suits)
your_face = random.choice(faces)
your_suit = random.choice(suits)
print("I have the", my_face, "of", my_suit)
print("You have the", your_face, "of", your_suit)
if faces.index(my_face) > faces.index(your_face):
print("I win!")
elif faces.index(my_face) < faces.index(your_face):
print("You win!")
else:
print("It's a tie!")
answer = input("Hit [Enter] to keep going, any key to exit: ")
keep_going = (answer == "")
Run the game, and it’ll print the computer’s card and your
card, followed by an announcement of who won and a prompt that
offers you the opportunity to play again or exit. Play a few rounds
and you’ll notice that the cards are random enough to make the
outcome fun—sometimes the computer wins, sometimes you win,
but it’s a fun game thanks to the element of chance.