random
lhj
summon randomBasic random numbers
lhj
random.rand() ## float in [0.0, 1.0)
random.randint(1, 10) ## integer in [1, 10] inclusive
random.randfloat(0, 5) ## float in [0, 5]Sampling
lhj
forge items = ["sword", "axe", "bow", "staff"]
random.choice(items) ## one random item
random.choices(items, k=2) ## 2 random items (with replacement)
random.sample(items, k=3) ## 3 random items (without replacement)Shuffling
shuffle modifies the list in place:
lhj
forge deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(deck)
echo deck ## some shuffled orderTo get a shuffled copy without modifying the original:
lhj
forge original = [1, 2, 3, 4, 5]
forge copy = list(original)
random.shuffle(copy)
echo original ## [1, 2, 3, 4, 5] unchanged
echo copy ## shuffledSeeding
Set the seed for reproducible output:
lhj
random.seed(42)
echo random.randint(1, 100) ## same number every time with seed 42Weighted choice
lhj
forge items = ["common", "rare", "legendary"]
forge weights = [70, 25, 5]
forge drop = random.weighted_choice(items, weights)
echo drop ## "common" 70% of the time, etc.Example: dice roller
lhj
summon random
blade roll(sides: int = 6) -> int:
release random.randint(1, sides)
blade roll_advantage(sides: int = 20) -> int:
forge a = roll(sides)
forge b = roll(sides)
blade a > b: release a
release b
echo "d6: {roll()}"
echo "d20: {roll(20)}"
echo "d20 with advantage: {roll_advantage()}"Example: shuffle a deck
lhj
summon random
forge suits = ["♠", "♥", "♦", "♣"]
forge ranks = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
forge deck = []
march suit in suits:
march rank in ranks:
deck.pack("{rank}{suit}")
random.shuffle(deck)
echo "Top 5 cards:"
march i in 0..4:
echo " {deck[i]}"