In this article, we will make a dice simulator. For this we will use 'time' and 'random' module. 'random' module will help us generate a random number between 1 and 6 (both inclusive) and 'time' module will help us with extra effects while simulating a dice.
We will not just output a number between 1 and 6, rather we will print a dice using the print() method. Next, we will ask the user if you want to roll the dice again and will roll again or stop based on the user's input.
Save the below code in a file named 'dice.py'.
import random
import time
x = "y"
while x == "y":
no = random.randint(1, 6)
print("Rolling...\n")
time.sleep(3)
if no == 1:
print("Dice:")
print("[ ]")
print("[ 0 ]")
print("[ ]")
if no == 2:
print("Dice:")
print("[0 ]")
print("[ ]")
print("[ 0]")
if no == 3:
print("Dice:")
print("[ ]")
print("[0 0 0]")
print("[ ]")
if no == 4:
print("Dice:")
print("[0 0]")
print("[ ]")
print("[0 0]")
if no == 5:
print("Dice:")
print("[0 0]")
print("[ 0 ]")
print("[0 0]")
if no == 6:
print("Dice:")
print("[0 0 0]")
print("[ ]")
print("[0 0 0]")
x = input("\nPress 'y' to roll again: ")
print("\n")
The code is simple. We are working in a while loop in which we first generate a random integer between 1 and 6. Then we print "Rolling%u2026" and delay for 3 seconds for extra effects. Then, we print the dice based on the random number previously generated.
After printing the dice we ask the user if they to roll again and exit the while loop if they input anything other than 'y' else we follow the procedure above again.
To run the simulator, enter the below command in a Terminal/Command Line:
python3 dice.py
A sample output looks like this
Rolling...
Dice:
[0 0]
[ ]
[0 0]
Press 'y' to roll again: y
Rolling...
Dice:
[0 ]
[ ]
[ 0]
Press 'y' to roll again: y
Rolling...
Dice:
[0 ]
[ ]
[ 0]
Press 'y' to roll again: n
Comments