Lucky Lenny Learning

From Game to Simulation

Track: the Week 16 classroom engine, src/farkle_ml (farkle-classroom-v1): target 4000, simplified scoring, no final round. The separate game_mechanics research track has different rule choices and evidence. Unification into game_mechanics is planned, not done; this chapter uses no research-track game scores as classroom results.

The Story

At a table, fairness can sound like a social promise: both players should get a proper chance. In a computer tournament it becomes a design question. When player A always moves first, a result may reflect both the strategy and the order in which the game lets players act.

The question matters because a computer can repeat a small unfairness very consistently. A program may use the same rules every time and still give one side an advantage. In this game, the first player who reaches the target wins immediately. A player who acts first may therefore have an opportunity the other player does not get. That is a possibility to investigate, not a result we should assume.

We already have observations from our research tournament. Its tune batch, the named seed set used for the first tournament comparison, and its judge batch, a separate named seed set used for a second comparison, both show Seat 1 winning more often than Seat 2. These are research-track observations: R0–R6 are the research tournament’s labels for its seven strategies, evaluated under its own protocol. They are not measurements from the classroom engine in this chapter, and they cannot tell us the size of a classroom-engine effect. They do show why we should record who starts and vary starting order when comparing players. In the tune batch, Seat 1 won 4465 games and Seat 2 won 3891, with 44 ties; in the judge batch, Seat 1 won 4409, Seat 2 won 3920, with 71 ties. The summary says these results make no causal claims.

We can translate the table game into software without hiding the choices that shape a result by starting with a written rulebook, giving a player a precise view of the game, and letting software carry out the repeated steps. Then we can examine both the game outcomes and the bookkeeping that generated them. The investigation will focus on how alternating starts changes what we can learn from a comparison.

Dragnet: Just the Facts

The classroom rulebook is the first piece of evidence. It is a deliberately small Farkle variant: six standard dice, a target of 4000 points, and no final round after a player reaches the target. A single 1 scores 100 points, and a single 5 scores 50. Three matching 1s score 1000, while three matching dice of another face score that face multiplied by 100. Matching dice beyond a triple double the triple’s score at each added die. Straights and three-pair bonuses are left out. All scoring dice are kept automatically, so the player does not decide which scoring subset to hold.

Those rules are a model: a selected description of a real or imagined process that software can execute. A simplification is not a defect by itself. It makes the task smaller and lets a class reason about the same game. But if a classroom discussion silently switches to another house rule, the code and the discussion stop describing the same experiment. The farkle-classroom-v1 label is the benchmark name, meaning the named version of the shared game definition.

An engine is the part of a program that applies the rules and updates the game. Here, engine.py rolls dice, scores a roll, constructs the information available to a player, and completes a turn. A roll with no points is a Farkle: the current turn ends and its unbanked points are lost, while points from earlier turns stay. If every die scores, the player gets all the dice again and may continue. The engine, rather than each strategy, decides these mechanics. That separation helps ensure players compete under one rulebook.

A state is a snapshot of the facts a player is allowed to use when deciding what to do. The classroom engine gives a strategy the current turn score, dice remaining, the player’s total, the target, and the opponent’s total. A policy is a rule for choosing an action from the state. The action vocabulary is intentionally narrow: roll or bank. A threshold policy such as bank_at_300 banks once the current turn score reaches its threshold; otherwise it rolls. The strategy can use the public state, but it cannot return a made-up action. An invalid action raises an error instead of being quietly interpreted as something else.

The full game simulator composes these pieces. It alternates turns, tracks each player’s score and Farkles, and stops when someone reaches the target or the turn limit is reached. It returns raw counts as well as summaries such as win rate and average score. Raw counts matter because a summary like “win rate” needs a denominator: a proportion without the number of games behind it is hard to judge. The simulator also records the starting player for each individual game.

A seed is the starting value for a pseudo-random number generator, a repeatable algorithm that produces values with random-like variation. With a fixed seed and the same program, a run can be repeated and inspected. But repeatability alone does not make a comparison fair. In run_many_games, the starting player alternates by game index, so strategy A starts half the games and strategy B starts the other half when the game count is even. This balances opportunity across the batch. It does not guarantee that each strategy will win equally often; the policies may differ in strength, and the dice still vary.

