Game Dev Exercises
Time to practise the fundamentals. Each exercise has a starter playground that already compiles and runs. Replace the TODO parts, press ▶ Run, and compare your result with the expected output in the task. When you're done, or stuck, open the solution.
Tip: There is always more than one correct solution. If your output matches, your answer is right.
Exercise 1: Frame-rate independent movement
The ship below moves 3 units per frame, so it travels further on faster machines. Change the update so the ship moves 90 units per second at every frame rate. Expected output:
30 FPS: 90.0 units after 1 s
60 FPS: 90.0 units after 1 s
120 FPS: 90.0 units after 1 susing System;
foreach (int fps in new[] { 30, 60, 120 })
{
double dt = 1.0 / fps;
double x = 0;
for (int frame = 0; frame < fps; frame++)
{
x += 3; // TODO: use a speed in units per second and dt
}
Console.WriteLine(quot;{fps,3} FPS: {x:F1} units after 1 s");
} 30 FPS: 90.0 units after 1 s
60 FPS: 180.0 units after 1 s
120 FPS: 360.0 units after 1 s
Show solution
using System;
const double speed = 90; // units per second
foreach (int fps in new[] { 30, 60, 120 })
{
double dt = 1.0 / fps;
double x = 0;
for (int frame = 0; frame < fps; frame++)
x += speed * dt;
Console.WriteLine(quot;{fps,3} FPS: {x:F1} units after 1 s");
}Exercise 2: Count the fixed steps
The fixed step is 25 ms. For each frame, add its time to an accumulator, run as many 25 ms steps as fit, and print the number of steps and the leftover. Expected output:
frame 10 ms: 0 steps, leftover 10
frame 30 ms: 1 steps, leftover 15
frame 60 ms: 3 steps, leftover 0
frame 20 ms: 0 steps, leftover 20
frame 5 ms: 1 steps, leftover 0using System;
int[] frames = { 10, 30, 60, 20, 5 };
const int step = 25;
int accumulator = 0;
foreach (int ms in frames)
{
int steps = 0;
// TODO: add ms to the accumulator and consume whole steps
Console.WriteLine(quot;frame {ms,2} ms: {steps} steps, leftover {accumulator}");
}frame 10 ms: 0 steps, leftover 0
frame 30 ms: 0 steps, leftover 0
frame 60 ms: 0 steps, leftover 0
frame 20 ms: 0 steps, leftover 0
frame 5 ms: 0 steps, leftover 0
Show solution
using System;
int[] frames = { 10, 30, 60, 20, 5 };
const int step = 25;
int accumulator = 0;
foreach (int ms in frames)
{
int steps = 0;
accumulator += ms;
while (accumulator >= step)
{
accumulator -= step;
steps++;
}
Console.WriteLine(quot;frame {ms,2} ms: {steps} steps, leftover {accumulator}");
}Exercise 3: A cooldown timer
Finish the Cooldown class: TryUse() returns true and restarts the timer when the ability is ready, otherwise false; Tick(dt) counts down. The dash has a 0.5 s cooldown; the player presses dash every 0.2 s. Expected output:
t=0.0 dash!
t=0.2 not ready
t=0.4 not ready
t=0.6 dash!
t=0.8 not ready
t=1.0 not ready
t=1.2 dash!using System;
var dash = new Cooldown(0.5);
for (int i = 0; i <= 6; i++)
{
double t = i * 0.2;
Console.WriteLine(quot;t={t:F1} {(dash.TryUse() ? "dash!" : "not ready")}");
dash.Tick(0.2);
}
class Cooldown
{
readonly double duration;
double remaining;
public Cooldown(double duration) => this.duration = duration;
public bool TryUse()
{
// TODO: if remaining <= 0, restart the timer and return true
return false;
}
public void Tick(double dt)
{
// TODO: count down, never below zero
}
}t=0.0 not ready
t=0.2 not ready
t=0.4 not ready
t=0.6 not ready
t=0.8 not ready
t=1.0 not ready
t=1.2 not ready
Show solution
class Cooldown
{
readonly double duration;
double remaining;
public Cooldown(double duration) => this.duration = duration;
public bool TryUse()
{
if (remaining > 0) return false;
remaining = duration;
return true;
}
// Math.Max stops the timer at exactly 0, so leftover floating-point dust can't keep it "almost ready".
public void Tick(double dt) => remaining = Math.Max(0, remaining - dt);
}Exercise 4: Round state machine
A multiplayer round goes Warmup → Countdown → Live → Results → Warmup. Fill in the transition table so the events below produce the expected output. Every event not in the table must be ignored. Expected output:
Warmup --ready--> Countdown
Countdown --go--> Live
Live ignores 'ready'
Live --timeUp--> Results
Results --next--> Warmupusing System;
using System.Collections.Generic;
var table = new Dictionary<(Round, string), Round>
{
[(Round.Warmup, "ready")] = Round.Countdown,
// TODO: add the other three transitions
};
var state = Round.Warmup;
foreach (string e in new[] { "ready", "go", "ready", "timeUp", "next" })
{
if (table.TryGetValue((state, e), out var next))
{
Console.WriteLine(quot;{state,-9} --{e}--> {next}");
state = next;
}
else Console.WriteLine(quot;{state,-9} ignores '{e}'");
}
enum Round { Warmup, Countdown, Live, Results }Warmup --ready--> Countdown
Countdown ignores 'go'
Countdown ignores 'ready'
Countdown ignores 'timeUp'
Countdown ignores 'next'
Show solution
var table = new Dictionary<(Round, string), Round>
{
[(Round.Warmup, "ready")] = Round.Countdown,
[(Round.Countdown, "go")] = Round.Live,
[(Round.Live, "timeUp")] = Round.Results,
[(Round.Results, "next")] = Round.Warmup,
};Exercise 5: Weight-limited backpack
Change Add so an item is refused when it would push the total weight over MaxWeight (20). It should return true if the item was added. Expected output:
sword (8): added, total 8
shield (9): added, total 17
potion (1): added, total 18
armor (12): too heavy, total 18
potion (1): added, total 19using System;
using System.Collections.Generic;
var bag = new Backpack();
foreach (var (name, weight) in new[] { ("sword", 8), ("shield", 9), ("potion", 1), ("armor", 12), ("potion", 1) })
Console.WriteLine(quot;{name} ({weight}): {(bag.Add(name, weight) ? "added" : "too heavy")}, total {bag.Weight}");
class Backpack
{
public const int MaxWeight = 20;
readonly List<(string Name, int Weight)> items = new();
public int Weight { get; private set; }
public bool Add(string name, int weight)
{
// TODO: refuse the item if it would exceed MaxWeight
items.Add((name, weight));
Weight += weight;
return true;
}
}sword (8): added, total 8
shield (9): added, total 17
potion (1): added, total 18
armor (12): added, total 30
potion (1): added, total 31
Show solution
public bool Add(string name, int weight)
{
if (Weight + weight > MaxWeight) return false;
items.Add((name, weight));
Weight += weight;
return true;
}Exercise 6: Migrate a save file
Version 1 saves stored "Hp"; version 2 renamed it to "Health" and added "MaxHealth" (default 100). Write the v1 → v2 step so both saves load. Expected output:
{"Version":2,"Name":"Ada","Health":42,"MaxHealth":100}
{"Version":2,"Name":"Lin","Health":80,"MaxHealth":120}using System;
using System.Text.Json.Nodes;
Console.WriteLine(Migrate("""{"Version":1,"Name":"Ada","Hp":42}"""));
Console.WriteLine(Migrate("""{"Version":2,"Name":"Lin","Health":80,"MaxHealth":120}"""));
static string Migrate(string json)
{
var data = JsonNode.Parse(json)!.AsObject();
int version = (int)data["Version"]!;
if (version == 1)
{
// TODO: move "Hp" to "Health", add "MaxHealth" = 100, set version to 2
}
data["Version"] = version;
return data.ToJsonString();
}{"Version":1,"Name":"Ada","Hp":42}
{"Version":2,"Name":"Lin","Health":80,"MaxHealth":120}
Show solution
if (version == 1)
{
int hp = (int)data["Hp"]!;
data.Remove("Hp");
data["Health"] = hp;
data["MaxHealth"] = 100;
version = 2;
}Exercise 7: Frame-rate independent smoothing (JavaScript)
smooth moves a value toward a target by a fixed 20% per frame, which depends on the frame rate. Rewrite it to use 1 - Math.exp(-rate * dt) with rate = 8, so both runs end at the same value. Expected output:
30 FPS after 0.5 s: 98.2
60 FPS after 0.5 s: 98.2function smooth(current, target, dt) {
return current + (target - current) * 0.2; // TODO: frame-rate independent factor
}
for (const fps of [30, 60]) {
let value = 0;
for (let i = 0; i < fps / 2; i++) value = smooth(value, 100, 1 / fps);
console.log(`${fps} FPS after 0.5 s: ${value.toFixed(1)}`);
}30 FPS after 0.5 s: 96.5
60 FPS after 0.5 s: 99.9
Show solution
function smooth(current, target, dt, rate = 8) {
return current + (target - current) * (1 - Math.exp(-rate * dt));
}Test yourself
In Exercise 2, a 60 ms frame arrives with 15 ms in the accumulator. How many 25 ms steps run?
- 2
- 3
- 4
- 1
Why does the Cooldown's Tick clamp the remaining time with Math.Max(0, …)?
- To make the cooldown shorter
- So the timer stops at exactly 0 instead of going negative or keeping floating-point leftovers
- C# can't store negative doubles
- It's faster