Shatterbelt
Break the rocks before they break you. Every hit splits a rock into two smaller, faster pieces.
Loading the belt
SHATTERBELT
Large rocks break into medium ones, medium into small, small into dust. Hunters come for you as the score climbs.
Paused
P or Esc to carry on.
Game over
0
CONTROLSHow to fly
Keyboard
- ← → or A D
- Turn
- ↑ or W
- Thrust. You keep drifting after you let go.
- Space
- Fire. Hold it to keep firing. Five shots can be in flight at once.
- Shift or H
- Hyperspace jump
- P or Esc
- Pause
- Enter
- Start, or play again
- M / N
- Sound / music on or off
Gamepad
- Left stick or d-pad
- Turn, and up to thrust
- Right trigger
- Thrust
- A
- Fire, and start
- B
- Hyperspace jump
- Start
- Pause
Phone or tablet
- Left thumb
- Turn left, turn right, and Thrust above them
- Right thumb
- Fire, and Jump for hyperspace
- Upright
- Holding the phone upright gives a taller field.
The rules
- Points
- Large rock 25, medium 60, small 120. Big hunter 250, small hunter 1,000.
- Ships
- Three to start, and one more every 15,000 points.
- Hunters
- The big one fires anywhere. The small one aims at you, and aims better as your score rises.
- Hyperspace
- You land anywhere, at rest, with no shield. One jump in eight fails.
- Edges
- Fly off one edge and you come back on the other. So do rocks and shots.
- Motion
- Losing a ship slows time for a moment. If your system is set to reduce motion, the screen does not shake.
THE INTERVIEW QUESTIONWhat this answers
I was asked this in a job interview:
"Asteroids: a spaceship shoots; rocks come in large, medium and small and get smaller each hit. Design the classes and the main loop."The question, as it was put to me
This page is my answer, built. It is an original game in that genre, with its own rules and numbers. The design is below, read straight out of the code, and the tests that hold the code to it are below that.
HOW IT IS BUILTThe classes
All the rules live in one file, core.js, with no browser code in it. The same file runs the game on this page and the tests in Node.
- Entity is anything that moves and can be hit: a position, a velocity, a facing, a spin, a radius and whether it is alive.
- Ship, Bullet, Rock and Hunter are entities with their own rules. A rock knows its size, its points and the size its pieces will be. A hunter knows where to aim.
- Pool makes a fixed number of objects when the game starts, each pool sized for its worst case. Each step's event records and the input log are made then too, so nothing a game keeps is made during play and a long game never grows (a test walks everything a game can reach after 20,000 steps). It also holds every add and every remove until
flush(), so no loop ever sees its list change under it. - Field is the play area. Its edges wrap, so it also knows the shortest way from one point to another, through an edge when that is shorter. Collisions and aiming both use it.
- Game owns everything and runs one fixed step at a time. FixedTimestep turns real time into those steps. Random is seeded and InputLog keeps one byte of input per step, with room for an hour of play, so a whole game replays from the two. A game that runs past the hour says it has no replay.
Click a class to open its code on GitHub, at the line where it starts.
Drawn by tools/class_diagram.js, which reads the class, field and method names out of core.js. A test fails if this picture and the code disagree. Arrows point from a class to the class it extends; a field's type names the class it holds.
The main loop
One step of the game, as it is written in Game.step():
step(input = 0) {
this.events.length = 0;
this.time += STEP;
this.steps += 1;
this.handleInput(input); // 1. input: steer, fire, hyperspace
this.update(STEP); // 2. update and integrate: move everything, run the timers
this.wrapAll(); // 3. screen wrap
this.collide(); // 4. collide: circle against circle; hits only mark things dead
this.flush(); // 5. spawn and destroy: the only place the world's lists change
this.checkGameOver(); // and the game ends here, once every hit of the step has counted
return this.events; // 6. events out, for the renderer and the sound
}
- Input steers the ship, fires and jumps. Hyperspace takes a fresh press, not a held key.
- Update and integrate moves everything by its velocity and runs the timers: shot lifetimes, waves, hunter arrivals, the respawn.
- Wrap brings anything that left one edge back in at the opposite one.
- Collide tests circle against circle, the short way round the field. A hit marks things dead at once, so a rock hit by two shots in one step breaks once, but nothing is removed yet.
- Spawn and destroy happen together in
flush(), after every loop over the world has finished. A broken rock's two pieces join here, one size down, at its position, turned apart and a little faster. Only then is the game over, if a ship was lost and none is left, so a ship earned in the same step always counts, whatever order the shots are in. - Events go out: what broke, what fired, what jumped, in records made once and filled again every step. The renderer and the sound read them. The rules never do.
Around it, main.js runs the frame loop: real time goes into FixedTimestep, which calls step() at exactly 60 Hz however fast the screen draws, and the time left over is used only to draw smoothly between two steps.
The same core in C++
The rules again in C++17, with the same classes, names and order: cpp/shatterbelt_core.h and cpp/shatterbelt_core.cpp. Pools are fixed arrays with a free list, nothing is allocated once a game exists, and there are no exceptions, no RTTI and no virtual functions. One step in each, read out of the two files:
core.js
step(input = 0) {
this.events.length = 0;
this.time += STEP;
this.steps += 1;
this.handleInput(input); // 1. input: steer, fire, hyperspace
this.update(STEP); // 2. update and integrate: move everything, run the timers
this.wrapAll(); // 3. screen wrap
this.collide(); // 4. collide: circle against circle; hits only mark things dead
this.flush(); // 5. spawn and destroy: the only place the world's lists change
this.checkGameOver(); // and the game ends here, once every hit of the step has counted
return this.events; // 6. events out, for the renderer and the sound
}cpp/shatterbelt_core.cpp
const EventList& Game::Step(uint8_t input)
{
events.length = 0;
time += STEP;
steps += 1;
HandleInput(input); // 1. input: steer, fire, hyperspace
Update(STEP); // 2. update and integrate: move everything, run the timers
WrapAll(); // 3. screen wrap
Collide(); // 4. collide: circle against circle; hits only mark things dead
Flush(); // 5. spawn and destroy: the only place the world's lists change
CheckGameOver(); // and the game ends here, once every hit of the step has counted
return events; // 6. events out, for a renderer and the sound
}Built by cpp/build.cmd with Microsoft C/C++ 19.44.35229 for x64, with 0 warnings:
cl /nologo /std:c++17 /permissive- /W4 /WX /EHs-c- /GR- /O2 /fp:precise replay_main.cpp shatterbelt_core.cppMeasured by tools/parity.js, which records each game's inputs, replays them through replay_main.cpp and core.js, and compares the whole game after every step. Between them the games lost 25 ships, ended in game over 7 times, jumped to hyperspace 70 times (9 jumps failed), met 74 hunters (22 of them Small) and earned 2 extra ships. In the C++ tests, a 20,000-step game made 0 calls to operator new.
Each game
| Game | Steps | What happened | First difference |
|---|---|---|---|
| 1. a player who changes what they hold every so often | 6,000 | 3 ships lost, game over; 5 jumps; 4 hunters (0 Small); 12 rocks broken; score 350, wave 1 | none |
| 2. spin and fire, thrusting now and then | 20,000 | 3 ships lost, game over; 0 jumps; 18 hunters (0 Small); 80 rocks broken; score 5,345, wave 3 | none |
| 3. fire, turn, and jump to hyperspace every 1.5 seconds | 8,000 | 3 ships lost, game over; 28 jumps; 6 hunters (0 Small); 45 rocks broken; score 4,105, wave 2 | none |
| 4. reckless: thrust and turn into everything | 6,000 | 3 ships lost, game over; 0 jumps; 4 hunters (0 Small); 21 rocks broken; score 1,275, wave 2 | none |
| 5. an upright phone field, 622 by 1005 | 6,000 | 3 ships lost, game over; 17 jumps; 5 hunters (0 Small); 31 rocks broken; score 1,650, wave 2 | none |
| 6. five ships, and a new random input every step | 8,000 | 5 ships lost, game over; 19 jumps; 5 hunters (0 Small); 20 rocks broken; score 1,500, wave 1 | none |
| 7. a bot that aims at the nearest rock or hunter | 25,000 | 5 ships lost, game over; 1 jump; 32 hunters (22 Small); 379 rocks broken; score 38,760, wave 9 | none |
Why there is a Trig class. Both cores take sin, cos, atan2 and hypot from Trig, written the same way in both, from + - * / and square root only. IEEE 754 requires those five to be correctly rounded, so they give the same bits on every machine that follows it. With each language's own functions instead (the browser's Math and the Microsoft C runtime), 7 of 7 games parted, the first as soon as it was made, before step 1, where snapshot.rocks[1][5] was 35.04896662064477 in core.js and 35.04896662064476 in C++. That was measured by the same comparison, on a copy of core.js with its 15 Trig calls turned back into Math calls. Trig's worst distance from the C runtime's functions in a million tries, in units in the last place: sin 2.00, cos 2.00, atan2 3.00, hypot 0.00.
Can these checks fail? tools/parity.js also plants one bug at a time in a copy of the C++ and runs the checks again. 12 of 12 were caught: 11 by the C++ tests, 1 only by the comparison with core.js.
| Planted in a copy of the C++ | What failed |
|---|---|
| Small rocks split too a Small rock's pieces are Small rocks | caught by 1 of 31 C++ tests: a hit Small rock breaks and leaves nothing |
| Destroy during iteration Release() takes the object out of the live list at once, mid-loop | caught by 10 of 31 C++ tests: a hit Large rock leaves two Medium rocks at its position, turned apart and a little faster; a hit Medium rock leaves two Small rocks; a hit Small rock breaks and leaves nothing; the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step; pool: releasing while walking the live list visits every item exactly once; deferred destroy in the game: three shots on three rocks in one step break all three; deferred destroy in the game: two shots on one rock break it once; the last ship lost and a ship earned in one step: the game goes on, whichever shot is first in the pool; a hyperspace landing has no shield, even from a jump taken while the respawn shield is up; waves grow: 3 Large rocks, one more each wave, at most 11 |
| Wrap forgets the top edge leaving through the top no longer comes back at the bottom | caught by 1 of 31 C++ tests: wrap: leaving any of the four edges comes back in at the opposite one |
| Extra ship on every score past 15,000 the threshold is checked, but never moves on | caught by 1 of 31 C++ tests: an extra ship at every 15,000 points, given exactly once |
| Game over decided at the crash the last ship lost ends the game before the rest of the step's hits count | caught by 1 of 31 C++ tests: the last ship lost and a ship earned in one step: the game goes on, whichever shot is first in the pool |
| Rock pool too small the rock pool holds 48, as it once did | caught by 1 of 31 C++ tests: the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step (the run stopped there: shatterbelt: rock pool too small) |
| Hyperspace keeps the shield a jump taken under the respawn shield lands with it still on | caught by 1 of 31 C++ tests: a hyperspace landing has no shield, even from a jump taken while the respawn shield is up |
| Hunter blind to a shielded ship the Small hunter aims only at a ship it can hit | caught by 1 of 31 C++ tests: a Small hunter aims at a ship that has just respawned under its shield |
| Angle never wrapped a spinning rock's angle grows for ever | caught by 1 of 31 C++ tests: spin: an angle is wrapped to within half a turn, and still turns by its spin every step |
| Game::Step allocates Collide() makes a scratch list with new on every step | caught by 1 of 31 C++ tests: Game::Step never allocates: no operator new in a 20,000-step game |
| Random is not quite mulberry32 one constant in Random::Next() is 63 where core.js has 61 | caught by 1 of 31 C++ tests: Random gives exactly the numbers core.js's Random gives |
| Two random draws in one call ArriveFromHyperspace() draws x and y inside the arguments of Place(), whose order C++ leaves open | not caught by the C++ tests. Caught by the comparison with core.js: game 1 parted at step 46, where snapshot.ship.pose[0] was 976.5482789371163 in core.js and 57.52346431836486 in C++ |
Why it is shaped this way
- Destroy later, never during a loop. Removing an item from a list while walking it skips the next item. That bug is real and easy to write, so the pool makes it impossible, and a test plants it to prove the tests notice.
- A fixed step. The same input gives the same game on a 60 Hz laptop and a 144 Hz monitor, and physics never takes a huge step after a stall.
- A seeded generator and an input log. A game is its seed plus one byte per step. Play a game and press "Watch the replay": the page plays it again from those two and checks it ends in exactly the same state.
- Rules out, events in. The rules know nothing about three.js or sound. Drawing reads the state and the events, so the rules can be tested in Node, and a different renderer could be dropped in.
The files
| File | Lines | What it is |
|---|---|---|
core.js | 976 | Shatterbelt: the rules of the game. |
main.js | 331 | the page around the game. It owns the frame loop, the menus, the HUD and the best score. |
render.js | 774 | draws a Game with three.js (r128, the global THREE that index.html loads). |
input.js | 112 | keyboard, gamepad and touch, turned into one byte of Input bits per game step. |
audio.js | 108 | plays the game's events as sound, with Web Audio. |
bots.js | 31 | Players that are not people. The title screen's demo plays with one, and the node tools use the same ones |
cpp/build.cmd | 62 | Builds the C++ twin of core.js with MSVC: replay.exe, replay_library_math.exe and test_core.exe. |
cpp/replay_main.cpp | 102 | Plays a recorded game through the C++ core and writes the whole game out as it goes, for tools/parity.js. |
cpp/shatterbelt_core.cpp | 862 | The rules of Shatterbelt in C++17: the method bodies. Read core.js beside it; the order is the same. |
cpp/shatterbelt_core.h | 564 | The rules of Shatterbelt in C++17: the twin of core.js. |
cpp/test_core.cpp | 852 | The rules of the C++ core, checked the way test/core.test.js checks core.js, plus what only C++ can |
test/core.test.js | 668 | The rules of Shatterbelt, checked in node. Run from the shatterbelt folder: node --test |
test/diagram.test.js | 51 | The page's class diagram and main loop are read out of core.js. These fail when the page and the |
test/render.test.js | 23 | Drawing between two steps, checked in node. render.js needs three.js only once a Renderer is made, so its |
tools/bench.js | 59 | How long one game step takes, measured in node on busy play, and written into index.html's speed block. |
tools/class_diagram.js | 268 | Reads core.js and writes two things into index.html: a class diagram (inline SVG) and the body of |
tools/convert_models.js | 121 | Converts Star Fighter's FBX models into one small binary file the game loads directly. |
tools/difficulty.js | 70 | How hard the game is, measured: 200 seeded games played to the end by two bots, written into index.html. |
tools/parity.js | 378 | Holds the C++ twin in cpp/ to core.js: builds it with MSVC, runs its tests, plants bugs in a copy of it |
tools/play_check.py | 420 | plays Shatterbelt in headless Chromium the way a player would, and fails on anything wrong. |
tools/proof.js | 176 | Runs the tests, then plants bugs one at a time to show the tests can fail, and writes what happened |
The whole folder is 1.7 MB with its models, textures and sounds. The sky, planets, nebula, rock surface and music (4.4 MB) are shared with Résumé Breakout and loaded from its folder.
HOW IT IS CHECKEDThe tests
The rules are tested in Node with its built-in runner: node --test in the shatterbelt folder. The numbers below were written by tools/proof.js from a real run.
Every test, by name
- a hit Large rock leaves two Medium rocks at its position, turned apart and a little faster
- a hit Medium rock leaves two Small rocks
- a hit Small rock breaks and leaves nothing
- the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step
- points by size: Large 25, Medium 60, Small 120, Big hunter 250, Small hunter 1000
- only the ship's shots score: a hunter's shot breaks a rock for no points
- wrap: leaving any of the four edges comes back in at the opposite one
- wrap: a moving rock crosses an edge in the real step, and things touch across an edge
- spin: an angle is wrapped to within half a turn, and still turns by its spin every step
- a shot lives for its lifetime, then is gone
- the ship never has more than its cap of live shots, however long fire is held
- pool: never grows past its capacity, and reuses a freed slot
- pool: releasing while walking the live list visits every item exactly once
- deferred destroy in the game: three shots on three rocks in one step break all three
- deferred destroy in the game: two shots on one rock break it once
- an extra ship at every 15,000 points, given exactly once
- respawn waits for a clear centre, then comes back shielded
- respawn: never before the delay, even on an empty field
- a freshly respawned ship survives a rock until its shield runs out
- game over when the last ship is lost, and no ship comes back
- no extra ship once the game is over, from a shot that lands after the last ship is lost
- the last ship lost and a ship earned in one step: the game goes on, whichever shot is first in the pool
- a hyperspace landing has no shield, even from a jump taken while the respawn shield is up
- hyperspace moves the ship, and about one jump in eight fails
- waves grow: 3 Large rocks, one more each wave, at most 11
- a new wave never starts a rock on top of the ship
- a Small hunter aims at the ship, the short way round the field
- in the game, a Small hunter's shot flies toward the ship
- a Small hunter aims at a ship that has just respawned under its shield
- a hunter's aim gets better as the score rises; the Big one fires anywhere
- a ship shot destroys a hunter; a hunter shot destroys the ship
- Trig: sin, cos, atan2 and hypot stay within 3 units in the last place of Math's
- fixed timestep: uneven frames become 60 steps a second; a stall is not raced through
- determinism: the same seed and the same input log give the same game after 5,000 steps
- the input log is made once, with room for an hour of play, and stops recording at its end
- play keeps no new objects: everything a game can reach after 20,000 busy steps was there at the start
- the class diagram on the page is the one core.js gives today
- the main loop on the page is Game.step() as written
- the diagram names every class core.js exports, and every Game method
- the reader follows the code: renaming a method changes the diagram
- every class box opens its own line of core.js on GitHub, so a reader goes from the picture to the code
- drawing between two steps turns the short way, also across the wrap of the angle
Can the tests fail?
A test that has only ever passed proves little. tools/proof.js copies the code to a scratch folder, plants one bug at a time, runs the tests against it and records which tests caught it. The real code is never touched.
| Planted bug | Tests that failed |
|---|---|
| Small rocks split too a Small rock's pieces are Small rocks | caught by 2 of 42: a hit Small rock breaks and leaves nothing; play keeps no new objects: everything a game can reach after 20,000 busy steps was there at the start |
| Pieces are not turned apart both pieces fly along the parent's line | caught by 1 of 42: a hit Large rock leaves two Medium rocks at its position, turned apart and a little faster |
| Destroy during iteration release() removes the item from the live list at once, mid-loop | caught by 12 of 42: a hit Large rock leaves two Medium rocks at its position, turned apart and a little faster; a hit Medium rock leaves two Small rocks; a hit Small rock breaks and leaves nothing; the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step; only the ship's shots score: a hunter's shot breaks a rock for no points; pool: releasing while walking the live list visits every item exactly once; deferred destroy in the game: three shots on three rocks in one step break all three; deferred destroy in the game: two shots on one rock break it once; the last ship lost and a ship earned in one step: the game goes on, whichever shot is first in the pool; a hyperspace landing has no shield, even from a jump taken while the respawn shield is up; waves grow: 3 Large rocks, one more each wave, at most 11; the class diagram on the page is the one core.js gives today |
| Wrap forgets the top edge leaving through the top no longer comes back at the bottom | caught by 2 of 42: wrap: leaving any of the four edges comes back in at the opposite one; play keeps no new objects: everything a game can reach after 20,000 busy steps was there at the start |
| Extra ship on every score past 15,000 the threshold is checked, but never moves on | caught by 1 of 42: an extra ship at every 15,000 points, given exactly once |
| Extra ships after game over a shot that lands after the last ship is lost still earns a ship | caught by 1 of 42: no extra ship once the game is over, from a shot that lands after the last ship is lost |
| Game over decided at the crash the last ship lost ends the game before the rest of the step's hits count | caught by 1 of 42: the last ship lost and a ship earned in one step: the game goes on, whichever shot is first in the pool |
| Rock pool too small the rock pool holds 48, as it once did | caught by 1 of 42: the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step |
| Hyperspace keeps the shield a jump taken under the respawn shield lands with it still on | caught by 1 of 42: a hyperspace landing has no shield, even from a jump taken while the respawn shield is up |
| Hunter blind to a shielded ship the Small hunter aims only at a ship it can hit | caught by 1 of 42: a Small hunter aims at a ship that has just respawned under its shield |
| Angle never wrapped a spinning rock's angle grows for ever | caught by 2 of 42: spin: an angle is wrapped to within half a turn, and still turns by its spin every step; the class diagram on the page is the one core.js gives today |
| A new event object every time emit() makes a fresh record instead of filling one made at the start | caught by 1 of 42: play keeps no new objects: everything a game can reach after 20,000 busy steps was there at the start |
| The input log grows a full log doubles its buffer mid-game instead of refusing the step | caught by 2 of 42: the input log is made once, with room for an hour of play, and stops recording at its end; the class diagram on the page is the one core.js gives today |
| Hunter aims the long way round aiming ignores the wrapping edges | caught by 1 of 42: a Small hunter aims at the ship, the short way round the field |
| Randomness not from the seed the generator is seeded from Math.random() | caught by 1 of 42: determinism: the same seed and the same input log give the same game after 5,000 steps |
| A method renamed, the page not updated breakRock becomes shatterRock in core.js only | caught by 3 of 42: the rock pool holds the worst case: every Medium rock of the fullest wave broken in one step; the class diagram on the page is the one core.js gives today; the reader follows the code: renaming a method changes the diagram |
In a real browser
tools/play_check.py opens this page in headless Chromium, plays it with scripted keys, and fails on any console error or a blank picture.
Measured by tools/play_check.py: 42 of 42 checks passed, including no blank pictures and no sideways scroll at 375 px on an emulated phone (an upright 622 x 1005 field). It drew 60 frames a second in headless Chromium on an NVIDIA GeForce RTX 2080.
How fast
A step has 16.7 ms of game time to stand for; the rules use a small part of it, so the rest is left for drawing. Two measurements: the rules alone in node, and a whole frame in the browser.
Measured by tools/bench.js: 60,000 steps of a bot with 1,000 ships that fires and turns at random, each step timed on its own after 2,000 warm-up steps; the slowest single step took 1,353 µs (a garbage collection or the JIT can land on any one step). One run, node v25.9.0 on Intel(R) Core(TM) i9-10980XE CPU @ 3.00GHz.
Measured by tools/play_check.py during the play above: the time each frame spends in the game steps and issuing the draw calls (main.js keeps it for the last 600 frames). The GPU’s own drawing time is not in it. The slowest frame took 1.60 ms. Headless Chromium on an NVIDIA GeForce RTX 2080, one run.
How hard
Two bots played the game to the end, a hundred seeded games each, to see how the rules pace a game.
| Player | Median wave reached | Median score | Median game | Best of 100 | Ships lost in wave 1 |
|---|---|---|---|---|---|
| Aims | 7 | 29,865 | 4.7 min | wave 9, 46,210 | 1% |
| Random | 1 | 855 | 0.5 min | wave 2, 3,915 | 96% |
Measured by tools/difficulty.js: 100 seeded games per player, each played to game over (or an hour). “Aims” turns to the nearest rock or hunter, fires when it faces it and jumps away from a hit; “Random” changes the keys it holds every so often. Neither is a person: this shows how the rules pace a game, not how people will score. Aims: 0 still going at an hour; Random: 0 still going at an hour.
CREDITSWho made what
- Code and design: RJ Thompson.
- Ship, hunter and rock models, the ship and hunter textures, the sound effects, and the engine, flame and shot sprites: by way of Star Fighter, RJ Thompson's browser space game. They are not his own art: the model files record their source as a 2013 project named “SpaceShooter”, which we believe is Unity's free Space Shooter tutorial. Only the converted geometry the game draws is published here, not the source files. If you made them and want a different credit, or want them taken down, tell RJ.
- The sky, both planets and their normal maps, the nebula, the rock surface and the music: art from RJ Thompson's projects, shared with Résumé Breakout on this site.
- three.js r128, MIT licence. The models were converted once, outside this site, with three.js's FBXLoader (MIT) and fflate (MIT).