Lucky Lenny Learning

Book 5: The Simulation, Line by Line

The Story

Suppose you are trying to decide whether a Farkle strategy is any good. You could ask a friend to play it a few times. But the friend might roll lucky, forget a rule, or start first every time. A computer can play many games while keeping a record. That sounds simple: roll dice, add points, repeat. The tricky part is making sure that the computer plays the same game every time, that strategies get the information they need, and that another person can repeat the experiment.

This chapter follows one turn and then follows the game runner that repeats turns. We will look at where dice randomness enters, how a strategy receives a decision state, where the engine checks its answer, and what a seed does. A seed is a starting value for a repeatable sequence of pseudo-random numbers. Pseudo-random numbers look like chance but are generated by a fixed calculation, so the same seed can recreate a run.

The track is the Week 16 classroom engine in src/farkle_ml: benchmark farkle-classroom-v1, a 4,000-point target, simplified scoring, and no final round. A benchmark is a fixed setup for comparing strategies, including its rules and measurement procedure. In this track, all scoring dice are automatically kept; a player chooses whether to roll or bank, not which scoring dice to keep. game_mechanics is the separate research track, with its own named rules and keep choices. A classroom preset for game_mechanics is planned, and unification is planned, not done. This tour uses no scores from that research track.

Dragnet: Just the Facts

The contract: a function of state

A strategy is a rule that chooses an action. In this engine, its contract is a function of the current public state: a bundle of information describing the decision point. The code does not hand the strategy a die generator. It calls the strategy with one argument, state, and expects an action back. The signature in src/farkle_ml/contract.py:15 is def decide(self, state):. A plain function is also supported through an adapter, a small wrapper that makes a plain function fit the engine's strategy interface: the adapter's real signature at src/farkle_ml/contract.py:30 is def __init__(self, function, name=None, complexity_note="single rule/function"), and its decide method passes the state to that function.

The state fields are turn_score, dice_remaining, total_score, target_score, and opponent_score (src/farkle_ml/engine.py:43-52). The turn score is the unbanked score accumulated in this turn; the total score is what the player banked before this turn; the opponent score is the other player's current banked score. Dice remaining says how many dice the next roll will use. The strategy can use these values to make a choice without owning the game rules. For example, bank_at_300 returns bank when turn_score is at least 300, and roll otherwise (src/farkle_ml/strategies.py:13-25).

This separation is useful because the engine owns the game and a strategy owns the decision rule. The engine can switch strategies without rewriting scoring. In ordinary words, the contract is an agreed doorway: the engine provides a state, the strategy returns one allowed action.

Who owns the dice?

The random number generator, or RNG, is the object that supplies repeatable pseudo-random values. The simulation creates one with random.Random(seed) inside run_many_games (src/farkle_ml/simulate.py:66-73). It passes that same RNG to each game and turn. take_turn passes it to roll_dice, which asks it for values (src/farkle_ml/engine.py:13-15, 55-64). This puts the game's dice stream at the simulation boundary, where the run is configured. Strategies do not secretly roll the game's dice.

Why keep that ownership clear? A strategy can be swapped while the engine continues to control the same game process. The caller can choose and record a seed. A teacher can also give the strategy the same state twice and expect the same simple threshold rule to answer the same way. Some strategy types may use their own random samples for an estimate, such as OneStepRolloutStrategy. A rollout is a simulated continuation of a decision, used to estimate what may happen after an action. This strategy has a separate RNG initialized with its own seed (src/farkle_ml/strategies.py:123-128). In this tour's example we use deterministic threshold strategies, so the game's RNG is the only source of dice variation.

A seed controls a run's pseudo-random stream. Repeating the same call with the same strategies and seed reproduces the same summary, as a committed test checks (tests/test_shared_farkle.py:119-126). It does not promise that two different strategies see matching rolls later in a game: their choices can make them use a different number of dice, which changes how many random values are consumed. When comparing strategies across a collection of seeds, say paired seeds if corresponding runs use the same seed values. Do not call the later rolls identical.

