Random Fun and Games: Go Ahead, Take a Chance! 129
looking at the value in the first dice element and comparing it to
the value in the fourth dice element. If the array is sorted, and
these are the same, we have four of a kind.
To test for three of a kind, we add another elif statement,
and we put the three-of-a-kind test after the four-of-a-kind test so
that we test for three of a kind only if there’s no five of a kind and
no four of a kind; we want the highest hand to be reported. There
are three possible cases of three of a kind if we’re working with
sorted dice: the first three dice match, the middle three, or the last
three. In code, that would be:
elif (dice[0] == dice[2]) or (dice[1] == dice[3]) or (dice[2] == dice[4]):
print("Three of a kind")
Now that we can test for various winning hands in our dice
game, let’s add the game loop and the dice a r ray.
Putting It All Together
Here’s the complete FiveDice.py program. Type the code in a new
window or download it from http://www.nostarch.com/teachkids/.
FiveDice.py
import random
Game loop
keep_going = True
while keep_going:
"Roll" five random dice
u dice = [0,0,0,0,0] # Set up an array for five values dice[0]-dice[4]
v for i in range(5): # "Roll" a random number from 1-6 for all 5 dice
w dice[i] = random.randint(1,6)
x print("You rolled:", dice) # Print out the dice values
Sort them
y dice.sort()
Check for five of a kind, four of a kind, three of a kind
Yahtzee - all five dice are the same
if dice[0] == dice[4]:
print("Yahtzee!")
FourOfAKind - first four are the same, or last four are the same
elif (dice[0] == dice[3]) or (dice[1] == dice[4]):
print("Four of a kind!")
ThreeOfAKind - first three, middle three, or last three are the same
elif (dice[0] == dice[2]) or (dice[1] == dice[3]) or (dice[2] == dice[4]):
print("Three of a kind")
keep_going = (input("Hit [Enter] to keep going, any key to exit: ") == "")