Appearance
Chapter 20: Themes and Accessibility
In Chapter 19: Seeds, the Clock and the Daily Challenge, you made every run repeatable from a seed. The game now plays the same way for everyone, but it looks the same way too. Every renderer names its own colour, such as Color.Cyan for the player, and the options screen only changes the difficulty and the audio.
In this chapter, you replace those fixed colours with named roles. A theme then becomes one object that every renderer reads, so the game can change its look, offer a colourblind palette, scale its text and calm its warning flash. Every change applies the moment the player makes it.
| Figure 20-1: The chapter 20 build. On the left, the options screen with its seven rows. On the right, a level drawn from the same palette roles. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 20]
In this chapter, you will:
- Learn the difference between a colour and a colour role.
- Build
ThemePalettewith three presets and a colourblind override. - Move the current palette into
GameServicesand addApplySettings, the one operation that applies a settings change. - Add the theme, colourblind, UI scale and reduced flash rows to the options screen.
- Draw the menus, the HUD, the powerups and the level from palette roles.
Requirements in this chapter
| ID | Short name |
|---|---|
| THM-01 | Three presets, nine colour roles each |
| THM-02 | Colourblind override replaces seven roles |
| THM-03 | Reduced flash keeps the trail colour during the fuse warning |
| THM-04 | UI scale from 0.8 to 1.5, clamped |
| THM-05 | Settings apply at once, including mid-run |
| AUD-03 | Audio on or off from the options |
Roles, not colours
Until now a renderer asked for a colour directly. The player renderer received Color.Cyan, and the trail renderer received Color.Yellow. A colour role is a name for what a thing is, such as "the player" or "the enemy". A theme maps each role to one colour. Code asks for the role, and the theme decides how the role looks.
This is the same idea as the tile states in Chapter 03: The Service Pattern and the Arena. Code that asks "is this tile claimed?" does not care how the claim is drawn. Code that asks for Palette.Enemy does not care which orange it receives. Swapping the whole theme then means swapping one object.
ThemePalette has nine roles: Background, Player, Trail, TrailSlow, Claimed, ClaimedSlow, Enemy, Accent and Warning. Figure 20-2 shows the colour each preset gives to each role, the colourblind override, and which part of the game reads the role.
| Figure 20-2: The nine palette roles, their colours in the three presets, the colourblind override and the code that reads each role |
The enum for the presets, ThemePreset, already exists. You added it to Source/Data/Enums.cs in an earlier chapter, together with the Theme, ColorblindMode, UiScale and ReducedFlash settings on GameSettings. This chapter is the first to use them.
Colourblind design
About one man in twelve has some form of colour vision deficiency. The common forms make red and green hard to tell apart. A game that shows the player's claim in one colour and the enemy in another is only fair if the two stay distinct for those players.
The colourblind override therefore replaces the roles that carry meaning: Player, Trail, TrailSlow, Claimed, ClaimedSlow, Enemy and Accent. These seven values come from the Okabe-Ito palette, a set of eight colours chosen so that people with the common deficiencies can still tell them apart. The override applies on top of any preset, so a player can combine it with the theme they like.
Two roles are left alone. Background carries no meaning, so changing it would not help anyone. Warning is the colour the fuse uses to say "danger", and it is also shown as text and as motion, so it does not rely on colour alone.
Flashing
When the player stops while drawing a trail, the fuse in Chapter 08: The Fuse Service first warns and then ignites. During the warning, the gameplay scene draws the trail a second time in the Warning colour. This second drawing is new in this chapter. The gameplay scene you have so far does not draw it, and you add it in "Drawing the level from the palette". Rapid colour changes can be uncomfortable, and for some players they are unsafe.
The reduced flash setting skips that second drawing. The trail keeps its normal colour. The WARN label in the HUD still appears, so the player is still told, without the colour change.
Scale
The HUD draws its text with a bitmap font, where every letter is made of square blocks. The size of a block is the scale. Until now the HUD used a block size of 2. The UI scale setting multiplies that size, clamped from 0.8 to 1.5, and the result is rounded to a whole number of pixels. The blocks must stay whole, because a font drawn at half a pixel looks smeared.
Rounding means that scales from 0.8 to 1.2 give blocks of 2 pixels, and scales from 1.3 to 1.5 give blocks of 3 pixels. The options screen steps the setting in tenths, so the text visibly grows once, at 1.3.
Apply at once
A player who changes the theme expects to see the result on the next frame, not after a restart. Two things must happen for that. The palette must be rebuilt from the new settings, and the audio must be reconfigured. GameServices.ApplySettings does both.
The third piece is the cache from Chapter 12: Events, Score and Feedback. The claimed area is drawn once into a texture and reused until a capture changes it. A texture drawn in the old colours would stay old. GameplayScene.Prepare therefore passes the current claimed colours to ClaimedAreaRenderer.UpdateColor on every frame. That method compares them with the colours it holds, and only a real change marks the cache dirty and so causes a rebuild. Figure 20-3 shows the path.
Figure 20-3: From a changed option to the next frame
Building the theme palette
ThemePalette is a record, a class compared by its values, with one property per role. The with expression builds a copy of a record with some properties changed, which is how the colourblind override works. New to records? See the C# primer. You build it in the usual rhythm, starting with a stub.
ThemePalette.Create
ThemePalette.Create(preset, colorblindMode) : ThemePalette
- Takes: a theme preset and a colourblind flag.
- Gives: a palette with all nine roles set.
- Promises: every preset sets all nine roles. With the flag on, exactly seven roles change, and
BackgroundandWarningdo not.- Refuses: nothing. A preset that is not one of the named two gives the
NeonVectorcolours.- Requirements: THM-01, THM-02.
In the Source/Data folder, create a new file named ThemePalette.cs and add the following code. The record has its nine roles in full, and Create is a stub.
new-file Source/Data/ThemePalette.cs
csharp
using Microsoft.Xna.Framework;
namespace LastPerimeter.Data;
public sealed record ThemePalette(
Color Background,
Color Player,
Color Trail,
Color TrailSlow,
Color Claimed,
Color ClaimedSlow,
Color Enemy,
Color Accent,
Color Warning)
{
public static ThemePalette Create(ThemePreset preset, bool colorblindMode)
{
throw new NotImplementedException();
}
}In a terminal, from the LastPerimeter folder, run dotnet build. The build should succeed, which proves the stub compiles.
Now the first test. In the Tests/Systems folder, create a new file named ThemePaletteTests.cs and add the following code. It is a theory, a test that runs once for each InlineData line, so it counts as three tests. It checks that every colour in every preset is set, by comparing it with default, the transparent black that an unset Color would have.
new-file Tests/Systems/ThemePaletteTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
namespace LastPerimeter.Tests.Systems;
public sealed class ThemePaletteTests
{
[Theory]
[InlineData(ThemePreset.NeonVector)]
[InlineData(ThemePreset.CrtGreen)]
[InlineData(ThemePreset.SunsetSynth)]
public void Create_EveryPresetFillsEveryRole(ThemePreset preset)
{
ThemePalette palette = ThemePalette.Create(preset, colorblindMode: false);
Color[] roles = [palette.Background, palette.Player, palette.Trail, palette.TrailSlow, palette.Claimed, palette.ClaimedSlow, palette.Enemy, palette.Accent, palette.Warning];
Assert.Equal(9, roles.Length);
Assert.All(roles, color => Assert.NotEqual(default, color));
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 157. The 157 passes are the tests from earlier chapters. The 3 failures are the three cases of your new test, which hit the NotImplementedException.
Open Source/Data/ThemePalette.cs, find the Create method and replace the whole method with the following. It builds the three presets and returns the result. The colourblind override comes after the next test.
replace-method Source/Data/ThemePalette.cs Create
csharp
public static ThemePalette Create(ThemePreset preset, bool colorblindMode)
{
ThemePalette palette = preset switch
{
ThemePreset.CrtGreen => new ThemePalette(
Color.Black,
new Color(120, 255, 120),
new Color(160, 255, 160),
new Color(220, 255, 180),
new Color(40, 120, 40, 180),
new Color(110, 160, 40, 180),
new Color(160, 255, 120),
new Color(120, 255, 120),
new Color(255, 220, 80)),
ThemePreset.SunsetSynth => new ThemePalette(
new Color(8, 4, 20),
new Color(255, 128, 196),
new Color(255, 210, 80),
new Color(255, 248, 140),
new Color(120, 60, 170, 180),
new Color(200, 90, 40, 180),
new Color(255, 112, 64),
new Color(120, 220, 255),
new Color(255, 96, 96)),
_ => new ThemePalette(
Color.Black,
Color.Cyan,
Color.Yellow,
new Color(255, 245, 140),
new Color(0, 160, 255, 180),
new Color(255, 140, 0, 180),
Color.OrangeRed,
Color.LimeGreen,
Color.OrangeRed),
};
return palette;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 160.
Open Tests/Systems/ThemePaletteTests.cs. Add the following test to the ThemePaletteTests class, below the Create_EveryPresetFillsEveryRole test. It loops over every preset, builds a normal and a colourblind palette, and checks that Background and Warning match while the other seven roles differ.
add-member Tests/Systems/ThemePaletteTests.cs after=Create_EveryPresetFillsEveryRole
csharp
[Fact]
public void ColorblindMode_ReplacesOnlyTheSevenRoles()
{
foreach (ThemePreset preset in Enum.GetValues<ThemePreset>())
{
ThemePalette normal = ThemePalette.Create(preset, colorblindMode: false);
ThemePalette safe = ThemePalette.Create(preset, colorblindMode: true);
Assert.Equal(normal.Background, safe.Background);
Assert.Equal(normal.Warning, safe.Warning);
Color[] before = [normal.Player, normal.Trail, normal.TrailSlow, normal.Claimed, normal.ClaimedSlow, normal.Enemy, normal.Accent];
Color[] after = [safe.Player, safe.Trail, safe.TrailSlow, safe.Claimed, safe.ClaimedSlow, safe.Enemy, safe.Accent];
for (int role = 0; role < before.Length; role++)
{
Assert.NotEqual(before[role], after[role]);
}
}
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 160. The new test fails because Create does not yet apply the override.
In Source/Data/ThemePalette.cs, find the Create method again and replace the whole method with the final version:
replace-method Source/Data/ThemePalette.cs Create
csharp
public static ThemePalette Create(ThemePreset preset, bool colorblindMode)
{
ThemePalette palette = preset switch
{
ThemePreset.CrtGreen => new ThemePalette(
Color.Black,
new Color(120, 255, 120),
new Color(160, 255, 160),
new Color(220, 255, 180),
new Color(40, 120, 40, 180),
new Color(110, 160, 40, 180),
new Color(160, 255, 120),
new Color(120, 255, 120),
new Color(255, 220, 80)),
ThemePreset.SunsetSynth => new ThemePalette(
new Color(8, 4, 20),
new Color(255, 128, 196),
new Color(255, 210, 80),
new Color(255, 248, 140),
new Color(120, 60, 170, 180),
new Color(200, 90, 40, 180),
new Color(255, 112, 64),
new Color(120, 220, 255),
new Color(255, 96, 96)),
_ => new ThemePalette(
Color.Black,
Color.Cyan,
Color.Yellow,
new Color(255, 245, 140),
new Color(0, 160, 255, 180),
new Color(255, 140, 0, 180),
Color.OrangeRed,
Color.LimeGreen,
Color.OrangeRed),
};
if (!colorblindMode)
{
return palette;
}
return palette with
{
Player = new Color(0, 114, 178),
Trail = new Color(240, 228, 66),
TrailSlow = new Color(255, 243, 128),
Claimed = new Color(0, 158, 115, 180),
ClaimedSlow = new Color(230, 159, 0, 180),
Enemy = new Color(213, 94, 0),
Accent = new Color(204, 121, 167),
};
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 161.
The key things to note are:
- The
switchexpression builds one complete palette per preset. The_arm catchesNeonVectorand any value added to the enum later, soCreatealways returns a full palette. - Colours with an alpha of 180 are for
ClaimedandClaimedSlow. They are drawn over the arena, and the partial transparency keeps what is drawn underneath visible. palette with { ... }copies the record and changes only the named properties.BackgroundandWarningare not named, so they keep the preset's values, which is exactly what the test checks.- The override values are the same for all three presets. That is deliberate, because the override exists to give a known-safe set of colours whatever the theme.
- A test over every preset covers all three presets without three copies of the same code. If you add a fourth preset to the enum, the loop covers it with no change.
Moving the palette into GameServices
The palette must be built from the settings and rebuilt when they change. GameServices, from Chapter 05: Scenes and the Gameplay Simulation, is the object every scene already receives, so it owns the current palette. The operation needs a window and a graphics device to build the services around it, so no unit test builds it. The checkpoints in "Running the game" prove it instead.
GameServices.Palette : ThemePaletteis the palette every scene draws from. It is set in the constructor and replaced byApplySettings. Requirements: THM-05.
GameServices.ApplySettings() : void
- Takes: nothing. It reads
Profile.Settings.- Gives: nothing.
Paletteis rebuilt and the audio is reconfigured.- Promises: after the call,
Palettematches the current theme and colourblind setting, and the audio matches the audio and volume settings.- Refuses: nothing.
- Requirements: THM-05, AUD-03.
AUD-03 has two halves. The master volume is clamped by AudioCuePlayer.Configure, which an earlier chapter tests. The on and off switch is the AUDIO row you add in this chapter, and you check it by listening in "Running the game".
Open Source/Game/GameServices.cs. Add the following property to the GameServices class, below the SetWindowTitle property. The setter is private, so only GameServices itself can replace the palette:
add-member Source/Game/GameServices.cs after=SetWindowTitle
csharp
public ThemePalette Palette { get; private set; }Add the following method to the GameServices class, below the Palette property:
add-member Source/Game/GameServices.cs after=Palette
csharp
// The one operation that rebuilds the palette and reconfigures the audio
// when the settings change.
public void ApplySettings()
{
Palette = ThemePalette.Create(Profile.Settings.Theme, Profile.Settings.ColorblindMode);
Audio.Configure(Profile.Settings.AudioEnabled, Profile.Settings.MasterVolume);
}In the same file, make two small changes in the GameServices constructor. Find this line:
find Source/Game/GameServices.cs
csharp
Audio.Configure(profile.Settings.AudioEnabled, profile.Settings.MasterVolume);Delete it. ApplySettings configures the audio now.
Find this line near the end of the constructor:
find Source/Game/GameServices.cs
csharp
SetWindowTitle = setWindowTitle;Add the following two lines directly below it. The smoke-run keyboard parameter at the end of the constructor stays as it is.
csharp
Palette = ThemePalette.Create(profile.Settings.Theme, profile.Settings.ColorblindMode);
ApplySettings();The key changes are:
- The constructor no longer calls
Audio.Configureitself. It builds the first palette, and then callsApplySettings, so the start-up path and the later path share one method. ApplySettingsis the only place that turns settings into a palette and into audio. A scene that changes a setting calls it and does not repeat either step.
The host clears the screen each frame, and it can now clear to the theme's background. Open Source/Game/LastPerimeterApp.cs. In the Draw method, find this line:
find Source/Game/LastPerimeterApp.cs
csharp
_scenes.Prepare();Add the following comment line directly above it:
csharp
// Rebuild cached render targets before clearing and starting the batch.In the same method, find this line:
find Source/Game/LastPerimeterApp.cs
csharp
GraphicsDevice.Clear(Color.Black);Replace it with the following line:
csharp
GraphicsDevice.Clear(services.Palette.Background);The key changes are:
GraphicsDevice.Clear(services.Palette.Background)replacesColor.Black. All three presets use a near-black background, so the difference is small, but the role is now in use.- A comment says why
Prepareruns first, as it did before.
Adding the options rows
The options screen has three rows today: difficulty, audio and back. You add theme, colourblind, UI scale and reduced flash, which gives seven rows. The row numbers matter, because the scene and the tests refer to them by number. The new order is 0 difficulty, 1 theme, 2 colourblind, 3 audio, 4 UI scale, 5 reduced flash and 6 back.
OptionsModel.GetLabels(settings) : string[]
- Takes: the settings.
- Gives: one label per row, in row order, with
BACKlast.- Promises: seven labels, each starting with the name of its row.
- Refuses: nothing.
- Requirements: THM-05.
OptionsModel.Change(settings, row, direction) : bool
- Takes: the settings, a row number and a direction of -1 or 1.
- Gives:
truewhen a setting changed.- Promises: rows 0 and 1 cycle through their enums, and rows 2, 3 and 5 toggle. Row 4 steps the UI scale by 0.1 and clamps it from 0.8 to 1.5.
- Refuses: the back row and a direction of 0 change nothing and give
false.- Requirements: THM-04, THM-05.
The two methods already exist from Chapter 17: Menus and the Front End, so no stub is needed. The tests come first, and they fail on the old three-row model.
Open Tests/Scenes/Menus/MenuTests.cs. Add the following test to the OptionsModelTests class, below the OptionsModel_Change_CyclesDifficulty test. It steps row 4 twenty times upwards and thirty times downwards, and checks both limits.
add-member Tests/Scenes/Menus/MenuTests.cs at=end type=OptionsModelTests
csharp
[Fact]
public void UiScale_IsClampedToRange()
{
GameSettings settings = new();
for (int step = 0; step < 20; step++)
{
OptionsModel.Change(settings, 4, 1);
}
Assert.Equal(1.5f, settings.UiScale, precision: 3);
for (int step = 0; step < 30; step++)
{
OptionsModel.Change(settings, 4, -1);
}
Assert.Equal(0.8f, settings.UiScale, precision: 3);
}Add the following test to the OptionsModelTests class, below the UiScale_IsClampedToRange test. It checks that there are seven labels in the new order.
add-member Tests/Scenes/Menus/MenuTests.cs at=end type=OptionsModelTests
csharp
[Fact]
public void OptionsModel_GetLabels_ListsEveryRow()
{
string[] labels = OptionsModel.GetLabels(new GameSettings());
Assert.Equal(7, labels.Length);
Assert.StartsWith("DIFFICULTY", labels[0]);
Assert.StartsWith("THEME", labels[1]);
Assert.StartsWith("COLORBLIND", labels[2]);
Assert.StartsWith("AUDIO", labels[3]);
Assert.StartsWith("UI SCALE", labels[4]);
Assert.StartsWith("REDUCED FLASH", labels[5]);
Assert.Equal("BACK", labels[OptionsModel.BackRow]);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 161. Both new tests fail against the old model.
Open Source/Scenes/Menus/OptionsModel.cs. Find the BackRow constant and replace it with the following three constants. The back row moves from 2 to 6, and the two new constants hold the UI scale limits.
replace-method Source/Scenes/Menus/OptionsModel.cs BackRow
csharp
public const int BackRow = 6;
public const float MinimumUiScale = 0.8f;
public const float MaximumUiScale = 1.5f;Find the GetLabels method and replace the whole method with the following:
replace-method Source/Scenes/Menus/OptionsModel.cs GetLabels
csharp
// One label per row, including Back.
public static string[] GetLabels(GameSettings settings)
{
return
[
$"DIFFICULTY {settings.Difficulty}",
$"THEME {settings.Theme}",
$"COLORBLIND {(settings.ColorblindMode ? "ON" : "OFF")}",
$"AUDIO {(settings.AudioEnabled ? "ON" : "OFF")}",
$"UI SCALE {settings.UiScale:0.0}",
$"REDUCED FLASH {(settings.ReducedFlash ? "ON" : "OFF")}",
"BACK",
];
}Find the Change method and replace the whole method with the following:
replace-method Source/Scenes/Menus/OptionsModel.cs Change
csharp
// Cycles enums, toggles flags and clamps the UI scale. Returns true when a setting changed.
public static bool Change(GameSettings settings, int row, int direction)
{
if (direction == 0)
{
return false;
}
switch (row)
{
case 0:
settings.Difficulty = Cycle(settings.Difficulty, direction);
return true;
case 1:
settings.Theme = Cycle(settings.Theme, direction);
return true;
case 2:
settings.ColorblindMode = !settings.ColorblindMode;
return true;
case 3:
settings.AudioEnabled = !settings.AudioEnabled;
return true;
case 4:
settings.UiScale = Math.Clamp(settings.UiScale + (0.1f * direction), MinimumUiScale, MaximumUiScale);
return true;
case 5:
settings.ReducedFlash = !settings.ReducedFlash;
return true;
default:
return false;
}
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 163.
The key things to note are:
OptionsModel_Change_CyclesDifficultystill passes. It uses theBackRowconstant and not a number, so it followed the back row from 2 to 6.- The
Cyclehelper, which is already in the file, steps through any enum. It now serves bothDifficultyPresetandThemePreset. Math.Clamplimits the UI scale after every step, so the setting can never leave the range, whatever is stored in the profile file.- The UI scale test uses more steps than the range needs, so it proves that the clamp holds at both ends. A test with one step would only prove that the value moves.
Applying settings from the options screen
OptionsScene called Audio.Configure after each change. It now calls ApplySettings, which does that and rebuilds the palette. The menu scenes also draw their highlight in Palette.Accent instead of Color.Gold.
Each of these five scene files has the same two edits. A draw call names a palette role instead of a colour. The file then no longer needs using Microsoft.Xna.Framework;, because nothing in it names a MonoGame colour or vector. You delete that line and change the draw call.
Open Source/Scenes/OptionsScene.cs. Find this line at the top of the file:
find Source/Scenes/OptionsScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Update method, find this line:
find Source/Scenes/OptionsScene.cs
csharp
_services.Audio.Configure(_services.Profile.Settings.AudioEnabled, _services.Profile.Settings.MasterVolume);Replace it with the following line:
csharp
_services.ApplySettings();In the Draw method, find this line:
find Source/Scenes/OptionsScene.cs
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "OPTIONS", "LEFT/RIGHT TO CHANGE", _labels, _menu.SelectedIndex, Color.Gold, _dimBackground);Replace it with the following line:
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "OPTIONS", "LEFT/RIGHT TO CHANGE", _labels, _menu.SelectedIndex, _services.Palette.Accent, _dimBackground);Open Source/Scenes/MainMenuScene.cs. Find this line at the top of the file:
find Source/Scenes/MainMenuScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Draw method, find this line:
find Source/Scenes/MainMenuScene.cs
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LAST PERIMETER", "ARCADE TERRITORY COURSE BUILD", Labels, _menu.SelectedIndex, Color.Gold);Replace it with the following line:
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LAST PERIMETER", "ARCADE TERRITORY COURSE BUILD", Labels, _menu.SelectedIndex, _services.Palette.Accent);Open Source/Scenes/LevelSelectScene.cs. Find this line at the top of the file:
find Source/Scenes/LevelSelectScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Draw method, find this line:
find Source/Scenes/LevelSelectScene.cs
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LEVEL SELECT", "CHOOSE A STARTING LEVEL", _labels, _menu.SelectedIndex, Color.Gold);Replace it with the following line:
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LEVEL SELECT", "CHOOSE A STARTING LEVEL", _labels, _menu.SelectedIndex, _services.Palette.Accent);Open Source/Scenes/PauseScene.cs. Find this line at the top of the file:
find Source/Scenes/PauseScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Draw method, find this line:
find Source/Scenes/PauseScene.cs
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "PAUSED", "PRESS ENTER TO SELECT", Labels, _menu.SelectedIndex, Color.Gold, overlay: true);Replace it with the following line:
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "PAUSED", "PRESS ENTER TO SELECT", Labels, _menu.SelectedIndex, _services.Palette.Accent, overlay: true);Open Source/Scenes/UpgradeScene.cs. Find this line at the top of the file:
find Source/Scenes/UpgradeScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Draw method, find this line:
find Source/Scenes/UpgradeScene.cs
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "CHOOSE AN UPGRADE", _subtitle, _options, _menu.SelectedIndex, Color.Gold, overlay: true);Replace it with the following line:
csharp
_services.Menus.DrawMenu(spriteBatch, _services.Pixel, "CHOOSE AN UPGRADE", _subtitle, _options, _menu.SelectedIndex, _services.Palette.Accent, overlay: true);The key change in these five files is the same. The DrawMenu call passes _services.Palette.Accent where it passed Color.Gold, and the using line for MonoGame's colour type is removed. In OptionsScene, _services.ApplySettings() also replaces the direct Audio.Configure call.
Drawing the level from the palette
The renderers still choose their own colours. Two of them, the powerup renderer and the HUD, receive the palette as a new parameter. The gameplay scene then passes it down.
Open Source/Rendering/PowerupRenderer.cs. Find the Draw method and replace the whole method with the following. It takes the palette and hands it to ColorFor.
replace-method Source/Rendering/PowerupRenderer.cs Draw
csharp
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, IReadOnlyList<Powerup> powerups, ThemePalette palette)
{
for (int index = 0; index < powerups.Count; index++)
{
Powerup powerup = powerups[index];
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, powerup.Position, powerup.Radius, ColorFor(powerup.Type, palette));
}
}Find the ColorFor method and replace the whole method with the following. The shield pickup now uses the Accent role and the fuse reset uses Warning. The other three pickups keep fixed colours, because each one is identified by its colour and must not change with the theme. New to switch expressions? See the C# primer.
replace-method Source/Rendering/PowerupRenderer.cs ColorFor
csharp
// One colour per powerup type.
public static Color ColorFor(PowerupType type, ThemePalette palette)
{
return type switch
{
PowerupType.Shield => palette.Accent,
PowerupType.Freeze => Color.LightBlue,
PowerupType.ExtraLife => Color.LimeGreen,
PowerupType.FuseReset => palette.Warning,
PowerupType.DoublePoints => Color.Gold,
_ => Color.White,
};
}Open Source/Rendering/HudRenderer.cs. First, one change that is not about colour. The GOAL text should read the goal from the level definition, which is where each level's required percentage is stored. In the Draw method, find this line:
find Source/Rendering/HudRenderer.cs
csharp
_textRenderer.DrawString(spriteBatch, pixel, $"GOAL:{config.WinClaimPercentage:0}%", new Vector2(config.ArenaMargin + 220, 52), Color.Gold, scale);Replace it with the following line. The number on screen does not change, because the level's config already carries the same goal. The text now reads it from the definition the level was built from.
csharp
_textRenderer.DrawString(spriteBatch, pixel, $"GOAL:{session.CurrentLevelDefinition.RequiredClaimPercentage:0}%", new Vector2(config.ArenaMargin + 220, 52), Color.Gold, scale);Now the colour and scale changes. In the same file, find the Draw method and replace the whole method with the following. Its GOAL line is the one you have just changed, with palette.Accent and the scale offset added:
replace-method Source/Rendering/HudRenderer.cs Draw
csharp
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, GameSession session, GameConfig config, ThemePalette palette, string statusMessage, bool fuseWarning, bool fuseActive, float uiScale = 1f)
{
int scale = Math.Max(1, (int)MathF.Round(2f * Math.Clamp(uiScale, 0.8f, 1.5f)));
Rectangle barBackground = new(config.ArenaMargin, 16, 220, 12);
spriteBatch.Draw(pixel, barBackground, Color.DarkSlateGray);
int filledWidth = (int)(barBackground.Width * MathHelper.Clamp(session.ClaimedAreaPercentage / 100f, 0f, 1f));
if (filledWidth > 0)
{
spriteBatch.Draw(pixel, new Rectangle(barBackground.X, barBackground.Y, filledWidth, barBackground.Height), palette.Claimed);
}
for (int index = 0; index < session.Player.Lives; index++)
{
Vector2 center = new(config.ScreenWidth - config.ArenaMargin - 12 - (index * 18), 22);
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, center, 5f, palette.Player);
}
_textRenderer.DrawString(spriteBatch, pixel, $"SCORE:{session.Score}", new Vector2(config.ArenaMargin, 34), Color.White, scale);
_textRenderer.DrawString(spriteBatch, pixel, $"HI:{session.HighScore}", new Vector2(config.ArenaMargin + 220, 34), palette.Accent, scale);
_textRenderer.DrawString(spriteBatch, pixel, $"LEVEL:{session.Level}", new Vector2(config.ArenaMargin + 420, 34), Color.White, scale);
_textRenderer.DrawString(spriteBatch, pixel, $"CLAIM:{session.ClaimedAreaPercentage:0}%", new Vector2(config.ArenaMargin, 52 + (4 * (scale - 2))), Color.White, scale);
_textRenderer.DrawString(spriteBatch, pixel, $"GOAL:{session.CurrentLevelDefinition.RequiredClaimPercentage:0}%", new Vector2(config.ArenaMargin + 220, 52 + (4 * (scale - 2))), palette.Accent, scale);
_textRenderer.DrawString(spriteBatch, pixel, "LIVES", new Vector2(config.ScreenWidth - config.ArenaMargin - 70, 34), Color.White, scale);
if (fuseWarning)
{
_textRenderer.DrawString(spriteBatch, pixel, fuseActive ? "FUSE" : "WARN", new Vector2(config.ScreenWidth / 2f - 24, 16), fuseActive ? palette.Warning : Color.Orange, scale);
}
if (session.RespawnGraceRemaining > 0f)
{
_textRenderer.DrawString(spriteBatch, pixel, "SAFE", new Vector2((config.ScreenWidth / 2f) - 24f, 34f), palette.Player, scale);
}
if (session.SlowDrawActive)
{
_textRenderer.DrawString(spriteBatch, pixel, "SLOW DRAW 2X", new Vector2(config.ArenaMargin, config.ScreenHeight - 64), palette.TrailSlow, scale);
}
if (session.ShieldCharges > 0)
{
_textRenderer.DrawString(spriteBatch, pixel, $"SHIELD:{session.ShieldCharges}", new Vector2(config.ArenaMargin + 220, config.ScreenHeight - 64), palette.Accent, scale);
}
if (session.DoublePointsRemaining > 0f)
{
_textRenderer.DrawString(spriteBatch, pixel, "DOUBLE PTS", new Vector2(config.ArenaMargin + 420, config.ScreenHeight - 64), palette.Warning, scale);
}
if (!string.IsNullOrWhiteSpace(statusMessage))
{
_textRenderer.DrawString(spriteBatch, pixel, statusMessage, new Vector2(config.ArenaMargin, config.ScreenHeight - 36), Color.LightGray, scale);
}
}The key changes are:
- The method takes a
ThemePaletteand auiScale. The scale defaults to 1, so a caller that does not pass one gets the old size. scalewas a constant of 2. It is nowMath.Max(1, (int)MathF.Round(2f * Math.Clamp(uiScale, 0.8f, 1.5f))), which is the rounding described under "Scale".- The second row of text moves down by
4 * (scale - 2)pixels, so larger text does not overlap the first row. - The claimed bar, the lives, the
HI,GOAL,SAFE,SLOW DRAW,SHIELDandDOUBLE PTSitems use the rolesClaimed,Player,Accent,TrailSlowandWarning. TheFUSEtext usesWarning. TheWARNtext keepsColor.Orange. - The
GOALtext reads the level definition, as in the previous step. It also usespalette.Accentand the scale offset.
The HUD and the powerup renderer now expect a palette, but their only caller, GameplayScene, has not been changed. In a terminal, from the LastPerimeter folder, run dotnet build. The build should fail with errors in GameplayScene.cs. This is expected, and the next step fixes it.
Open Source/Scenes/GameplayScene.cs and make four edits. The file no longer needs using Microsoft.Xna.Framework;, because the scene no longer names a colour. Find this line at the top of the file:
find Source/Scenes/GameplayScene.cs
csharp
using Microsoft.Xna.Framework;Delete it.
In the Prepare method, find this line:
find Source/Scenes/GameplayScene.cs
csharp
_claimedArea.Prepare();Add the following line directly above it, below the comment. It passes the current claimed colours before the cache is rebuilt.
csharp
_claimedArea.UpdateColor(_services.Palette.Claimed, _services.Palette.ClaimedSlow);Find the Draw method and replace the whole method with the following. Most of its lines change, so type it in full:
replace-method Source/Scenes/GameplayScene.cs Draw
csharp
public override void Draw(SpriteBatch spriteBatch)
{
GameSession session = _simulation.Session;
LevelServices level = _simulation.Level;
ThemePalette palette = _services.Palette;
Texture2D pixel = _services.Pixel;
_arenaRenderer.Draw(spriteBatch, pixel, level.Arena.Bounds, session.PlayableWallPath);
_claimedArea.Draw(spriteBatch);
_trailRenderer.Draw(spriteBatch, pixel, session.Player.CurrentTrail, session.SlowDrawActive ? palette.TrailSlow : palette.Trail, session.SlowDrawActive ? 5f : 3f);
_powerupRenderer.Draw(spriteBatch, pixel, session.Powerups, palette);
if (level.Fuse.IsActive)
{
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, level.Fuse.Position, 4f, palette.Warning);
}
else if (level.Fuse.IsWarning && session.Player.CurrentTrail is not null && !_services.Profile.Settings.ReducedFlash)
{
_trailRenderer.Draw(spriteBatch, pixel, session.Player.CurrentTrail, palette.Warning, 4f);
}
for (int index = 0; index < session.Enemies.Count; index++)
{
_enemyRenderer.Draw(spriteBatch, pixel, session.Enemies[index], palette.Enemy);
}
_playerRenderer.Draw(spriteBatch, pixel, session.Player, palette.Player);
_hudRenderer.Draw(spriteBatch, pixel, session, level.Config, palette, _status, level.Fuse.IsWarning || level.Fuse.IsActive, level.Fuse.IsActive, _services.Profile.Settings.UiScale);
}Find the CreateClaimedArea method and replace the whole method with the following:
replace-method Source/Scenes/GameplayScene.cs CreateClaimedArea
csharp
private ClaimedAreaRenderer CreateClaimedArea(LevelServices level)
{
ThemePalette palette = _services.Palette;
return new ClaimedAreaRenderer(level.Arena, _services.GraphicsDevice, _services.Pixel, palette.Claimed, palette.ClaimedSlow);
}The key changes are:
- In
Prepare,_claimedArea.UpdateColor(...)passes the current claimed colours before the cache is rebuilt. A theme change therefore recolours the claimed area on the next frame. - In
Draw, a localpaletteholds_services.Palette, and each renderer receives a role:TrailorTrailSlowfor the trail,Warningfor the fuse spark,Enemyfor the enemies andPlayerfor the player. - The
else ifbranch is the second drawing of the trail that the "Flashing" section describes, and it is new in this chapter. When the fuse is warning but not yet active, and the player has a trail, and reduced flash is off, the trail is drawn again inWarning, 4 pixels wide. With reduced flash on, the branch is skipped. CreateClaimedAreatakes its two colours from the palette instead ofColor.RoyalBlueandColor.Orange.- The
using Microsoft.Xna.Framework;line is gone, because the scene no longer names a colour.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 163. The 163 tests are the 157 from earlier chapters and the 6 new cases of this chapter. They are 3 preset cases, the colourblind test, the UI scale test and the labels test.
| Test | Proves |
|---|---|
Create_EveryPresetFillsEveryRole | THM-01 |
ColorblindMode_ReplacesOnlyTheSevenRoles | THM-02 |
UiScale_IsClampedToRange | THM-04 |
OptionsModel_GetLabels_ListsEveryRow | THM-05, the options rows |
THM-03, THM-05 applied at once, and AUD-03 have no test, because they depend on what the player sees and hears. The steps in the next section prove them.
Running the game
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The main menu opens.
Press Down four times to reach OPTIONS, then press Enter. The options screen shows seven rows, as in Figure 20-1, starting with DIFFICULTY Classic and ending with BACK.
Press Down once to select the THEME row. Press Right. The label changes to THEME CrtGreen, and the highlight on the selected row changes from lime green to a lighter green at once. Press Right again for SunsetSynth, where the highlight is light blue. Press Right once more to return to NeonVector.
Press Down to the COLORBLIND row and press Right. The label reads COLORBLIND ON. The menu highlight changes to the pink-purple Accent of the override. Press Right again to turn it off.
Press Down to the AUDIO row and press Right. The label reads AUDIO OFF, and the menu move sounds stop. Move with Up and Down, and listen. Press Right to turn audio on again. This is the check for AUD-03.
Press Down to the UI SCALE row and press Right three times. The label reads UI SCALE 1.3. Press Escape to go back to the main menu, then choose START RUN and press Enter. The text in the HUD is larger than before, because 1.3 rounds to blocks of 3 pixels.
Now check reduced flash and applying settings mid-run. Hold the Right arrow for about a second, release it, then hold the Down arrow. The yellow trail follows the dot. Release every key and wait. After about one second the WARN label appears at the top and the trail turns orange-red. This is the warning flash.
Hold the Right arrow to move again, which cancels the warning. Press Escape to pause. Choose OPTIONS, move to REDUCED FLASH, press Right, and press Escape to return to the pause menu. Choose RESUME. Draw a trail, release every key and wait again. The WARN label appears, but the trail stays yellow. This is the check for THM-03, and the change you made while paused is the check for THM-05 mid-run.
Close the window with its close button. The settings are saved with your profile, so they are still set the next time you start the game.
TIP
Open the pause menu mid-run, change the theme, and resume. The claimed area changes colour at once. This is the UpdateColor call in Prepare at work.
You need a window to see the colours, the flash and the text size, and speakers or headphones for the audio row. The test counts alone prove the palette values and the options labels. The next section is optional. It replaces your files with the chapter 20 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 20 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/20-Themes-And-Accessibility"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" TestsIn 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/20-Themes-And-Accessibility"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" TestsThen run dotnet test from the LastPerimeter folder and check for Passed: 163.
Common mistakes
- The build fails in
GameplayScene.csafter the HUD change. This is expected until you replaceGameplayScene.cs. If it still fails afterwards, check that the file passespaletteand the UI scale to_hudRenderer.Draw. Create_EveryPresetFillsEveryRolefails with aNotImplementedException. You left the stub inThemePalette.cs. Replace theCreatemethod.- Changing the theme does nothing in a level.
GameplayScene.Preparelost itsUpdateColorcall, so the cached claimed area keeps its old colours. - A row in the options screen changes the wrong setting. The cases in
Changeand the labels inGetLabelsare in different orders. Both must follow the order 0 to 6 in this chapter. - The options screen has no back row, or Back changes a setting.
BackRowis still 2. It must be 6. - The text does not grow until UI scale reaches 1.3. This is correct. The scale is rounded to whole pixels, so 0.8 to 1.2 all give the same size.
Conclusion
In this chapter, you accomplished the following:
- Learned the difference between a colour and a role, and why code that asks for roles lets a theme change freely.
- Built
ThemePalettewith three presets and a colourblind override that replaces seven roles. - Moved the palette into
GameServiceswithApplySettings, the one operation that applies a settings change. - Added four rows to the options screen, with a clamped UI scale.
- Drew the menus, the HUD, the powerups and the level from palette roles, with the warning flash switched off by reduced flash.
The tests now prove THM-01, THM-02 and THM-04, and the checkpoints prove THM-03, THM-05 and AUD-03. In the final chapter, Chapter 21: Shipping, you publish the game, build it in CI and walk through the requirements list.
Test Your Knowledge
Why does the colourblind override leave
Backgroundunchanged?Answer
The background carries no meaning, so changing it helps nobody. The override only changes the roles a player must tell apart.
Warningis also left alone, because the warning is shown as text as well as colour.Why must a theme change mark the claimed-area cache dirty?
Answer
The cache is a texture drawn in the old colours. Without a rebuild it keeps them until the next capture.
UpdateColormarks the cache dirty only when the colours really changed, so a frame with no change costs nothing.What is the difference between a colour and a role?
Answer
A role says what something is, such as the enemy. A colour is how one theme shows it. Code asks for roles, so a theme can change every colour without any renderer changing.
Why does
OptionsModel_Change_CyclesDifficultystill pass after the back row moved from 2 to 6?Answer
It refers to
OptionsModel.BackRowand not to a number. The test follows the constant, so moving the row does not break it.
Extensions
- Add a fourth preset to
ThemePresetand a matching arm toCreate. Rundotnet testand check that the two theory-style tests still pass with no change. Which test needs a newInlineDataline? - Make the UI scale step by 0.05. Which test fails, and what does that tell you about the rounding in
HudRenderer?

