Skip to content

Chapter 01 - New Project and Basic Rendering ​

Where this chapter fits: from nothing to a window that draws the arena frame and the player marker every frame. Nothing moves yet; the point is a render loop you can trust.

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

The chapter 01 window: a light-grey arena frame and a cyan player dot on black

What you will have at the end of this chapter: a 1024 x 768 window, the arena outline, and the player marker at the arena centre. Captured from the chapter 01 snapshot build.

Prerequisites ​

Chapter 00 (the three kinds of space), basic C#, and a terminal. No MonoGame experience is assumed; this chapter includes the full environment setup and explains every MonoGame type it touches.

Learning objectives ​

By the end of this chapter you should be able to:

  1. install the .NET SDK and the MonoGame templates, and create the solution this course uses: a shared Source folder, platform projects and a test project,
  2. explain what MonoGame gives you and describe the responsibilities of the Game methods Initialize, LoadContent, Update, and Draw,
  3. explain screen coordinates in MonoGame (origin top-left, Y downward) and read GameConfig.ArenaBounds,
  4. create a 1x1 pixel texture once and use it to draw lines, rectangles, and circles with SpriteBatch,
  5. explain what GameTime provides and why per-frame pixel steps are wrong (the maths itself is implemented in chapter 03),
  6. build and run the chapter 01 snapshot and pass its 3 tests.

Code anchors ​

  • Platforms/DesktopVK/Program.cs and Platforms/DesktopVK/LastPerimeter.DesktopVK.csproj (the same under Platforms/WindowsDX12/)
  • Directory.Packages.props, Directory.Build.props, Directory.Build.targets
  • Tests/LastPerimeter.Tests.csproj
  • Source/Game/GameLaunchOptions.cs
  • Source/Game/LastPerimeterApp.cs (the chapter 01 snapshot uses a staged version with only rendering wired up)
  • Source/Data/GameConfig.cs, Source/Data/Enums.cs
  • Source/Entities/PlayableWallPath.cs, Source/Entities/Player.cs (staged, without a trail)
  • Source/Rendering/PrimitiveDrawing.cs, ArenaRenderer.cs, PlayerRenderer.cs
  • Tests/Game/GameLaunchOptionsTests.cs

What MonoGame is (and is not) ​

MonoGame is a code-first framework, not an editor. There is no scene view and no drag-and-drop: you write a C# class that inherits from Game, and the framework gives you:

  • a window and a graphics device (through GraphicsDeviceManager),
  • a batched 2D drawing API (SpriteBatch),
  • polling input for keyboard, mouse, and gamepads,
  • audio playback (SoundEffect),
  • and an optional content pipeline for compiling assets such as images, fonts, and sounds.

The template builds for several platforms. This course uses DesktopVK, which runs the same code on Windows, macOS, and Linux on top of Vulkan, and WindowsDX12, which runs on Windows only. Both are built from one shared Source folder.

This course deliberately uses no assets at all. Every visible thing in the game is drawn from a single 1x1 white texture. Text is rendered from a tiny bitmap font defined in code, and sound effects are synthesised sine tones (both in chapter 08). That keeps the build to dotnet build and keeps every chapter snapshot self-contained. You never have to learn the content pipeline to finish the course. Chapter 15 discusses when you would want it.

Setting up your environment ​

This section follows the official MonoGame getting started guide. Read it if you want screenshots or IDE instructions. Everything here uses the terminal.

Install the .NET SDK ​

The .NET SDK holds the compiler and the command line tools that build your game. MonoGame 3.8.6 recommends the .NET 10 SDK or later. Download it from dotnet.microsoft.com/download/dotnet/10.0, or on Ubuntu run:

bash
sudo apt-get update && sudo apt-get install -y dotnet-sdk-10.0

Open a new terminal window, because a terminal that was open during the install cannot find dotnet. Then check the install:

bash
dotnet --list-sdks

The list must show a version of 10.0 or later. This course has no global.json, so any .NET 10 SDK works.

Install the MonoGame templates ​

A template is a starting project that dotnet new can create. Install the MonoGame templates, then check that they arrived:

bash
dotnet new install MonoGame.Templates.CSharp
dotnet new list monogame

The list must show MonoGame Empty Game. The template has the short name monogame and also mg-emptygame. Use mg-emptygame if another template on your machine also claims monogame. Running the install command again updates the templates.

Choose your platforms ​

