Adventure is boring if everything is predictable. We need chaos! We need luck!
The random scroll allows us to add chance to our world.
The random Spell
Two useful spells from this scroll:
random.randint(min, max): Pick a random number.random.choice(list): Pick a random item from a list.
import random # Roll a 6-sided die (1 to 6) print(random.randint(1, 6)) # Pick a card cards = ["Ace", "King", "Queen"] print(random.choice(cards))
1
Import random
At the top, type import random.
2
Roll for Initiative
Use random.randint(1, 20) to generate a number between 1 and 20. Assign it to the variable roll.
3
Flip a Coin
Use random.choice(["Heads", "Tails"]) to pick a side. Assign it to the variable coin.
Computer randomness is "pseudo-random" (math tricks), but it's good enough for games!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
import random
# Step 1: Roll 1-20
roll = random.randint(1, 20)
print("Initiative Roll: " + str(roll))
# Step 2: Coin flip
coin = random.choice(["Heads", "Tails"])
print("Coin flip: " + coin)Advanced TipsWant more? Click to expandClick to collapse
F. The Seed
- Computers can't be truly random. They use a starting number called a "seed".
- If you type
random.seed(42)at the start, you will get the exact same "random" numbers every time you run the code! Useful for testing.
Loading...
Terminal
Terminal
Ready to run...