Appearance
Chapter 01: The Project and the Host
This is the first chapter, so nothing comes before it. You need basic C# and a terminal. You do not need any MonoGame experience, because every MonoGame type the chapter touches is explained when it first appears.
In this chapter, you create the game project from the MonoGame template, learn what the Game class does, and write a host class that does as little as possible. You also write the first three tests of the course. The result is a black window that can close itself after a set time.
| Figure 01-1: The chapter 01 window, a black 1024 x 768 area with nothing drawn in it. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 01]
In this chapter, you will:
- Create the project from the MonoGame Empty Game template with the Vulkan and DirectX 12 platforms.
- Make the changes to the template that the course needs, and learn why each one is there.
- Learn what
Initialize,LoadContent,UpdateandDraware for, and when MonoGame calls each. - Write
LastPerimeterApp, the thin host, and promise to keep it thin. - Add the test project and write your first three tests, for
GameLaunchOptions.
Requirements in this chapter
| ID | Short name |
|---|---|
| PLT-01 | Template layout on .NET 10 and MonoGame 3.8.6.1 |
| PLT-02 | One shared Source/ folder |
| PLT-03 | No content files (first half: the empty Content/ project) |
| PLT-04 | The smoke-test option |
| PLT-05 | 1024 x 768 window |
What MonoGame is
MonoGame is a framework, not an editor. There is no scene view and no drag and drop. You write a C# class that inherits from Game. The framework then gives you a window and a graphics device. It also gives you a batched 2D drawing API called SpriteBatch, polled input from the keyboard, mouse and gamepad, and audio playback.
MonoGame also has a content pipeline, a tool that compiles images, fonts and sounds into files the game loads. This course does not use it. Every picture in the game is drawn from one white pixel, which Chapter 02 creates in code. The template still creates the pipeline project, and you leave it alone.
Setting up your environment
The .NET SDK is the compiler and the command line tools that build your game. MonoGame 3.8.6 needs the .NET 10 SDK or later. Download it from dotnet.microsoft.com/download/dotnet/10.0, or on Ubuntu run sudo apt-get install -y dotnet-sdk-10.0.
Open a new terminal after the install, because a terminal that was already open cannot find dotnet. In the new terminal, run the following command. It works in PowerShell and in bash.
text
dotnet --list-sdksThe list must include a version that starts with 10.. If it does not, install the SDK again before you go on.
A template is a starting project that dotnet new can create. In a terminal, run the following two commands, one at a time. The first installs the MonoGame templates and the second lists them.
text
dotnet new install MonoGame.Templates.CSharp
dotnet new list monogameThe list must show MonoGame Empty Game. The template has the short name monogame.
A platform is a graphics system that the game runs on. The --Platforms option of the template chooses which platform projects it creates.
| Value | Platform | Runs on |
|---|---|---|
vk | DesktopVK, which uses Vulkan | Windows, macOS and Linux |
dx12 | WindowsDX12, which uses DirectX 12 | Windows only |
gl | DesktopGL, which uses the older OpenGL | Windows, macOS and Linux |
This course runs on DesktopVK on every operating system. It also builds WindowsDX12 on Windows. Both projects compile the same game code.
NOTE
DesktopVK needs a graphics driver that supports Vulkan. If the game does not start later in this chapter, update your graphics driver first.
What the template creates
The template creates one solution and several folders. This is the layout after you run the command in the next section. A folder tree reads better as text than as a picture, so it has no figure number.
text
LastPerimeter
.vscode editor launch settings
Content the content pipeline project (left unused)
Platforms
DesktopVK Program.cs, a .csproj and app.manifest
WindowsDX12 the same three files for DirectX 12
Resources the window icon and Identity.props
Source the shared game code, with one file: Game1.cs
Directory.Packages.props one property, MonoGameVersion
LastPerimeter.sln the solution fileA solution is a file that groups projects so that one command builds them all. Each platform .csproj contains the line <Compile Include="..\..\Source\**\*.cs" />. That line makes the project compile every C# file under Source/. This is how one code folder serves every platform, and it is the reason the course has a single Source folder (PLT-02).
Source/Game1.cs is the class that every MonoGame tutorial starts from. You delete it in this chapter and replace it with LastPerimeterApp, which has the same shape.
The changes this course makes
You follow the template layout and change only what the course needs. Each change has its own step below.
| Template | This course | Why |
|---|---|---|
Game1 in Source/Game1.cs and a 2-line Program.cs | LastPerimeterApp in Source/Game/ and a 5-line Program.cs | The host reads launch options such as --smoke-test-seconds. |
MonoGameVersion is 3.8.*, and each .csproj hard-codes 3.8.6.1 | MonoGameVersion is 3.8.6.1, and every .csproj reads it | One place sets the version for every project. |
| No shared build settings | Directory.Build.props and Directory.Build.targets | Nullable checking and implicit usings are on, and a namespace clash is removed. |
| No test project | Tests/LastPerimeter.Tests.csproj, which also compiles Source/ | Game rules can be tested without a window. |
The app title is LastPerimeter | The app title is Last Perimeter | The title is the name a player reads. |
The game lifecycle
Game.Run() drives a fixed sequence of calls, and everything you write in this course hangs off one of them. Figure 01-2 shows the order.
Figure 01-2: The life of a MonoGame game. The constructor, Initialize and LoadContent run once, then Update and Draw repeat until Exit is called |
| Method | Runs | It is the place for |
|---|---|---|
| Constructor | Once, before a window exists | GraphicsDeviceManager, the back buffer size and IsMouseVisible |
Initialize | Once, when the window exists but no graphics resources do | Game systems and configuration |
LoadContent | Once, when the graphics device is ready | SpriteBatch and textures |
Update | Every frame | Input and rules |
Draw | Every frame, after Update | Drawing only, never rules |
Dispose | Once, at exit | Releasing anything that holds graphics memory |
Two defaults matter for the whole course. IsFixedTimeStep is true, so MonoGame calls Update on a fixed schedule of 60 times a second. If a frame runs long, MonoGame calls Update more than once to catch up, and it may skip a Draw. This is why rules belong in Update: they run the same number of times however slow the drawing is.
The GameTime value passed to both methods holds two clocks. ElapsedGameTime is the time since the previous Update, about 16.7 milliseconds. TotalGameTime is the time since the game started. This chapter uses TotalGameTime for the smoke test, and Chapter 04 uses ElapsedGameTime to move the player.
A thin host
The class that inherits from Game is the host. A game that puts its rules in the host ends up with one very large class, which is hard to test because it needs a window to exist. This course makes a promise instead.
The host owns the MonoGame lifetime and nothing else. It creates the window, owns the graphics objects, and hands every decision to other classes. In Chapter 05, it hands the whole game to a scene manager. The host stays under 150 lines for the whole course. Chapter 21 checks that promise at the end. At the end of this chapter it is 47 lines.
Creating the project
In a terminal, from the folder where you keep your projects, run the following command. On macOS and Linux, run dotnet new monogame -n LastPerimeter --Platforms vk instead, because WindowsDX12 runs only on Windows. Wherever this chapter says "Windows only", skip that step on macOS and Linux.
text
dotnet new monogame -n LastPerimeter --Platforms vk dx12The command creates a LastPerimeter folder with the layout above. Use only letters and numbers in a project name, and do not start it with a number.
IMPORTANT
The rest of the course assumes DesktopVK. If your driver has no Vulkan support, run dotnet new monogame -n LastPerimeter instead, which creates a Platforms/DesktopGL project. Wherever the course says Platforms/DesktopVK, use Platforms/DesktopGL. Its .csproj names MonoGame.Framework.DesktopGL, and you apply the version change in the next section to that line.
From the folder where you keep your projects, go into the new folder. Stay in the LastPerimeter folder for the rest of the chapter, because every command below runs from there.
text
cd LastPerimeterNow build the solution once. The platform projects use the content pipeline project, so NuGet, the .NET package manager, must restore every project first. The first build downloads the MonoGame packages and can take a minute.
text
dotnet buildThe build should succeed. Then run the empty game once with dotnet run --project Platforms/DesktopVK. A cornflower blue window opens. Close it with its close button. DesktopVK also prints graphics information to the terminal, which is normal.
Setting the MonoGame version in one place
The template sets MonoGameVersion to 3.8.* in Directory.Packages.props. It also hard-codes 3.8.6.1 in each platform .csproj and in Content/Content.csproj, so changing the props file alone does nothing. This step has five parts, and each part changes only a few lines.
Open Directory.Packages.props in the LastPerimeter folder. Find this line:
xml
<MonoGameVersion>3.8.*</MonoGameVersion>Replace it with the following line. Version 3.8.6.1 is the one the course is written for.
xml
<MonoGameVersion>3.8.6.1</MonoGameVersion>Open Platforms/DesktopVK/LastPerimeter.DesktopVK.csproj. Find these four lines:
xml
<PackageReference Include="MonoGame.Framework.Native" Version="3.8.6.1" />
<PackageReference Include="MonoGame.Runtime.Windows.Vulkan" Version="3.8.6.1" />
<PackageReference Include="MonoGame.Runtime.Mac.Vulkan" Version="3.8.6.1" />
<PackageReference Include="MonoGame.Runtime.Linux.Vulkan" Version="3.8.6.1" />Replace them with the following lines. Each version now reads $(MonoGameVersion). Nothing else in the file changes.
xml
<PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)" />
<PackageReference Include="MonoGame.Runtime.Windows.Vulkan" Version="$(MonoGameVersion)" />
<PackageReference Include="MonoGame.Runtime.Mac.Vulkan" Version="$(MonoGameVersion)" />
<PackageReference Include="MonoGame.Runtime.Linux.Vulkan" Version="$(MonoGameVersion)" />Windows only: open Platforms/WindowsDX12/LastPerimeter.WindowsDX12.csproj. Find these two lines:
xml
<PackageReference Include="MonoGame.Framework.Native" Version="3.8.6.1" />
<PackageReference Include="MonoGame.Runtime.Windows.DX12" Version="3.8.6.1" />Replace them with the following lines. The two versions change in the same way.
xml
<PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)" />
<PackageReference Include="MonoGame.Runtime.Windows.DX12" Version="$(MonoGameVersion)" />Open Content/Content.csproj. Find these two lines:
xml
<PackageReference Include="MonoGame.Framework.Content.Pipeline" Version="3.8.6.1" />
<PackageReference Include="MonoGame.Framework.Native" Version="3.8.6.1">Replace them with the following lines. The other package references keep their own versions.
xml
<PackageReference Include="MonoGame.Framework.Content.Pipeline" Version="$(MonoGameVersion)" />
<PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)">The key changes in these files are:
Directory.Packages.propsnames one version,3.8.6.1.- Each
MonoGamepackage reference in the platform projects and the content project reads$(MonoGameVersion)instead of a number. - Every project you add later, including the test project, takes its MonoGame version from the same line.
Open Resources/Identity.props. Every platform project imports this file, and it holds the name of your game. Find this line:
xml
<ApplicationTitle>LastPerimeter</ApplicationTitle>Replace it with the following line, so that the title is the name a player reads.
xml
<ApplicationTitle>Last Perimeter</ApplicationTitle>Adding the shared build settings
MSBuild is the .NET build system. It reads any file named Directory.Build.props or Directory.Build.targets automatically, for every project in the folders below it. In the LastPerimeter folder, next to LastPerimeter.sln, create a new file named Directory.Build.props and add the following code. It turns on nullable reference checking, which warns about values that might be missing. New to nullable types? See the C# primer. It also turns on implicit usings, which add common using lines such as System and System.Linq to every file.
replace-file Directory.Build.props
xml
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>In the same folder, create a new file named Directory.Build.targets and add the following code. It removes a name clash. The WindowsDX12 project uses WinForms, a Windows desktop library. With implicit usings on, WinForms adds the namespaces System.Drawing and System.Windows.Forms to every file. Both define types called Color, Point and Rectangle, and so does MonoGame, so the compiler cannot tell which one you mean. This file loads after the SDK adds those namespaces and removes them again.
replace-file Directory.Build.targets
xml
<Project>
<ItemGroup>
<!-- With ImplicitUsings on, WinForms (used by WindowsDX12) adds global usings for System.Drawing and System.Windows.Forms. They clash with MonoGame types such as Color, Point and Rectangle. This file loads after the SDK adds them, so it can remove them. -->
<Using Remove="System.Drawing" />
<Using Remove="System.Windows.Forms" />
</ItemGroup>
</Project>If you build only DesktopVK, this file does nothing. Keep it anyway, so your project builds the same way on every platform.
Building the host
The host needs two things. The first is a record that reads the launch options, and the second is the host class itself. You build the record with its tests first, as the later chapters do.
In a terminal, from the LastPerimeter folder, run the following command. It creates the folder for the host. The command is the same in PowerShell and bash.
text
mkdir Source/GameReading the launch options
The smoke test lets a script run the real game for a few seconds and close it. It matters for continuous integration, which is a build server that runs your tests on every change. The smoke run proves start-up and shutdown only. It does not play the game, until Chapter 13: Proving the Level makes it play a short scripted capture. The option is --smoke-test-seconds N on the command line, or the environment variable LASTPERIMETER_SMOKE_TEST_SECONDS. A record is a class that is compared by its values. GameLaunchOptions is a record with one value, the time after which the game exits, which is empty when no smoke test was asked for. New to records? See the C# primer.
GameLaunchOptions.Parse(args, environmentValue) : GameLaunchOptions
- Takes: the command line arguments and an optional text value from the environment.
- Gives: a
GameLaunchOptionswhoseAutoExitAfteris aTimeSpan, or null.- Promises: an argument beats the environment value. With neither,
AutoExitAfteris null. A blank or unreadable environment value counts as no value.- Refuses:
--smoke-test-secondswith no value after it throwsArgumentException. So does a value that is not a number above zero.- Requirements: PLT-04.
The tests in this chapter check the argument, the environment fallback and the missing value. No test in this course checks the invalid number, so that refusal is proved only by the code and by the first extension at the end of the chapter.
In the Source/Game folder, create a new file named GameLaunchOptions.cs and add the following code. This is the stub: Parse throws NotImplementedException, so the project compiles and the tests can fail for the right reason. The using System.Globalization; line is for the body that you add later.
replace-file Source/Game/GameLaunchOptions.cs
csharp
using System.Globalization;
namespace LastPerimeter.Game;
public sealed record GameLaunchOptions(TimeSpan? AutoExitAfter)
{
public static GameLaunchOptions Parse(string[] args, string? smokeTestSecondsEnvironmentValue = null)
{
throw new NotImplementedException();
}
}Writing the host class
LastPerimeterApp is the host. It overrides only two methods this chapter, Update and Draw. In the Source/Game folder, create a new file named LastPerimeterApp.cs and add the following code.
new-file Source/Game/LastPerimeterApp.cs
csharp
using Microsoft.Xna.Framework;
namespace LastPerimeter.Game;
// The thin MonoGame host. It owns the MonoGame lifetime and nothing else.
public sealed class LastPerimeterApp : Microsoft.Xna.Framework.Game
{
private readonly GraphicsDeviceManager _graphics;
private readonly GameLaunchOptions _launchOptions;
public LastPerimeterApp(GameLaunchOptions? launchOptions = null)
{
_launchOptions = launchOptions ?? new GameLaunchOptions(null);
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
_graphics.PreferredBackBufferWidth = 1024;
_graphics.PreferredBackBufferHeight = 768;
}
protected override void Update(GameTime gameTime)
{
if (ShouldAutoExit(gameTime))
{
return;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
}
private bool ShouldAutoExit(GameTime gameTime)
{
if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)
{
Exit();
return true;
}
return false;
}
}The cards for the host are short, because the host has no tests. A test would need a window, and the course keeps window code out of the tests. These operations are proved by running the game.
LastPerimeterApp(launchOptions) : constructor
- Takes: the launch options, or null.
- Gives: a host with a 1024 x 768 back buffer, the content root set to
Content, and a visible mouse.- Promises: it creates nothing that needs a graphics device, because none exists yet.
- Refuses: nothing. Null launch options become options with no smoke test.
- Requirements: PLT-05. It is proved in "Running the game".
LastPerimeterApp.Update(gameTime)andDraw(gameTime)
- Takes: the
GameTimefor this frame.- Gives: nothing.
Updateexits the game once the smoke test time has passed.Drawclears the window to black.- Promises: with no smoke test, the window stays open until the player closes it.
- Refuses: nothing.
- Requirements: PLT-04. It is proved in "Running the game".
The key things to note are:
- The class is
sealed, which stops anything inheriting from it (see the C# primer), and the namespace isLastPerimeter.Game. The base class is written in full asMicrosoft.Xna.Framework.Game, because the namespace nameGamewould otherwise confuse the compiler. - The constructor creates the
GraphicsDeviceManager, which owns the window. It sets the back buffer to 1024 by 768 pixels. The back buffer is the image MonoGame draws into before it shows it. UpdatecallsShouldAutoExitfirst and returns early when the game has asked to exit.base.Updatethen runs the game components, of which there are none yet.ShouldAutoExitcomparesTotalGameTimewithAutoExitAfter. The patternis TimeSpan autoExitAfter(see the C# primer) is false when the value is null, so with no smoke test it never exits.Drawclears the window to black. Chapter 02 draws the arena after the clear.
Running the platform programs
Each platform project has a Program.cs that starts the game. Open Platforms/DesktopVK/Program.cs and replace the whole file with the following. It reads the launch options from the arguments and the environment, then runs the host. The using keyword before game disposes the host when Run returns.
replace-file Platforms/DesktopVK/Program.cs
csharp
using LastPerimeter.Game;
GameLaunchOptions launchOptions = GameLaunchOptions.Parse(args, Environment.GetEnvironmentVariable("LASTPERIMETER_SMOKE_TEST_SECONDS"));
using LastPerimeterApp game = new(launchOptions);
game.Run();Windows only: open Platforms/WindowsDX12/Program.cs and replace the whole file with the same code. Both platforms start the same host, and only the graphics package differs.
replace-file Platforms/WindowsDX12/Program.cs
csharp
using LastPerimeter.Game;
GameLaunchOptions launchOptions = GameLaunchOptions.Parse(args, Environment.GetEnvironmentVariable("LASTPERIMETER_SMOKE_TEST_SECONDS"));
using LastPerimeterApp game = new(launchOptions);
game.Run();The template's Game1 is no longer used. In PowerShell, from the LastPerimeter folder, run Remove-Item Source/Game1.cs. In bash, from the LastPerimeter folder, run rm Source/Game1.cs. Then, from the LastPerimeter folder, run dotnet build. The build should succeed with 0 warnings and 0 errors. This proves the stub compiles.
Creating the test project
The test project lets you check the game's rules without a window. It compiles the same Source folder as the platform projects, so it can create any class from the game. In a terminal, from the LastPerimeter folder, run the following command. It works in PowerShell and bash.
text
dotnet new xunit -o Tests -n LastPerimeter.TestsThis creates Tests/LastPerimeter.Tests.csproj and a sample test file named Tests/UnitTest1.cs. xUnit is the test framework. In PowerShell, from the LastPerimeter folder, run Remove-Item Tests/UnitTest1.cs. In bash, from the LastPerimeter folder, run rm Tests/UnitTest1.cs.
Open Tests/LastPerimeter.Tests.csproj and replace the whole file with the following.
replace-file Tests/LastPerimeter.Tests.csproj
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Source\**\*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)" />
</ItemGroup>
</Project>The key changes are:
- The test package versions are fixed, so every learner runs the same versions.
<Using Include="Xunit" />addsusing Xunit;to every test file.<Compile Include="..\Source\**\*.cs" />compiles the game code into the test project.- The
MonoGame.Framework.Nativereference gives that code the MonoGame types. The template file had its own nullable and implicit usings settings, whichDirectory.Build.propsnow supplies.
Now add the project to the solution. In a terminal, from the LastPerimeter folder, run the following command.
text
dotnet sln add Tests/LastPerimeter.Tests.csprojThe command should say that the project was added to the solution. Then run mkdir Tests/Game from the LastPerimeter folder, to create the folder for this chapter's tests.
Testing the launch options
In the Tests/Game folder, create a new file named GameLaunchOptionsTests.cs and add the following code. It starts with one test, marked [Fact], which checks that an argument of 1.5 seconds gives a 1.5 second delay.
New to [Fact] tests? See the C# primer.
new-file Tests/Game/GameLaunchOptionsTests.cs
csharp
using LastPerimeter.Game;
namespace LastPerimeter.Tests.Game;
public sealed class GameLaunchOptionsTests
{
[Fact]
public void Parse_UsesSmokeTestArgument_WhenProvided()
{
GameLaunchOptions options = GameLaunchOptions.Parse(["--smoke-test-seconds", "1.5"]);
Assert.Equal(TimeSpan.FromSeconds(1.5), options.AutoExitAfter);
}
}Open Tests/Game/GameLaunchOptionsTests.cs. Add the following test to the GameLaunchOptionsTests class, below the Parse_UsesSmokeTestArgument_WhenProvided test. It passes no argument and an environment value of 2.25.
add-member Tests/Game/GameLaunchOptionsTests.cs after=Parse_UsesSmokeTestArgument_WhenProvided
csharp
[Fact]
public void Parse_FallsBackToEnvironmentValue_WhenNoArgumentProvided()
{
GameLaunchOptions options = GameLaunchOptions.Parse([], "2.25");
Assert.Equal(TimeSpan.FromSeconds(2.25), options.AutoExitAfter);
}Add the following test below the Parse_FallsBackToEnvironmentValue_WhenNoArgumentProvided test. It gives the option with no value after it, and expects the refusal from the card. The () => is a lambda. New to lambdas? See the C# primer.
add-member Tests/Game/GameLaunchOptionsTests.cs after=Parse_FallsBackToEnvironmentValue_WhenNoArgumentProvided
csharp
[Fact]
public void Parse_ThrowsForMissingArgumentValue()
{
Assert.Throws<ArgumentException>(() => GameLaunchOptions.Parse(["--smoke-test-seconds"]));
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 0. All three tests hit the NotImplementedException in the stub. The third test fails too, because Assert.Throws<ArgumentException> accepts only that exact exception type.
Now write the body. Open Source/Game/GameLaunchOptions.cs, find the Parse method and replace the whole method with the following:
replace-method Source/Game/GameLaunchOptions.cs Parse
csharp
public static GameLaunchOptions Parse(string[] args, string? smokeTestSecondsEnvironmentValue = null)
{
TimeSpan? autoExitAfter = TryParseSeconds(smokeTestSecondsEnvironmentValue);
for (int index = 0; index < args.Length; index++)
{
if (!string.Equals(args[index], "--smoke-test-seconds", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (index + 1 >= args.Length)
{
throw new ArgumentException("Missing value for --smoke-test-seconds.");
}
autoExitAfter = TryParseSeconds(args[index + 1])
?? throw new ArgumentException("Invalid value for --smoke-test-seconds.");
index++;
}
return new GameLaunchOptions(autoExitAfter);
}Add the following method to the GameLaunchOptions record, below the Parse method. It is a private helper, so it has no card of its own.
add-member Source/Game/GameLaunchOptions.cs after=Parse
csharp
private static TimeSpan? TryParseSeconds(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (!double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double seconds) || seconds <= 0d)
{
return null;
}
return TimeSpan.FromSeconds(seconds);
}Run dotnet test again from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 3.
The key things to note are:
Parsereads the environment value first. An argument found in the loop overwrites it, which is how the argument beats the environment.TryParseSecondsreturns null for blank text, for text that is not a number, and for a number that is zero or less. The caller decides whether null is an error.- An invalid environment value is ignored, because its result is null and nothing throws. An invalid argument throws, because the
??(see the C# primer) afterTryParseSecondsturns null into anArgumentException. CultureInfo.InvariantCulturemakes1.5mean one and a half on every machine. Without it, a computer set to a language that writes decimals with a comma would reject the text.index++skips the value after the option, so the loop does not read it again as an option.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 3.
| Test | Proves |
|---|---|
Parse_UsesSmokeTestArgument_WhenProvided | PLT-04 |
Parse_FallsBackToEnvironmentValue_WhenNoArgumentProvided | PLT-04 |
Parse_ThrowsForMissingArgumentValue | PLT-04 |
Running the game
The first three requirements are proved by the build. PLT-01 is true when the solution builds on .NET 10 with MonoGame 3.8.6.1. PLT-02 is true because both the platform project and the test project compile one Source folder. PLT-03 is true because the content project holds no files.
The window checks below need a screen, and the game makes no sound yet. You can confirm everything else from the build result, the test counts and the exit code.
From the LastPerimeter folder, run dotnet build LastPerimeter.sln. It should report 0 Warning(s) and 0 Error(s).
Run dotnet run --project Platforms/DesktopVK. A black window opens, 1024 pixels wide and 768 high, as in Figure 01-1. This proves PLT-05. Close it with its close button.
Now run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 2. The window opens and closes by itself after about 2 seconds. The -- separates the arguments for dotnet from the arguments for your game. Check the exit code of that run. In PowerShell, run $LASTEXITCODE. In bash, run echo $?. Both should print 0. On exit, the graphics back end may print a message about the swapchain. This is normal.
Remember that this smoke run proves only that the game starts and shuts down.
To use the environment variable instead, set it before the run. In PowerShell, run $env:LASTPERIMETER_SMOKE_TEST_SECONDS = "2" and then dotnet run --project Platforms/DesktopVK. In bash, run LASTPERIMETER_SMOKE_TEST_SECONDS=2 dotnet run --project Platforms/DesktopVK. The window closes after 2 seconds again. In PowerShell, run Remove-Item Env:LASTPERIMETER_SMOKE_TEST_SECONDS afterwards, so later runs do not close by themselves.
The next section is optional. It replaces your files with the chapter 01 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 01 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/01-The-Project-And-The-Host"
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/01-The-Project-And-The-Host"
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: 3. If the build still fails, the problem is in a project file, so compare each one with its listing in this chapter.
Common mistakes
- Warnings about
CS8618inGame1.cs. You did not deleteSource/Game1.cs. With nullable checking on, the template class warns about fields it never sets. - Errors saying
Color,PointorRectangleis ambiguous.Directory.Build.targetsis missing, misspelt, or in the wrong folder. It belongs next toLastPerimeter.sln. - The build says
LastPerimeterAppwas not found.Program.cswas replaced beforeLastPerimeterApp.cswas created, or the file is not inSource/Game. - Errors saying
FactorAssertdoes not exist. The<Using Include="Xunit" />line is missing fromTests/LastPerimeter.Tests.csproj. - A restore error naming a MonoGame package. One
.csprojstill holds a version number, orDirectory.Packages.propsstill says3.8.*. Check all four files in the version step. dotnet runfails before the window opens. You skipped the firstdotnet build. Build the whole solution once, so that every project restores.
Conclusion
In this chapter, you accomplished the following:
- Created the project from the MonoGame template and made the changes the course needs.
- Learned what
Initialize,LoadContent,UpdateandDraware for and when MonoGame calls each. - Wrote
LastPerimeterApp, the thin host, and promised to keep it under 150 lines. - Added the test project and wrote your first three tests.
The tests now prove PLT-04. PLT-01, PLT-02, PLT-03 and PLT-05 are proved by the build and by running the game. In the next chapter, Chapter 02: Drawing from One Pixel, you create a single white pixel and draw the arena outline and the player from it.
Test Your Knowledge
Why does the game have two platform projects but only one
Sourcefolder?Answer
The rules and the drawing are the same everywhere. Only the graphics back end differs, and the platform project's package chooses it. Each platform project compiles the same
Sourcefolder.Which method runs more often if the game falls behind,
UpdateorDraw?Answer
Update. With a fixed time step, MonoGame catches up by callingUpdateextra times and may skip aDraw. This is why rules go inUpdate.Why does the smoke test read an environment variable as well as an argument?
Answer
A build server can set the variable once for every run, without changing each command line.
Why do you write the stub before the test, and not the test alone?
Answer
Without the stub, the test would not compile, and you would see a compiler error instead of a failing test. The stub makes the failure a clean one, so you know the test checks the right thing.
Extensions
- Add a test that passes
["--smoke-test-seconds", "abc"]toParseand expects anArgumentException. This proves the refusal that no test in the chapter covers. - Add a test that passes
["--smoke-test-seconds", "0"]. Decide first what you expect, then check the card.

