DEV LOG

The Engine Behind the Games

Every game on this site is only a few hundred lines of Rust. Not because they're simple — because of the engine underneath them.

Why build an engine?

The hard part of making a game isn't the game — it's everything around it: how entities are represented, how behaviour is organised, how state is shared, how any of it gets tested. I spent the hours (many, many hours) thinking that through once, in a small ECS-style engine, so that every game after it became cheap to build.

~400lines of engine
300–400lines per game
120unit tests

Snake, Pong, Breakout and Space Invaders were each built in a sitting — complete with rendering, UI, restart flow and a test suite — because the engine already answers the structural questions. Below are the ideas it's built on.

1. Entities are just data

There is no class hierarchy. An entity is a rectangle plus a set of optional components — have them or don't. A paddle is an entity with a render colour. A ball is the same thing plus physics. Composition over inheritance, assembled with a builder:

let ball = Entity::new(rect)
    .with_tag(Tag::Ball)
    .with_render(WHITE)
    .with_physics(Physics::new());

2. Tags and queries

Games never walk raw entity lists. They ask the world for what they care about, and get an iterator back. One line of engine code replaces a filter loop in every system of every game:

for enemy in world.with_tag_mut(Tag::Enemy) {
    enemy.transform.x -= speed * input.dt;
}

3. Systems are plain functions

All behaviour lives in free functions with one shape: fn(&mut World, &mut GameState, &Input). No traits, no scheduling framework, no magic. A game is a list of these functions, run in order every frame:

let game = Game::new(world)
    .with_update_systems(vec![
        direction_system,
        movement_system,
        food_system,
        collision_system,
    ])
    .with_render_systems(vec![render_board, ui_system]);

That list is the whole architecture of a game. Reading it top to bottom tells you exactly what happens each frame, in what order.

4. Resources: shared state without globals

Not everything is an entity. Pong's two scores, Snake's direction and step timer, the Invaders fleet's marching direction — that's game-wide state. The engine stores it in a type-indexed map (TypeId → Box<dyn Any>), so any system can look state up by its type, safely:

world.insert_resource(Scores { player: 0, cpu: 0 });

if let Some(scores) = world.get_resource_mut::<Scores>() {
    scores.player += 1;
}

5. Input is data, so everything is testable