A platform is a type of device or graphics system that the game runs on. The --Platforms option of the template selects which platform projects it creates.

ValuePlatformRuns on
vkDesktopVK (Vulkan)Windows, macOS and Linux
dx12WindowsDX12 (DirectX 12)Windows only
glDesktopGL (OpenGL, the older desktop platform)Windows, macOS and Linux

This course builds for DesktopVK on every operating system, and also for 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, update your graphics driver. If that does not help, use the DesktopGL fallback in Step 1.

What the template generates ​

The template creates one solution with a shared Source folder, one project per platform and a Content Builder project. Step 1 below shows the exact command. You write your game code once, and each platform project builds the same code.

PathWhat it holds
Source/the shared game code. The template puts one file here, Game1.cs
Content/the Content Builder project (Content.csproj, Builder/, Assets/, BuildContent.targets) that compiles images, fonts and sounds
Platforms/one project per platform you selected, each with a Program.cs, a .csproj and an app.manifest
Resources/the window icon (Icon.ico, Icon.bmp), Identity.props with the app name and version, and macOS/ packaging files
Directory.Packages.propsone property, MonoGameVersion, for the MonoGame package version
LastPerimeter.slnthe solution file that ties the projects together
.vscode/, LastPerimeter.slnLaunch, README.mdeditor launch settings and a short readme

Each platform .csproj contains the line <Compile Include="..\..\Source\**\*.cs" />. That line makes the project compile every C# file under Source/, which is how one code folder serves every platform.

Source/Game1.cs is the skeleton every MonoGame tutorial starts from. It is worth reading once, because our LastPerimeterApp has exactly the same shape. This is the 3.8.6.1 template text with the TODO comments and the #if !__IOS__ guard (iOS does not allow an app to close itself) removed:

csharp
public class Game1 : Microsoft.Xna.Framework.Game
{
    private GraphicsDeviceManager _graphics;
    private SpriteBatch _spriteBatch;

    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        base.Draw(gameTime);
    }
}

Run it and you get the cornflower-blue window. That is all a MonoGame game is: a class with four overridable methods and a loop the framework runs for you.

How this course changes the template ​

The course keeps the template layout and changes only a few things. Each change has its own step below.

TemplateThis courseWhy
Game1 in Source/Game1.cs and a 2-line Program.csLastPerimeterApp in Source/Game/ and a 5-line Program.csthe host reads launch options such as --smoke-test-seconds
MonoGameVersion is 3.8.*, and each platform .csproj hard-codes 3.8.6.1MonoGameVersion is 3.8.6.1, and the .csproj files read itone place sets the version for every project
no shared build settingsDirectory.Build.props and Directory.Build.targetsnullable checking and implicit usings on, and no WinForms namespace clash
no test projectTests/LastPerimeter.Tests.csproj, which also compiles Source/game logic is testable without a window
a Content Builder projectthe same project, left unusedevery visual and sound is made in code

You could generate the template just to look at it, but for the course itself follow the steps below, so that your build matches every chapter snapshot.

The MonoGame game lifecycle ​

Game.Run() drives this sequence. Everything you write in this course hangs off one of these methods.

MethodRunsPut here
constructoronce, before a window existsGraphicsDeviceManager, back-buffer size, IsMouseVisible
Initializeonce, window exists, no GPU resources yetgame systems, entities, configuration
LoadContentonce, graphics device readySpriteBatch, textures, render targets
Updateevery frameinput, simulation, state transitions
Drawevery frame after Updaterendering only, never game logic
Dispose(bool)once at exitdispose anything that owns GPU memory

Two defaults matter for the whole course. IsFixedTimeStep is true, so MonoGame calls Update on a fixed 60 Hz schedule (TargetElapsedTime is 1/60 s) and catches up with extra Update calls if a frame ran long. And GameTime carries two clocks: ElapsedGameTime (the time since the previous Update, about 16.7 ms) and TotalGameTime (time since the game started). Chapter 03 uses the first; the smoke-test runner in chapter 09 uses the second.

Screen coordinates ​

MonoGame's 2D coordinate system has its origin in the top-left corner of the window, with X growing to the right and Y growing downward. One unit is one pixel of the back buffer.

Screen coordinates: origin top-left, Y down, the arena rectangle inside the 1024 x 768 window

