Dev.to WebDev 🛠 Dev 👁 0 📖 2 min read

A fair spy draw in code: weighting a random choice by past roles

Picking the spy at random sounds easy: choose a player. In a game played over several rounds, a plain random choice has a problem. The same player can be spy twice in a row, or three times, while someone else is never pi

Picking the spy at random sounds easy: choose a player. In a game played over several rounds, a plain random choice has a problem. The same player can be spy twice in a row, or three times, while someone else is never picked. Who's the Spy fixes that with a fair draw. This is how you could build one.

The rule

Two things, as the game states them. Last round's spy is not picked again, unless the table is too small. And each player's chance shrinks with every round they have already been the spy.

A sketch

I do not have the source in front of me for this post, so here is my own version of the idea, not the game's code.

weight(player) = 0 if player was last round's spy and table > 2
weight(player) = 1 / (1 + timesSpy(player))   otherwise
pick = weightedRandom(players, weight)

A player who has never been the spy has weight 1. One who has been the spy once has weight 0.5. Twice, 0.33.

What it does

At a table of four after one round, suppose A was the spy. In round two, A has weight 0. B, C and D each have weight 1, so each has a one-in-three chance. After round two, if B was the spy, then in round three A has weight 0.5, B has 0 and C and D have 1 each. The chances are 20%, 0, 40% and 40%.

The spread evens out over the game without ever becoming a fixed rotation. A pure rotation would be predictable, and a spy who is known in advance would ruin the game.

Why not a rotation

Rotation is fair but guessable. If you know the order, you know who the spy is. A weighted random keeps surprise.

Edge cases

  1. Small tables. With three players you cannot always avoid the last spy.
  2. Late joiners. Give them a weight of 1, as though they had never been the spy.
  3. Multiple spies. Pick without replacement, using the same weights.

Where to see it

Boardit's Who's the Spy uses a fair draw. The host can choose more than one spy, capped at half the table.

Small tables

The draw matters most at a small table. At a table of three a random voter names the lone spy 50% of the time, so the spy at a small table already has little room to hide, and the draw's job is only to keep the role moving.

Fair, but unpredictable

Fair, but not predictable.

Ahmed Moaz builds Boardit, a free browser game site.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.