# 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
print(random.randint(1,6))```

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] ”’
DiceSimulator.py
I don’t know if I should say die or dice :()
Author: Alan Richmond, Python3.codes
”’
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))
d.fill(diecol)
pygame.display.set_caption("Dice Simulator")

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

pygame.display.flip()
time.sleep(0.2)
[/python]