This project draws directly in screen space, so world coordinates and screen coordinates are the same thing. That is why Direction.Up maps to the vector (0, -1) in chapter 03, and why the arena's Top is a smaller number than its Bottom.

One shared source folder ​

The solution has three projects that all compile the same Source/ folder:

  • Source/ holds all game logic, systems, entities and rendering helpers, including the Game subclass itself,
  • Platforms/DesktopVK and Platforms/WindowsDX12 are thin hosts. Each Program.cs only parses launch options and runs the game,
  • Tests is an xUnit project. It compiles the same Source/ files and needs only the MonoGame package, not a window.

The entire host program is five lines, and both platform projects use the same text:

csharp
using LastPerimeter.Game;

GameLaunchOptions launchOptions = GameLaunchOptions.Parse(args, Environment.GetEnvironmentVariable("LASTPERIMETER_SMOKE_TEST_SECONDS"));

using LastPerimeterApp game = new(launchOptions);
game.Run();

Because the tests compile the game code directly, they can construct systems without a window, and no separate class library is needed. The --smoke-test-seconds option lets scripts run the real game briefly and exit. Both pay off in chapter 09.

A preview of the first equation ​

The course's first equation is nextPosition = currentPosition + directionVector * speed * deltaTime. Nothing moves in this chapter, so the equation waits until chapter 03, where it is implemented and drawn. Knowing it is coming explains why Player.Speed is already expressed in pixels per second and never in pixels per frame.

Build it step by step ​

If you prefer not to create projects from scratch, every chapter has a ready-made buildable snapshot under DOCUMENTATION/LastPerimeter-Source/NN-Chapter-Name in the course repository. DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering is exactly the project this section builds. Building the project by hand once is worth the effort, because you will know where every file lives.

This chapter is type-along. You type every file yourself except three, which you copy whole from the snapshot because the listings show only part of them: Source/Data/Enums.cs (Step 7), Source/Entities/PlayableWallPath.cs (Step 8) and Tests/Game/GameLaunchOptionsTests.cs (Step 12). Each of those steps gives the copy command. Replace <course-repo> in those commands with the path to your copy of the course repository (the course index explains how to get it).

Run every command from the solution folder (the LastPerimeter folder that Step 1 creates) unless a step says otherwise.

Step 1 - Create the project from the template ​

Run the command for your operating system in the folder where you keep your projects. On Windows, run this:

bash
dotnet new monogame -n LastPerimeter --Platforms vk dx12

On macOS and Linux, run this:

bash
dotnet new monogame -n LastPerimeter --Platforms vk

The command creates a new LastPerimeter folder with the layout from the table above. Use only letters and numbers in the project name, and do not start it with a number. If your graphics driver has no Vulkan support, create the DesktopGL fallback instead by leaving out --Platforms:

bash
dotnet new monogame -n LastPerimeter

IMPORTANT

With the DesktopGL fallback you get Platforms/DesktopGL and no DesktopVK or WindowsDX12 project. Wherever this course says Platforms/DesktopVK, use Platforms/DesktopGL. The .csproj there references MonoGame.Framework.DesktopGL instead of MonoGame.Framework.Native. Apply the version change in Step 2 to that line.

Now go into the new folder and run the empty game once. Stay in the LastPerimeter folder for the rest of the chapter:

bash
cd LastPerimeter
dotnet build
dotnet run --project Platforms/DesktopVK

Build the whole solution once before you build or run a single project. The platform projects use the Content Builder project, so NuGet must restore every project first. The first build downloads the MonoGame packages and can take a minute. A cornflower-blue window opens. Press Escape to close it. DesktopVK also prints Vulkan information to the terminal, which is normal. On Windows you can also run dotnet run --project Platforms/WindowsDX12.

The Content/ folder holds the Content Builder project. It stays in the solution but this course does not use it, because every visual and sound is made in code.

Step 2 - Set the MonoGame version in one place ​

The template sets MonoGameVersion to 3.8.* in Directory.Packages.props, but it hard-codes 3.8.6.1 in each platform .csproj and in Content/Content.csproj. So changing the props file alone does nothing. Do all three parts of this step.

First, replace the content of Directory.Packages.props in the solution folder:

xml
<Project>
  <PropertyGroup>
    <MonoGameVersion>3.8.6.1</MonoGameVersion>
  </PropertyGroup>
</Project>

Second, in each .csproj under Platforms/, change every MonoGame PackageReference so the version reads $(MonoGameVersion). In Platforms/DesktopVK/LastPerimeter.DesktopVK.csproj the package group becomes:

