Alan Richmond

A Graphical Dice Simulator

This PyGame program simulates the roll of a die (or dice if you prefer). It’s a fairly simple, straightforward thing to do, though it may be worth noting that the spots display is oh-so-slightly clever. Some spots appear in more than one number, e.g. the middle spot is in all the odd numbers, hence the test if n % 2 == 1: serves to display the middle spot for 3 numbers. By the time we get down to n==6 we only have 2 more spots to display. It’s an example of DRY 🙂

Of course, this isn’t the simplest possible program that could simulate the roll of a dice; this is:

import random

However, this is a bit dull, hence we spruce it up with a graphical interface, and just to add a bit more realism, we let the dice ‘roll’ a little while. It displays a dozen faces with a small delay between each, and stops on the last. Without the delay you won’t see the faces before the last.

[python] ”’
I don’t know if I should say die or dice :()
Author: Alan Richmond,
import pygame, random, time

size = 256 # Size of window/dice
spsz = size//10 # size of spots
m = int(size/2) # mid-point of dice (or die?)
l=t=int(size/4) # location of left and top spots
r=b=size-l # location of right and bottom spots
rolling = 12 # times that dice rolls before stopping
diecol = (255,255,127) # die colour
spotcol = (0,127,127) # spot colour

d = pygame.display.set_mode((size, size))
pygame.display.set_caption("Dice Simulator")

for i in range(rolling): # roll the die…
n=random.randint(1,6) # random number between 1 & 6
d.fill(diecol) # clear previous spots
if n % 2 == 1:,spotcol,(m,m),spsz) # middle spot
if n==2 or n==3 or n==4 or n==5 or n==6:,spotcol,(l,b),spsz) # left bottom,spotcol,(r,t),spsz) # right top
if n==4 or n==5 or n==6:,spotcol,(l,t),spsz) # left top,spotcol,(r,b),spsz) # right bottom
if n==6:,spotcol,(m,b),spsz) # middle bottom,spotcol,(m,t),spsz) # middle top


Comments are closed.