Prelude
Modules
| Animation | |
| Audio | Making noise. |
| Bench | Measuring the computer player. |
| Bunkers | The four bunkers the player shelters behind. |
| Cabinet | |
| Collide | Axis-aligned rectangle overlap. |
| Demo | A computer player. |
| Game | The rules of Invaders, as a pure function. |
| Meta | What this build calls itself. |
| Palette | The shared palette. |
| Rules | The numbers that define the game. |
| Scores | The high-score table. |
| Screens | Drawing the cabinet, as opposed to drawing the game. |
| Session | The layer above the game. |
| Sketch | The frame loop. |
| Sprites | The artwork. |
| Stats | Keeping the performance figures. |
| Still | A still picture: no state, no time, no input. |
| Surface | A lightweight, Processing-shaped drawing surface built on Swing and Java2D. |
| Tuning | Reading and writing the demo player's numbers. |
| View |
Effects
| Canvas | Drawing, as an effect. |
| Input | Reading the input devices, as an effect. |
| Sound | Making a noise, as an effect. |
Enums
| BlastKind | What blew up. The two look different and last for different lengths of time. |
| BombKind | The three kinds of bomb the invaders drop, as in the original: "slow straight ones, fast straight ones and wiggly ones which are the most powerful". |
| Color | Colours and draw commands. |
| DrawCmd | A single drawing instruction. |
| InvaderKind | The three kinds of invader, worth different points -- as in the original. |
| Key | A key, named rather than numbered. |
| Phase | What the game is currently doing. |
| Rng | A pseudo-random number generator, as a value. |
| Screen | What the cabinet is currently showing. |
| SoundCmd | Something the game wants heard. |
| Sprite | Pixel art, as data. |
Type Aliases
type alias Ball = { dx = Float32, dy = Float32, radius = Float32, tint = Color, x = Float32, y = Float32 }§ SourceA moving picture: state, time, and input, but still no game.
This is the step up from Still. Four balls of different sizes bounce around a box and
off each other. The whole simulation is the pure function step, which the runtime calls
exactly 60 times a second regardless of how fast the display is -- so the balls move at
the same speed on every machine.
Collisions are elastic and mass-weighted: mass goes with area, so the big ball shoves the
small one aside while barely changing course. test/TestAnimation.flix checks that both
momentum and kinetic energy come out unchanged, which is a far sharper test than looking
at it.
Read step and note what is not there: no clock, no frame counter, no window. It takes
a world and an input snapshot and returns the next world. That is the whole idea the game
is built on, and it is why these sketches can be tested without a display.
Run it: bin/sketch animation
Try this: change gravity from 0 to something small like 0.15 and watch the balls fall,
or add a fourth lane in makeBalls.
A ball: position, velocity, size, colour. All data.
A short-lived explosion. ticksLeft counts down to zero, at which point it is dropped.
A falling bomb. age counts ticks since it was dropped, and drives the wiggler's sway --
keeping the phase on the bomb rather than deriving it from the world clock is what lets two
wigglers dropped at different moments sway out of step, and what keeps step a pure
function of its argument.
The bouncing world: the balls plus the sideways nudge currently being applied.
A defensive bunker: a grid of small blocks, each of which is either still there or shot
away. origin is the top-left corner of the block grid.
type alias Cabinet = { otherScore = Int32, ownGameOver = Bool, player = Int32, players = Int32 }§ SourceDrawing a world.
Uses only the Canvas effect, so Canvas.runWithCollector can record a frame as data and
the rendering tests need no display. Nothing here changes the world -- given the same
world, render always produces the same commands, which is why a replayed game renders
identically.
Who else is playing, from the point of view of one game.
The rules know nothing about a second player -- a World is one game. This is the little
bit of cabinet context the HUD needs in order to fill in the other score and show whose
turn it is.
What a single game needs to know about the machine around it.
ownGameOver is whether View should announce the end of the game itself. Standing
alone it must -- there is nobody else to do it, and Enter really does start a new game.
Inside the cabinet the session owns what happens next, so it draws its own and this is
false; otherwise the screen carries two GAME OVERs and an invitation to press a key that
the cabinet has already taken charge of.
It says nothing about the banner between waves. That one belongs to the game either way -- gating both on one flag is what made the level banner disappear from the cabinet and left a silent three-second pause where it used to be.
One line of an overlay: what it says, how big, and in what colour.
Everything the cabinet knows: which screen, whose turn, and a game running behind the title for anybody who walks past.
A score waiting for its initials, and whose it is.
The player number is carried alongside rather than added to Entry, because Entry is
what gets written to the high-score file and which of two people set a score is not a
property of the score.
The demo player's hand and attention.
State, because the things that make play look human are all things that persist. A person misjudges a shot and commits to the misjudgement for a beat; they do not re-misjudge sixty times a second. They keep pushing the stick the way it is already going. They look away for a third of a second, not for a single frame.
The first version of this bot had none of that -- it drew a fresh aim error every tick, which around the target swamped the 1.5px movement deadzone and reversed the cannon's direction about six times a second. Measured, that was 9-11 reversals per 100 moving ticks against 3 for the bot with no error at all: the shake was the jitter, not the game.
One occupied column of the formation: its lowest invader, and how deep it is.
type alias Config = { fontPath = Option[String], height = Int32, hz = Int32, maxFrames = Option[Int32], seed = Int64, title = String, width = Int32 }§ SourceHow a sketch is configured.
seed makes the run reproducible; hz is the logical simulation rate, which is
deliberately independent of the display's frame rate. maxFrames stops the sketch after
a fixed number of frames, which is how the smoke test terminates on a CI runner.
fontPath is an optional path to a TrueType file. If it is missing or unreadable the
sketch simply keeps the platform's default font, so a broken path costs you looks, not a
crash.
The bot's movement and progress while eight or fewer invaders remain in a formation.
One line of the high-score table.
type alias Hand = { error = Float32, lapse = Int32, moving = Int32, rng = Rng, settled = Int32 }§ SourceThe imperfect player's state: RNG stream, current error, and timers for movement/lapses.
type alias Invader = { alive = Bool, kind = InvaderKind, pos = Vec2, row = Int32 }§ SourceOne invader in the formation. Dead ones keep their slot so the grid never reshuffles.
The mystery ship, while one is on screen. dir is -1.0 or 1.0.
type alias Outcome = { deaths = Int32, drops = Int32, endgame = Endgame, invaded = Bool, kills = Int32, level = Int32, lives = Int32, score = Int32, seed = Int64, ticks = Int32 }§ SourceWhat one benchmarked game came to.
ticks is here so every other number can be turned into a rate. Totals on their own are
what made three separate measurements in this project's history say the opposite of the
truth: a change that ends games sooner posts fewer deaths and fewer row drops while being
strictly worse, and the totals look like an improvement.
type alias Session = { current = Int32, demo = World, demoHand = Hand, handover = Int32, nerds = Bool, over = Int32, pending = List[Claim], players = Int32, scores = List[Entry], screen = Screen, seed = Int64, tuning = Tuning, typing = String, worlds = Vector[World] }§ SourceThe arcade cabinet's complete state across games, players, screens, and high scores.
Everything a single simulation step is allowed to know about the input devices.
held is the set of keys down for the whole of this step. pressed and released are
the edges since the previous step, so a step can distinguish "the key is down" from "the
key just went down" without keeping its own history.
A keyboard and nothing else. There was a pointer here too, carried from the window to every step and read by nothing in eight releases -- the cabinet, the rules and the demo bot are all played with the arrows. It went when the window did.
type alias Stats = { catchUps = Int32, drawMs = Float32, fps = Float32, frames = Int32, simMs = Float32, steps = Int32 }§ SourceWhat the runtime knows about its own performance.
The frame loop is the only thing that can measure any of this, and the view is the only thing that can show it, so it travels from one to the other as an ordinary value. Nothing in between -- not the rules, not the cabinet -- learns that a clock exists.
Timings are of the work, not of the frame. The loop waits to hold the target rate, so a
stopwatch around a whole frame measures the pacing: at 60Hz every sketch reports about
16.7ms whether it spends 1ms or 15ms. simMs and drawMs bracket the simulation and the
drawing themselves, which is the number that tells you anything.
type alias Tuning = { aimJitter = Int32, blockedCost = Float32, calm = Float32, dangerWidth = Float32, finishFlank = Float32, fireWindow = Float32, imminence = Float32, judgeFor = Int32, judgeSpread = Int32, lapseFor = Int32, lapseOneIn = Int32, lapseSpread = Int32, narrowTo = Float32, narrowing = Float32, reverseAt = Float32, selfPreservation = Float32, shelterRelief = Float32, startAt = Float32, stragglers = Int32, urgency = Float32 }§ SourceEvery number that decides how the demo player behaves.
A record rather than sixteen defs, because they were sixteen defs and every one of them
had to be found, edited and recompiled to try a different value. As data they can be varied
in a loop, read from a file, and searched -- see bin/bench --recalc.
None of them can be reasoned about in isolation. Widening dangerWidth from 30 to 60 cut
deaths sixfold; a cleverer dodge that predicted where the cannon would be when each bomb
landed measured worse at every setting. They are tuned by measurement, and the record of
that is in docs/ARCHITECTURE.md.
The state of a game of Invaders.
Everything here is plain immutable data, including the random number generator. A World
plus a list of input snapshots completely determines every world that follows, which is
what the replay tests rely on.
A point, or a size, depending on context.
type alias World = { blasts = List[Blast], bombs = List[Bomb], bullets = List[Vec2], bunkers = Vector[Bunker], hiScore = Int32, invaders = Vector[Invader], level = Int32, lives = Int32, marchDir = Float32, marchNote = Int32, marchedSince = Float32, mystery = Option[Mystery], mysteryTimer = Int32, nextBonusAt = Int32, pause = Int32, phase = Phase, playerX = Float32, rng = Rng, score = Int32, seed = Int64, shield = Int32, shotsFired = Int32, tick = Int32 }§ SourceThe whole game state.
playerXis the player's x position; its y never changes.bulletstravel up and are fired by the player;bombstravel down and are dropped by the invaders.marchDiris which way the formation is marching,-1.0or1.0.rngis threaded through every step rather than drawn from a global source.seedis kept so that restarting rebuilds exactly the same starting position.hiScoresurvives a restart, the way an arcade cabinet's does.levelcounts from 1 and drives the difficulty curve.pauseis ticks remaining in a non-playing phase, used for the between-levels beat.shieldis ticks of invulnerability remaining, earned by shooting the mystery ship.nextBonusAtis the score at which the next extra life is awarded.shotsFiredcounts the cannon's shots on this board, and sets the saucer's value.marchNoteandmarchedSincedrive the bassline: notes are spaced by distance marched, not by time, so the tempo tracks the formation's speed for free.
Definitions
Space Invaders.
Notice how little there is here. The runtime owns the window and the frame loop, Game
owns the rules, View owns the drawing, and Session owns the cabinet around them --
this file only introduces them. If it ever needs to grow much beyond this, something has
leaked across the boundary.
It is also the only place that touches a file. Sketch.start takes a pure init and
returns the state the window closed on, so the table is read before the window opens and
written after it closes, and nothing in between knows a filesystem exists. That is what
keeps Session.step testable without a disk.
Run it: ./flixw run
The stored high scores, or none at all if they cannot be read.
A missing file is the ordinary first run and is silent. Anything else is reported and then tolerated: not being able to read a score table is no reason to refuse to play.
The demo player's numbers, or the shipped defaults if there is no config.
The attract screen is the only thing this affects, so a config that cannot be read costs
you a slightly different demo and nothing else. bin/bench --recalc is what writes it.
Opens the window and returns the session it closed on.
Separate from main so that the one function reaching a disk is not also the one building
a window, and main reads as what it is: read the files, play the game, write the files.
The table and the tuning arrive as arguments rather than being read here, which is what
keeps Sketch.start's init a pure function of the seed.