Systems never touch the keyboard. The main loop samples input once per frame into a plain struct (including the frame's delta time), and systems consume that. The payoff: every mechanic runs headless. A test builds a world, fakes an input, calls the system directly — no window, no GPU:

#[test]
fn cannot_reverse_into_itself() {
    let mut world = snake_world();
    let input = Input { left: true, ..Default::default() };

    direction_system(&mut world, &mut state, &input);

    assert_eq!(snake.next_dir, Dir::Right); // ignored!
}

Every game ships with a test suite like this, and they all run in CI on every pull request.

6. Lifecycle: the dead-flag pattern

Removing entities mid-frame invalidates every index into the world, so nothing is ever removed mid-frame. Systems just mark entities dead; one engine call sweeps them up afterwards. Breakout's bricks and Invaders' bullets both live and die through this:

brick.alive = false;   // any system, any time
world.despawn_dead();  // one safe sweep

7. Events: detection tells, consumers decide

Some systems detect things; several others need to react. In Space Invaders one bullet-hit means a score bump, a fleet speed-up, and two despawns — and one day a sound effect. Instead of one function doing all of it, the detector emits a typed event and any number of later systems read it. Events live exactly one frame; the explicit system order above decides who sees them:

// detection
world.emit(BulletHit { bullet, invader });

// any number of consumers, later in the list
for hit in world.events::<BulletHit>() {
    // score it, despawn it, play a sound...
}

8. The JS ⇄ Rust bridge

The leaderboards you see on the game-over screens cross three worlds: a Rust game compiled to WebAssembly, JavaScript in the browser, and a serverless API. The games use macroquad, which targets bare wasm32-unknown-unknown — no wasm-bindgen, no generated glue. So the bridge between JS and Rust is hand-rolled: the Rust side declares raw extern "C" imports, the binary links with --allow-undefined, and a tiny JS plugin supplies the implementations when the wasm module is instantiated:

// Rust: symbols left dangling in the binary...
unsafe extern "C" {
    fn lb_generation() -> u32;
    fn lb_read_entry_name(i: u32, buf: *mut u8, cap: u32) -> u32;
}

// JS: ...filled in at load time via miniquad's plugin hook
importObject.env.lb_generation = function () { return state.generation; };

The design rule that makes it work: JS owns everything asynchronous — fetch(), the auth token, localStorage — and Rust never blocks or takes a callback. Once per frame the game polls one integer, a generation counter that JS bumps on every visible change. If it hasn't moved, the whole bridge costs a single FFI call per frame; only when it changes does Rust re-read the full state. No async across the boundary, no re-entrancy, no per-frame string decoding at 60fps.

Strings are the fiddly part, because raw wasm only passes numbers. Rust hands JS a pointer + length into linear memory for game ids; coming back the other way, Rust lends a fixed buffer and JS writes UTF-8 into it with encodeInto and returns the byte count:

let mut buf = [0u8; 64];
let n = ffi::read_username(&mut buf);
lb.username = String::from_utf8_lossy(&buf[..n]).into_owned();

Two footguns are dodged deliberately: JS creates its memory views fresh on every call, because growing wasm memory detaches old buffers and a cached view silently reads garbage; and Rust clamps lengths and decodes lossily, so a misbehaving JS side can at worst mangle a name — never corrupt memory. On native builds the whole FFI module is swapped for no-op stubs behind #[cfg(target_arch = "wasm32")], so every game and every test runs headless, unchanged. Even "submit the score exactly once per death" is a pure function with unit tests, not a flag buried in a render loop.

9. Sign-in without collecting anything

The games are served as static files from DigitalOcean's App Platform — there is no server to hold a session. Accounts live in a small TypeScript serverless API (DigitalOcean Functions + Neon Postgres), and identity is a stateless JWT the browser keeps in localStorage. Two rules shaped the whole design: signed-out players generate zero network traffic (their best score stays in the browser), and the system stores no personal data at all. You don't pick a username or give an email — the server generates a name like CleverOtter42 from a CSPRNG, and registration is literally just a password. Nothing to leak, nothing to moderate, nothing to impersonate.

The details are where the security lives. Passwords are hashed with bcrypt at cost 10, and validation rejects anything over 72 bytes — bcrypt silently truncates there, so a longer password would be only partially compared at login. Login itself defends against username enumeration by timing: if the account doesn't exist, the server still runs a bcrypt compare against a dummy hash, so unknown-user and wrong-password cost the same and return the same generic 401:

const user = await getRepo().findUserByUsername(username);
const ok = await bcrypt.compare(password, user?.passwordHash ?? DUMMY_HASH);
if (!user || !ok) throw new HttpError(401, "invalid_credentials");

Tokens are HS256 JWTs with the algorithm pinned on verification (the classic alg: none attack relies on trusting the token's own header), and every failure mode collapses into one indistinguishable 401 — the client's response to any of them is to quietly drop the token and fall back to local-only mode. Around that: exact-origin CORS with default deny, parameterised SQL only, per-game maximum plausible scores, and a submit throttle. And one honest caveat, stated rather than hidden: scores come from a wasm binary running on the player's machine, so the leaderboard is best-effort by design — knowing exactly where the trust boundary ends is the point.

The result

The engine is ~400 lines. It doesn't try to be Bevy or Unity — it makes exactly one promise: a new game costs an afternoon, not a rewrite. Each of the games on the homepage is a single file you can read top to bottom, and each one exercised the engine enough to grow it a little: Snake added directional input, Breakout added the dead-flag sweep, Pong added a second score. Hours into the engine so that minutes go into the games.