Sub topic 12
Shuffle bags: randomness with guarantees
This chapter assumes you can read basic Python. It also assumes you know the earlier chapters on probability, variance and streaks, the gambler's fallacy, and weighted random tables. The goal is a draw system that stays random from one draw to the next but keeps the long-run frequency and the worst streak under your control.
Why independent draws are not enough
A weighted table, such as the random.choices example from the previous chapter, draws with replacement. Every draw ignores the draws before it. That is correct mathematically, but it causes the problem described in the variance and gambler's fallacy chapters. Players judge fairness over short runs, and short runs of independent draws vary a lot.
Take a 2-in-3 chance of a hit. The probability of five hits in a row is (2/3)^5 = 32/243, about 13%. Over a long session, long runs of misses and hits are certain to appear. Players read them as "the game is rigged" or "I'm due", and neither reading is accurate.
A shuffle bag removes that variance by drawing without replacement. You put the outcomes you want into a bag in the exact proportions you want. Then you draw them one at a time in random order. When the bag is empty, you refill and reshuffle it. The deck of cards behind the Tetris "7-bag" piece generator works this way.
An implementation
The bag stores a template list (items) and a working list (bag). Passing in your own random.Random instance keeps the bag compatible with seeding and replays, covered in the seeds chapter.
import random
from itertools import groupby
class ShuffleBag:
def __init__(self, items, rng=None):
if not items:
raise ValueError("a shuffle bag needs at least one item")
self.items = list(items)
self.rng = rng or random.Random()
self.bag = []
def draw(self):
if not self.bag:
self.bag = self.items[:]
self.rng.shuffle(self.bag)
return self.bag.pop()
def longest_run(seq, item):
return max((len(list(g)) for k, g in groupby(seq) if k == item), default=0)
rng = random.Random(5)
bag = ShuffleBag(['hit', 'hit', 'miss'], rng)
bag_draws = [bag.draw() for _ in range(3000)]
plain_draws = [rng.choice(['hit', 'hit', 'miss']) for _ in range(3000)]
print(bag_draws.count('hit')) # 2000
print(longest_run(bag_draws, 'hit') <= 4) # True
print(longest_run(bag_draws, 'miss') <= 2) # True
print(longest_run(plain_draws, 'hit')) # varies with the seed, usually well above 4Each draw costs one list pop. Each refill costs one copy and one shuffle, so the work per draw is small and constant on average.
The constructor rejects an empty list. Without that check, draw would shuffle an empty list and then fail with an IndexError at the first draw, far from the code that created the bad bag.
What the bag guarantees
The bag gives you two exact properties.
- Exact frequency per cycle. Every complete bag of three contains exactly two hits and one miss. After 3000 draws, the count is exactly 2000 hits. A weighted table only approaches that number.
- A hard cap on streaks. An item that appears
ctimes in the bag can never run longer than2cdraws. In one bag it can occupy at mostcconsecutive slots. It can also sit at the end of one bag and at the start of the next, which givescplusc.
For ['hit', 'hit', 'miss'], the longest possible run of hits is 4 and the longest run of misses is 2. The five-hit run that independent draws produce 13% of the time at any given position is impossible here.
The cap is the difference between a shuffle bag and a random table. You are not reducing the odds of bad streaks. You are making them impossible beyond a known length.
Building a bag from a weighted table
Designers usually think in percentages. You can turn a weight table into a bag by choosing a bag size and giving each outcome a count.
import random
def bag_from_counts(counts, rng=None):
items = [name for name, n in counts.items() for _ in range(n)]
return ShuffleBag(items, rng)
# 70 / 25 / 5 as a bag of 100
loot = bag_from_counts({'common': 70, 'rare': 25, 'epic': 5}, random.Random(42))This snippet reuses the ShuffleBag class from the earlier listing. Bag size is a real design decision, and it trades control against predictability.
| Choice | Effect |
|---|---|
| Small bag (3 to 10 items) | Tight streak limits, but a player who tracks the draws can predict the end of the bag |
| Large bag (100 items) | Resembles a weighted table over short spans, but the long-run count is exact |
| Plain weighted table | No guarantees. Streaks are unbounded, but nothing can be predicted |
A 1% item needs a bag of 100 to be represented exactly. At that size, an epic could come on the first draw of one bag and the last draw of the next, 198 draws apart. A shuffle bag fixes the average spacing. It does not fix the spacing of any particular pair. If you need a maximum drought for a rare item, use the pity timer from the next chapter.
Predictability: the gambler's fallacy becomes true
An earlier chapter explained that "I'm due" is wrong for independent events. A shuffle bag is not independent. After two hits in a bag of hit, hit, miss, the third draw is certainly a miss. A player who counts draws is correct to expect it.
Several mitigations exist.
- Refill early. Refill when the bag drops below a threshold, such as half full, and discard the remainder. This hides the cycle boundary but weakens the exact-frequency guarantee.
- Use a larger bag so the end of the cycle is hard to track.
- Keep the bag hidden unless the predictability is part of the design, as in a deck-building game where the draw pile is visible by design.
Edge cases
- Save and load. The bag's current contents are game state. If you save only the item list, loading a save refills the bag and a player can reload to reset their position in it. Save
bagas well, and the state ofrngif you use seeded replays. - Separate bags per purpose. Do not share one bag between unrelated systems, such as critical hits and loot drops. Each system's guarantee holds only over its own draws.
- Changing the odds mid-game. If a buff changes the proportions, rebuild
itemsand clearbag, or the old proportions will persist until the current bag runs out. - Per-player bags. Share one bag between players and the draws of one player become dependent on the other's.
Exercise
A critical-hit bag holds 3 crit and 7 normal items, and refills when empty. What is the longest possible run of normal draws, and the longest possible run of crit draws?
Show answer
The longest run of normal is 14, because 7 can sit at the end of one bag and 7 at the start of the next (2 × 7). The longest run of crit is 6 (2 × 3). A plain 30% crit chance has no upper limit on its miss streak.
Exercise
You change the bag from the previous exercise so that it refills as soon as 3 items remain, discarding those 3. What do you gain, and what do you lose?
Show answer
You gain unpredictability. A player can no longer be certain what the final draws of a cycle will be, because those draws are discarded. You lose the exact frequency guarantee, because the discarded items may be skewed toward normal or crit, so the long-run ratio is only approximately 3 to 7.