Randomness: Let the Robot Roll the Dice!
Introduce surprise and chance to your Python games! Learn how to use the random module to roll dice and choose random items.
Welcome back, game designer! 🎲
If video games were completely predictable, they would be very boring. Imagine if a coin flip always landed on heads, or if monsters in a game always walked in the exact same pattern. We need surprises!
Today, we are going to teach our Python robot how to roll a magical, invisible dice inside its head to make random choices.
To do this, we use the random module!
The Magic Dice Roller (How randomness works)#
Just like we import the turtle library to draw shapes, we can import random to bring randomness into our code.
graph TD
Start([Start Game]) --> Choice["Options: ['Rock', 'Paper', 'Scissors']"]
Choice --> Random["random.choice() rolls the magic dice"]
Random --> Result{"What did it choose?"}
Result -->|Option 1| Rock["✊ Rock!"]
Result -->|Option 2| Paper["✋ Paper!"]
Result -->|Option 3| Scissors["✌️ Scissors!"]
Here are two main spells inside the random library:
1. Choice: Pick a Random Item from a List#
If you have a backpack list of options, you can ask Python to pick one out at random:
import random
options = ["Rock", "Paper", "Scissors"]
robot_choice = random.choice(options)
print("The robot chose: " + robot_choice)pythonEvery time you run this code, the robot might choose something different! ✊ ✋ ✌️
2. Randint: Roll a Number Range#
If you want to roll a standard 6-sided dice, you want a random integer (number) between 1 and 6:
import random
dice_roll = random.randint(1, 6)
print("You rolled a: " + str(dice_roll) + "! 🎲")pythonTry It Yourself! 🎮#
Open your Python editor and try creating a fortune-telling robot:
import random
fortunes = [
"You will find a shiny gold coin today! 🪙",
"Watch out for mud puddles! 🌧️",
"A friendly dog will wave its tail at you! 🐶",
"You will learn a cool new coding trick! 💻"
]
input("Ask the robot a Yes/No question and press Enter... ")
print("Your fortune: " + random.choice(fortunes))pythonRun this program multiple times to see if your fortune changes!
Next time, we will learn about Dictionaries, which act like a robot’s secret address book to look up phone numbers and inventory details. See you then!