xml
  <ItemGroup>
    <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)" />
  </ItemGroup>

In Platforms/WindowsDX12/LastPerimeter.WindowsDX12.csproj it becomes:

xml
  <ItemGroup>
    <PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)" />
    <PackageReference Include="MonoGame.Runtime.Windows.DX12" Version="$(MonoGameVersion)" />
  </ItemGroup>

Nothing else in these two files changes.

Third, in Content/Content.csproj, two package references also carry the literal version. Change both to read $(MonoGameVersion). The other package references in that file keep their own versions:

xml
    <PackageReference Include="MonoGame.Framework.Content.Pipeline" Version="$(MonoGameVersion)" />
    <PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)">
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>

Every project, including the test project in Step 4, now takes its MonoGame version from one line.

Step 3 - Add the shared build settings ​

Create two new files in the solution folder, next to LastPerimeter.sln. MSBuild, the .NET build system, reads files with these exact names automatically for every project below that folder.

The first is Directory.Build.props. It turns on nullable reference checking and implicit usings. Implicit usings add the common using lines, such as System and System.Linq, to every file for you:

xml
<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

The second is Directory.Build.targets. It fixes a name clash. The WindowsDX12 project uses WinForms, a Windows desktop library. When implicit usings are 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 runs after the SDK adds those namespaces and removes them again:

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 only build DesktopVK the file does nothing, but keep it so the project matches every snapshot.

Step 4 - Create the test project ​

From the LastPerimeter folder, create the test project:

bash
dotnet new xunit -o Tests -n LastPerimeter.Tests

This creates Tests/LastPerimeter.Tests.csproj and Tests/UnitTest1.cs. Delete Tests/UnitTest1.cs. Then replace the whole content of Tests/LastPerimeter.Tests.csproj with the version below. The template file turns on implicit usings and nullable checking itself, which Directory.Build.props now does for every project. Our file pins the test package versions the snapshots use, compiles Source/, and references MonoGame:

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>

<Using Include="Xunit" /> saves a using Xunit; line in every test file. Now add the project to the solution and build everything:

bash
dotnet sln add Tests/LastPerimeter.Tests.csproj
dotnet build

The build succeeds. You may see a few CS8618 nullable warnings from the template Game1.cs. They disappear in Step 11, when Game1.cs is removed.

NOTE

The listings in the next steps leave out the using and namespace lines to save space. The namespace is LastPerimeter plus the folder name, for example LastPerimeter.Data for Source/Data. The table below lists the using lines each file needs. If a file will not compile, copy the whole file from the matching path in DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering in the course repository. The snapshot has these 10 code files, plus the Tests/LastPerimeter.Tests.csproj you made in Step 4.

Fileusing linesNamespace
Source/Data/Enums.csnoneLastPerimeter.Data
Source/Data/GameConfig.csMicrosoft.Xna.FrameworkLastPerimeter.Data
Source/Entities/PlayableWallPath.csMicrosoft.Xna.FrameworkLastPerimeter.Entities
Source/Entities/Player.csMicrosoft.Xna.Framework, LastPerimeter.DataLastPerimeter.Entities
Source/Game/GameLaunchOptions.csSystem.GlobalizationLastPerimeter.Game
Source/Game/LastPerimeterApp.csMicrosoft.Xna.Framework, Microsoft.Xna.Framework.Graphics, Microsoft.Xna.Framework.Input, LastPerimeter.Data, LastPerimeter.Entities, LastPerimeter.RenderingLastPerimeter.Game
Source/Rendering/ArenaRenderer.csMicrosoft.Xna.Framework, Microsoft.Xna.Framework.Graphics, LastPerimeter.EntitiesLastPerimeter.Rendering
Source/Rendering/PlayerRenderer.csMicrosoft.Xna.Framework, Microsoft.Xna.Framework.Graphics, LastPerimeter.EntitiesLastPerimeter.Rendering
Source/Rendering/PrimitiveDrawing.csMicrosoft.Xna.Framework, Microsoft.Xna.Framework.Graphics, LastPerimeter.EntitiesLastPerimeter.Rendering
Tests/Game/GameLaunchOptionsTests.csLastPerimeter.GameLastPerimeter.Tests.Game

Step 5 - Launch options: GameLaunchOptions ​

