Mini Project: Arena Survivor
This project puts the whole course together in one small game: Arena Survivor, a one-dimensional arena where enemies pour in from both edges and the player fights back automatically. It's tiny on purpose, but it has everything a real game has: entities, a seeded spawner, a fixed-timestep loop, combat with events, a game-flow state machine with pausing, buffered input, and a high-score table saved as JSON.
You'll build it in four steps. Each step is a complete, runnable program that extends the previous one, so experiment at every stage: change the seed, the spawn rate or the input script and run it again.
| Step | Adds | Lessons used |
|---|---|---|
| 1 | arena, entities, seeded spawner, a text renderer | Entities & Components, Number Guessing |
| 2 | combat, health, score, events | Game Events, Turn-Based Combat |
| 3 | frame loop with accumulator, game-flow state machine, pause, buffered input | Fixed Timestep, State Machines, Pausing & Time Scale |
| 4 | a high-score table saved to and loaded from JSON | Save & Load with JSON |
Note: A real version would read the keyboard and draw sprites. Here the "keyboard" is a script of key presses and the "screen" is one line of text per snapshot, so every run is deterministic and the output can be checked. The structure is exactly what you'd write in an engine.
Step 1: The arena and its enemies
The arena runs from x = −10 to 10, with the player (@) in the middle. A spawner adds an enemy at a random edge every 8 ticks, using a seeded generator so the same seed always produces the same wave. Enemies walk one cell toward the player every 3 ticks and stop when they're adjacent. Render draws the world as text: e is an enemy, E several in one cell.
using System;
using System.Collections.Generic;
var world = new World(seed: 5);
for (int tick = 1; tick <= 36; tick++)
{
world.Step(tick);
if (tick % 4 == 0) Console.WriteLine(quot;t{tick:00} {world.Render()} enemies: {world.Enemies.Count}");
}
class Enemy { public int X; }
class World
{
public const int Left = -10, Right = 10;
public int PlayerX = 0;
public readonly List<Enemy> Enemies = new();
readonly Random rng;
public World(int seed) => rng = new Random(seed);
public void Step(int tick)
{
if (tick % 8 == 1) // spawner: every 8 ticks, at a random edge
Enemies.Add(new Enemy { X = rng.Next(2) == 0 ? Left : Right });
if (tick % 3 == 0) // enemies walk one cell every 3 ticks
foreach (var e in Enemies)
if (Math.Abs(e.X - PlayerX) > 1) e.X += Math.Sign(PlayerX - e.X);
}
public string Render()
{
var cells = new char[Right - Left + 1];
Array.Fill(cells, '.');
foreach (var e in Enemies)
cells[e.X - Left] = cells[e.X - Left] == '.' ? 'e' : 'E'; // E = several enemies
cells[PlayerX - Left] = '@';
return "|" + new string(cells) + "|";
}
}t04 |.e........@..........| enemies: 1
t08 |..e.......@..........| enemies: 1
t12 |..e.e.....@..........| enemies: 2
t16 |...e.e....@..........| enemies: 2
t20 |.e..e.e...@..........| enemies: 3
t24 |...e..e.e.@..........| enemies: 3
t28 |....e..e.e@........e.| enemies: 4
t32 |.....e..ee@.......e..| enemies: 4
t36 |..e....e.E@.....e....| enemies: 5
Step only changes state and Render only reads it: the update/render split from Input, Update, Render. Change seed: 5 and the spawn pattern changes, but it's the same every time you run it with that seed.
Step 2: Combat and events
Now everyone fights. The player automatically attacks the first enemy in reach, with a 3-tick cooldown; enemies have 2 HP. An enemy that reaches the player winds up for 3 ticks, then hits for 1 damage every 5 ticks. After tick 40 the spawner speeds up from every 8 to every 5 ticks, the difficulty ramp.
World raises two events, EnemyKilled and PlayerHurt. The code at the top subscribes to them to print a log; in an engine the same events would drive sounds, screen shake and the HUD without World knowing any of those exist.
using System;
using System.Collections.Generic;
using System.Linq;
var world = new World(seed: 5);
int tick = 0;
world.EnemyKilled += e => Console.WriteLine(quot;t{tick:00} enemy defeated at x={e.X}, score {world.Score}");
world.PlayerHurt += hp => Console.WriteLine(quot;t{tick:00} player hit! {hp} HP left");
while (world.PlayerAlive && tick < 100)
{
tick++;
world.Step(tick, moveX: 0);
if (tick % 10 == 0) Console.WriteLine(quot;t{tick:00} {world.Render()} hp {world.PlayerHp} score {world.Score}");
}
Console.WriteLine(world.PlayerAlive ? quot;Survived {tick} ticks." : quot;Game over at tick {tick}, score {world.Score}.");
class Enemy { public int X; public int Hp = 2; public int AttackCooldown = 3; }
class World
{
public const int Left = -10, Right = 10;
public int PlayerX, PlayerHp = 5, Score;
public bool PlayerAlive => PlayerHp > 0;
public readonly List<Enemy> Enemies = new();
public event Action<Enemy> EnemyKilled;
public event Action<int> PlayerHurt;
readonly Random rng;
int attackCooldown;
public World(int seed) => rng = new Random(seed);
public void Step(int tick, int moveX)
{
// 1. player movement
PlayerX = Math.Clamp(PlayerX + moveX, Left, Right);
// 2. spawner: every 8 ticks at first, every 5 after tick 40
int interval = tick <= 40 ? 8 : 5;
if (tick % interval == 1) Enemies.Add(new Enemy { X = rng.Next(2) == 0 ? Left : Right });
// 3. enemy movement
if (tick % 3 == 0)
foreach (var e in Enemies)
if (Math.Abs(e.X - PlayerX) > 1) e.X += Math.Sign(PlayerX - e.X);
// 4. player auto-attack: the first enemy in reach, every 3 ticks
if (attackCooldown > 0) attackCooldown--;
var target = Enemies.FirstOrDefault(e => Math.Abs(e.X - PlayerX) <= 1);
if (target != null && attackCooldown == 0)
{
attackCooldown = 3;
if (--target.Hp == 0)
{
Enemies.Remove(target);
Score += 10;
EnemyKilled?.Invoke(target);
}
}
// 5. enemy attacks: adjacent enemies wind up, then hit every 5 ticks
foreach (var e in Enemies.Where(e => Math.Abs(e.X - PlayerX) <= 1))
{
if (e.AttackCooldown > 0) { e.AttackCooldown--; continue; }
e.AttackCooldown = 5;
PlayerHp = Math.Max(0, PlayerHp - 1);
PlayerHurt?.Invoke(PlayerHp);
if (!PlayerAlive) break;
}
}
public string Render()
{
var cells = new char[Right - Left + 1];
Array.Fill(cells, '.');
foreach (var e in Enemies)
cells[e.X - Left] = cells[e.X - Left] == '.' ? 'e' : 'E';
cells[PlayerX - Left] = '@';
return "|" + new string(cells) + "|";
}
}t10 |.e.e......@..........| hp 5 score 0
t20 |.e..e.e...@..........| hp 5 score 0
t30 enemy defeated at x=-1, score 10
t30 |.....e..e.@.......e..| hp 5 score 10
t36 enemy defeated at x=-1, score 20
t40 |...e....e.@....e.....| hp 5 score 20
t45 enemy defeated at x=-1, score 30
t50 |.e....e...@.e....e...| hp 5 score 30
t54 enemy defeated at x=1, score 40
t60 enemy defeated at x=-1, score 50
t60 |.....e....@..e..e.e..| hp 5 score 50
t69 enemy defeated at x=1, score 60
t70 |...e....e.@..e.e..e..| hp 5 score 60
t75 enemy defeated at x=-1, score 70
t78 player hit! 4 HP left
t80 |.e.e..e...@ee..e.....| hp 4 score 70
t81 enemy defeated at x=1, score 80
t84 player hit! 3 HP left
t87 enemy defeated at x=1, score 90
t90 player hit! 2 HP left
t90 |..e.ee.e.e@e.........| hp 2 score 90
t93 enemy defeated at x=-1, score 100
t93 player hit! 1 HP left
t99 enemy defeated at x=1, score 110
t99 player hit! 0 HP left
Game over at tick 99, score 110.
Read the log as a difficulty curve: for the first 70 ticks the player keeps up; once the faster spawner fills the arena, enemies reach the player on both sides and the hits start. Change PlayerHp, the attack cooldown or the spawn intervals and watch how long the player survives. That's balancing.
Step 3: Game flow, the frame loop and pausing
Step 2 called Step directly. A real game runs frames of uneven length and converts them into fixed ticks with an accumulator. This step adds that loop, plus:
- a game-flow state machine (
Title → Playing ⇄ Paused,Playing → GameOver) with a transition table; - input read every frame: flow commands go to the state machine immediately, movement is buffered and consumed by the next fixed tick (so a key press between ticks is never lost);
- pausing by not feeding the accumulator while not Playing, so game time stops while real time goes on.
The World class is unchanged from step 2.
using System;
using System.Collections.Generic;
using System.Linq;
// Input script: frame number -> what the player pressed on that frame.
var pressed = new Dictionary<int, string>
{
[30] = "start", [240] = "pause", [330] = "resume",
[420] = "right", [425] = "right", [430] = "right", [600] = "left", [606] = "left",
};
int[] framePattern = { 16, 17, 17 }; // about 60 FPS
const int TickMs = 100; // fixed simulation step: 10 ticks per second
var flow = new GameFlow();
var world = new World(seed: 5);
int tick = 0, accumulatorMs = 0, realMs = 0, bufferedMove = 0;
world.EnemyKilled += e => Console.WriteLine(quot;t{tick:00} enemy defeated, score {world.Score}");
world.PlayerHurt += hp => Console.WriteLine(quot;t{tick:00} player hit! {hp} HP left");
for (int frame = 0; flow.State != GameState.GameOver && frame < 2000; frame++)
{
int frameMs = framePattern[frame % 3];
realMs += frameMs;
// 1. input: every frame. Game-flow commands go to the state machine,
// movement is buffered until the next fixed tick.
if (pressed.TryGetValue(frame, out string key))
{
if (key is "left" or "right") bufferedMove = key == "left" ? -1 : 1;
else if (flow.Handle(key)) Console.WriteLine(quot;[{realMs,5} ms] {flow.State}");
}
// 2. update: fixed ticks, only while Playing (pause = time scale 0)
if (flow.State != GameState.Playing) continue;
accumulatorMs += frameMs;
while (accumulatorMs >= TickMs && world.PlayerAlive)
{
accumulatorMs -= TickMs;
tick++;
world.Step(tick, bufferedMove);
bufferedMove = 0;
if (tick % 20 == 0) Console.WriteLine(quot;t{tick:00} {world.Render()} hp {world.PlayerHp} score {world.Score}"); // 3. render (sampled)
}
if (!world.PlayerAlive && flow.Handle("die")) Console.WriteLine(quot;[{realMs,5} ms] {flow.State}");
}
Console.WriteLine(quot;Final score {world.Score}, survived {tick / 10.0:F1} s of game time in {realMs / 1000.0:F1} s of real time.");
enum GameState { Title, Playing, Paused, GameOver }
class GameFlow
{
static readonly Dictionary<(GameState, string), GameState> Transitions = new()
{
[(GameState.Title, "start")] = GameState.Playing,
[(GameState.Playing, "pause")] = GameState.Paused,
[(GameState.Paused, "resume")] = GameState.Playing,
[(GameState.Playing, "die")] = GameState.GameOver,
};
public GameState State { get; private set; } = GameState.Title;
public bool Handle(string e)
{
if (!Transitions.TryGetValue((State, e), out var next)) return false;
State = next;
return true;
}
}
class Enemy { public int X; public int Hp = 2; public int AttackCooldown = 3; }
class World
{
public const int Left = -10, Right = 10;
public int PlayerX, PlayerHp = 5, Score;
public bool PlayerAlive => PlayerHp > 0;
public readonly List<Enemy> Enemies = new();
public event Action<Enemy> EnemyKilled;
public event Action<int> PlayerHurt;
readonly Random rng;
int attackCooldown;
public World(int seed) => rng = new Random(seed);
public void Step(int tick, int moveX)
{
// 1. player movement
PlayerX = Math.Clamp(PlayerX + moveX, Left, Right);
// 2. spawner: every 8 ticks at first, every 5 after tick 40
int interval = tick <= 40 ? 8 : 5;
if (tick % interval == 1) Enemies.Add(new Enemy { X = rng.Next(2) == 0 ? Left : Right });
// 3. enemy movement
if (tick % 3 == 0)
foreach (var e in Enemies)
if (Math.Abs(e.X - PlayerX) > 1) e.X += Math.Sign(PlayerX - e.X);
// 4. player auto-attack: the first enemy in reach, every 3 ticks
if (attackCooldown > 0) attackCooldown--;
var target = Enemies.FirstOrDefault(e => Math.Abs(e.X - PlayerX) <= 1);
if (target != null && attackCooldown == 0)
{
attackCooldown = 3;
if (--target.Hp == 0)
{
Enemies.Remove(target);
Score += 10;
EnemyKilled?.Invoke(target);
}
}
// 5. enemy attacks: adjacent enemies wind up, then hit every 5 ticks
foreach (var e in Enemies.Where(e => Math.Abs(e.X - PlayerX) <= 1))
{
if (e.AttackCooldown > 0) { e.AttackCooldown--; continue; }
e.AttackCooldown = 5;
PlayerHp = Math.Max(0, PlayerHp - 1);
PlayerHurt?.Invoke(PlayerHp);
if (!PlayerAlive) break;
}
}
public string Render()
{
var cells = new char[Right - Left + 1];
Array.Fill(cells, '.');
foreach (var e in Enemies)
cells[e.X - Left] = cells[e.X - Left] == '.' ? 'e' : 'E';
cells[PlayerX - Left] = '@';
return "|" + new string(cells) + "|";
}
}[ 516 ms] Playing
t20 |.e..e.e...@..........| hp 5 score 0
t30 enemy defeated, score 10
[ 4016 ms] Paused
[ 5516 ms] Playing
t36 enemy defeated, score 20
t40 |...e....e.@....e.....| hp 5 score 20
t45 enemy defeated, score 30
t54 enemy defeated, score 40
t60 |.....e....e.@e..e.e..| hp 5 score 40
t63 player hit! 4 HP left
t66 enemy defeated, score 50
t69 enemy defeated, score 60
t72 player hit! 3 HP left
t75 enemy defeated, score 70
t78 player hit! 2 HP left
t80 |.e.e..e....e@e.e.....| hp 2 score 70
t81 enemy defeated, score 80
t86 player hit! 1 HP left
t87 enemy defeated, score 90
t90 player hit! 0 HP left
[11000 ms] GameOver
Final score 90, survived 9.0 s of game time in 11.0 s of real time.
Things to notice:
- The game starts at 516 ms (frame 30), when "start" is pressed; until then the world doesn't exist in game time.
- During the pause (4016–5516 ms) no ticks run, so 11.0 s of real time contain only 9.0 s of game time.
- The player steps right three times at frame 420 (about 7 s). Compare with step 2: moving put the player between two groups and the run ended earlier, at tick 90 instead of 99. Try other key presses in
pressedand see if you can beat 110 points.
Step 4: High scores, saved as JSON
Finally, the game remembers the best runs. The high-score table keeps the top 3, loads from JSON (falling back to an empty table on a first launch or a corrupt file), and saves back to JSON. The run from step 3 scored 90, so it's submitted as "YOU", along with two other players' runs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
// What the save file contained before this run (null = first launch).
string previousSave = """{"Version":1,"Scores":[{"Name":"ADA","Score":120,"Seconds":10.4},{"Name":"LIN","Score":60,"Seconds":7.2}]}""";
var table = HighScores.Load(previousSave);
Console.WriteLine("Before:");
table.Print();
bool madeTable = table.Submit(new Entry("YOU", 90, 9.0));
bool rejected = !table.Submit(new Entry("BOB", 10, 3.1));
table.Submit(new Entry("KIM", 130, 11.8));
Console.WriteLine(quot;YOU made the table: {madeTable}; BOB rejected: {rejected}");
Console.WriteLine("After:");
table.Print();
string json = table.Save();
Console.WriteLine(json);
var reloaded = HighScores.Load(json);
Console.WriteLine(quot;Reloaded {reloaded.Entries.Count} entries, best: {reloaded.Entries[0].Name} {reloaded.Entries[0].Score}");
Console.WriteLine(quot;First launch: {HighScores.Load(null).Entries.Count} entries; corrupt file: {HighScores.Load("{oops").Entries.Count} entries");
record Entry(string Name, int Score, double Seconds);
class HighScores
{
const int Capacity = 3;
public int Version { get; set; } = 1;
public List<Entry> Entries { get; set; } = new();
public static HighScores Load(string json)
{
if (json is null) return new HighScores();
try
{
using var doc = JsonDocument.Parse(json);
var table = new HighScores();
foreach (var e in doc.RootElement.GetProperty("Scores").EnumerateArray())
table.Submit(new Entry(e.GetProperty("Name").GetString(), e.GetProperty("Score").GetInt32(), e.GetProperty("Seconds").GetDouble()));
return table;
}
catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException)
{
return new HighScores(); // never crash on a bad save: start a fresh table
}
}
// Adds the entry if it belongs in the top 3. Returns true if it was kept.
public bool Submit(Entry entry)
{
Entries.Add(entry);
Entries = Entries.OrderByDescending(e => e.Score).ThenBy(e => e.Seconds).Take(Capacity).ToList();
return Entries.Contains(entry);
}
public string Save() => JsonSerializer.Serialize(new { Version, Scores = Entries });
public void Print()
{
for (int i = 0; i < Entries.Count; i++)
Console.WriteLine(quot; {i + 1}. {Entries[i].Name,-4} {Entries[i].Score,4} ({Entries[i].Seconds:F1} s)");
}
}Before:
1. ADA 120 (10.4 s)
2. LIN 60 (7.2 s)
YOU made the table: True; BOB rejected: True
After:
1. KIM 130 (11.8 s)
2. ADA 120 (10.4 s)
3. YOU 90 (9.0 s)
{"Version":1,"Scores":[{"Name":"KIM","Score":130,"Seconds":11.8},{"Name":"ADA","Score":120,"Seconds":10.4},{"Name":"YOU","Score":90,"Seconds":9}]}
Reloaded 3 entries, best: KIM 130
First launch: 0 entries; corrupt file: 0 entries
The save code follows the rules from the save/load lesson: a Version field for future migrations, validation on load (a malformed file gives an empty table instead of a crash), and only plain data (names, scores, times) in the file. In a real game, Save()'s string would be written to Application.persistentDataPath, user:// or Saved/SaveGames, using a temporary file and a rename.
Ideas to extend it
- Two dimensions. Replace
int Xwith a position(X, Y)on a grid and move enemies with the vector maths from Math for Games. - Enemy types. Add a fast enemy with 1 HP and a slow tank with 4 HP, as components or a small
EnemyDeftable (data, not new classes). - A boss. At tick 60, spawn the state-machine boss from A State-Machine Boss.
- Juice. In the log, print
*SHAKE*when the player is hit and+10pop-ups on kills: the hooks are already there as events. - Replays. Record
pressedand the seed into the high-score entry; replaying it must reproduce the same score (see Field Notes: Building). - Make it real. Port it to a canvas game in 2D Games with JavaScript & Canvas, or to Unity, Godot or Unreal. The
Worldclass barely changes; only input and rendering do.
Test yourself
In step 3, why is movement input buffered instead of applied immediately?
- Buffering is faster
- Input is read every frame but the world only changes in fixed ticks, so a press between ticks must wait for the next tick
- C# requires it
- To make the player slower
How does step 3 pause the game?
- It stops the frame loop
- It stops adding frame time to the accumulator while the state isn't Playing
- It sets every enemy's speed to 0
- It saves and reloads the game
What happens when the high-score file is corrupt?
- The game crashes
- Load returns an empty table instead of throwing
- The scores are guessed
- The file is ignored forever