Sub topic 11
Weighted random tables
A weighted random table picks one outcome from a list, where each outcome has its own chance of being picked. Loot drops, enemy spawns, card pack contents, and critical hits all use this structure. This chapter assumes you know basic probability (a chance of 25 out of 100 is 25%), can read simple Python, and have met expected value in an earlier chapter.
Why weights instead of equal chances
A plain random choice gives every outcome the same chance. If a chest holds a sword, a potion, and a legendary crown, equal chances would hand out crowns a third of the time. Designers want some outcomes common and others rare, so each entry gets a number called a weight. The bigger the weight, the more often the entry appears.
Weights do not have to add up to 100. They are relative. A table with weights 70, 25, and 5 behaves exactly like a table with weights 14, 5, and 1, because only the ratios matter.
To turn a weight into a probability, divide it by the total of all weights.
| Item | Weight | Probability |
|---|---|---|
| common | 70 | 70 / 100 = 70% |
| rare | 25 | 25 / 100 = 25% |
| epic | 5 | 5 / 100 = 5% |
Using weights that sum to 100 makes the table easy to read in a design document. Using other totals is often easier to edit, because adding a new entry does not force you to shrink the others.
Drawing from a table in Python
Python's random.choices takes a list of items and a matching list of weights.
import random
rng = random.Random(42)
table = {'common': 70, 'rare': 25, 'epic': 5}
drops = rng.choices(list(table), weights=list(table.values()), k=1000)
print({name: drops.count(name) for name in table})The counts will be close to 700, 250, and 50, but they will almost never match exactly. That gap is variance, covered in an earlier chapter. A thousand draws is a lot, and the counts still wobble by a few percent.
How the draw works inside
The standard method is the cumulative-sum approach. Lay the weights end to end on a number line, pick a random number between 0 and the total, and see which segment it lands in.
import random
def pick(rng, table):
total = sum(table.values())
roll = rng.uniform(0, total)
running = 0
for name, weight in table.items():
running += weight
if roll < running:
return name
return name # guards against floating-point edge cases
rng = random.Random(5)
table = {'common': 70, 'rare': 25, 'epic': 5}
print([pick(rng, table) for _ in range(10)])With weights 70, 25, and 5, rolls from 0 to 70 give common, 70 to 95 give rare, and 95 to 100 give epic. The final return handles the rare case where rounding leaves roll equal to the total. This loop is fine for small tables. For tables with thousands of entries, precompute the running totals and use binary search, which is what random.choices does when you pass cum_weights.
Expected value of a table
Each entry can carry a value, such as gold or a power rating. The expected value of one draw is the sum of each value times its probability.
table = {'common': (70, 10), 'rare': (25, 50), 'epic': (5, 400)}
total_weight = sum(w for w, _ in table.values())
ev = sum(w / total_weight * value for w, value in table.values())
print(ev) # 39.5The result is 0.70 × 10 + 0.25 × 50 + 0.05 × 400 = 7 + 12.5 + 20 = 39.5. This number tells you the average reward per drop over a long run. It is the main tool for balancing the economy, because you can compare it with what the player pays to open the chest.
Notice that the epic entry contributes more than half of the expected value while appearing in only 5% of draws. Most players see a table that pays around 10 to 50 per drop, and an occasional spike pays the average up. This is why a rare, valuable entry makes the average misleading for a single session.
Nested and conditional tables
Real games rarely use one flat table. A common pattern is a two-step draw. The first table picks a category, and a second table inside that category picks the item.
import random
tables = {
'weapon': {'sword': 5, 'bow': 3, 'staff': 2},
'armor': {'helmet': 4, 'boots': 4, 'shield': 2},
'consumable': {'potion': 8, 'scroll': 2},
}
categories = {'weapon': 20, 'armor': 30, 'consumable': 50}
def roll_loot(rng):
cat = rng.choices(list(categories), weights=list(categories.values()))[0]
sub = tables[cat]
return cat, rng.choices(list(sub), weights=list(sub.values()))[0]
rng = random.Random(9)
print([roll_loot(rng) for _ in range(5)])The chance of a specific item is the product of the two stages. A sword needs the weapon category (20%) and then the sword entry (5 out of 10, or 50%), so it appears 10% of the time. Nested tables keep each table short and let different designers own different parts. The cost is that the final odds are hidden behind multiplication, so write a helper that prints the flattened probabilities whenever you change a table.
Common errors
- Treating weights as percentages by accident. If you edit one weight in a table that was summing to 100, the total changes and every other probability shifts too. Compute probabilities from the total, and check the total in a test.
- Zero or negative weights. A weight of zero means the item never drops, which is a valid way to disable it. A negative weight raises an error in
random.choices. Validate tables when you load them. - Empty tables. If every weight is zero, there is nothing to pick. Python raises an error. Decide in advance what a monster with no valid loot should do.
- Forgetting independence. Each draw is independent. Getting a rare item does not make the next one less likely. Players often expect otherwise, which the gambler's fallacy chapter explains.
- Judging a table from a small sample. Ten drops tell you almost nothing about a 5% entry. Check odds with a large simulation, not with a few playtests.
- Rarity that is too rare. A 0.1% drop has a 1 in 1000 chance per draw, but a player can still go several thousand draws without one. Tables alone cannot promise a reward. Shuffle bags and pity timers, covered in the next chapters, add that guarantee.
Designing the weights
Start from the experience you want, then pick numbers. A useful process:
- Decide how often a player should see each tier, such as "an epic about once per session."
- Estimate how many draws a session contains.
- Set the weight as the desired count divided by the draw count. If a session has 20 draws and you want one epic, the probability is about 5%.
- Compute the expected value and compare it with the cost of a draw.
- Simulate many sessions and look at the spread, not only the average.
Step 5 matters because a 5% chance over 20 draws gives an epic in at least one draw only about 64% of the time (1 − 0.95²⁰ ≈ 0.64). More than a third of sessions would have no epic at all. A designer who wanted "one per session" has built a table that disappoints one session in three.
import random
def sessions_with_epic(trials=10000, draws=20, seed=11):
rng = random.Random(seed)
hits = 0
for _ in range(trials):
drops = rng.choices(['other', 'epic'], weights=[95, 5], k=draws)
hits += 'epic' in drops
return hits / trials
print(sessions_with_epic()) # about 0.64Summary
A weighted table is a list of outcomes with relative weights. Probability is weight divided by total weight, and expected value is the probability-weighted sum of the values. Nested tables multiply odds across stages. A table controls the long-run average but not the short run, so check it with simulation and add shuffle bags or pity timers when players need a guarantee.
Exercise
A table has weights iron 60, silver 30, gold 10, worth 5, 20, and 100 coins. (a) What is the chance of gold? (b) What is the expected value of one draw? (c) If you add a "diamond" entry with weight 100 and leave the others unchanged, what is the new chance of gold?
Show answer
(a) The total weight is 100, so gold is 10 / 100 = 10%. (b) 0.60 × 5 + 0.30 × 20 + 0.10 × 100 = 3 + 6 + 10 = 19 coins. (c) The total becomes 200, so gold falls to 10 / 200 = 5%. Adding an entry lowers every other probability, because weights are relative.
Exercise
In the two-stage loot example, the categories have weights 20, 30, and 50, and the armor table has helmet 4, boots 4, shield 2. What is the chance that one chest gives a shield?
Show answer
The armor category is chosen 30% of the time. Within armor, the shield has weight 2 out of 10, or 20%. The chance is 0.30 × 0.20 = 0.06, or 6%.