Create the folder Source/Game and the file Source/Game/GameLaunchOptions.cs. It is a small record that turns --smoke-test-seconds N or the LASTPERIMETER_SMOKE_TEST_SECONDS environment variable into an optional TimeSpan. The file starts with using System.Globalization; and the namespace is LastPerimeter.Game:

csharp
public sealed record GameLaunchOptions(TimeSpan? AutoExitAfter)
{
    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);
    }

    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);
    }
}

It is the first thing in the course with a unit test, because it is pure logic with no window.

Step 6 - Configuration: GameConfig ​

Create the folder Source/Data and the file Source/Data/GameConfig.cs. All tuning numbers live in this one immutable record. init properties give every value a default and let tests override just the ones they need (TestConfigFactory in chapter 02 does exactly that). ArenaBounds is computed from the window size, the margin, and the two HUD reserves; chapter 02 draws the layout.

csharp
public sealed record GameConfig
{
    public int ScreenWidth { get; init; } = 1024;
    public int ScreenHeight { get; init; } = 768;
    public int ArenaMargin { get; init; } = 50;
    public int HudTopReserve { get; init; } = 72;
    public int HudBottomReserve { get; init; } = 44;
    public int TileSize { get; init; } = 4;
    public float PlayerSpeed { get; init; } = 150f;
    public float MinimumTrailLength { get; init; } = 20f;
    public float EnemySpeed { get; init; } = 90f;
    public float EnemyRetargetIntervalSeconds { get; init; } = 0.65f;
    public float RespawnGraceSeconds { get; init; } = 1.2f;
    public float FuseWarningDelaySeconds { get; init; } = 1.0f;
    public float FuseTriggerDelaySeconds { get; init; } = 2.0f;
    public float FuseBurnSpeed { get; init; } = 60f;
    public float WinClaimPercentage { get; init; } = 75f;
    public Color PlayerColor { get; init; } = Color.Cyan;
    public Color TrailColor { get; init; } = Color.Yellow;
    public Color ClaimedColor { get; init; } = new Color(0, 160, 255, 180);
    public Color EnemyColor { get; init; } = Color.OrangeRed;

    public Rectangle ArenaBounds => new(
        ArenaMargin,
        ArenaMargin + HudTopReserve,
        ScreenWidth - (ArenaMargin * 2),
        ScreenHeight - (ArenaMargin * 2) - HudTopReserve - HudBottomReserve);
}

Most of those values belong to later chapters. Defining them now costs nothing and means no chapter ever has to hard-code a number.

Step 7 - Vocabulary: Enums.cs ​

Chapter 00 introduced TileState and TrailState. They live in Source/Data/Enums.cs, which you copy whole from the snapshot instead of typing. From the LastPerimeter folder, run the command for your shell.

In PowerShell:

powershell
Copy-Item "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Source/Data/Enums.cs" Source/Data/

In bash:

bash
cp "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Source/Data/Enums.cs" Source/Data/

The file holds Direction and two extension methods that later chapters lean on constantly:

csharp
public enum Direction { None, Up, Down, Left, Right, }

public static class DirectionExtensions
{
    public static Direction Opposite(this Direction direction) => direction switch
    {
        Direction.Up => Direction.Down,
        Direction.Down => Direction.Up,
        Direction.Left => Direction.Right,
        Direction.Right => Direction.Left,
        _ => Direction.None,
    };

    public static Vector2 ToVector(this Direction direction) => direction switch
    {
        Direction.Up => new Vector2(0f, -1f),
        Direction.Down => new Vector2(0f, 1f),
        Direction.Left => new Vector2(-1f, 0f),
        Direction.Right => new Vector2(1f, 0f),
        _ => Vector2.Zero,
    };
}

Note that Up is (0, -1), because screen Y grows downward. The file also declares the enums for later chapters (GameStatus, EnemyVariant, PowerupType, and so on), and they are harmless to have now. That is why the listing above shows only part of the file.

Step 8 - Two entities: Player and PlayableWallPath ​

Create the folder Source/Entities and the file Source/Entities/Player.cs. The chapter 01 Player is a plain data class (the trail reference arrives in chapter 05):

csharp
public sealed class Player
{
    public Vector2 Position { get; set; }
    public Direction CurrentDirection { get; set; } = Direction.None;
    public float Speed { get; set; }
    public float Radius { get; set; } = 6f;
    public int Lives { get; set; } = 3;
    public bool IsInvulnerable { get; set; }
}