The research tournament summaries teach another useful term. There, paired seeds means each game has a seat-reversed counterpart that uses the same seed. It does not mean “identical later rolls”: when players make different choices, they consume different numbers of random values, so later dice can diverge. Pairing holds the seed fixed across the two seat orders; it does not force the games to follow the same roll sequence. The classroom run_many_games function uses a different design: it alternates the starting player by game index within one seeded run, rather than pairing each game with a same-seed, seat-reversed counterpart.

An interval is a range of plausible values calculated from observed data under a stated method. In the research tournament, the paired 95% interval describes uncertainty in a measured win share, with the seed as the unit. If an interval includes zero when reporting a difference, that means no difference detected by that analysis; it does not show that the strategies are equivalent. An interval around a win share can instead be compared with 50%, the equal-share reference, but uncertainty remains. The classroom example below is intentionally a tiny demonstration, not a statistical verdict.

One documented classroom-engine error was the handling of an invalid strategy action. The engine’s file comment says this behavior was tightened so an invalid action raises clearly instead of being treated as an implicit roll. In take_turn, the engine checks the returned action against roll and bank, then raises ValueError for anything else. The tests check that ValueError is raised for a bad strategy object and for a strategy returning "cheat". This is a specific implementation and test behavior; those files do not document when the earlier behavior occurred or how often it happened. The research-track seat counts above remain observations, not mistakes and not classroom-engine measurements. The classroom test suite also checks that an even-sized batch gives the two strategies the same number of starts, and that wins plus ties account for all games. Tests can catch bookkeeping mistakes, though they cannot prove every rule is the right rule for a classroom’s purpose.

The Scripted Journey

The companion script runs a small comparison using only the committed classroom package and Python’s standard library. From the repository root, run:

PYTHONPATH=src python3 capstone/curriculum/drafts/2-game-to-simulation_example.py

It pits bank_at_300 against bank_at_800. Those names describe when each policy banks: at a turn score of 300 or 800, respectively. The program asks the simulator to run the batch, with a fixed seed so this exact demonstration can be reproduced. The simulator alternates the starting player and formats its returned counts into readable lines. This is a short execution of real engine code, not a forecast about all possible games.

The actual output is:

20 games, seed=20261121 (starts A/B=10/10)
  bank_at_300                  wins    17 win rate 85.0% avg score 4028 farkle/own-turn 17.7%
  bank_at_800                  wins     3 win rate 15.0% avg score 2365 farkle/own-turn 75.9%
  ties 0 (0.0%) avg turns/game 19.4

Start by checking the bookkeeping. The two policies received an equal number of starts, as intended. Their wins and ties sum to the batch total. The output also reports each policy’s average score and Farkle rate per own turn; that last denominator is important because one player can take a different number of turns than the other. The displayed percentages are calculated from this small run. They describe these games under this seed, not a stable ranking of the policies.

Now trace one decision through the code. simulate.run_many_games initializes its random generator from the supplied seed, loops through games, and chooses a starting player from whether the game index is even or odd. play_game chooses whose turn it is and calls engine.take_turn. The engine rolls the number of dice still available, scores them, and gives the strategy the public state after a scoring roll. The policy responds with roll or bank; on a Farkle, the turn ends before a decision. When a player’s total reaches the target, the game stops. The result dictionary keeps scores, Farkle counts, turns, the starter, and the winner so that later summaries can be checked against what happened.

Try changing one choice at a time. You could swap the strategies’ positions in the call while leaving the seed alone, or change the seed while keeping the policies the same. Check that the simulator still gives each strategy the same number of starts, then look at whether the winner counts move. If the result changes, that is an observation about the chosen run; a larger, planned experiment would be needed to estimate how often such differences persist. Do not interpret a changed random stream as a bug: a policy that chooses to roll consumes dice, while one that banks ends its turn, so later random draws naturally occur at different points.

The design has a boundary worth noticing. The classroom engine uses simplified scoring and immediate victory at the target without a final round. The research track’s tournament evidence belongs to its own game and protocol. We have used that evidence to motivate attention to seat order, while the runnable comparison and the classroom tests use src/farkle_ml. The planned unification into game_mechanics has not happened yet. Keeping those labels visible prevents a classroom result from being accidentally presented as a research-track result.

What you can now do: You can read a rulebook as a specification, trace a roll from the engine to a strategy decision, explain why a seed helps repeat a run, and inspect the start and outcome counts in a simulation.

Before changing or extending the program, make your prediction: if the same two policies are compared over many games with the starting player alternating, what will happen to the apparent seat advantage?

