🐸

The Dice

Python Basicspython-architect-14-dice
Reward: 80 XP
|

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:

  1. random.randint(min, max): Pick a random number.
  2. 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 Solution
Expand
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 Tips
Want more? Click to expand

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...