PlayableWallPath (Source/Entities/PlayableWallPath.cs) is the star of chapter 04. In this chapter you only use it as a container of axis-aligned PathSegment values so the arena renderer has something to draw:

csharp
public readonly record struct PathSegment(Vector2 Start, Vector2 End) { /* Contains, Snap, DistanceSquared: chapter 04 */ }

public sealed class PlayableWallPath
{
    public PlayableWallPath(IEnumerable<PathSegment> segments)
    {
        _segments = segments.ToList();
        _nodes = _segments.SelectMany(segment => new[] { segment.Start, segment.End }).Distinct().ToList();
    }

    public IReadOnlyList<PathSegment> Segments => _segments;
    public IReadOnlyList<Vector2> Nodes => _nodes;
    // movement and snapping members: chapter 04
}

Do not type this one. The listing shows only part of the file, so copy the whole file from the snapshot. From the LastPerimeter folder, run the command for your shell.

In PowerShell:

powershell
Copy-Item "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Source/Entities/PlayableWallPath.cs" Source/Entities/

In bash:

bash
cp "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Source/Entities/PlayableWallPath.cs" Source/Entities/

The extra members do not hurt, and you will read them in chapter 04.

Step 9 - Drawing everything from one pixel ​

The single most reused resource in the project is a 1x1 white texture, created once in LoadContent:

csharp
private static Texture2D CreatePixel(GraphicsDevice graphicsDevice)
{
    Texture2D pixel = new(graphicsDevice, 1, 1);
    pixel.SetData([Color.White]);
    return pixel;
}

CreatePixel is a private static method of the LastPerimeterApp class. That class does not exist until Step 10, which tells you where the method goes, so only read it for now. SpriteBatch.Draw can stretch, tint, and rotate any texture, so one white pixel is enough for every primitive the game needs.

One 1x1 texture becomes a rectangle, a rotated line, and a scanline-filled circle

Create the folder Source/Rendering and the file Source/Rendering/PrimitiveDrawing.cs. It is the whole toolkit:

csharp
internal static class PrimitiveDrawing
{
    public static void DrawLine(SpriteBatch spriteBatch, Texture2D pixel, Vector2 start, Vector2 end, Color color, float thickness = 2f)
    {
        Vector2 edge = end - start;
        float angle = (float)Math.Atan2(edge.Y, edge.X);
        spriteBatch.Draw(pixel, new Rectangle((int)start.X, (int)start.Y, Math.Max(1, (int)edge.Length()), Math.Max(1, (int)thickness)), null, color, angle, Vector2.Zero, SpriteEffects.None, 0f);
    }

    public static void DrawSegment(SpriteBatch spriteBatch, Texture2D pixel, PathSegment segment, Color color, float thickness = 2f)
    {
        DrawLine(spriteBatch, pixel, segment.Start, segment.End, color, thickness);
    }

    public static void DrawFilledCircle(SpriteBatch spriteBatch, Texture2D pixel, Vector2 center, float radius, Color color)
    {
        int radiusInt = (int)Math.Ceiling(radius);
        for (int y = -radiusInt; y <= radiusInt; y++)
        {
            float width = (float)Math.Sqrt((radius * radius) - (y * y));
            spriteBatch.Draw(pixel, new Rectangle((int)(center.X - width), (int)(center.Y + y), Math.Max(1, (int)(width * 2)), 1), color);
        }
    }
}

Read DrawLine slowly: the destination rectangle is length x thickness, rotated by the angle of the edge vector around its top-left corner. DrawFilledCircle is the circle equation x^2 + y^2 = r^2 solved once per scanline.

The two renderers are tiny wrappers over that toolkit. Create two more files. Put the ArenaRenderer class in Source/Rendering/ArenaRenderer.cs and the PlayerRenderer class in Source/Rendering/PlayerRenderer.cs:

csharp
public sealed class ArenaRenderer
{
    public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Rectangle arenaBounds, PlayableWallPath playableWallPath)
    {
        spriteBatch.Draw(pixel, arenaBounds, Color.Black);

        foreach (PathSegment segment in playableWallPath.Segments)
        {
            PrimitiveDrawing.DrawSegment(spriteBatch, pixel, segment, Color.LightGray, 2f);
        }
    }
}