One turn, one line at a time

At the start of a turn, take_turn sets the dice count to six and the turn score to zero (src/farkle_ml/engine.py:55-61). Each pass through its loop rolls the dice still available and calls score_roll (engine.py:62-65). In this classroom scoring rule, single ones and fives count, and three or more matching dice score a set amount; extra matching dice double that amount (engine.py:18-36, docs/rules.md:7-19). The rule document is the readable description; the function is the executable version.

If no points were scored, is_farkle says the roll is a Farkle. The turn immediately returns zero, which means the unbanked turn points are lost (engine.py:39-40, 71-75). Otherwise, the engine adds roll points to the turn score and subtracts the scoring dice from the available dice. If none remain, the player gets all six back; this is called hot dice (engine.py:76-82).

Now the engine constructs the public state and calls the strategy (engine.py:83-90). It validates the returned action against VALID_ACTIONS, which contains only roll and bank (engine.py:8-10, 91-95). An invalid answer raises ValueError, a Python error used here to reject an action that breaks the contract. If the strategy says bank, the turn returns its accumulated points; if it says roll, the loop continues (engine.py:97-104). The engine, not the strategy, applies the consequences of rolling or banking.

From turns to games

play_game keeps two player scores and alternates whose turn it is (simulate.py:18-32). After each turn, it adds returned points, counts zero-point turns as Farkles, and checks whether the current player reached the target (simulate.py:34-47). There is no trailing-player final round in this benchmark: reaching the target ends the game at the end of that turn. If the turn limit is reached first, the higher score wins; equal scores are recorded as a tie (simulate.py:49-63).

Repeated comparisons alternate the starting player. In run_many_games, one game starts with strategy A, the next with strategy B, then the pattern repeats (simulate.py:81-90). This avoids giving one strategy every first turn. The returned dictionary keeps counts such as wins, ties, starts, and turns as well as rates and average scores (simulate.py:104-133). A rate is a fraction of events divided by a stated total; for example, win rate divides wins by games. Keeping counts beside rates makes it possible to check what was divided by what.

The game runner uses a single RNG across the games in one run, so its seed identifies the sequence for that run. The example below calls the committed runner twice from the same starting point and compares the complete summaries. It is deliberately small: it demonstrates repeatability without trying to establish which strategy is best in general.

A real surprise from our work

The rules code has a small but useful history lesson. The connector receipt records that, before extraction, invalid strategy actions silently behaved like another roll (sidecar/runs/003_extract_shared_core_connector_receipt.md:50-55, commit 223b44c). The extraction prompt then allowed the shared layer to reject an invalid action instead of silently treating it as another roll (sidecar/prompts/003_extract_reconcile_shared_core.md:62-69, commit 85ca8c4). Commit ec66eb1 adds the validating engine file that implements this permitted tightening. Silently translating a typo or unsupported answer into roll could let a bad strategy keep playing while hiding its mistake. Failing at the boundary makes the problem visible. This is a design choice supported by the repository history, not a claim that every strategy bug has been eliminated.

The Scripted Journey

Run this from the repository root. It imports the committed package directly through PYTHONPATH; it needs only Python's standard library. The two threshold strategies are committed built-ins. The runner alternates the starting player in its game batch. We print the returned comparison and then check whether the second execution produced the same dictionary.

from farkle_ml import simulate, strategies

def run():
    return simulate.run_many_games(
        strategies.bank_at_300,
        strategies.bank_at_800,
        num_games=4,
        seed=17,
    )

first = run()
second = run()
print(simulate.format_comparison(first))
print(f"same_seed_repeat_equal={first == second}")

Command: PYTHONPATH=src python3 followed by the code above.

Actual output:

