Skip to content

Chapter 19: Seeds, the Clock and the Daily Challenge ​

In Chapter 18: Runs and Upgrades, you built RunFactory, a draft of upgrades and a run summary. A Classic run takes a fresh random seed, so no two runs are alike. The factory already accepts today's date, but it does nothing with it.

In this chapter, you make a run a pure function of its seed and its input. One date gives one seed, that seed drives every random choice, and two players on the same day face the same game. You then use that to add the Daily Challenge to the main menu.

Figure 19-1: The main menu with the new DAILY CHALLENGE row
Figure 19-1: The main menu with the new DAILY CHALLENGE row. This is a drawn illustration, not a screenshot.

Time: [TODO Simon: time estimate for chapter 19]

In this chapter, you will:

  • Learn what makes a run deterministic, and the three things that can break it: unseeded randomness, wall-clock time and shared random streams.
  • Build DailySeed, a pure function from a date to a seed.
  • Build RunRandom, which splits one seed into independent streams for enemies, powerups and the draft.
  • Inject the clock through GameServices, so a test can choose today's date.
  • Prove that the same seed and the same input give the same run.
  • Add the Daily Challenge to the main menu and record the best daily score.

Requirements in this chapter ​

IDShort name
RUN-01Run modes (Daily Challenge)
RUN-06The daily seed from an injected clock
RUN-07DailyChallengeActive follows the mode
RUN-08Fully seeded daily runs
FE-02The Daily Challenge menu item
PRO-07The best daily score

Determinism ​

A program is deterministic when the same inputs always give the same outputs. For a game, the inputs are the starting seed and the keys the player presses on each frame. If the game is deterministic, those two things are enough to rebuild every frame of a run, every score and every enemy position.

Three things can break this, and the game must close all three. The first is randomness that nobody controls, such as new Random() with no seed, which starts from a value the operating system picks. The second is the wall clock. A rule that reads the time gives a different answer a second later. The third is shared random streams, which the next sections explain.

A fourth source is frame time. If the length of a frame changed from run to run, a player would move a slightly different distance each time. The simulation avoids this because Tick receives its time step as an argument, so the rules never measure time themselves. The tests pass the same step every frame. The real host leaves MonoGame's fixed time step switched on, which is its default, so each Update call also receives the same step.

Time is an input ​

Suppose a rule asked for DateTime.UtcNow to find today's seed. A test could not choose the date. It would pass on one day and fail on another, and a daily run could never be reproduced after midnight.

The fix is to treat the date as one more input. DailySeed.For takes a DateOnly and returns a number. It never asks what day it is. The caller decides which date to pass. In the real game the caller passes today's date, and in a test the caller passes any date it likes.

The game reads the real clock in exactly one place, the host. The host gives GameServices a function, TodayUtc, and every scene asks that function for the date. A test builds the services with a function that returns a fixed date. This is called injecting a dependency: the object receives it from outside and does not reach for it.

One seed, several streams ​

A seed starts a Random. Every call to Next or NextDouble takes the next number from one fixed sequence. Two Random objects with the same seed give the same sequence.

Now suppose the enemies and the powerups share one Random. Both take numbers from the same sequence, in the order the game happens to ask. If one run spawns an extra powerup, that powerup takes one number. Every number after it moves along by one place, and the enemies now receive different numbers from the ones they got in the other run. Figure 19-2 shows this.

Figure 19-2: One shared stream against separate streams, when one run makes an extra powerup roll
Figure 19-2: One shared stream against separate streams, when one run makes an extra powerup roll

The fix is one stream for each purpose. RunRandom takes the run seed and builds three independent sources: one for the enemies, one for the powerups and one number for the draft. The extra powerup roll now takes a number from the powerup stream only, and the enemy stream does not notice.

The streams must be different from each other. If two streams used the same seed, they would give the same numbers, and the powerups would move in step with the enemies. So RunRandom mixes a fixed stream number into the seed with plain integer arithmetic. It does not use HashCode.Combine, which is built for hash tables. .NET gives HashCode.Combine a different random salt in each process, so the same seed would give different streams every time the game started.

Fair comparison ​

When one date gives one seed, and one seed gives one run, every player on that day plays the same game. Their scores are comparable. This is the base for later features such as a leaderboard, a ghost of a good run, or a replay file. Each of those only has to store the seed and the inputs.

The game does not build any of those features. It only keeps the best daily score on the player's own profile, in the same file as the other statistics.