public sealed class PlayerRenderer
{
    public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Player player, Color color)
    {
        Color drawColor = player.IsInvulnerable ? Color.Lerp(color, Color.White, 0.45f) : color;
        PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, player.Position, player.Radius, drawColor);
    }
}

Renderers take the SpriteBatch and the pixel as parameters instead of owning them. That keeps them stateless, and keeps every GPU resource owned by the one class that knows when to dispose it.

Step 10 - The game class: LastPerimeterApp (chapter 01 version) ​

Create Source/Game/LastPerimeterApp.cs. This is the chapter's Game1. Read it against the lifecycle diagram; every method does exactly one lifecycle job.

csharp
public sealed class LastPerimeterApp : Microsoft.Xna.Framework.Game
{
    private readonly GraphicsDeviceManager _graphics;
    private readonly GameConfig _config = new();
    private readonly GameLaunchOptions _launchOptions;
    private SpriteBatch? _spriteBatch;
    private Texture2D? _pixel;
    private ArenaRenderer? _arenaRenderer;
    private PlayerRenderer? _playerRenderer;
    private PlayableWallPath? _playableWallPath;
    private Player? _player;

    public LastPerimeterApp(GameLaunchOptions? launchOptions = null)
    {
        _launchOptions = launchOptions ?? new GameLaunchOptions(null);
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
        _graphics.PreferredBackBufferWidth = _config.ScreenWidth;
        _graphics.PreferredBackBufferHeight = _config.ScreenHeight;
    }

    protected override void Initialize()
    {
        _playableWallPath = CreateRectanglePath(_config.ArenaBounds);
        _player = new Player
        {
            Position = new Vector2(_config.ArenaBounds.Center.X, _config.ArenaBounds.Center.Y),
            Speed = _config.PlayerSpeed,
        };

        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
        _pixel = CreatePixel(GraphicsDevice);
        _arenaRenderer = new ArenaRenderer();
        _playerRenderer = new PlayerRenderer();
    }

    protected override void Update(GameTime gameTime)
    {
        if (ShouldAutoExit(gameTime))
        {
            return;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.Escape) || GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        {
            Exit();
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        if (_spriteBatch is null || _pixel is null || _arenaRenderer is null || _playerRenderer is null || _playableWallPath is null || _player is null)
        {
            base.Draw(gameTime);
            return;
        }

        GraphicsDevice.Clear(Color.Black);
        _spriteBatch.Begin(samplerState: SamplerState.PointClamp);
        _arenaRenderer.Draw(_spriteBatch, _pixel, _config.ArenaBounds, _playableWallPath);
        _playerRenderer.Draw(_spriteBatch, _pixel, _player, _config.PlayerColor);
        _spriteBatch.End();

        base.Draw(gameTime);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _pixel?.Dispose();
            _spriteBatch?.Dispose();
        }

        base.Dispose(disposing);
    }

    private bool ShouldAutoExit(GameTime gameTime)
    {
        if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)
        {
            Exit();
            return true;
        }

        return false;
    }

    private static PlayableWallPath CreateRectanglePath(Rectangle bounds)
    {
        return new PlayableWallPath(
        [
            new PathSegment(new Vector2(bounds.Left, bounds.Top), new Vector2(bounds.Right, bounds.Top)),
            new PathSegment(new Vector2(bounds.Right, bounds.Top), new Vector2(bounds.Right, bounds.Bottom)),
            new PathSegment(new Vector2(bounds.Right, bounds.Bottom), new Vector2(bounds.Left, bounds.Bottom)),
            new PathSegment(new Vector2(bounds.Left, bounds.Bottom), new Vector2(bounds.Left, bounds.Top)),
        ]);
    }
}

The listing above leaves out CreatePixel. Add the CreatePixel method from Step 9 to this class now, because LoadContent calls it. It can go anywhere inside the class, and the bottom is as good a place as any.

Points to dwell on:

  • the fields are nullable (SpriteBatch?) because they cannot exist until LoadContent; the is null guard in Draw is the honest way to say so with nullable reference types enabled,
  • Draw has a fixed shape that every later chapter keeps: clear, begin, draw the world back to front, end,
  • SamplerState.PointClamp keeps stretched pixels crisp instead of blurry,
  • in this chapter the arena outline is hand-built as four PathSegment values around _config.ArenaBounds; deriving it from real arena state is chapter 04's job,
  • Escape closes the window here and in every chapter up to 12; from chapter 12 it opens the pause menu instead.

