Back

The dice game

Introductory tasks
You could introduce this task by recapping the random module and the different sorts of things you can do with it. 

The problem
You will write a game that simulates two people playing dice, except you will play against the computer. A welcome screen should be displayed, explaining what the game is about and how to win. The computer will roll two dice and then you will roll two dice. Whoever has the highest score, wins that game. You will play ten games. Whoever wins most games wins the match and is the champion. The ten games should play automatically, one after another. After each game, you should display the two scores and who won that game. After all ten games, you should summarise the total wins for the computer and player, and how many draws there were, and the overall winner of the match. 

Overview of our solution
As always, there are a number of ways of approaching this problem. It should, however, be broken down into functions where possible.

import random
a function to roll one dice and return the result
a function to roll two dice and return the total
a function for the welcome screen
a function for main()

welcome()
main() 

Pseudo-code

import random

def dice_roll():
    return a random number between 1 and 6

def two_dice():
    return the total of rolling a dice twice

def welcome()
    display a welcome message and basic rules

def main()
    initialise stats variables to 0
    while games < 10:
        get the computer and human's scores and display them
        if computer > human:
            increment computer stats variable
            print 'Computer won'
        elif human > computer:
            increment human stats variable
            print 'Human won'
        else:

            increment draw stats variable
            print 'Draw'
        increment games counter

        print stats
        if computer > human:
            print The computer is the champion'
        elif human > computer:
            print 'Human is the champion'
        else:
             print 'Draw'

welcome()
main()

Solution
dice1

Extension
When there is e.g. one draw in a match, the computer will print out '1 games were drawn'. Students could ensure that sentences are grammatically correct when the computer or player wins only one match, or there is one draw. Students could keep track of how many times a one or a two or a three etc was rolled. At the end of the game, they could display these statistics. The best students should be able to figure out how to display the distribution as a graph. 

Back