# Efail: making a game (read this first)

Efail is a 2D game engine written in [Bend](https://github.com/bendlang/bend).
A game is one file, `game.bend`, with pure functions. Efail handles the window,
the clock, input, replays, screenshots and headless runs. You never write a
game loop, a renderer or input handling.

## The loop you work in

```sh
efail check                                  # type-check (do this after every edit)
efail sim --ticks 300 --every 60             # run headless, print show(state)
efail shot --ticks 120 --input keys.txt      # run, then save build/shot.png; look at it
efail film --ticks 120 --every 10            # frames every 10 ticks in one build/film.png
efail run                                    # a human plays; Esc quits
efail replay --every 30                      # rerun exactly what the human just did
efail web                                    # build/game.html: the game in one web page
```

Everything is deterministic. The same seed and the same input give the same
states and the same pixels on every run. To reproduce a bug a human hit, run
`efail replay`. To check that a change works, write an input file, run `efail
sim` or `efail shot`, and read the output or open the PNG. For anything that
moves or animates, `efail film` is the one image to open: a grid of frames,
each labelled with its tick (`T 40`), matching the tick lines it prints.

## The contract: what game.bend defines

```python
import Base
import ./efail/efail.bend as E

def title() -> String:            # window title
def width() -> U32:               # pixels
def height() -> U32:
def background() -> U32:          # a color

type State is Data:               # your state; it must be `is Data`
  ...

def init(seed: U32) -> State:                  # the first state
def step(+input: E.Input, s: State) -> State:  # one tick; 60 a second
def draw(s: State) -> List<E.Shape>:           # what to show, back to front
def show(s: State) -> String:                  # one line for efail sim

# optional: the sounds that start this tick, from the state before and after
def sounds(old: State, now: State) -> List<E.Sound>:
```

The parameter quantities must match exactly: `+input` in `step`, and plain
`s`, `old`, `now` everywhere (destructure a state once to reuse its fields).
All the functions are pure: no IO, no time, no randomness except what you
derive from the seed. `efail check` checks this contract too.

## API (`E.` is efail/efail.bend)

**Shapes** (coordinates are F32 pixels from the top left; partly or fully off
the screen is fine):
- `E.rect(x, y, w, h, color) -> E.Shape`
- `E.circle(cx, cy, r, color) -> E.Shape`
- `E.text(string, x, y, size, color) -> List<E.Shape>`: a 3x5 pixel font,
  `size` pixels per cell, so a glyph is 3·size wide and 5·size tall, spaced
  every 4·size. It has A–Z (lowercase is drawn as uppercase), 0–9, and
  `: . , - + ! ? / ( ) = % ' < > _ # *`.
- `E.text_width(string, size) -> F32`: use it to center text.

**Sprites** are pixel art written as text, one character per pixel:
```python
def ship() -> List<&2, String>:
  ["..w..",
   ".wbw.",
   "wwwww"]

def inks() -> List<&2, E.Ink>:
  [E.ink('w', E.white()), E.ink('b', E.blue())]

# in draw:  E.sprite(ship(), inks(), x, y, 4.0)   # 4 pixels per character
```
- `.` and space are transparent. A character with no ink draws **magenta**:
  if a shot shows magenta, add the ink.
- `E.flip(rows)` mirrors a sprite left to right. `E.frame([a(), b()], tick,
  8)` picks an animation frame, switching every 8 ticks.
- `E.sprite_w(rows, scale)` and `E.sprite_h(rows, scale)` give the size, for
  `E.overlap`.
- Keep every row the same length. `examples/sprites` shows all of this.

Join lists with `a <> b` (one shape in front of a list), `List.append(&1,
E.Shape, xs, ys)` or `List.concat(&1, E.Shape, [xs, ys, zs])`.

**Colors** are U32 `0xRRGGBB` values. Bend has no hex literals, so use
`E.rgb(r, g, b)` or a named color: `E.black() white() gray() red() orange()
yellow() green() blue() purple() pink() navy()`.

**Input** (`input: E.Input`):
- `E.move_x(input) -> F32` and `E.move_y(input) -> F32`: -1.0, 0.0 or 1.0
  from the arrows **or** WASD (x: left/right, y: up/down, where down is +).
  Use these for movement: players reach for either.
- `E.held(input, key) -> Bool`: the key is down this tick.
- `E.pressed(input, key) -> Bool`: the key went down this tick (it was up the
  tick before). A tap, however short, is held for at least one tick.
- `E.axis(input, neg_key, pos_key) -> F32`: -1.0, 0.0 or 1.0 from two keys you
  choose.
- `E.tick(input) -> U32`: the tick number.
- Mouse: `E.mouse_x(input)`, `E.mouse_y(input)` (F32 game pixels, whole
  numbers), `E.clicked(input)` (the left button went down this tick) and
  `E.mouse_held(input)`. The buttons are keys too: `E.mouse_left()`,
  `E.mouse_right()`, for `E.held`/`E.pressed`. Test a click on something
  with `E.inside(E.mouse_x(input), E.mouse_y(input), x, y, w, h)`.
- Keys: `E.left() right() up() down() space() enter() escape() tab() shift()`,
  and `E.key('w')` for a letter or digit. Esc always quits `efail run`.

**Random:** keep a `seed: U32` in your state. `E.rand(seed)` returns a random
U32, which is also your next seed. `E.rand_range(r, lo, hi) -> U32` gives a
number in [lo, hi), and `E.randf(r) -> F32` one in [0, 1).

**Collisions** (rects are `x, y, w, h` from the top left, circles `cx, cy,
r`; touching edges don't count):
- `E.overlap(ax, ay, aw, ah, bx, by, bw, bh) -> Bool`: two rects.
- `E.inside(px, py, x, y, w, h) -> Bool`: a point in a rect.
- `E.circles_meet(ax, ay, ar, bx, by, br)`, `E.circle_rect(cx, cy, r, x, y,
  w, h)`, and `E.dist(ax, ay, bx, by) -> F32`.

**Math and choices are in Base already:** `F32.min max clamp lerp hypot abs
sqrt sin cos atan2 floor`, `F32.pi()`, `U32.min max clamp`. `Bool.pick(T, c,
a, b)` is a one-line "if" for any type (`a` when `c` is True), and `E.only(c,
shapes)` draws shapes only when `c` is True.

**Sound:** retro tones, described as data. You can't hear them; you check
them in text. `efail sim` prints each sound on the tick it starts:
`tick 141: sound slide 440>60 400ms square`.
- `E.beep(freq, ms, wave)`: a tone (`880.0` Hz for `60` ms).
  `E.slide(from, to, ms, wave)`: a sliding pitch (jumps rise, falls drop).
- Waves: `E.square()` (classic blip), `E.sine()` (soft), `E.saw()` (buzzy),
  `E.noise()` (hits, explosions; freq sets its grain).
- `E.when(cond, sound) -> List<E.Sound>`: the sound or nothing. Join
  several with `List.append(&1, E.Sound, a, b)`.
- In `sounds(old, now)`, compare the two states: score went up, a life was
  lost, a state changed (`match old now:` with a case per pair).
- `efail sim --wav out.wav` also writes the audio (16-bit, 24 kHz) for a
  human; the text lines are what you check. `efail run` plays the sounds
  (and plays silently, saying so, where there is no audio device).

## The web page (`efail web`)

`efail web` writes `build/game.html`, one self-contained file that plays the
game in a browser (open it as a file, or put it on any static host). It runs
your own `init`/`step`/`draw`/`show`/`sounds`, compiled to JavaScript by
Bend, with the native rules: 60 ticks a second, the same keys and mouse, the
same pixels and sounds. Its "Save replay" button downloads `last.replay`.
`efail sim --input last.replay` reruns that play exactly, so a bug a person
hits in the browser is reproduced headless like any other replay. Nothing
in game.bend changes for the web.

## Input files (and replays)

Plain text with one line per change: a tick, then the keys held from that
tick on. `efail run` writes the same format to `build/last.replay`.

```
# comments start with #
seed 42          # optional: the seed (--seed wins)
0                # nothing held at tick 0
30 right         # right held from tick 30
90 right space   # space also goes down at tick 90 (so pressed() is true then)
120              # all keys up
150 @100,60      # move the mouse pointer to (100, 60); it stays until the next @
160 mouse_left   # left button down at tick 160 (clicked() is true then)
165              # button up
end 300          # optional: how many ticks (--ticks wins)
```

Key names: `left right up down space enter escape tab shift mouse_left
mouse_right`, a single letter or digit, or a raw key code. `@x,y` (whole
pixels, no spaces) moves the pointer. Recorded replays use the same words.

A replay belongs to the game version that recorded it: change the controls
or the rules, and an old replay plays out differently. Keep the input files
your checks depend on next to the game and rerun them after each change.

## Writing Bend: the rules that bite

Bend is Python-shaped but strict. Read `bend guide` once; these are the rules
you will run into:

1. **A def must come before every use** in the file, types included. Put
   helpers above their callers.
2. **No mutual recursion, and recursion must shrink something.** A recursive
   call takes a smaller piece from a `match` (a list's tail, `n` from
   `1n+n`). For a loop of N steps, count down a `Nat`.
3. **There is no `if`.** Write a helper that matches on a `Bool` parameter:
   ```python
   def pickf(c: Bool, a: F32, b: F32) -> F32:
     match c:
       case True{}:
         a
       case False{}:
         b
   ```
   For values, `Bool.pick(T, c, a, b)` does this for any type (and `E.pick`
   for U32, `E.pickf` for F32). A match is still needed when the branches do
   different work, such as recursion or building different states.
4. **`match` and destructuring work only on parameters or pattern fields,**
   never on a computed value. Pass the value to a helper that takes it as a
   parameter. A `let` may not come before a `match` on a parameter.
5. **Variables are used at most once,** unless marked `+`: `+x = ...`, `+x:
   T` in a parameter list, or `Con{+h, t}` in a pattern. Mark a value `+`
   when you need it twice. A Nat predecessor you reuse is `1n+(+k)`.
6. **Operators need a type and spaces:** `(a + b * 2.0 : F32)` and `(n > 3
   : U32)`. Equality is a call: `U32.is_eq(a, b)`. `&&` and `||` work on
   Bool; `++` joins Strings.
7. **Literals:** `3` is U32, `3.0` is F32, `3n` is Nat. There are no negative
   literals, so write `(0.0 - 3.0 : F32)`. There are no hex literals.
   Conversions: `U32.to_f32`, `F32.to_u32`, `U32.show`, `Nat.show`.
8. **A list of shapes is `List<E.Shape>`. A list inside your State is
   `List<&2, T>`,** because State is `is Data` and its fields must be
   copyable.
9. When the checker can't tell a type, annotate it: `{x : U32}`.

`bend base` prints the standard library. `bend base List` prints one part.

## Laws (optional, Bend's superpower)

Add `LAWS.bend` to state facts that must always hold, for example "Esc quits",
"the score never drops" or "a game over stays over until space". Prove them
in `PROOF.bend`; `efail check` then proves them. See `bend guide` (Laws and
Proofs). Write laws about your step logic, not about F32 math: F32 can't be
proven.

## Files

```
game.bend         your game (edit this)
efail/efail.bend  the engine's API, a copy (`efail upgrade` refreshes it); every
                  E.* name is here with its doc comment: read it if unsure
efail/lib/        the engine's parts (rendering, PNG, sound, ...); no need to read
build/            made by efail; safe to delete
AGENTS.md         this file
```