Step 11 - Remove Game1 and switch the host ​

Delete Source/Game1.cs. Then replace the whole content of Platforms/DesktopVK/Program.cs and Platforms/WindowsDX12/Program.cs with the five-line host, the same text in both files:

csharp
using LastPerimeter.Game;

GameLaunchOptions launchOptions = GameLaunchOptions.Parse(args, Environment.GetEnvironmentVariable("LASTPERIMETER_SMOKE_TEST_SECONDS"));

using LastPerimeterApp game = new(launchOptions);
game.Run();

The template Program.cs created Game1 and ran it. This one creates LastPerimeterApp with the parsed launch options. With the DesktopGL fallback, change Platforms/DesktopGL/Program.cs instead.

Step 12 - The first tests ​

The tests live in Tests/Game/GameLaunchOptionsTests.cs, which you copy whole from the snapshot. From the LastPerimeter folder, run the commands for your shell. The first one creates the Tests/Game folder.

In PowerShell:

powershell
New-Item -ItemType Directory -Force Tests/Game
Copy-Item "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Tests/Game/GameLaunchOptionsTests.cs" Tests/Game/

In bash:

bash
mkdir -p Tests/Game
cp "<course-repo>/DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering/Tests/Game/GameLaunchOptionsTests.cs" Tests/Game/

The file starts with using LastPerimeter.Game;, its namespace is LastPerimeter.Tests.Game, and it holds three facts against GameLaunchOptions.Parse. This is the first:

csharp
[Fact]
public void Parse_UsesSmokeTestArgument_WhenProvided()
{
    GameLaunchOptions options = GameLaunchOptions.Parse(["--smoke-test-seconds", "1.5"]);

    Assert.Equal(TimeSpan.FromSeconds(1.5), options.AutoExitAfter);
}

The other two check the environment-variable fallback and that a missing value throws. Small as they are, they establish the habit: anything with no window gets a test.

Step 13 - Build, test, run ​

Run these commands from the LastPerimeter folder:

bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVK

dotnet test reports 3 passing tests. The run command opens a window with the arena frame and the player dot. Press Escape to close it. On Windows you can also run dotnet run --project Platforms/WindowsDX12.

To check that the launch options work, run this:

bash
dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 2

The bare -- tells dotnet run to stop reading its own options and to pass everything after it to the game. The game then exits by itself after two seconds. To read the exit code, run $LASTEXITCODE in PowerShell or echo $? in bash straight afterwards. A 0 means the game closed cleanly.

Chapter snapshot ​

The matching buildable project is DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering. It is standalone: run dotnet build and dotnet test from that folder. At this point one test file exists, Tests/Game/GameLaunchOptionsTests.cs, and dotnet test should report 3 passing tests (smoke-test argument parsing).

Checkpoint ​

Verify the chapter before moving on:

  1. In your LastPerimeter folder, run dotnet test: 3 tests pass. If yours differ, compare your files with the snapshot in DOCUMENTATION/LastPerimeter-Source/01-New-Project-And-Basic-Rendering.
  2. Run dotnet run --project Platforms/DesktopVK: a 1024 x 768 window opens showing the arena frame and a cyan player dot at the centre, as in the screenshot at the top of this chapter. Press Escape and the window closes.
  3. Run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 2: the game opens and exits by itself after two seconds.
  4. Open Source/Data/GameConfig.cs and change the PlayerColor default from Color.Cyan to Color.Magenta. Run the game again and confirm the dot changes colour. Then change it back to Color.Cyan.

What you should have now ​

By the end of this chapter you have:

  • a running game window,
  • a visible arena,
  • a visible player marker,
  • a configurable GameConfig.

Common mistakes ​

  • creating textures or a SpriteBatch every frame instead of once in LoadContent,
  • putting game logic in Draw or drawing in Update,
  • forgetting base.Update / base.Draw, which stops MonoGame's own bookkeeping,
  • calling SpriteBatch.Draw outside a Begin / End pair (MonoGame throws),
  • touching GraphicsDevice in the constructor, before the device exists,
  • hard-coding dimensions instead of reading GameConfig,
  • assuming a stable frame rate (chapter 03 shows why that breaks movement).

Questions to think about ​

  • why a single pixel texture can support most 2D primitives,
  • why screen space and world space are identical in this project, and what a camera would change,
  • why positions should still use Vector2 even in a tile-aware game.