4 games, seed=17 (starts A/B=2/2)
  bank_at_300                  wins     3 win rate 75.0% avg score 3875 farkle/own-turn 17.9%
  bank_at_800                  wins     1 win rate 25.0% avg score 2788 farkle/own-turn 68.4%
  ties 0 (0.0%) avg turns/game 19.2
same_seed_repeat_equal=True

The output is one tiny run, not a verdict about long-run strength. It illustrates what the program reports and that repeating this run gives the same result. The starter counts are balanced in this batch. The formatter rounds the raw avg_score_b value of 2787.5 to 2788, and rounds the raw avg_turns_per_game value of 19.25 to 19.2. Those raw values are present in the summary dictionary, even though the displayed line uses the formatter's rounded values. The printed percentages describe these few games only. A bigger experiment would still need a clear question, recorded settings, and enough evidence to support its conclusion.

What you can now do

You can trace a roll from the simulation's RNG through scoring, state construction, a strategy function, action validation, and the game's score update. You can explain why the engine owns the game dice stream, name the state fields a strategy may inspect, and distinguish a repeatable seed from a promise that two changing strategies receive the same later rolls. You can run the short example and inspect raw counts as well as rates.

Evidence table

ClaimValueEvidence path or commandCommit
Classroom benchmark name and simplified scoring, automatic keeps, target, and no final roundfarkle-classroom-v1; 4,000 target; six dice; simplified scoring; no final rounddocs/rules.mde108e57
Engine's target, dice count, valid actions, scoring, state fields, turn flow and invalid-action checktarget 4000; six dice; fields and actions as describedsrc/farkle_ml/engine.pyec66eb1
Strategy contract and function-of-state signaturedecide(self, state); only roll or banksrc/farkle_ml/contract.pyef6c3c5
Built-in thresholds and separate strategy RNG for the optional rollout strategy300 and 800 thresholds; rollout defaults and seed as citedsrc/farkle_ml/strategies.py1317d54
Shared seeded game RNG, alternating starts, collected summary fields and output formattingmechanism and fields described abovesrc/farkle_ml/simulate.pye1d565c
Test for seed reproducibility and balanced starterstest uses 50 games, seed 17; test confirms equal resultstests/test_shared_farkle.pyff0f2f6
The executed example output4 games; seed 17; raw avg_score_b 2787.5 and avg_turns_per_game 19.25 (formatted as 2788 and 19.2); printed wins, rates, Farkles, and equality shown aboveCommand PYTHONPATH=src python3 with the displayed snippet; summary dictionarysrc/farkle_ml/simulate.py at e1d565c; src/farkle_ml/strategies.py at 1317d54
Earlier invalid actions silently behaved like another roll; extraction was allowed to tighten this by rejecting invalid actions; the validating engine file was addedReceipt records prior implicit-roll behavior; prompt permits the rejection; ec66eb1 adds the engine filesidecar/runs/003_extract_shared_core_connector_receipt.md:50-55; sidecar/prompts/003_extract_reconcile_shared_core.md:62-69; src/farkle_ml/engine.py223b44c; 85ca8c4; ec66eb1
Classroom engine is the Week 16 computational machineWeek 16README.md:5 (`nl -ba README.mdsed -n '1,8p'`)cc82eb8
Matching-dice scoring thresholdThree or more matching dicesrc/farkle_ml/engine.py:26 (`nl -ba src/farkle_ml/engine.pysed -n '24,35p'`)ec66eb1
Farkle turn return value0 pointssrc/farkle_ml/engine.py:71-74 (`nl -ba src/farkle_ml/engine.pysed -n '71,75p'`)ec66eb1
Player score slots initialized by play_gameTwo (scores = [0, 0])src/farkle_ml/simulate.py:18-29 (`nl -ba src/farkle_ml/simulate.pysed -n '18,30p'`)e1d565c

One unanswered question: if you changed a strategy so it rolled more often, what do you predict would happen to its score and Farkle rate across a much larger set of paired seeds?