Local statistics ​

The profile from Chapter 16 already counts runs, deaths, levels cleared, powerups, captures and the best daily score. All of it stays on the player's machine, in profile.json. Nothing is sent anywhere, and the game needs no network. The only change in this chapter is that a finished Daily Challenge run now raises the best daily score, which the profile tracker already knew how to do.

Building the daily seed ​

DailySeed is the smallest service in the course. It has one operation, and the operation is a pure function.

DailySeed.For(utcDate) : int

  • Takes: a date in UTC.
  • Gives: the seed for that date.
  • Promises: the seed is the date's day number, which counts days from 1 January of year 1. The same date always gives the same seed, and the next day gives a different one.
  • Refuses: nothing. Every date has a seed.
  • Requirements: RUN-06.

In the Source/Systems folder, create a new file named DailySeed.cs and add the following code. The body is a stub.

new-file Source/Systems/DailySeed.cs
csharp
namespace LastPerimeter.Systems;

public static class DailySeed
{
    // The same UTC date always gives the same seed, so every player gets the same daily run.
    public static int For(DateOnly utcDate) => throw new NotImplementedException();
}

The tests for this chapter live in one file. In the Tests/Simulation folder, create a new file named DeterminismTests.cs and add the following code. The test checks one known date, and that the next day gives a different seed.

new-file Tests/Simulation/DeterminismTests.cs
csharp
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Simulation;

