Dice by Artem Kovyazin from the Noun Project
You may have recently attended our “Introduction to Python Programming” workshop, or attended the recommended Python courses on Lynda.com. To keep the skills that you’ve learnt fresh in your mind, it is best to find some time per week to work on a simple Python program or two. To help you get started, we will be starting a series of posts on Python activities. Let’s kick-start the series with a simple dice game.
Estimated Time: 40min
Objective: Create a simple dice game between the user and the dealer (PC)
Before you begin, try out the game!
STEP 1: VISUALIZATION
Before writing any codes, visualize what the output of the program is supposed to look like. By playing around with the application above, you can get a feel of what mechanisms are used in the code e.g. loops, branching.
STEP 2: ALGORITHM
When creating any kind of program, the next thing to think about is the ALGORITHM – the approach we need to tackle this problem. For this game, these are a few things that we need to take note of:
- How many dice are being rolled each round
- How do we get the output of a die?
- How do we compare the results of the rolled die?
- What are the possible outputs/scenarios?
Take some time to visualize the flow of the program in a flowchart, like this:
In this game, you will need to use loop and branching (if, else, elif) statements.
For the dice roll, we need to introduce random.randint(min,max), which returns a random value between the minimum and maximum. As such, we will have to make use of:
import random
STEP 3: IMPLEMENTATION
Below, we have included several versions of how the code is meant to look. If you are having difficulties coding the game right off the bat, refer to the PSEUDO-CODE. If you need more assistance, view the FILL-IN-THE-BLANKS section.
After you have finished your code, cross-check against our codes under CODE to see if you got it right.
Step 4: IMPROVE YOUR GAME
Once you manage to create your own dice game, try to work on improving it. Here are some examples:
- What if the user enters an invalid input?
- What would happen if you introduce a maximum number of plays?
- Can we let the player bet on who will be the winner?
- Can the player bet on the number(s) that will be rolled?