I have been building a shoot-‘em-up in Phaser — a Gradius-flavored thing with vertical-shmup DNA — and hit the classic genre problem: sometimes the screen fills with bullets in a way the player genuinely cannot answer. Spiral arcs from a transforming boss plus aimed tracking fire can blanket the lower field at the same time. The death that follows doesn’t read as player error. It reads as engine failure.
The fix I shipped is invisible. No corridor telegraphs, no visible shield, no
difficulty slider the player ever sees. It’s a small module called
EscapeValve, and it does exactly one thing: watch where enemy bullets are
headed, and hold fire when the next second of shooting would leave the player
nowhere to be.
This post is about that mechanism — and more precisely about the abstraction behind it, because the interesting part isn’t the grid math. It’s where you draw the lines between measuring, deciding, and acting.
The invariant
Before any code, state the rule the game must never break:
At every moment of combat, at least one region of the playfield must be survivable — a pocket the player can occupy and realistically reach without taking an unavoidable hit.
Everything else in the mechanism is in service of that sentence. Once you write it down as an invariant, you can test it, and once you can test it, you can stop guessing during playtests.
Three layers, three responsibilities
The mechanism splits cleanly into three layers, and I think that split is the actual design contribution here:
| Layer | Lives in | Role |
|---|---|---|
| Measurement | EscapeValve.evaluate(bullets) | Pure function: project every bullet’s path forward, stamp a coarse grid, count clean cells |
| Decision | EscapeValve.update(bullets, deltaMs) | Stateful: turn “unsafe” into a hold flag, with hysteresis so it doesn’t flicker |
| Effect | GameScene | Apply the hold through mechanisms that already existed |
Measurement
The playfield becomes a 6 × 8 grid of cells. Each active enemy bullet
projects itself forward by LOOKAHEAD_MS (900ms — roughly one cell of travel
at current bullet speed) and marks every cell along its velocity ray:
evaluate(bullets) {
cells.fill(0);
const step = Math.min(this.cellW, this.cellH) / 2;
for (const bullet of bullets) {
const dx = bullet.vx * this.lookaheadMs / 1000;
const dy = bullet.vy * this.lookaheadMs / 1000;
const samples = Math.max(1, Math.ceil(Math.hypot(dx, dy) / step));
for (let i = 0; i <= samples; i += 1) {
const t = i / samples;
this.mark(bullet.x + dx * t, bullet.y + dy * t);
}
}
// …count clean cells, require one in the bottom band
}
Marking is inflated by a margin of bullet radius + player half-width, so a
cell only counts as clean if the plane can actually be there, not merely
survive a near-miss. A cell with no projected bullet is clean. The field
is safe when clean cells stay above a threshold and at least one clean
cell exists in the bottom band — where the plane spends most of its life.
Crucially, this function takes a flat array of {x, y, vx, vy} snapshots and
returns numbers. No Phaser import. No pool access. No scene reference. That’s
what makes it testable with node:test in milliseconds, ten cases covering
offscreen bullets, edge cells, ray projection, margin inflation, and the
threshold flip.
Decision
Safety alone would make the game stutter — fire on, fire off, fire on — so the decision layer adds hysteresis:
update(bullets, deltaMs) {
const { cleanCells, safe } = this.evaluate(bullets);
if (!safe) {
this.holdFire = true; // engage instantly
this.cleanMs = 0;
} else if (this.holdFire) {
this.cleanMs += deltaMs; // release only after RECOVER_MS
if (this.cleanMs >= this.recoverMs) this.holdFire = false;
}
return { cleanCells, safe, holdFire: this.holdFire };
}
Asymmetric on purpose: hold engages the instant the field saturates, release requires 350ms of continuous safety. One flag of state, one timing accumulator, nothing else.
Effect
The layer that touches the game does as little as possible. When holdFire
is set:
- Selected shooters take the exact code path non-shooters already take —
their
shotElapsedMsclamps to zero. No new branch, no special case. - The boss’s fire interval doubles. Slowed, never silenced — a boss that stops shooting entirely looks broken.
The evaluation runs every 250ms over live bullets from the existing pool,
and the QA snapshot exposes combat.escape = { cleanCells, holdFire } so
tests can assert the invariant directly instead of inferring it from damage
events.
Where the abstraction leaks
It’s not all clean, and the rough edges are worth naming:
Timing lives in the scene, not the valve. The 250ms accumulator is
hand-rolled in GameScene.update(), while the valve merely accepts a
deltaMs. The valve knows nothing about its own cadence. Folding that loop
into a tick(bullets, deltaMs) would make the module the whole mechanism
instead of half of it — and would fix a first-frame artifact where the
initial elapsed time overshoots by one delta.
State is duplicated. The scene keeps its own escapeState copy of
{cleanCells, safe, holdFire} alongside the valve’s internal holdFire.
Two sources of truth for one flag is how drift starts.
“Hold” means three different things in three files. The clamp in
updateEnemies, the multiplier in updateBoss, the ?? false fallback in
the snapshot — each consumer reinterprets the flag. Adding a fourth consumer
means editing the scene again. A single event on the EventBus (the project’s
own architecture rule #1) would turn “hold” into one contract instead of a
scattered convention.
Spec drift. The design doc promised evaluate() also returns
holdFire and that the danger margin would be derived from constants at load
time. The implementation does neither. Cosmetic — but the spec is what the
next session reads.
The honest limits
Two things the valve explicitly does not do, because pretending otherwise would be worse than the bug it fixes:
- It bounds coverage, not reachability. A clean cell in the bottom band doesn’t prove there’s a path to it. The next refinement, if playtesting demands it, is a corridor check between the player’s cell and the nearest clean pocket. Until then it’s a documented approximation.
- It’s global, not regional. One corner can saturate while the rest of
the field stays empty and the
cleanCellstotal still passes. The bottom-band requirement is a partial guard against that, not a full one.
And the test suite reflects the same honesty: the full-stage soak asserts
cleanCells > 0 at every sample — the invariant as literally stated — rather
than the stricter threshold the valve itself enforces. A weak floor is still
a floor; it just tells you when the game became unfair, not when it became
merely tight.
Generalizing it
Once the shape is visible — project occupancy, count free space, gate
pressure with hysteresis — the same mechanism answers other questions. Would
the boss take so much incoming fire it becomes unreadable? Are bombs about to
clear the screen so completely that the stage goes dead? Rename it
PressureValve, make the input “projected occupancy segments plus a region
constraint,” and each of those becomes a configuration instead of a new
module.
That’s the part I keep coming back to. The grid, the 900ms lookahead, the 6×8 cell size — all tunable, all replaceable. What actually made the game fair was deciding, in advance, which invariant must never break, and then building the thinnest possible layer that checks it.
The player will never know the valve exists. That’s the whole point.