Evidence table

ClaimValueArtifact path or script + commandCommit
Course track labelWeek 16 classroom engine src/farkle_mlsidecar/plans/CH-wave2-brief.md, Extra rules learned in Wave 14957971 (base)
Classroom track identity, target and final-round rulefarkle-classroom-v1; target 4000; no final rounddocs/rules.md4957971 (base)
Classroom dice, scoring and hot-dice rulessix dice; single 1 = 100; single 5 = 50; triple 1 = 1000; other triple = face × 100; extra matching dice double; straights and three-pair bonuses excluded; all scoring dice keptdocs/rules.md; scoring implementation: src/farkle_ml/engine.py4957971 (base)
Engine turn behavior and strategy state/action contractFarkle loses current turn points; hot dice restore six dice; public state fields and valid actions are implemented in the enginedocs/rules.md; src/farkle_ml/engine.py; tests/test_shared_farkle.py4957971 (base)
Invalid classroom strategy actions raise an errorEngine checks actions against roll and bank, then raises ValueError; tests assert errors for invalid strategy outputssrc/farkle_ml/engine.py lines 3–5 and 90–95; tests/test_shared_farkle.py lines 60–694957971 (base)
Simulation alternates starts and retains countsstarting_player = game_index % 2; starter counts and raw results returned by run_many_gamessrc/farkle_ml/simulate.py; tests/test_shared_farkle.py4957971 (base)
Research tournament seat outcome, tuneSeat 1: 4465 wins; Seat 2: 3891; ties: 44artifacts/tournament_v1/summary.md, Tune / Seat balance4957971 (base)
Research tournament seat outcome, judgeSeat 1: 4409 wins; Seat 2: 3920; ties: 71artifacts/tournament_v1/summary.md, Judge / Seat balance4957971 (base)
Tournament protocol and uncertainty interpretationBoth seat orders per seed, using the same seed for a game and its seat-reversed counterpart; seed is interval unit; interval including 50% means no clear difference at this sample size; summary says results make no causal claimsartifacts/tournament_v1/summary.md, Protocol and “How to read this”; `rg -n '^Protocol:95% interval' artifacts/tournament_v1/summary.md`d2080ae
Research tournament interval levelPaired 95% intervalartifacts/tournament_v1/summary.md + `rg -n '^Protocol:95% interval' artifacts/tournament_v1/summary.md`d2080ae
Runnable classroom comparison outputFull output pasted above; 20 games, seed 20261121, 10 starts eachcapstone/curriculum/drafts/2-game-to-simulation_example.py + PYTHONPATH=src python3 capstone/curriculum/drafts/2-game-to-simulation_example.py6d0c6a9
Runnable output: bankat30017 wins; 85.0% win rate; average score 4028; 17.7% Farkle per own turncapstone/curriculum/drafts/2-game-to-simulation_example.py + PYTHONPATH=src python3 capstone/curriculum/drafts/2-game-to-simulation_example.py6d0c6a9
Runnable output: bankat8003 wins; 15.0% win rate; average score 2365; 75.9% Farkle per own turncapstone/curriculum/drafts/2-game-to-simulation_example.py + PYTHONPATH=src python3 capstone/curriculum/drafts/2-game-to-simulation_example.py6d0c6a9
Runnable output: ties and game length0 ties; 0.0% tie rate; 19.4 average turns per gamecapstone/curriculum/drafts/2-game-to-simulation_example.py + PYTHONPATH=src python3 capstone/curriculum/drafts/2-game-to-simulation_example.py6d0c6a9
Research tournament strategy labelsR0–R6: seven strategiesartifacts/tournament_v1/summary.md + rg -n '^Protocol:' artifacts/tournament_v1/summary.mdd2080ae
Classroom bankat300 and bankat800 thresholds300 and 800 pointssrc/farkle_ml/strategies.py + `nl -ba src/farkle_ml/strategies.pysed -n '13,30p'`1317d54
Classroom thresholds named in the paired-policy comparisonbankat300 = 300 points; bankat800 = 800 pointssrc/farkle_ml/strategies.py + `nl -ba src/farkle_ml/strategies.pysed -n '13,30p'`1317d54
Classroom tests preserve expected score examples, strategy action validation, and balanced startsAssertions in SharedFarkleTests cover scoring, invalid actions, repeated seeds, and equal startstests/test_shared_farkle.py4957971 (base)