public sealed class DeterminismTests
{
    [Fact]
    public void DailySeed_IsTheUtcDayNumber()
    {
        DateOnly date = new(2026, 12, 2);

        Assert.Equal(date.DayNumber, DailySeed.For(date));
        Assert.NotEqual(DailySeed.For(date), DailySeed.For(date.AddDays(1)));
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 152. The 152 passes are the tests from earlier chapters, and the failure is your new test.

Open Source/Systems/DailySeed.cs, find the For method and replace the whole method with the following:

replace-method Source/Systems/DailySeed.cs For
csharp
    // The same UTC date always gives the same seed, so every player gets the same daily run.
    public static int For(DateOnly utcDate) => utcDate.DayNumber;

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 153.

The key things to note are:

  • The method is a single expression and reads nothing but its argument. For 2 December 2026 the day number is 739951, on every machine.
  • A day number is a good seed because it changes by one each day and needs no calendar rules. The streams are mixed from it later, so neighbouring days still give very different runs.
  • DateOnly has no time of day and no time zone. The caller decides that the date is the UTC date, which is why the parameter is called utcDate.

Building the random streams ​

RunRandom holds the seed and the three streams.

RunRandom(seed)

  • Takes: the run seed.
  • Gives: an object with Seed, two Random streams, Enemies and Powerups, and DraftSeed, a number for the draft.
  • Promises: the same seed always gives the same three streams. A roll taken from one stream does not change the numbers that another stream gives.
  • Refuses: nothing. Every seed is valid.
  • Requirements: RUN-08.

In the Source/Simulation folder, create a new file named RunRandom.cs and add the following code. The three stream numbers and the properties are in full, and the constructor is a stub.

new-file Source/Simulation/RunRandom.cs
csharp
namespace LastPerimeter.Simulation;

// The run seed and three independent streams. Separate streams mean an extra
// powerup roll cannot change how the enemies move. Each stream seed uses plain
// integer arithmetic, because HashCode.Combine differs between processes.
public sealed class RunRandom
{
    private const int EnemyStream = 1;
    private const int PowerupStream = 2;
    private const int DraftStream = 3;

    public RunRandom(int seed)
    {
        throw new NotImplementedException();
    }

    public int Seed { get; }
    public Random Enemies { get; }
    public Random Powerups { get; }
    public int DraftSeed { get; }
}

Open Tests/Simulation/DeterminismTests.cs. At the top of the file, add the following line above the using LastPerimeter.Systems; line. The test needs RunRandom, which lives in LastPerimeter.Simulation.

add-using Tests/Simulation/DeterminismTests.cs before=LastPerimeter.Systems
csharp
using LastPerimeter.Simulation;

Add the following test to the DeterminismTests class, below the DailySeed_IsTheUtcDayNumber test. It makes two RunRandom objects from one seed and takes two extra numbers from the powerup stream of the second. It then checks that the next ten enemy rolls are the same in both. This is the situation in Figure 19-2.

add-member Tests/Simulation/DeterminismTests.cs after=DailySeed_IsTheUtcDayNumber
csharp
    [Fact]
    public void RunRandom_ExtraPowerupRoll_DoesNotShiftEnemyRolls()
    {
        RunRandom plain = new(1234);
        RunRandom disturbed = new(1234);

        disturbed.Powerups.NextDouble();
        disturbed.Powerups.NextDouble();

        for (int roll = 0; roll < 10; roll++)
        {
            Assert.Equal(plain.Enemies.Next(), disturbed.Enemies.Next());
        }

        Assert.Equal(plain.DraftSeed, disturbed.DraftSeed);
        Assert.NotEqual(new RunRandom(1235).DraftSeed, plain.DraftSeed);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 153.

Open Source/Simulation/RunRandom.cs. Add the following method to the RunRandom class, below the DraftSeed property. The constructor needs it, so you write it first.

add-member Source/Simulation/RunRandom.cs at=end
csharp
    private static int StreamSeed(int seed, int stream)
    {
        return unchecked((seed * 1664525) + (stream * 1013904223));
    }

In the same file, find the RunRandom constructor and replace the whole constructor with the following:

replace-method Source/Simulation/RunRandom.cs RunRandom
csharp
    public RunRandom(int seed)
    {
        Seed = seed;
        Enemies = new Random(StreamSeed(seed, EnemyStream));
        Powerups = new Random(StreamSeed(seed, PowerupStream));
        DraftSeed = StreamSeed(seed, DraftStream);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 154.

The key things to note are:

  • StreamSeed is a small linear mix. It multiplies the seed by one constant, adds the stream number times another, and keeps the lowest 32 bits. Different stream numbers give different results for the same seed.
  • unchecked allows the multiplication to overflow and wrap round. In .NET, an int overflow is silent by default, and unchecked says that you mean it.
  • Each stream has its own number, EnemyStream, PowerupStream or DraftStream. The draft has no Random of its own. It exposes one number, and RunUpgradeDraft builds a Random from it with the level.
  • The test compares ten rolls, not one. A single roll could match by chance. The test also checks that two different seeds give different draft seeds.

Using the streams in the simulation ​

The simulation must take a RunRandom instead of a plain Random, and give each system its own stream. This changes the constructor, and so it changes every caller.

Open Source/Simulation/GameplaySimulation.cs. Add the following property to the GameplaySimulation class, below the Level property. The upgrade scene reads the draft seed through it.

add-member Source/Simulation/GameplaySimulation.cs after=Level
csharp
    public RunRandom Rng { get; }

In the same file, find the GameplaySimulation constructor and replace the whole constructor with the following:

replace-method Source/Simulation/GameplaySimulation.cs GameplaySimulation
csharp
    public GameplaySimulation(GameConfig baseConfig, GameSession session, RunRandom random)
    {
        _baseConfig = baseConfig;
        _session = session;
        Rng = random;
        _enemies = new EnemySystem(random.Enemies);
        _powerups = new PowerupSystem(random.Powerups);
        _level = BuildLevel(session.Level);
        EnterLevel();
    }

The key changes are:

  • The third parameter is a RunRandom, and the simulation keeps it in Rng.
  • EnemySystem receives random.Enemies and PowerupSystem receives random.Powerups. The two systems no longer share a stream.
  • The comment about a future chapter is gone, because this is the chapter.

In a terminal, from the LastPerimeter folder, run dotnet build. The build fails on purpose. RunFactory and the test builder still pass a plain Random, and the compiler reports an error for each.

Open Tests/TestHelpers/SimulationBuilder.cs, find the Create method and replace the whole method with the following. The only change is new RunRandom(seed).

replace-method Tests/TestHelpers/SimulationBuilder.cs Create
csharp
    public static GameplaySimulation Create(int seed = 1, bool withEnemies = false, int margin = 0, int level = 1)
    {
        GameConfig config = TestConfigFactory.Create(width: 80 + (margin * 2), height: 80 + (margin * 2), margin: margin, tileSize: 4);
        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Level = level,
            Seed = seed,
        };
        GameplaySimulation simulation = new(config, session, new RunRandom(seed));
        if (!withEnemies)
        {
            session.Enemies.Clear();
        }

        return simulation;
    }

Open Source/Simulation/RunFactory.cs, find the Create method and replace the whole method with the following. This is a first step. It builds the new random object and leaves the daily branch for the next section.

replace-method Source/Simulation/RunFactory.cs Create
csharp
    // Builds the session and the simulation, and starts the first level. The seed
    // is stored on the session so the run can be replayed. Chapter 19 adds the daily
    // seed and separate random streams.
    public static GameplaySimulation Create(RunMode mode, int startingLevel, GameSettings settings, DateOnly todayUtc, int? seed = null, GameConfig? config = null)
    {
        int runSeed = seed ?? Random.Shared.Next();

        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Difficulty = settings.Difficulty,
            RunMode = mode,
            Level = startingLevel,
            Seed = runSeed,
        };
        session.Player.Lives = new LevelProgressionSystem().GetStartingLives(settings.Difficulty);

        return new GameplaySimulation(config ?? new GameConfig(), session, new RunRandom(runSeed));
    }

Run dotnet test from the LastPerimeter folder. The build works again, and every test still passes. The summary line should report Failed: 0 and Passed: 154.

Adding the daily branch to the factory ​

A daily run takes its seed from the date and ignores any seed passed in. The card from Chapter 18 gains a line.

RunFactory.Create(mode, startingLevel, settings, todayUtc, seed, config) : GameplaySimulation

  • Takes: as before.
  • Gives: a simulation with the first level started.
  • Promises: a DailyChallenge run has the seed DailySeed.For(todayUtc), whatever seed was passed. Every other run has the given seed, or a fresh one.
  • Refuses: nothing.
  • Requirements: RUN-01, RUN-06.

The test for this already exists. You extend the factory test from Chapter 18 with one line. Open Tests/Simulation/RunFactoryTests.cs. At the top of the file, add the following line below the using LastPerimeter.Simulation; line:

add-using Tests/Simulation/RunFactoryTests.cs
csharp
using LastPerimeter.Systems;

In the same file, find the StartRun_FromLevelSelect_StartsAtChosenLevel method and replace the whole method with the following. The new last line creates a daily run with a seed of 5 and checks that the session has the daily seed instead.

replace-method Tests/Simulation/RunFactoryTests.cs StartRun_FromLevelSelect_StartsAtChosenLevel
csharp
    [Fact]
    public void StartRun_FromLevelSelect_StartsAtChosenLevel()
    {
        GameSettings settings = new() { Difficulty = DifficultyPreset.Hardcore };

        GameplaySimulation sim = RunFactory.Create(RunMode.LevelSelect, 4, settings, new DateOnly(2026, 12, 2), seed: 99);

        Assert.Equal(4, sim.Session.Level);
        Assert.Equal(4, sim.Level.Definition.Number);
        Assert.Equal(RunMode.LevelSelect, sim.Session.RunMode);
        Assert.Equal(2, sim.Session.Player.Lives);
        Assert.Equal(99, sim.Session.Seed);
        Assert.Contains(sim.Events, e => e is LevelStarted { Level: 4 });
        Assert.Equal(DailySeed.For(new DateOnly(2026, 12, 2)), RunFactory.Create(RunMode.DailyChallenge, 1, settings, new DateOnly(2026, 12, 2), seed: 5).Session.Seed);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 153. The factory does not know the daily mode yet.

Open Source/Simulation/RunFactory.cs, find the Create method and replace the whole method with the following:

replace-method Source/Simulation/RunFactory.cs Create
csharp
    // Builds the session, the random streams and the simulation, and starts the
    // first level. A daily run uses the seed for today's UTC date. Any other run
    // uses the given seed or a fresh one, stored on the session so the run can be replayed.
    public static GameplaySimulation Create(RunMode mode, int startingLevel, GameSettings settings, DateOnly todayUtc, int? seed = null, GameConfig? config = null)
    {
        int runSeed = mode == RunMode.DailyChallenge
            ? DailySeed.For(todayUtc)
            : seed ?? Random.Shared.Next();

        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Difficulty = settings.Difficulty,
            RunMode = mode,
            Level = startingLevel,
            Seed = runSeed,
        };
        session.Player.Lives = new LevelProgressionSystem().GetStartingLives(settings.Difficulty);

        return new GameplaySimulation(config ?? new GameConfig(), session, new RunRandom(runSeed));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 154.

The key things to note are:

  • The daily branch is one conditional expression. This is the benefit of having one factory: a new mode is one change, in one place.
  • The seed argument is ignored for a daily run. If it were honoured, two players could start the same day with different seeds, and the comparison would be unfair.
  • The RunRandom is built from runSeed, so the session's Seed and the streams always agree.

Proving the run is deterministic ​

Now the payoff. Everything that could vary in a run is an input: the seed, the date and the keys. If those are the same, the run must be the same. This test plays the same daily run twice and compares what it produced.

Open Tests/Simulation/DeterminismTests.cs. At the top of the file, add the following line above the using LastPerimeter.Simulation; line:

add-using Tests/Simulation/DeterminismTests.cs before=LastPerimeter.Simulation
csharp
using LastPerimeter.Data;

Add the following line below the using LastPerimeter.Systems; line. The test uses ScriptedInput, from Chapter 13.

add-using Tests/Simulation/DeterminismTests.cs after=LastPerimeter.Systems
csharp
using LastPerimeter.Tests.TestHelpers;

Add the following test to the DeterminismTests class, below the RunRandom_ExtraPowerupRoll_DoesNotShiftEnemyRolls test:

add-member Tests/Simulation/DeterminismTests.cs after=RunRandom_ExtraPowerupRoll_DoesNotShiftEnemyRolls
csharp
    [Fact]
    public void SameSeedAndInput_GiveTheSameRun()
    {
        static GameplaySimulation Play()
        {
            GameplaySimulation sim = RunFactory.Create(RunMode.DailyChallenge, 1, new GameSettings(), new DateOnly(2026, 12, 2));
            ScriptedInput.Run(sim, ScriptedInput.Right, 10);
            ScriptedInput.Run(sim, ScriptedInput.Down, 30);
            ScriptedInput.Run(sim, ScriptedInput.Idle, 400);
            return sim;
        }

        GameplaySimulation first = Play();
        GameplaySimulation second = Play();

        Assert.Equal(DailySeed.For(new DateOnly(2026, 12, 2)), first.Session.Seed);
        Assert.Equal(first.Session.Score, second.Session.Score);
        Assert.Equal(first.Session.Player.Position, second.Session.Player.Position);
        Assert.Equal(first.Session.Enemies.Select(enemy => enemy.Position), second.Session.Enemies.Select(enemy => enemy.Position));
        Assert.Equal(first.Session.Powerups.Select(powerup => (powerup.Type, powerup.Position)), second.Session.Powerups.Select(powerup => (powerup.Type, powerup.Position)));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 155. The test passes at once, because the three earlier steps already closed every gap.

The key things to note are:

  • Play is a local static function with no access to anything outside it. Every run it makes starts from the same date and the same keys, so any difference between the two runs would be a real bug.
  • The input is 10 frames to the right, 30 frames down, then 400 frames of no input. The 400 idle frames matter, because enemies and powerups keep moving and spawning while the player stands still. That is where an uncontrolled random number would show.
  • The test compares the score, the player position, every enemy position and every powerup. If any one random choice came from outside the seed, one of them would differ.
  • The test also checks that the session seed is the daily seed for the date. The seed is chosen from the date, and nothing else.

TIP

To see the test catch a leak, open Source/Simulation/RunRandom.cs and change new Random(StreamSeed(seed, EnemyStream)) to new Random(). Run dotnet test. At least one test fails, and usually three do: the stream test, SameSeedAndInput_GiveTheSameRun and one of the earlier scripted replay tests. All of them depend on the enemies starting from the same stream every time, so several failures are a good sign that the guard works. Change the line back and run the tests again before you go on.

Injecting the clock ​

The factory takes the date, but GameplayScene.StartRun still reads DateTime.UtcNow. The last clock read must move to the host. GameServices gains a TodayUtc member, a function that returns the date. New to Func? See the C# primer.

Open Source/Game/GameServices.cs. Two small changes add the clock. The constructor gets a new parameter, todayUtc, between quit and setWindowTitle. Find this line in the constructor's parameter list:

find Source/Game/GameServices.cs
csharp
        Action quit,

Add the following line directly below it. It goes before the optional readKeyboard parameter at the end, because an optional parameter must come last.

csharp
        Func<DateOnly> todayUtc,

In the same constructor, find this line:

find Source/Game/GameServices.cs
csharp
        SetWindowTitle = setWindowTitle;

Add the following line directly above it:

csharp
        TodayUtc = todayUtc;

Add the following property to the GameServices class, below the Quit property:

add-member Source/Game/GameServices.cs after=Quit
csharp
    public Func<DateOnly> TodayUtc { get; }

The host must now supply the function. Open Source/Game/LastPerimeterApp.cs. In the LastPerimeterApp constructor, find this line in the call to new GameServices:

find Source/Game/LastPerimeterApp.cs
csharp
            Exit,

Add the following line directly below it. It passes a function that reads the real clock, and it is the only place that does. The lines after it, which start the scripted smoke run, stay as they are.

csharp
            () => DateOnly.FromDateTime(DateTime.UtcNow),

Open Source/Scenes/GameplayScene.cs. In the StartRun method, find this line:

find Source/Scenes/GameplayScene.cs
csharp
        GameplaySimulation simulation = RunFactory.Create(mode, startingLevel, services.Profile.Settings, DateOnly.FromDateTime(DateTime.UtcNow), seed: seed, config: services.Config);

Replace it with the following line. It asks the services for the date. The seed: seed argument is the fixed seed that the smoke run passes, and it stays.

csharp
        GameplaySimulation simulation = RunFactory.Create(mode, startingLevel, services.Profile.Settings, services.TodayUtc(), seed: seed, config: services.Config);

The key changes are:

  • TodayUtc is a Func<DateOnly>, a stored function. A scene calls services.TodayUtc() to get the date.
  • The host passes () => DateOnly.FromDateTime(DateTime.UtcNow). This is the only clock read in the game that decides anything about a run.
  • A test that needs a scene can pass () => new DateOnly(2026, 12, 2) and know today's seed in advance.

The daily flag ​

The session needs to say whether the run is a daily one. The value is not stored. It is worked out from RunMode, so the two can never disagree.

GameSession.DailyChallengeActive : bool

  • Takes: nothing.
  • Gives: true only when RunMode is DailyChallenge.
  • Promises: it follows the mode at all times, because it reads the mode on each call.
  • Refuses: nothing.
  • Requirements: RUN-07.

Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the SlowDrawActive property. It is a stub.

add-member Source/Data/GameSession.cs after=SlowDrawActive
csharp
    public bool DailyChallengeActive => throw new NotImplementedException();

Open Tests/Systems/RunModifiersTests.cs. Add the following test to the RunModifiersTests class, below the ApplyUpgrade_HigherScoring_UpdatesRunModifiers test. It checks the flag is false for a new session, then changes the mode and checks it is true.

add-member Tests/Systems/RunModifiersTests.cs before=CreateSession
csharp
    [Fact]
    public void DailyChallengeActive_FollowsRunMode()
    {
        GameSession session = CreateSession();
        Assert.False(session.DailyChallengeActive);

        session.RunMode = RunMode.DailyChallenge;

        Assert.True(session.DailyChallengeActive);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 155.

Open Source/Data/GameSession.cs, find the DailyChallengeActive property and replace the whole property with the following:

replace-method Source/Data/GameSession.cs DailyChallengeActive
csharp
    public bool DailyChallengeActive => RunMode == RunMode.DailyChallenge;

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 156.

The property has no field behind it, so there is nothing to keep in step with RunMode. A stored flag could be set to the wrong value, and a calculated one cannot.

The Daily Challenge menu row ​

The main menu is a table of labels and commands, so a new row is a new command and a new line in the table. Open Source/Scenes/Menus/MenuCommand.cs and find this line in the MenuCommand enum:

find Source/Scenes/Menus/MenuCommand.cs
csharp
    StartRun,

Add the following line directly below it:

csharp
    StartDaily,

The main menu test is a theory, which runs once for each InlineData line. New to [Theory]? See the C# primer. Each line gives a row and the command that row must issue. Open Tests/Scenes/Menus/MenuTests.cs. In the MenuListTests class, find the MainMenu_ConfirmOnEachItem_IssuesItsCommand method and replace the whole method, with its attributes, with the following. The new case is row 1, and the later rows move down by one.

replace-method Tests/Scenes/Menus/MenuTests.cs MainMenu_ConfirmOnEachItem_IssuesItsCommand
csharp
    [Theory]
    [InlineData(0, MenuCommand.StartRun)]
    [InlineData(1, MenuCommand.StartDaily)]
    [InlineData(2, MenuCommand.LevelSelect)]
    [InlineData(3, MenuCommand.Tutorial)]
    [InlineData(4, MenuCommand.Options)]
    [InlineData(5, MenuCommand.Quit)]
    public void MainMenu_ConfirmOnEachItem_IssuesItsCommand(int row, MenuCommand expected)
    {
        MenuList menu = new(MenuTables.Labels(MenuTables.Main));
        for (int press = 0; press < row; press++)
        {
            menu.HandleInput(new InputState { IsMenuDownPressed = true });
        }

        MenuInput result = menu.HandleInput(new InputState { IsConfirmPressed = true });

        Assert.Equal(MenuInput.Confirmed, result);
        Assert.Equal(expected, MenuTables.Main[menu.SelectedIndex].Command);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 5 and Passed: 152. The theory now has six cases and the table still has five rows, so rows 1 to 5 do not match.

Open Source/Scenes/Menus/MenuTables.cs. In the Main field, find this line:

find Source/Scenes/Menus/MenuTables.cs
csharp
        ("START RUN", MenuCommand.StartRun),

Add the following line directly below it:

csharp
        ("DAILY CHALLENGE", MenuCommand.StartDaily),

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 157.

The scene that carries out the commands needs a case for the new one. Open Source/Scenes/MainMenuScene.cs. In the Update method, find these lines:

find Source/Scenes/MainMenuScene.cs
csharp
            case MenuCommand.StartRun:
                Scenes.Change(GameplayScene.StartRun(_services, RunMode.Classic, 1));
                break;

Add the following lines directly below them. The new case starts a DailyChallenge run at level 1.

csharp
            case MenuCommand.StartDaily:
                Scenes.Change(GameplayScene.StartRun(_services, RunMode.DailyChallenge, 1));
                break;

Seeding the draft and recording the daily score ​

Two scenes still use the Chapter 18 behaviour. The upgrade scene seeds its draft from Session.Seed, and the gameplay scene records every run as a normal run.

Open Source/Scenes/UpgradeScene.cs. In the UpgradeScene constructor, find this line:

find Source/Scenes/UpgradeScene.cs
csharp
        _session.PendingUpgradeChoices = RunUpgradeDraft.CreateChoices(_session.Level, _session.Seed);

Replace it with the following line. The draft now uses Rng.DraftSeed, so it comes from the run's own draft stream.

csharp
        _session.PendingUpgradeChoices = RunUpgradeDraft.CreateChoices(_session.Level, gameplay.Simulation.Rng.DraftSeed);

Open Source/Scenes/GameplayScene.cs. In the FinishRun method, find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _services.Profile.RecordRunFinished(session.Score);

Replace it with the following line. It tells the profile whether the run was a daily one, so the profile can raise the best daily score.

csharp
        _services.Profile.RecordRunFinished(session.Score, dailyChallenge: session.DailyChallengeActive);

In the same file, find these lines at the start of the React method that takes a single GameEvent:

find Source/Scenes/GameplayScene.cs
csharp
        string text = StatusText.For(gameEvent);
        if (text.Length > 0)

Replace them with the following lines. When a daily level starts, the status line shows the seed.

csharp
        string text = StatusText.For(gameEvent);
        if (gameEvent is LevelStarted && _simulation.Session.DailyChallengeActive)
        {
            text = $"DAILY SEED {_simulation.Session.Seed}";
        }

        if (text.Length > 0)

The key changes are:

  • FinishRun passes dailyChallenge: session.DailyChallengeActive. The profile raises BestDailyChallengeScore only for a daily run, which a test from Chapter 16 already checks.
  • React replaces the normal text for LevelStarted with DAILY SEED and the seed when the run is a daily one. Every other event keeps its normal text.
  • The upgrade draft no longer reads Session.Seed. For a daily run the draft stream comes from the date, so every player is offered the same cards on the same day.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 157. The 157 tests are the 152 from earlier chapters and 5 new test cases.

TestProves
DailySeed_IsTheUtcDayNumberRUN-06
DailyChallengeActive_FollowsRunModeRUN-07
RunRandom_ExtraPowerupRoll_DoesNotShiftEnemyRollsRUN-08
SameSeedAndInput_GiveTheSameRunRUN-08
MainMenu_ConfirmOnEachItem_IssuesItsCommand (the new Daily case)FE-02
StartRun_FromLevelSelect_StartsAtChosenLevel (its new last line)RUN-01, RUN-06
RecordRunFinished_UpdatesDailyBestOnlyForDailyRuns (Chapter 16)PRO-07

PRO-07 has two halves. Chapter 16 tests that the profile raises the daily best only for daily runs. This chapter makes the gameplay scene pass the flag, and no test covers that call. You check it in the next section.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The main menu now has six rows, as in Figure 19-1. Press Down once to move to DAILY CHALLENGE, then press Enter.

Level 1 starts. The status line shows DAILY SEED and today's number. Hold Right for a second or two, then note where the enemy is. Press Escape to pause, move to QUIT TO MENU and press Enter. Choose DAILY CHALLENGE again and make the same moves for the same time. The enemy follows the same path as before. The timing of key presses by hand is not exact, so the paths match closely and not to the pixel. The test above checks the exact case. You need a window to watch the enemy and read the status line. The seed values, the profile score and the test counts you can confirm without watching.

Now choose START RUN from the menu and play for the same time. The enemy follows a different path, because a Classic run takes a fresh seed every time.

Finally, play a Daily Challenge run and lose every life. Press Enter on the summary. Quit the game and open profile.json, which is in your local application data folder in a folder named LastPerimeter. The BestDailyChallengeScore value is at least your score. This proves the flag reaches the profile.

Close the window with its close button when you finish. The next section is optional. It replaces your files with the chapter 19 snapshot.

If you got lost ​

This section is optional. Use it only when your project no longer builds or the tests no longer match this chapter. It overwrites your Source and Tests folders with the chapter 19 snapshot, so any change of your own in those folders is lost. <course-repo> is the folder where you cloned the course repository.

WARNING

These commands overwrite your own changes in Source and Tests. Copy your project folder elsewhere first if you want to keep it.

In PowerShell, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

powershell
$snapshot = "<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/19-Seeds-The-Clock-And-The-Daily-Challenge"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" Tests

In bash, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

bash
snapshot="<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/19-Seeds-The-Clock-And-The-Daily-Challenge"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" Tests

Then run dotnet test from the LastPerimeter folder and check for Passed: 157.

Common mistakes ​

  • The daily enemy moves differently each time. Something still uses an unseeded Random. Search Source for new Random() and Random.Shared. Only RunFactory may use Random.Shared, and only for runs that are not daily. The search also finds random ?? new Random() in EnemySystem and PowerupSystem. Those fallbacks are never used in a real run, because the run always passes its own Random, so you can leave them.
  • Two daily runs differ after a powerup appears. The powerups were given random.Enemies, or the enemies were given random.Powerups. Check the constructor of GameplaySimulation.
  • The enemy and powerup streams look linked. StreamSeed was given the same stream number twice. Each stream needs its own constant.
  • The daily seed changes during play. The date was read inside a rule. Read it once, in RunFactory.Create, from the todayUtc argument.
  • DAILY CHALLENGE starts a Classic run. The StartDaily case in MainMenuScene passes RunMode.Classic. It must pass RunMode.DailyChallenge.
  • The best daily score never changes. FinishRun calls RecordRunFinished without dailyChallenge: session.DailyChallengeActive.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove RUN-06 to RUN-08 and FE-02, with RUN-01 and PRO-07 completed by the factory test and the game. In the next chapter, Chapter 20: Themes and Accessibility, you add colour themes and a colourblind mode.

Test Your Knowledge ​

  1. Why is DailySeed.For a function of a date and not of "now"?

    Answer

    A test can then ask about any date, and the rule never depends on when it runs. The host is the only place that reads the clock, and it passes the date in.

  2. Why must enemies and powerups use separate random streams?

    Answer

    With one stream, a single extra roll anywhere changes every roll after it. Two runs with the same seed then drift apart. Separate streams confine an extra roll to its own stream.

  3. What else, besides randomness, could make two runs with the same seed differ?

    Answer

    The clock, and variable frame times. The fixed time step keeps the time step constant, and the injected clock keeps the date out of the rules.

  4. Why does RunRandom not use HashCode.Combine to derive its streams?

    Answer

    .NET gives HashCode.Combine a different random salt in each process. The same seed would then give different streams on each start, and a daily run could not be reproduced.

  5. Why does SameSeedAndInput_GiveTheSameRun run 400 frames with no input?

    Answer

    Enemies and powerups act while the player stands still, so the idle frames give every random choice time to happen. A random number that escaped the seed would show up as a difference.

Extensions ​

  • Add a test that builds two RunRandom objects from different seeds, and checks that the first ten enemy rolls differ.
  • Write a test that builds the daily run for 2 December 2026 and for 3 December 2026, and checks that the enemy positions differ after 100 idle frames.
  • Change the input in SameSeedAndInput_GiveTheSameRun so the second run presses one extra key. Which of the five comparisons fail first?