flix

0.81.0

Prelude

Modules

Animation
AudioMaking noise.
BenchMeasuring the computer player.
BunkersThe four bunkers the player shelters behind.
Cabinet
CollideAxis-aligned rectangle overlap.
DemoA computer player.
GameThe rules of Invaders, as a pure function.
MetaWhat this build calls itself.
PaletteThe shared palette.
RulesThe numbers that define the game.
ScoresThe high-score table.
ScreensDrawing the cabinet, as opposed to drawing the game.
SessionThe layer above the game.
SketchThe frame loop.
SpritesThe artwork.
StatsKeeping the performance figures.
StillA still picture: no state, no time, no input.
SurfaceA lightweight, Processing-shaped drawing surface built on Swing and Java2D.
TuningReading and writing the demo player's numbers.
View

Effects

CanvasDrawing, as an effect.
InputReading the input devices, as an effect.
SoundMaking a noise, as an effect.

Enums

BlastKindWhat blew up. The two look different and last for different lengths of time.
BombKindThe 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".
ColorColours and draw commands.
DrawCmdA single drawing instruction.
InvaderKindThe three kinds of invader, worth different points -- as in the original.
KeyA key, named rather than numbered.
PhaseWhat the game is currently doing.
RngA pseudo-random number generator, as a value.
ScreenWhat the cabinet is currently showing.
SoundCmdSomething the game wants heard.
SpritePixel art, as data.

Type Aliases

type alias Ball = { dx = Float32, dy = Float32, radius = Float32, tint = Color, x = Float32, y = Float32 }§ Source

A 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.

type alias Blast = { kind = BlastKind, pos = Vec2, ticksLeft = Int32 }§ Source

A short-lived explosion. ticksLeft counts down to zero, at which point it is dropped.

type alias Bomb = { age = Int32, kind = BombKind, x = Float32, y = Float32 }§ Source

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.

type alias Bouncing = { balls = List[Ball], nudge = Float32 }§ Source

The bouncing world: the balls plus the sideways nudge currently being applied.

type alias Bunker = { cells = Vector[Bool], origin = Vec2 }§ Source

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 }§ Source

Drawing 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.

type alias Caption = { colour = Color, size = Float32, text = String }§ Source

One line of an overlay: what it says, how big, and in what colour.

type alias Claim = { entry = Entry, player = Int32 }§ Source

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.

type alias Column = { depth = Int32, x = Float32, y = Float32 }§ Source

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 }§ Source

How 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.

type alias Endgame = { kills = Int32, pixels = Float32, ticks = Int32 }§ Source

The bot's movement and progress while eight or fewer invaders remain in a formation.

type alias Entry = { level = Int32, name = String, score = Int32 }§ Source

One line of the high-score table.

type alias Hand = { error = Float32, lapse = Int32, moving = Int32, rng = Rng, settled = Int32 }§ Source

The imperfect player's state: RNG stream, current error, and timers for movement/lapses.

type alias Invader = { alive = Bool, kind = InvaderKind, pos = Vec2, row = Int32 }§ Source

One invader in the formation. Dead ones keep their slot so the grid never reshuffles.

type alias Mystery = { dir = Float32, x = Float32 }§ Source

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 }§ Source

What 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] }§ Source

The arcade cabinet's complete state across games, players, screens, and high scores.

type alias Snapshot = { held = Set[Key], pressed = Set[Key], released = Set[Key] }§ Source

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 }§ Source

What 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 }§ Source

Every 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.

type alias Vec2 = { x = Float32, y = Float32 }§ Source

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 }§ Source

The whole game state.

  • playerX is the player's x position; its y never changes.
  • bullets travel up and are fired by the player; bombs travel down and are dropped by the invaders.
  • marchDir is which way the formation is marching, -1.0 or 1.0.
  • rng is threaded through every step rather than drawn from a global source.
  • seed is kept so that restarting rebuilds exactly the same starting position.
  • hiScore survives a restart, the way an arcade cabinet's does.
  • level counts from 1 and drives the difficulty curve.
  • pause is ticks remaining in a non-playing phase, used for the between-levels beat.
  • shield is ticks of invulnerability remaining, earned by shooting the mystery ship.
  • nextBonusAt is the score at which the next extra life is awarded.
  • shotsFired counts the cannon's shots on this board, and sets the saucer's value.
  • marchNote and marchedSince drive the bassline: notes are spaced by distance marched, not by time, so the tempo tracks the formation's speed for free.

Definitions

def main(): Unit \ { FileRead, FileWrite, Env, Exit, IO }§ Source

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

def readScores(): List[Entry] \ { FileRead, Env, IO }§ Source

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.

def readTuning(): Tuning \ { FileRead, Env, IO }§ Source

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.

def runSession(saved: List[Entry], tuning: Tuning): Session \ IO§ Source

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.

def writeScores(scores: List[Entry]): Unit \ { FileWrite, Env, IO }§ Source

Stores the high scores, reporting rather than throwing if it cannot.

Losing a table to a full disk should not be the last thing the player sees.