plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


70c9b8d — Peter John 2026-11-12T22:52:24+05:30
docs: game.md around the screen view (the view and its frame, actors, how std draws a view, the slice, clicks, effects and navigation, undo and time travel, the kit, beside master: every signature that differs and why); language.md (subtrait defaults, imports from the importing file's folder), std.md, the backlog (screen views: what is open, the closure match bug), the scene-tree results kept as a record
README.md CHANGED
@@ -82,7 +82,7 @@ plum editor helix # set up your editor (or vscode)
82
82
 
83
83
  - [The language](docs/language.md): the full guide
84
84
  - [The standard library](docs/std.md): strings, lists, maps, JSON, files and more
85
- - [The game engine](docs/game.md): drawing, input, sound and scene graphs
85
+ - [The game engine](docs/game.md): screens and their views, drawing, input, sound, record and replay, undo
86
86
  - [Tools](docs/tools.md): every command and option, editors, building from source
87
87
  - [Performance](docs/performance.md): how the compiler optimises your code
88
88
  - [Examples](examples): a runnable file per feature, and example games
docs/backlog.md CHANGED
@@ -2,12 +2,22 @@
2
2
 
3
3
  Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open is here: finished and dismissed items were removed (history is in git and in `docs/plans/`). Numbers come from `docs/benchmarks/2026-11-11-simpler-language-before-after.md` unless a line says otherwise.
4
4
 
5
+ ## Screen views (branch `sl/view`, 2026-11-12)
6
+
7
+ The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, `Control` for effects, undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks is master's (925878360). Open:
8
+
9
+ - **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test block, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`, `headless.isRestart`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
10
+ - **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); trmc on `List.map` with a coercion (`xs.map(|m| m)` into a `List<Actor>`) fails its re-check (`actor.all(xs)` lifts through a typed helper); dead-code removal is reverted when it removes every type a downcast to a trait could match (`Container as c`; `declared` became an `Actor` method).
11
+ - **Frames on demand in the hosts**: `Game.idle()` works, but no host is told (master's `frameIdle` extern, and the browser skipping the draw and waiting for input).
12
+ - **Development keys** (`plum run --dev`, master's `remakeGame` host call): a game offers undo only through its own effects.
13
+ - **`plum run <folder>`** (master runs a game's folder; here the main file is named).
14
+ - **Master's other games** (`clockwork`, `menu`) are not ported.
15
+ - **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master.
16
+
5
17
  ## Decided, not built
6
18
 
7
19
  - **Compile-time layer** (`docs/plans/2026-11-09-comptime-generics.review.md`). The `<>` syntax, the trait list in `[]` and the trait jump table from that plan are done. Still to build: `@hasMethod`, `@hasField`, `@fields`, `@field`, `comptime if` and `comptime for`, `@compileError`, `@embedFile`, `@src`, constants computed while compiling, `comptime fun`, value generics and type aliases, default type parameters, `Option` of a reference as a nullable reference (no allocation for `Some`, allocation-free `for` loops), derives in std (`hash`, `eq`, `toStr`, `lerp`, JSON), replay checksums with snapshot and rewind, easing and tweens in `Anim`.
8
- - **`Clickable` as a compile-time flag.** The pointer walk tests each node with a trait downcast (one tag check). Once the compile-time layer exists, compute "is clickable" once at spawn and store it in the node. Needs a node field `RoseTree` does not have.
9
20
  - **Testing** (user: "All 3 please"): `group "name"` blocks with scoped helpers; compare-mode tests (one flag runs a test with and without fusion and in-place updates); property tests in std (`check(|a, b| a + b == b + a)` with generated inputs).
10
- - **Optional or automatic actor keys.** Most actors need no `key`. Either a default `key() -> Option<Int>`, or ids handed out by the tree from a counter and stored in the node. Open: how a spawner learns its child's id.
11
21
  - **Constant map literals.** `[k => v]` lowers to `Map.empty().with(..)`, O(n log n). When every key is a compile-time constant, build the tree while compiling.
12
22
 
13
23
  ## Performance
@@ -16,11 +26,9 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
16
26
  - **`Map` reuse stops as soon as any map in the program is shared.** A uniquely owned map is now updated in its own cells (the `map` workload went from 479 to 281 ms; the old hash table took about 200), and `Int`, `Byte` and `Float.compare` are native and inlined. But field uniqueness is decided per type over the whole program, so one kept old version of a `Map` anywhere turns deep reuse off for every `Map`: Orb Run gets none. Reuse alongside sharing needs a per-value deep-uniqueness analysis. Also open: `Map.get` allocates an `Option` on a hit (fusion treats `Map.get` as an impure producer).
17
27
  - **Closure calls are untyped.** A closure is held as `anyref`: each call does two casts and an indirect call, and building one allocates two objects. A typed closure struct per signature with `call_ref` would fix it. Indirect evidence: `cons_rec` (1.94 s) and `cons` without fusion (1.0 s) did not move.
18
28
  - **A value struct inside an enum payload is boxed twice** (`Some(Pos)` allocates two objects). No measurement yet.
19
- - **Scene tree with kept snapshots**: "60 kept" at N = 10000 costs 11 times a plain step. Ideas, all functional: a 32-way chunked vector for children instead of the sibling chain; skipping subtrees that cannot change; world transforms cached per node; reusing last frame's draw list when the root is the same object.
20
29
  - **In-place updates still miss** 36 of Orb Run's 56 spreads. Reasons, by count: a value rebound by a pattern (8), the receiver read again after a method call (5), a shared value (4), a field passed on without being written back (4), an argument passed from inside a closure (4).
21
30
  - **Static functions are slower than free functions** (0.78 s against 0.57 s on `benchmarks/static_calls`).
22
31
  - **Smaller codegen items**: match arms test then cast (`br_on_cast` would do one check); the inliner skips leaves that use their locals (`unbox.*`); every struct has its own empty supertype; purity treats every closure-taking function as impure, so pipelines fuse only after closure specialisation.
23
- - **The hover lookup costs about 3% per tick** (the context holds the tree being stepped).
24
32
  - No evidence either way, so not planned: unchecked reads in `for` over a `Slice` (checked `at` showed no cost).
25
33
 
26
34
  ## Bugs
@@ -39,7 +47,7 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
39
47
  - **Type arguments on a static call's type** (`T<Int>.make()`) are not supported, and type arguments in an expression must be on one line.
40
48
  - **Struct field defaults** (`struct Place(x: Float, scaleX: Float = 1.0)`) and **`fn` types as type arguments** (`Slice<fn(Int) -> Int>`): both need grammar changes.
41
49
  - **No private members.** `Decimal`'s big-number helpers are public statics (`Decimal.bigAdd`).
42
- - **No warnings.** A `hit` method on an actor that does not list `Clickable` is silently never called. Open question below.
50
+ - **No warnings.** A `hit` method on an actor that is not `Sized` is silently never called. Open question below.
43
51
  - **A nested closure cannot call the outer self-calling closure** (a checker error today), and a self-calling closure whose parameter has no type and no later hint cannot be checked.
44
52
  - From master's gap list, not yet looked at here: `..` in patterns, tests that expect a crash.
45
53
 
@@ -51,11 +59,11 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
51
59
  ## Candidates from other branches (not started, not decided)
52
60
 
53
61
  - From `self-hosting`: a WASI preview 2 target (`plum compile --target wasi`); running tests on the standalone wasmtime CLI and dropping the embedded host; `plum chrome` with a browser runtime for parity checks; `plum dump-ast` and its invalid-parse fixtures.
54
- - From `master`: typed `Assets` with `Assets.none()` for tests; compiling a trait's default method once instead of once per implementer, if that is what happens here (not checked); the wasm-gc dispatch write-up.
62
+ - From `master`: compiling a trait's default method once instead of once per implementer, if that is what happens here (not checked); the wasm-gc dispatch write-up.
55
63
 
56
64
  ## Open questions for the user
57
65
 
58
- 1. Should the checker gain warnings, starting with "`hit` without `Clickable`"?
66
+ 1. Should the checker gain warnings, starting with "`hit` without `Sized`"?
59
67
  2. `Str.runeAt`: keep the `Option`, or crash like `at` and add `getRune`?
60
68
  3. `Map.getEntryAt`: keep the name?
61
69
  4. Which performance item first after the Map work: compile time, typed closure calls, or the scene tree with snapshots?
docs/benchmarks/2026-11-08-scene-trees-branch.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # The persistent scene tree on simpler-language, against master's three trees
2
2
 
3
+ (A record: the scene tree and `benchmarks/scene_trees` were removed on branch `sl/view`, where each screen draws its `view` instead; `git show 8b93d564:benchmarks/scene_trees/run.py` has the last version of the code. `benchmarks/screen_views` times the screens that replaced it.)
4
+
3
5
  Taken 2026-11-09 on an Apple M3 Pro (18 GB), macOS 26.6.2, load average about 3 (2.8 to 3.7 during the run). Master at `e0ccfc7` (lazy `ctx.world()`, kills and spawns in the step's walk, bitsets: "After T30" in master's docs/benchmarks/2026-11-08-scene-trees.md, which is not on this branch), this branch at `ed1be37` plus this change. Five rounds, each cell the median with the range in brackets, in ms.
4
6
 
5
7
  The question: the branch has in-place updates for values only one place holds (FBIP: a spread written into the old value, a rebuilt enum cell written over the old one) and fusion. Does that make a persistent tree, which rebuilds the bodies and links every tick, competitive with master's mutable trees? And what would master need to get the same gain?
docs/game.md CHANGED
@@ -7,318 +7,455 @@ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It
7
7
  ## Try it
8
8
 
9
9
  ```sh
10
- plum run examples/games/orb_run.plum
10
+ plum run examples/games/orbitrunner/OrbitRunner.plum
11
11
  ```
12
12
 
13
- This builds the game, starts a local server and opens your browser. Press Enter or click Play, then steer with the arrow keys or WASD, collect the orbs and dodge the mines. Press a key first, because browsers only start sound after you interact with the page.
13
+ This builds the game, starts a local server and opens your browser. Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back.
14
+
15
+ ## A game's files
16
+
17
+ A game is a folder: the file with `main`, its `assets`, and the rest of its source in as many files as it likes. Each file is a module, and the files of a game import each other by their path from the game's folder, whichever folder the importing file is in: an import is looked for beside the importing file, then in each folder above it, nearest first, then from the folder that holds `std` (`import std/..` only there; see [Modules](language.md#modules)). The example games are laid out like this:
18
+
19
+ ```
20
+ examples/games/orbitrunner/
21
+ OrbitRunner.plum main, the Assets, and what several files share
22
+ screens/PlayingScreen.plum one file per screen: the screen, its slice (its state in
23
+ its fields, its actions, reducer, effects, input mapping
24
+ and view)
25
+ actors/Ship.plum one file per kind of actor (Orb.plum, Mine.plum, Star.plum,
26
+ Ring.plum)
27
+ assets/
28
+ ```
29
+
30
+ `screens/PlayingScreen.plum` writes `import actors/Ship` (one import per file) and `actors/Ship.plum` writes `import OrbitRunner` for the `Arena` it flies in (files may import each other). Each file keeps its own `test` blocks, and `plum test examples/games/orbitrunner` runs every file's. A screen struct's name ends in `Screen` (`PlayingScreen`); the name its `name()` gives stays short (`"play"`). The example games carry no comments: their names and their tests say what they do.
14
31
 
15
32
  ## A minimal game
16
33
 
17
- There is one way to make a game: `main` returns a `Game<S, M>` ([`std/game/Game.plum`](../std/game/Game.plum)), made by `Game.start(tree, state)`. A game is three things you write, and `Game` runs the loop:
34
+ A game is a `Game` (`std/game/Game`): a list of screens. A screen implements the `Screen` trait. Its state is plain fields, and its `view` says what the frame shows: a list of actors, made again from those fields every time the frame is drawn. A screen with rules is a slice of the game ([The slice](#the-slice), below): an enum of its actions, the input mapped to them, and a reducer that returns the next screen. If `main` returns a `Game`, `plum run` runs it as a game. Any other `main` is a command line program.
18
35
 
19
- - **Actors.** Each thing on the screen is its own struct that implements `Actor<M>` ([Scenes](#scenes)), with its own `step` (its next version, every tick), `paint`, and `input` (a pointer event on it). One the pointer can hit is `Clickable` too, and says where with `hit`.
20
- - **Screens.** The game's tree of actors has a root whose children are the screens (a title, the play, a game over). A screen is a struct that implements `Screen<S, M>`, an actor too, and its subtree is what it shows. Only one screen is shown at a time, the one the state names. A screen's `rules` run after the actors stepped (collisions, keys), its `react` shows a new state after each message, its `enter` sets it up when the state switches to it, its `transition` says how it comes in, and its `draw` draws the frame ([Screens and transitions](#screens-and-transitions)). By convention a screen's struct name ends in `Screen`.
21
- - **A reducer.** The game's state `S` is a `Reducer<M>` ([`std/game/Store.plum`](../std/game/Store.plum)). `update(self, msg)` is the rules of the state: pure, with no `io`. `handle(self, io, msg)` is the effects of a message (a sound, a save), run after the tick. `screen(self)` names the screen to show. `M` is the game's message type: actors and rules send messages with `ctx.send(msg)`, and a button sends its `onClick`.
36
+ This game counts the clicks on a box and rolls a ball while Right is held, and ends on Escape. The box says it takes presses (`touch: Enabled`; a ready-made box is decoration otherwise), and the screen keeps it in a field, so a press on it comes to the screen as that box. It is [`examples/games/clicks.plum`](../examples/games/clicks.plum):
22
37
 
23
38
  ```plum
24
- import std/Int
25
- import std/Float
26
- import std/Str
27
- import std/Option
28
- import std/Io
29
- import std/math/Affine
30
- import std/game/Color
31
- import std/game/gfx
32
- import std/game/input
33
- import std/game/ui
34
- import std/game/Store
35
- import std/game/Game
36
- import std/collections/RoseTree
37
- import std/game/Place
38
- import std/game/Actor
39
- import std/game/Ctx
40
- import std/game/SceneTree
41
-
42
- # What can happen to the state.
43
- enum Msg = Clicked | Cleared
44
-
45
- # The state: the clicks so far.
46
- struct Clicks[Reducer<Msg>](n: Int) =
47
- fun update(self, msg: Msg) -> Clicks = match msg
48
- Clicked => Clicks(n: self.n + 1)
49
- Cleared => Clicks(n: 0)
50
-
51
- # A ball that rolls right while the Right key is held.
52
- struct Ball[Actor<Msg>](id: Int, x: Float, y: Float) =
39
+ enum TapAction = Tapped | Push(dx: Float) | Tick(dt: Float) | Quit
53
- fun key(self) -> Int = self.id
54
40
 
41
+ struct Ball[Actor](x: Float, y: Float, vx: Float) =
55
42
  fun place(self) -> Place = place.at(self.x, self.y)
56
43
 
57
- fun step(self, ctx: Ctx<Msg>, dt: Float) -> Ball =
44
+ fun view(self) -> List<Actor> = [Circle.of(0.0, 0.0, 10.0, Color.Yellow)]
58
- if ctx.input.isKeyDown(Key.Right) then Ball(..self, x: self.x + 100.0 * dt) else self
59
45
 
60
- fun paint(self, io: Io, m: Affine, alpha: Float) =
46
+ fun push(self, vx: Float) -> Ball = Ball(..self, vx: vx)
61
- actor.circlePaint(io, m, alpha, 0.0, 0.0, 10.0, Color.Yellow)
62
47
 
63
- # The one screen, the root of the ball, a button that sends `Clicked`, and a label with
48
+ fun update(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
64
- # the count. Its name is its type's, `RoomScreen.name()`; a game of one screen needs no
65
- # `screen()` in its state.
66
- struct RoomScreen[Screen<Clicks, Msg>](id: Int) =
67
- fun key(self) -> Int = self.id
68
49
 
50
+ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
69
- fun place(self) -> Place = place.at(0.0, 0.0)
51
+ fun start() -> TapScreen =
52
+ TapScreen(taps: 0, box: Box(x: 350.0, y: 250.0, w: 100.0, h: 100.0, color: Color.Red, touch: Enabled), ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
70
53
 
71
- # Escape clears the count.
54
+ fun name(self) -> Str = "tap"
72
- fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: Clicks, dt: Float) -> SceneTree<Msg> =
73
- if ctx.input.isKeyPressed(Key.Escape)
74
- ctx.send(Cleared)
75
- t
76
55
 
77
- # After each message: the label shows the new count.
78
- fun react(self, t: SceneTree<Msg>, state: Clicks, msg: Msg) -> SceneTree<Msg> =
79
- t.updateAs<Label<Msg>>(3, |l| l.relabel("clicks {state.n}"))
56
+ fun view(self) -> List<Actor> = [self.box, self.ball, Label.of(20.0, 20.0, "Taps: {self.taps}", 24.0, Color.White)]
80
57
 
81
- fun draw(self, io: Io, shown: SceneTree<Msg>) =
58
+ fun onPress(self, target: Actor, at: Vec2) -> Option<TapAction> = if @sameRef(target, self.box) then Some(Tapped) else None
82
- gfx.clear(io, Color.Black)
83
- shown.draw(io)
84
59
 
85
- fun main(io: Io) -> Game<Clicks, Msg> = start()
60
+ fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
61
+ KeyDown(k) => if k == Key.Escape then Some(Quit) else None
62
+ _ => None
86
63
 
64
+ fun held(self, input: Input) -> Option<TapAction> = Some(Push(dx: if input.isKeyDown(Key.Right) then 100.0 else 0.0))
65
+
66
+ fun tick(self, dt: Float) -> Option<TapAction> = Some(Tick(dt: dt))
67
+
68
+ fun reduce(self, a: TapAction) -> TapScreen = match a
69
+ Tapped => TapScreen(..self, taps: self.taps + 1)
70
+ Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
71
+ Tick(dt) => TapScreen(..self, ball: self.ball.update(dt))
72
+ Quit => self
73
+
74
+ fun effect(self, io: Io, a: TapAction, game: Control) = match a
75
+ Quit => game.exit()
76
+ _ => Unit
77
+
87
- fun start() -> Game<Clicks, Msg> =
78
+ fun main(io: Io) -> Game =
88
- room: RoseTree<Actor<Msg>> := RoseTree.of(RoomScreen(id: 0), [
89
- RoseTree.leaf(Ball(id: 1, x: 20.0, y: 150.0)),
90
- RoseTree.leaf(ui.button(2, 20.0, 20.0, 120.0, 40.0, "Click", Clicked)),
91
- RoseTree.leaf(Label(id: 3, x: 20.0, y: 80.0, text: "clicks 0", size: 16.0, color: Color.White))])
92
- Game.start(SceneTree.ofScreens([room]), Clicks(n: 0))
79
+ only: Screen := TapScreen.start()
80
+ Game(screens: [only])
93
81
  ```
94
82
 
95
- This is [`examples/games/clicks.plum`](../examples/games/clicks.plum), a game of one screen: `SceneTree.ofScreens(screens)` makes a tree whose root (a `Group` with id -1) has the screens as its children, and a state that doesn't say `screen()` shows the first one. `main` runs once, after your assets have loaded. If `main` returns anything else, `plum run` runs it as an ordinary program. A type of your own with `update` and `draw` was the old way to make a game; `main` returning one is now a compile error that names `Game.start`.
83
+ `main` runs once, after your assets have loaded. Then the game runs in ticks of 1/60 s: each tick is delivered to the shown screen as actions, and its reducer returns the next screen, which the game keeps; once per frame the game draws it, which only reads it: it clears the screen with the screen's `background()` (black by default) and draws the screen's view. Nothing is bound to anything and nothing is kept between frames: the label shows `self.taps` because the view reads it each time.
96
84
 
97
- ### One tick
85
+ Something that moves on its own moves in the reducer, on the tick action (`tick(dt)` above, `Tick(dt) => .. self.ball.update(dt)`): the reducer calls the actor's own method, which returns the actor's next version.
98
86
 
99
- Each tick, `Game.update(io, input, dt)` does this, in this order:
87
+ ## A screen's view
100
88
 
101
- 1. Each pointer event of the tick goes to the topmost shown `Clickable` actor of the current screen under it that says it is hit (`hit`), through its `input`, then to each of its parents up to the root. Each gets the event in its own coordinates. A `PointerMove` that leaves the pointer where it was goes to no actor.
102
- 2. The root and the current screen's actors step (`step`), parents before children, then the screen's `rules` run. Both see the tick's input in `ctx.input` (held keys, the pointer) and the screen's size in `ctx.view`.
103
- 3. The spawns and kills apply to the root and the current screen (`ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`): those pushed by `input`, then by the steps, then by the rules. The root's children are the screens, so a node spawned under the root itself must be a `Screen` (it joins the others); any other actor there stops the program with a message naming the current screen to spawn it under, since it would never be stepped or drawn.
104
- 4. Each message sent, in order: the store reduces it (`update`), then the current screen `react`s to the new state.
105
- 5. After the tick: `handle(io, msg)` runs for each message, in order, with the state after the tick. Then, if `state.screen()` names another screen, that one `enter`s and becomes current, coming in by its `transition`. Then `ctx.out.push(Restart)` starts the game over from its first tree and state, and `ctx.out.push(Exit)` ends it: no tick runs after it, and the last frame stays drawn.
89
+ A screen's `view(self) -> List<Actor>` is what the frame shows: a list of actors, placed in the world's coordinates, made from the screen's fields. Orbit Runner's play:
106
90
 
107
- `Game.draw(io)` draws a frame through the current screen's `draw`. Nothing is changed in place: each tick returns the next game.
91
+ ```plum
92
+ fun view(self) -> List<Actor> =
93
+ back: List<Actor> := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
94
+ mines := actor.all(self.mines)
95
+ orbs := actor.all(self.orbs)
96
+ ship: List<Actor> := if self.over then Nil else [self.ship]
97
+ rings := actor.all(self.rings)
98
+ hud: List<Actor> := [
99
+ Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
100
+ Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
101
+ over: List<Actor> := if self.over
102
+ [Overlay.of(Arena.W, Arena.H, [
103
+ Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
104
+ Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
105
+ else
106
+ Nil
107
+ back.append(starsFrom(0, self.clock)).append(mines).append(orbs).append(ship).append(rings).append(hud).append(lifeIcons(0, self.lives, self.assets.sheet)).append(over)
108
+ ```
109
+
110
+ What shows only sometimes is left out (the ship once the run is over, the game over panel until it is), what repeats is a list made by a function or a fold, and a list the screen holds is appended, lifted to a `List<Actor>` by `actor.all` (a `List<Mine>` is not a `List<Actor>`, see [Coercion](language.md#coercion)). Later items draw over earlier ones. (Master writes the same view as one list literal with `if`, `for` and `..` elements, which this dialect's list literals don't have.)
111
+
112
+ - **Drawn, not live.** The view is made again every time the frame is drawn, and its items keep nothing from one frame to the next: they are not stepped. So each takes plain values read from the fields (a `Label`'s `text`, a `Sprite`'s `frame`). A `Group` or an `Overlay` in a view draws the children it is made with (an actor's `declared(self) -> List<Actor>`, empty by default), and an actor with a view of its own draws that, so views nest.
113
+ - **Two kinds of item.** An actor the screen holds in a field and names in its view (the ship, each mine of `self.mines`) is the very object in the field when the frame is drawn: a press on it reaches the screen as that object ([Clicks](#clicks)), and `@sameRef(target, self.box)` tells which. An item made inside `view` (the HUD's labels, the stars, the game over panel) is a new object every frame, made from the fields.
114
+ - **The state rule.** `view` only reads; the state changes in the reducer and in what it calls. A screen is a value, so this holds by construction: there is nothing for the draw to change.
115
+
116
+ What else a screen says about its frame, each with a default:
117
+
118
+ | `Screen`'s method | Default | What it does |
119
+ |---|---|---|
120
+ | `view(self) -> List<Actor>` | empty | what the frame shows (above) |
121
+ | `size(self) -> Vec2` | 0 by 0 | the world the view is placed in, in its own units: Orbit Runner's arena, 800 by 600. 0 by 0 is the screen's own pixels |
122
+ | `viewport(self) -> Scaling` | `Fit` | how that world is put on the screen (`std/game/Viewport`): `Fit` letterboxes it, `Extend` grows it to fill the screen, `Fill`, `Stretch`, `Pixels` |
123
+ | `background(self) -> Color` | black | what the frame is cleared with before the view is drawn |
124
+ | `culls(self) -> Bool` | false | true skips each `Sized` item (and what is under it) whose bounds miss what the screen shows |
125
+ | `busy(self) -> Bool` | false | true asks an `OnDemand` screen's next tick ([Frames on demand](#frames-on-demand)) |
126
+ | `frames(self) -> Frames` | `Always` | `OnDemand` for a screen that only changes when something happens |
127
+ | `draw(self, io, m, alpha, area)` | the view | draws the frame through `m` (the world to the screen's pixels); define it to draw more (a HUD with `gfx`), not to clear |
108
128
 
109
- ### Screens and transitions
129
+ The pointer is mapped through the same viewport, so a press arrives in the world's coordinates: a screen has no fit or resize code of its own (`resize(self, w, h) -> Self` is there for a screen that wants the size, as a layout).
110
130
 
111
- The screens are the children of the tree's root, and each is a `Screen<S, M>` ([`std/game/Game.plum`](../std/game/Game.plum)). A screen's name is its type's: `PlayScreen.name()` is `"PlayScreen"` (the trait's static `name()` defaults to `@typeName(Self)`, see [Built-ins](language.md#built-ins)), so game code never writes it as a string. The state keeps the name of the screen to show and its reducer sets it: `Start => State(..self, on: PlayScreen.name())`, with `fun screen(self) -> Str = self.on`. After a tick whose messages changed it, `Game` switches to that screen.
131
+ ### Actors
112
132
 
113
- Each method gets `t`, the screen's own subtree (its root is the screen), and returns it changed:
133
+ An actor is a struct of the game's own that implements `Actor` (`std/game/Actor`): `place(self) -> Place` (`std/game/Place`: position, rotation, scale, the origin it turns about and its `alpha`), and what it looks like, its own `view` of ready-made items placed in its coordinates. Its other fields are plain and public. It moves in a method of its own that returns its next version, which the screen's reducer calls each tick (`update(self, dt, frozen) -> Mine` in the example games):
114
134
 
115
- - `rules(self, t, ctx, state, dt)`: after the actors stepped (collisions, keys); acts through `ctx`.
116
- - `react(self, t, state, msg)`: after each message was reduced, while the screen is current: show the new state (`t.updateAs<Label<Msg>>(ScoreId, ..)`).
117
- - `enter(self, t, state, tree)`: when the state switches to it. `tree` is the whole tree, so a screen can start from what another shows (`tree.subtree(PlayScreenId)`). By default the screen resumes as it was left.
118
- - `transition(self, from)`: how it comes in from the screen named `from`: `Cut` (the default), `Fade(secs)`, or `Slide(from: FromRight, secs)` (also `FromLeft`, `FromTop`, `FromBottom`). The screen coming in chooses, since how it appears belongs with it, and the state stays only the game's rules.
119
- - `draw(self, io, shown)`: draws the frame while it is current; `shown` is the root with what is shown (by default `shown.draw(io)`, through the tree's camera).
135
+ ```plum
136
+ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture) =
137
+ Radius = 11.0
138
+
139
+ fun create(start: Motion, tex: Texture) -> Mine =
140
+ Mine(at: place.pivoted(start.x, start.y, Sheet.Size / 2.0, Sheet.Size / 2.0), vx: start.vx, vy: start.vy, clock: 0.0, tex: tex)
141
+
142
+ fun place(self) -> Place = self.at
120
143
 
121
- Only the current screen is shown, gets input and steps. The others are paused and kept: the tick starts from the root and the current screen, and never walks into a hidden screen's subtree, so a big hidden screen costs nothing per tick (2000 ticks with a hidden screen of 20000 actors take as long as with none). Coming back to a screen resumes it where it was. Its `rules`, `react`, `findAs`, `updateAs`, spawns, kills and pointer events reach only its own subtree, so an id needs to be unique only within its screen.
144
+ fun view(self) -> List<Actor> =
145
+ [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 2.0 * Sheet.Cell, Sheet.Cell, Sheet.Cell, Sheet.frame(self.clock, 4, 4.0))]
146
+
147
+ fun update(self, dt: Float, frozen: Bool = false) -> Mine =
148
+ clock := self.clock + dt
149
+ if frozen
150
+ Mine(..self, clock: clock)
151
+ else
152
+ moved := Mine(..self, clock: clock).put(self.motion().drifted(Mine.Radius, dt))
153
+ Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
154
+ ```
122
155
 
123
- During a transition other than `Cut`, both screens are drawn, the one going out fading or sliding out and the one coming in fading or sliding in over `secs` seconds of ticks. Only the one coming in gets input and steps, and reacts to messages; the one going out is frozen. `Game` animates them with a parent of each screen that has an offset and an opacity, so the screens' actors see it in their `ctx` too (and a sliding screen is hit where it is drawn). A transition that starts on a tick is first drawn with the old screen fully shown; `game.shift` is the transition in progress.
156
+ and the screen's tick moves what it holds, then runs the rules:
124
157
 
125
158
  ```plum
126
- import std/Int
127
- import std/Float
128
- import std/Str
129
- import std/Option
130
- import std/Io
131
- import std/math/Vec2
132
- import std/game/Color
133
- import std/game/gfx
134
- import std/game/input
135
- import std/game/ui
136
- import std/game/Store
137
- import std/game/Game
138
- import std/collections/RoseTree
139
- import std/game/Place
140
- import std/game/Actor
141
- import std/game/Ctx
142
- import std/game/SceneTree
143
-
144
- enum Msg = Start | Back
145
-
146
- # The state names the screen shown, by the screen's own name.
147
- struct State[Reducer<Msg>](on: Str, starts: Int) =
148
- fun update(self, msg: Msg) -> State = match msg
159
+ fun advance(self, dt: Float) -> PlayingScreen =
160
+ over := self.over
161
+ moved := PlayingScreen(
162
+ ..self, clock: self.clock + dt, mines: self.mines.map(|m| m.update(dt, over)), orbs: self.orbs.map(|o| o.update(dt, over)),
149
- Start => State(..self, on: PlayScreen.name(), starts: self.starts + 1)
163
+ ship: self.ship.update(dt, over), rings: self.rings.map(|r| r.update(dt)).filter(|r| !r.done()))
150
- Back => State(..self, on: TitleScreen.name())
164
+ ruled := if over then moved else moved.rules()
151
-
152
- fun screen(self) -> Str = self.on
153
-
154
- # The title: Enter starts.
155
- struct TitleScreen[Screen<State, Msg>](id: Int) =
156
- fun key(self) -> Int = self.id
157
-
158
- fun place(self) -> Place = place.at(0.0, 0.0)
159
-
160
- fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
161
- if ctx.input.isKeyPressed(Key.Enter)
162
- ctx.send(Start)
163
- t
164
-
165
- # The play: it fades in over the title in half a second, and Escape goes back to the
165
+ if ruled.again then PlayingScreen(..ruled, again: false).dispatch(StartOver) else ruled
166
- # title, which resumes as it was left.
167
- struct PlayScreen[Screen<State, Msg>](id: Int) =
168
- fun key(self) -> Int = self.id
169
-
170
- fun place(self) -> Place = place.at(0.0, 0.0)
171
-
172
- fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
173
-
174
- fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
175
- if ctx.input.isKeyPressed(Key.Escape)
176
- ctx.send(Back)
177
- t
178
-
179
- # Each time the state switches to it: the label shows how many runs there were. (The
180
- # `Start` that switched came while the title was current, so the title reacted to it.)
181
- fun enter(self, t: SceneTree<Msg>, state: State, tree: SceneTree<Msg>) -> SceneTree<Msg> =
182
- t.updateAs<Label<Msg>>(1, |l| l.relabel("run {state.starts}"))
183
-
184
- fun draw(self, io: Io, shown: SceneTree<Msg>) =
185
- gfx.clear(io, Color.Black)
186
- shown.draw(io)
187
-
188
- fun main(io: Io) -> Game<State, Msg> = start()
189
-
190
- fun start() -> Game<State, Msg> =
191
- tree: SceneTree<Msg> := SceneTree.ofScreens([
192
- RoseTree.of(TitleScreen(id: 10), [RoseTree.leaf(Label(id: 1, x: 20.0, y: 20.0, text: "Press Enter", size: 24.0, color: Color.White))]),
193
- RoseTree.of(PlayScreen(id: 20), [RoseTree.leaf(Label(id: 1, x: 20.0, y: 20.0, text: "run 0", size: 24.0, color: Color.Yellow))])])
194
- Game.start(tree, State(on: TitleScreen.name(), starts: 0))
195
166
  ```
196
167
 
197
- This is [`examples/games/two_screens.plum`](../examples/games/two_screens.plum). `Game.start` stops the program if a child of the root is not a screen, if two screens have one name, or if no screen has the state's. A name the state asks for later that no screen has keeps the current screen and is reported once on the host's output (`game.unknown` holds it). `Restart` goes back to the tree and the state `Game.start` was given, with no transition.
168
+ An actor that draws something no ready-made actor does (an additive glow, a line) overrides `paint(self, io, m, alpha)` and draws with `gfx` through `m`; `actor.paintView(io, self.view(), m, alpha)` then draws its view as well (Orbit Runner's `Orb`, Balloon Pop's `Balloon`, whose string is a line). `Actor.plum` also has helpers for drawing in an actor's own coordinates (`actor.rectPaint`, `circlePaint`, `linePaint`, `spritePaint`, `textPaint`).
198
169
 
199
- [`orb_run.plum`](../examples/games/orb_run.plum) is a whole game this way, with a title, a play and a game-over screen, the play fading in over the title; its header comment explains how it is put together.
170
+ What else an actor is, it says with a small trait:
171
+
172
+ | Trait | What it says |
173
+ |---|---|
174
+ | `Sized` (`std/game/Sized`) | `bounds(self) -> Aabb`, the box it covers in its own coordinates. An actor with bounds can be hit; one without cannot. `hit(self, p) -> Bool` is inside the bounds, edges included, unless the actor says otherwise for an exact shape (`Circle` is hit inside its circle; a balloon on its body, its knot and its string). Culling goes by the bounds too |
175
+ | `Touch` (`std/game/Touch`) | `touch(self) -> Touchable`: whether it takes presses. `Enabled`: it is hit where it is (when it is `Sized`) and what is under it is; `Disabled`: neither it nor anything under it is hit; `ChildrenOnly`: what is under it is, it is not. An actor that says nothing is `ChildrenOnly` |
176
+
177
+ The ready-made kinds take every field (struct fields have no defaults in this dialect), and each has a static that fills in the usual ones:
178
+
179
+ | Kind | Fields | Usual |
180
+ |---|---|---|
181
+ | `Group` | `x, y, touch, children` | `Group.of(x, y, children)`, `ChildrenOnly` |
182
+ | `Box` | `x, y, w, h, color, touch` | `Box.of(x, y, w, h, color)`, decoration (`Disabled`) |
183
+ | `Circle` (`std/game/Circle`) | `x, y, r, color, touch` (x, y the top-left of its bounding box) | `Circle.of(x, y, r, color)` |
184
+ | `Sprite` (`std/game/Sprite`) | `x, y, tex, w, h, srcX, srcY, srcW, srcH, frame, tint, touch`; `frame` picks the cell along a strip of `srcW`-wide cells from (`srcX`, `srcY`) | `Sprite.cell(x, y, tex, w, h, srcX, srcY, srcW, srcH, frame)` |
185
+ | `Label` (`std/game/Label`) | `x, y, text, size, color, touch` | `Label.of(x, y, text, size, color)` |
186
+ | `Overlay` (`std/game/Overlay`) | `x, y, w, h, color, touch, open, children`: a panel that dims what is under it and takes every press on it | `Overlay.of(w, h, children)`: black at 0.6 alpha, `Enabled`, open |
187
+
188
+ A colour's alpha is the colour's: a box in a half-transparent red paints at half alpha.
189
+
190
+ ### How std draws a view
191
+
192
+ `Game.draw` asks the shown screen for its viewport (its `size()` fitted to the screen by its `viewport()`, `std/game/Viewport`), clears with its `background()` and calls its `draw` with the viewport's transform, which by default draws the view (`actor.paintView`): each shown item through its own place, at its alpha times its parents', its own `paint` (so its own view), then its declared children. There is no tree between the screen and the draw: the view is walked as it is made. `actor.viewDrawn` lists what a view draws, each item with its transform and alpha (the test kit reads it), and `actor.viewHit` finds what a press is on ([Clicks](#clicks)).
200
193
 
201
194
  ## Fixed timestep and determinism
202
195
 
203
196
  The host adds up the time between frames and runs one tick (`Game.update`) for each whole tick, always with the same `dt` of 1/60 s. A slow frame runs several ticks (a 50 ms frame runs 3) and a fast one, on a 120 Hz screen say, may run none. A frame runs at most eight ticks: after a longer stall the rest is dropped, so the game slows down for a moment instead of falling ever further behind. The clock that does this is `Clock` in [`std/game/input.plum`](../std/game/input.plum).
204
197
 
205
- The tick's `Input` (`ctx.input`) is read from the host once per frame, before the ticks. A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. Actors and rules have no `io`, so they can't read input any other way.
206
-
207
- Keep randomness in the state `S`: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, drawn from only in `update` (`r := self.rng.nextFloat()`, then keep `r.rng` in the next state). Then the same seed and the same inputs give the same game, tick for tick, and a test can play one: `game.step(io, input, 1.0 / 60.0, view)` from one seed and one list of inputs gives the same game each time. Orb Run's `same_seed_same_game` test does exactly this.
198
+ The tick's `Input` is read from the host once per frame, before the ticks. A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. A slice gets it through its mapping (`onKey`, `held`, ..); don't read input any other way.
208
199
 
209
- The maths is the same everywhere too. std's maths (`math.sin`, `math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick reads is the screen size (`ctx.view`), and a replay records it (see below).
200
+ Keep randomness in the screen: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, threaded through each draw (`r := self.rng.nextFloat()`, then keep `r.rng` in the next screen). Then the same seed and the same inputs give the same game, tick for tick. Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has the same checksum as master's imperative Orbit Runner (`benchmarks/screen_views/orbit.plum`).
210
201
 
211
- Keep the rest of your rules in plain functions over plain data, like `ship.moved(ax, ay, dt)`. Those need no browser to test.
202
+ The maths is the same everywhere too. std's maths (`math.sin`, `math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick reads is the screen size, and a replay records it.
212
203
 
213
204
  ## Record and replay
214
205
 
215
206
  A run of a game is its seed and one `Input` per tick, so a recording is that and nothing else: a `Replay` ([`std/game/Replay.plum`](../std/game/Replay.plum)). Neither needs a change to the game.
216
207
 
217
208
  - **In the browser**, open the game's page with `?record` (`http://127.0.0.1:8080/?record` under `plum run`). The page records from the start and shows a **Save replay** button, which downloads `replay.txt`; `plumReplay()` in the console gives the same text. Open the page with `?replay=<url>` to watch a recording: put the file in the game's `assets` folder and use `?replay=assets/replay.txt`. The ticks keep their pace, but their input comes from the file, so the keyboard and mouse do nothing, and the game stops when the recording ends.
218
- - **Headless**, `plum run examples/games/orb_run.plum --replay replay.txt` replays every tick with no browser, wall clock or input and prints the draw calls of the last frame. Two runs of the same file print the same thing.
219
- - **In a test**, `clock.accept(input, dt).dueInputs()` gives the inputs of the ticks a frame runs, which is what the host records, and `Clock.playing(r)` is a clock that replays `r` (each frame's time goes in with `clock.paced(dt)`). A game made from `r.seed` and run with that clock reaches the same state. `r.encode()` and `Replay.decode(text)` turn a replay into its text and back. [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) records a run this way and replays it.
209
+ - **Headless**, `plum run examples/games/orbitrunner/OrbitRunner.plum --replay replay.txt` replays every tick with no browser, wall clock or input and prints the draw calls of the last frame. Two runs of the same file print the same thing.
210
+ - **Going back**, a game that keeps its history can rewind to any tick, undo and redo ([Undo and time travel](#undo-and-time-travel)), by the same idea: the game made again and the recorded ticks played into it.
211
+ - **In a test**, the kit records with `t.record(seed)`, runs frames with `t.frame(input, frameDt)` and gives the recording with `t.recorded()`; a rig of a game made from `r.seed` and given `t.replay(r)` reaches the same state. `r.encode()` and `Replay.decode(text)` turn a replay into its text and back. Each example game replays a run this way; Orbit Runner's [`screens/PlayingScreen.plum`](../examples/games/orbitrunner/screens/PlayingScreen.plum) replays a 600-tick run and a run through a game over and a restart, and compares the score and every position.
212
+
213
+ While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `Clock` hands it the inputs of each frame's ticks. While replaying, `io.randomSeed()` returns the recorded seed and the screen size is the recorded one. Only the first `io.randomSeed()` call is recorded; while recording or replaying, any later call returns a seed derived from that one, the same in the browser and natively, so it replays too. The screen size is the one at the start of the recording: resizing the window while recording isn't recorded.
214
+
215
+ The text is one line for the seed and screen size, then one line per tick (the held keys, the mouse button, the pointer, the wheel and the tick's events). Floats are written exactly. The details are at the top of `std/game/Replay.plum`.
216
+
217
+ ## Undo and time travel
218
+
219
+ A game can go back to any tick it has played, and forward again along what it undid: a player's undo in a puzzle, or stepping through a bug tick by tick. Going back is **re-simulation**: the game is made again from the screens it was made with and the recorded ticks are played into it. A game is a value, so old games could be kept as they are; but keeping one at every tick keeps every state of a long run, and re-simulation keeps only the input, as master does.
220
+
221
+ ```plum
222
+ fun playground(seed: Int, assets: Assets) -> Game =
223
+ sky: Screen := PlaygroundScreen.seeded(seed, assets)
224
+ Game(screens: [sky])
225
+
226
+ fun main(io: Io) -> Game =
227
+ assets := Assets.load(io)
228
+ assets.music.loop(io, 0.2)
229
+ playground(io.randomSeed(), assets).timeTravel(History.Cap)
230
+ ```
231
+
232
+ `g.timeTravel(cap)` switches it on, before the first tick. It needs no function to make the game again (master's `timeTravel(make)` does): the game keeps the screens it was made with (`initial`). From then on the game keeps its **history** (`std/game/History`), one entry per tick. Then, each returning the game moved:
233
+
234
+ | `Game` | What it does |
235
+ |---|---|
236
+ | `rewindTo(io, tick)` | the state the game was in after `tick` ticks. Going back makes the game again from `initial`, then plays the first `tick` recorded ticks into it; going forward plays the ticks undone on from where it is |
237
+ | `undo(io)`, `redo(io)` | back to just before the last user action (below); forward to just before the next user action undone, or to the end |
238
+ | `canUndo()`, `canRedo()` | whether there is one |
239
+ | `stepBack(io)`, `stepForward(io)` | one tick back or forward, for scrubbing |
240
+ | `tickNow()`, `ticksRecorded()` | the tick the game is at, and how far the history reaches |
241
+ | `pause()`, `resume()`, `paused` | hold the game still: no tick runs and nothing is recorded, while the moves above still work; `resume()` goes on from where the game is and drops what could be redone |
242
+ | `travels()`, `rewound`, `moved` | whether a history is kept and not full; how many ticks the last move played; whether the last move could be made |
243
+
244
+ A move that can't be made (no history, a full one, a tick out of reach) leaves the game as it was with `moved` false. After a move the game plays on from there: the ticks undone stay as the future, for `redo`, until a user action cuts them.
245
+
246
+ **What is recorded.** Each tick's `Input`, the screen's size, the tick's length, whether it was a user action, and what its effects asked of the game. Not actions: an action may hold an actor (`onPress(target, ..)`), and the recorded input is mapped again into fresh actions against the state made again.
247
+
248
+ **What a rewind does with effects.** It runs none: no sound plays. What the effects of a tick asked of the screens (`goTo`, `restart`) is done again at the same point; an `exit` is not, nor an undo, a redo or a rewind.
220
249
 
221
- While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `Clock` hands it the inputs of each frame's ticks. While replaying, `io.randomSeed()` returns the recorded seed and the screen size is the recorded one. Only the first `io.randomSeed()` call is recorded; while recording or replaying, any later call returns a seed derived from that one, the same in the browser and natively, so it replays too. Still, seed the game's `Random` once, in `main`, and keep it. The screen size is the one at the start of the recording: resizing the window while recording isn't recorded.
250
+ **A user action** is a tick in which the shown slice screen's mapping gave an action for one of the tick's events (`onKey`, `onPointer`, `onPress`), or `held` gave an action while what is held differs from the tick before. The `tick` action is not one, nor an unchanged `held`, nor what a reducer dispatches. A tick whose effects asked for an undo, a redo or a rewind is not one either. `undo` lands just before the last user action; again, just before the one before.
222
251
 
223
- The text is one line for the seed and screen size, then one line per tick (the held keys, the mouse button, the pointer, the wheel and the tick's events). Floats are written exactly. The details are at the top of `std/game/Replay.plum`. State checksums and snapshots aren't planned.
252
+ **Offering undo in a game.** An effect asks through its `Control`: `game.undo()`, `game.redo()`, `game.rewindTo(tick)`, done once the tick is over. Balloon Pop maps Z and Backspace to `TakeBack`, whose effect is `game.undo()`: the last press is taken back, and the balloon it popped is whole again.
224
253
 
225
- ## What `io` gives you
254
+ **What it costs.** A rewind back costs the ticks it plays: `rewindTo(k)` plays `k` ticks from the start, with no drawing and no effects. A move forward plays only the ticks ahead. The history is a list of ticks; `timeTravel(cap)` bounds it (`History.Cap` is 30 minutes of ticks). Once full, the history lets its ticks go and every move is refused from then on; the game plays on.
226
255
 
227
- The host's calls are module functions that take `io` first: drawing and textures in [`std/game/gfx.plum`](../std/game/gfx.plum) (`gfx.clear(io, Color.Black)`, `gfx.loadTexture(io, "sprites.png")`), keys and the mouse in [`std/game/input.plum`](../std/game/input.plum) (actors and rules read them from the tick's `Input`, as `ctx.input.isKeyDown(Key.Right)`; the raw calls below are for `draw`), sound in [`std/game/audio.plum`](../std/game/audio.plum). General calls such as `io.printLn` stay methods of `io` ([`std/Io.plum`](../std/Io.plum)).
256
+ **Not here yet.** Master's development keys (`plum run --dev`: pause, step, undo and redo from the keyboard, with a line on the screen) need the host's dev mode and `remakeGame`, which this branch's hosts don't have; a game offers undo through its own effects.
257
+
258
+ ## What a game can use
259
+
260
+ Three modules talk to the host, files of `std/game`. Each function takes `io` first.
261
+
262
+ **`std/game/gfx`:** drawing
228
263
 
229
264
  | Group | Functions |
230
265
  |---|---|
231
- | Screen | `screenWidth()`, `screenHeight()`, `frameTime()`, `clear(color)` |
232
- | Shapes | `drawRect(x, y, w, h, c)`, `drawCircle(x, y, r, c)`, `drawLine(x1, y1, x2, y2, thickness, c)` |
233
- | Text | `drawText(s, x, y, size, c)` |
234
- | Camera | `setCamera(x, y, scale)`, `resetCamera()` |
235
- | Blending | `blendMode(m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` |
236
- | Keyboard (raw; a tick uses `ctx.input`) | `isKeyDown(k)`, `isKeyPressed(k)`, with `Key.Space`, `Key.KeyA`, `Key.Up`, `Key.Enter`, ... |
237
- | Mouse and touch (raw; a tick uses `ctx.input`) | `mousePos()`, `isMouseDown(b)`, `isMousePressed(b)`, `mouseWheel()`, with `Mouse.Left`, `Mouse.Right`, `Mouse.Middle` |
238
- | Random | `randomSeed()` |
239
-
240
- Images and sounds are handles you load once, in `main`, and keep in your game (in an actor or in the state, which plays sounds in `handle`). Do not load them every frame. `Sound.Silent` is a sound that plays nothing, for tests.
241
-
242
- | Handle | Functions |
266
+ | Screen | `screenWidth(io)`, `screenHeight(io)`, `frameTime(io)`, `clear(io, color)` |
267
+ | Shapes | `drawRect(io, x, y, w, h, c)`, `drawCircle(io, x, y, r, c)`, `drawLine(io, x1, y1, x2, y2, thickness, c)` |
268
+ | Text | `drawText(io, s, x, y, size, c)` |
269
+ | Images | `loadTexture(io, name)` gives a `Texture` with `draw(io, x, y)`, `width(io)`, `height(io)`, `setSmooth(io, smooth)`; `drawTextureEx(io, t.id, sx, sy, sw, sh, x, y, w, h, rotation, flipX, tint)` |
270
+ | Camera | `setCamera(io, x, y, scale)`, `resetCamera(io)` |
271
+ | Draw into an image | `createTexture(io, w, h)`, `t.renderTarget(io)`, `renderToScreen(io)` |
272
+ | Blending | `blendMode(io, m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` |
273
+ | Files | `loadFile(io, name)`, the file's text; `fileExists(io, name)` |
274
+
275
+ **`std/game/input`:** keyboard, mouse and touch. A tick's input is an `Input`, a value: a slice's `held(input)` gets it, and its `onKey` and `onPointer` get its events one at a time.
276
+
277
+ | Method | What it gives you |
243
278
  |---|---|
279
+ | `isKeyDown(k)`, `isKeyPressed(k)` | key state, with `Key.Space`, `Key.KeyA`, `Key.Up`, `Key.Enter`, ... |
244
- | `gfx.loadTexture(io, name)` | `draw(io, x, y)`, `width(io)`, `height(io)`, `setSmooth(io, smooth)` |
280
+ | `pointer()` | a `Pointer` with `pos`, `down`, `pressed`, `released`, for the mouse or one finger |
245
- | `gfx.createTexture(io, w, h)` | a blank texture; `renderTarget(io)` draws into it and `gfx.renderToScreen(io)` goes back to the screen |
246
- | `audio.loadSound(io, name)` | `play(io)`, `loop(io)`, `stop(io)`, `setVolume(io, v)` |
281
+ | `isMouseDown()`, `isMousePressed()`, `mousePos()`, `mouseWheel()` | mouse state |
247
- | `gfx.loadFile(io, name)` | the file's text |
282
+ | `events` | this tick's `InputEvent`s: `PointerDown`, `PointerUp`, `PointerMove`, `KeyDown`, `KeyUp` |
248
283
 
249
- A missing file stops the game and names the file, so typos show up straight away. For a texture region, rotation or flip, use `gfx.drawTextureEx(io, ...)`.
284
+ **`std/game/audio`:** `loadSound(io, name)` gives a `Sound` with `play(io, volume)`, `loop(io, volume)`, `stop(io)` and `setVolume(io, volume)`.
250
285
 
251
- Colors come from `Color.White`, `Color.Red` and so on, or `Color.rgb(r, g, b)`.
286
+ A missing file stops the game and names the file, so typos show up straight away. Load an asset once, in `main`. The example games keep theirs in a typed `Assets` struct of their own (`Assets.load(io)` in `main`) and pass it to the screens that draw it and play it. For a test with no host, `Assets.none()` fills it with `Texture.none()` and `Sound.none()`, placeholders that draw and play nothing.
252
287
 
253
- ### Input as events
288
+ ## Screens
254
289
 
255
- `InputEvent.poll(io, prev)` in [`std/game/input.plum`](../std/game/input.plum) is the one place that reads input, and the game's clock calls it once a frame. The tick's `Input` has its `events` (`PointerDown`, `PointerUp`, `PointerMove`, `KeyDown`, `KeyUp`) and the keys held, with `isKeyDown(k)`, `isKeyPressed(k)`, `pointer()`, `mousePos()` and `mouseWheel()`. `Game` routes the pointer events to the actors under them, and the actors and rules read the rest from `ctx.input`; a game reads nothing else, so a recorded list of inputs replays it exactly (see [Record and replay](#record-and-replay)).
290
+ A game with more than one screen (a title, a level select, the play) gives each its own `Screen`, with its own name, its own state and its own view. What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of the view of the screen it sits on, drawn while the state says so, as Orbit Runner's game over `Overlay`. The keys still go to the screen's mapping, so Enter can play again while the game over shows.
256
291
 
257
- ## Assets
292
+ The first screen of the list shows first. A screen never gets the game: it changes screen through its effects (below). A screen says how it comes in with `transition(self, from: Str) -> Transition`: `Cut` (the default), `Fade(secs: 0.5)` or `Slide(from: FromRight, secs: 0.4)`. While a transition runs, the game draws both screens, the one going out and then the one coming in, each moved and faded. Only the screen coming in gets ticks.
258
293
 
259
- Images and sounds load from an `assets` folder next to your game, or the nearest one in a parent folder, or the folder you pass with `--assets`. WAV and OGG sounds are supported. Paths are relative to that folder and can't leave it.
294
+ A screen's other hooks each return its next version: `enter(self, from) -> Self` when the game goes to it, `leave(self, to) -> Self` when it goes from it, `resize(self, w, h) -> Self` when the screen's size is first known or changes. A screen left and shown again is as it was left; a screen whose `fresh()` is true comes back as the game was made with it. [`examples/games/two_screens.plum`](../examples/games/two_screens.plum) is a title that fades into a play, which counts its runs in `enter`.
260
295
 
261
- ## Hot reload
296
+ ## Frames on demand
262
297
 
263
- While `plum run` serves a game, it watches your code and assets. Save a file and the game rebuilds and the page reloads.
298
+ Most screens change every tick, but a title, a menu or a level select only changes when the player does something. Such a screen says so:
264
299
 
265
- If the new code has a compile error, the old game keeps running and the error appears over it. Fix the error and the page reloads. The game restarts on each reload, so its state isn't kept. Turn this off with `--no-watch`.
300
+ ```plum
301
+ fun frames(self) -> Frames = OnDemand
302
+ ```
266
303
 
267
- ## Scenes
304
+ `Always`, the default, ticks the screen every tick. An `OnDemand` screen sleeps through every tick in which nothing needs doing: the game delivers it no tick (no action, no effect). Something needs doing, and the screen ticks, when any of these holds:
268
305
 
269
- A game's actors live in a scene tree from [`std/game`](../std/game): a `SceneTree<M>` ([`SceneTree.plum`](../std/game/SceneTree.plum)) is a tree of actors that lives from frame to frame, and `M` is the game's message type. It is a value like the rest of your game: every change returns a new tree, and a kept old tree stays as it was. When nothing holds the old one, the compiler writes the new one into its cells.
306
+ - the tick's input has an event: a key, a press, a pointer that moved (a move to where it already was doesn't count), or what is held maps to an action (its `held` gives one);
307
+ - the tick before left the screen `busy()`, ran an effect that asked the game for something, or a transition is in progress;
308
+ - the screen was just entered, or the screen's size changed.
270
309
 
271
- Each kind of actor is its own struct, with only its own fields, that implements `Actor<M>` ([`Actor.plum`](../std/game/Actor.plum)). It must say which actor it is (`key`, the id the tree finds it by) and where it is in its parent (`place`, a `Place` with a position, scale, rotation and origin). Everything else has a default that it may override:
310
+ It then ticks as an `Always` screen until it goes quiet again. A tick it sleeps through is still a tick of the run: a recording keeps its input, and whether the screen sleeps is worked out from that input and the screen's state alone, so a replay sleeps through the same ticks. `Game.delivered` and `Game.skipped` count the ticks delivered and slept through. `Game.idle()` is true when the shown screen is `OnDemand`, no transition runs and no tick has run since the last frame drawn (`drawn()`, which a test calls).
272
311
 
273
- - `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/Ctx.plum)) has its parent's world transform and alpha, the tick's input (`ctx.input`), the screen's size (`ctx.view`) and, during a tree's step, the key of the actor a pointer event would go to (`ctx.pointedAt()`, an `Option`), and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`, `ctx.send(msg)`, `ctx.out.push(Restart)` and `ctx.out.push(Exit)`.
274
- - `input(self, ctx, e)` returns its next version after a pointer event on it or on one of its children, before the tick's steps. `e` is in its own coordinates.
275
- - `paint(self, io, m, alpha)` draws it in its own coordinates seen through `m`. `Actor.plum` has helpers for boxes, circles, lines, sprites and text (`actor.boxPaint(io, m, alpha, w, h, color)`, ...).
276
- - `shown`, `gone` and `opacity`: a hidden actor isn't drawn or hit, a gone one is dropped with its subtree, and opacities multiply down the tree.
312
+ **The host.** On master the frame entry point tells the host when a frame is idle (`frameIdle`) and the browser skips the draw and waits for input. This branch's hosts have no such call yet: they draw every frame, and only the ticks sleep.
277
313
 
278
- An actor the pointer can hit says so with a second trait, `Clickable` ([`Clickable.plum`](../std/game/Clickable.plum)): `struct Target[Actor<Msg>, Clickable](..) =`, with `hit(self, p) -> Bool`, whether a point in its own coordinates is on it. Only a `Clickable` actor that says it is hit gets a pointer event (and its parents after it, clickable or not), and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first. The tree's pointer walk skips every other actor with one type-tag test, and computes the transform of one only when it has children (who may be clickable). A `hit` on an actor that isn't `Clickable` is a plain method the tree never calls, and nothing warns about it: if an actor gets no clicks, check its trait list.
314
+ ## The slice
279
315
 
280
- ```plum
281
- import std/Int
282
- import std/Float
283
- import std/math/Vec2
284
- import std/game/input
285
- import std/game/Place
286
- import std/game/Actor
287
- import std/game/Clickable
288
- import std/game/Ctx
316
+ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux Toolkit: one slice per screen, its state, an enum `A` of its actions, a reducer and an effect handler. (Master calls the trait `Slice<A>`; here `Slice` is std's growable array, and a trait can't share a type's name.) `ScreenSlice<A>` extends `Screen`, so the screen is the slice: its own fields are the state, plain values and the actors it holds.
289
317
 
318
+ | A `ScreenSlice<A>`'s method | Default | What it does |
290
- enum Msg = Hit(id: Int)
319
+ |---|---|---|
320
+ | `reduce(self, a: A) -> Self` | required | applies `a`: the next version of the screen. An exhaustive `match`, with no `Io` |
321
+ | `dispatch(self, a: A) -> Self` | std's | dispatches `a` from the slice's own reducer (below) |
322
+ | `effect(self, io, a: A, game: Control)` | nothing | what `a` does after the tick (a sound, a change of screen); it only reads the slice |
323
+ | `onKey(self, e) -> Option<A>` | None | the action for a key event |
324
+ | `onPointer(self, e, at: Vec2) -> Option<A>` | None | the action for a pointer event, `at` its point in the world |
325
+ | `onPress(self, target: Actor, at: Vec2) -> Option<A>` | None | the action for a press on an item that takes presses ([Clicks](#clicks)) |
326
+ | `held(self, input) -> Option<A>` | None | the action for what is held, every tick |
327
+ | `tick(self, dt) -> Option<A>` | None | the tick action |
291
328
 
292
- struct Target[Actor<Msg>, Clickable](id: Int, x: Float, y: Float) =
293
- fun key(self) -> Int = self.id
329
+ **Dispatch** reduces at once and queues. Each action std delivers is reduced as it is made, so the next mapping and the next action see what it did, and it is queued for its effect after the tick. A reducer dispatches more with `self.dispatch(a)`, which returns the slice after it (Orbit Runner's rules: `scored := if caught.points > 0 then collected.dispatch(Scored(points: caught.points)) else collected`): reduced at once, and queued before the action that dispatched it. Called outside a tick (a test calling `reduce` itself), `dispatch` only reduces. How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
294
330
 
331
+ ## Input and the tick as actions
332
+
295
- fun place(self) -> Place = place.at(self.x, self.y)
333
+ Each tick, std delivers to the shown screen's slice, in this order:
296
334
 
297
- fun hit(self, p: Vec2) -> Bool = actor.circleHit(0.0, 0.0, 16.0, p)
335
+ 1. **Each of the tick's events**, in the order they came: a key through `onKey(e)`; a press (a `PointerDown`) on an item that takes presses through `onPress(target, at)`, and if that gives None, through `onPointer` as any pointer event is; any other pointer event through `onPointer(e, at)`, with `at` the event's point in the world.
336
+ 2. **`held(input)`**: an action for what is held, every tick, events or none (the steering keys).
337
+ 3. **`tick(dt)`**: the tick action.
298
338
 
299
- fun input(self, ctx: Ctx<Msg>, e: InputEvent) -> Target = match e
300
- PointerDown(_, _) =>
301
- ctx.send(Hit(id: self.id))
302
- self
303
- _ => self
339
+ A mapping that gives None sends nothing. Then the transition in progress moves on, and the effects run. std moves nothing of a slice screen: what moves, its reducer moves, on the tick action.
340
+
341
+ The input comes before the tick, so a rule that must see the tick's motion first notes the action and acts on it in the tick: Orbit Runner's `PlayAgain` notes that the run is to start over (`again`), and its `Tick` dispatches `StartOver` once the actors have moved.
342
+
343
+ ## Clicks
344
+
345
+ A press is hit-tested by std against what the shown screen's view draws: the press is on the top-most shown item under it that is `Sized` with `touch` `Enabled` and whose `hit(p)` says the point (in its own coordinates) is on it: what is drawn later before what is drawn earlier, what is under an item (the children of a `Group` or an `Overlay`, then its own view) before the item, through every turn and scale on the way. A `Disabled` item takes everything under it out of the walk. The view is made again for the press, from the screen as the tick has left it so far. [`tests/port/game/routing.plum`](../tests/port/game/routing.plum) checks the walk against a brute-force reference on 300 random nested views.
346
+
347
+ The item hit becomes the slice's action through `onPress(target, at)`. Balloon Pop's balloons are such actors, each `Sized` with its exact shape and `Enabled` while whole:
348
+
349
+ ```plum
350
+ fun onPress(self, target: Actor, at: Vec2) -> Option<PopAction> = match target
351
+ Balloon as b => Some(Pop(balloon: b))
352
+ _ => None
304
353
  ```
305
354
 
306
- Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. An actor that doesn't change should return `self` from `step` and `input` (the defaults do), not a copy: an `input` that returns the actor as it was leaves the tree as it was (`@sameRef`, see [Built-ins](language.md#reference-identity)), and a screen's `react` that returns its tree as it was (the default) leaves the game's tree as it was. std gives `Group` (a parent that paints nothing) and `Box` (`Clickable`, hit inside it); [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button` (`Clickable`) (`ui.button(id, x, y, w, h, label, onClick)`). A button shows the pointer over it and a press on it, and a press and a release on it send its `onClick` message. It counts as under the pointer only when a pointer event there would go to it (`ctx.pointedAt()`, the key of the topmost hit `Clickable` actor, found once per step), so of two overlapping buttons only the top one, the one a click reaches, shows hovered.
355
+ and `Pop(b)` bursts the balloon of `self.balloons` with `b`'s id. A balloon that has burst says `Disabled`, so a press goes through it to one behind. An item made inside `view` (Orbit Runner's game over panel) can be hit, and so keeps a press from what is under it, but it is a new object each time: compare its kind (`Overlay as o`), not its identity.
356
+
357
+ ## Effects that outlive a tick
358
+
359
+ A flash, a ripple, a slide: something that runs for a while after what started it is plain state too. The reducer adds it, ages it on each tick, and drops it once it is done; the view draws it at its age. Orbit Runner's ripple where the ship is hit is a `Ring`, an actor with its age: `Hit` appends one to `rings` where the ship is; each `Tick` ages them and keeps those not done; the view appends them.
307
360
 
308
- The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills; `input(ctx, e)` routes one pointer event. `Game` calls both. `add`, `update`, `kill` and `find` work by id, and `updateAs<T>(id, f)` and `findAs<T>(id)` act on an actor of the type `T` only, which is how a screen's `rules` and `react` read and change one kind's own fields in its subtree. `allAs<T>()` is every actor of the type `T`, in tree order, and `kidsAs<T>(parent)` the `T`s among one actor's children (a layer: `t.kidsAs<Balloon>(BalloonLayer)`), which is how `rules` reads one kind's actors. `subtree(id)` is an actor with its subtree as a tree of its own, and `withTop(a)` a tree with its root actor replaced. A pattern `Orb as o` on an `Actor<M>` matches an `Orb`.
361
+ ## Effects and navigation
309
362
 
310
- [`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time.
363
+ After the tick, the game runs `effect(io, a, game)` for every action dispatched in it, in the order dispatched, each with the slice as the tick left it, and right after each effect what it asked of `game`, a `Control` (`std/game/Control`):
364
+
365
+ | `Control` | What the game does |
366
+ |---|---|
367
+ | `game.goTo("over")` | shows the screen of that name from the next tick on: the shown screen `leave`s, the other (as the game was made with it, if it is `fresh`) `enter`s and comes in by its `transition(from)`. A name no screen has stops the program and lists the screens. |
368
+ | `game.restart()` | every screen back as the game was made with it, and the first one shown, at once. (On master a restart builds the trees again and a view screen keeps its state; here a screen's state is the screen, so starting over is going back to it.) |
369
+ | `game.exit()` | no tick runs after this one. |
370
+ | `game.undo()`, `game.redo()`, `game.rewindTo(tick)` | once the tick is over, a move through the game's history ([Undo and time travel](#undo-and-time-travel)); nothing if the game keeps none |
371
+
372
+ An effect returns nothing; a `Control` is the one thing a tick writes in place. Navigation is the game's own actions: std has none. Orbit Runner's effects play the sounds, and `StartOver`'s starts the music again (its reducer has dealt the new run already).
373
+
374
+ ## Assets
375
+
376
+ Images and sounds load from an `assets` folder next to your game, or the nearest one in a parent folder, or the folder you pass with `--assets`. WAV and OGG sounds are supported. Paths are relative to that folder and can't leave it.
377
+
378
+ ## Hot reload
379
+
380
+ While `plum run` serves a game, it watches your code and assets, the game's own files found as its imports are. Save a file and the game rebuilds and the page reloads. If the new code has a compile error, the old game keeps running and the error appears over it. The game restarts on each reload, so its state isn't kept. Turn this off with `--no-watch`.
311
381
 
312
382
  ## Testing a game
313
383
 
314
- Put your rules in plain functions with `test` blocks, and `plum test` runs them with no browser. A test can run whole ticks of a game with `game.step(io, input, dt, view)`, which is `update` with the screen's size given (`update` asks the host for it). Build the game in a function of its own that `main` calls, since a test that calls `main` gets the host's wrapper. Calling a drawing or sound function under `plum test` stops with an error, so keep those calls out of the code you test: draw only in `paint` and `draw`, and give the state `Sound.Silent` in tests.
384
+ Put your rules in code that takes no `Io`, with `test` blocks, and `plum test` runs them with no browser. An actor's own methods are tested by calling them (`ship.update(0.1)`); a reducer the same way (`s.reduce(a)`); a screen, or a whole game, with the kit below. To check a game actually renders, the browser test tool runs it in headless Chromium. See [its README](../compiler/game/web-test/README.md).
385
+
386
+ ### Testing a screen
387
+
388
+ `std/game/headless` runs a screen, or a whole game, with no host: the test sends input, runs ticks through the game's own tick, and reads back the screen, what its view draws and what its effects did. A rig is a value, like the game in it: each input and tick returns the next rig.
389
+
390
+ ```plum
391
+ test "the play scores and starts over"
392
+ t := headless.mount(io, PlayingScreen.start(Random.seeded(7), Assets.none()))
393
+ u := t.hold(Key.Right).ticks(30)
394
+ assert u.text(u.first<Label>()) == "Score {u.screen.score}"
395
+ v := u.press(Key.Enter).tick()
396
+ assert v.count<Overlay>() == 0
397
+ ```
398
+
399
+ `headless.mount(io, screen)` makes a game of that one screen; `headless.play(io, game)` takes a whole game. Either sizes the view to 800 by 600 (`t.resize(w, h)` changes it). The rig, a `TestRig<S>`, is generic over the screen's type, so `t.screen` is the screen itself as the last tick left it (for `play`, the first screen, a `Screen`).
400
+
401
+ | | |
402
+ |---|---|
403
+ | Input, for the next tick | `press(key)` (down and up within the tick: one key down for the mapping, not held after), `hold(key)`, `release(key)`, `click(actor)` (a press and release at the actor's centre, its bounds' if it is `Sized`, in screen pixels through the viewport, so it goes through the real hit test: a panel in front gets it), `clickAt(x, y)`, `pointerMove(x, y)`, `send(e)`, `next(held, events)` |
404
+ | Time | `tick()` (the game's own tick: mapping, reducer, transition, effects and what they ask), `ticks(n)` (`n` ticks, the input going to the first), `tick(dt)` for a tick of another length, `frame(input, frameDt)` for the host's frame with the `Clock` turning wall time into ticks |
405
+ | An action | `dispatch(a)`: reduced into the screen as its reducer would dispatch it, then its effects |
406
+ | Reading | `find<T>()` (the items of type `T` the view draws, in the order drawn, an item before what is under it), `first<T>()` (none stops the test: "headless: first: no actor of the type asked for is in the view"), `count<T>()`, `text(label)`, `shown(actor)` (the view draws it), `hit(x, y)` (what a press at that screen pixel lands on), `worldOf(actor)` (its transform), `toWorld(x, y)` (a screen pixel in the world), `drawn()` (what the frame draws, culled, each item with its transform and alpha) |
407
+ | What came out of the last `tick` or `ticks` | `effects<A>()` (the actions of type `A` whose effects ran, in order), `restarted()`, `wentTo()` (an `Option`), `exited()`; `showing()` names the screen shown |
408
+ | A whole run | `record(seed)`, `recorded()`, `replay(r)`, and `game` (its counters) |
409
+ | Time travel | `mountWith(io, screen)` and `playWith(io, game)` keep the history; then `rewindTo(k)`, `undo()`, `redo()`, `stepBack()`, `stepForward()`, `pause()`, `resume()`, with `moved()`, and `t.screen` is the one made again |
410
+
411
+ Orbit Runner's game over test:
412
+
413
+ ```plum
414
+ test "while the game over panel shows, Enter or R plays again: the run starts over after the tick"
415
+ t := lastLife(io).press(Key.Enter).tick()
416
+ assert names(ruledLast(t)) == "PlayAgain Hit"
417
+ u := t.press(Key.Space).tick()
418
+ assert u.screen.over
419
+ v := u.press(Key.Enter).tick()
420
+ assert names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({Clock.Tick})"
421
+ assert !v.screen.over
422
+ ```
315
423
 
316
- To check a game actually renders, the browser test tool runs it in headless Chromium. See [its README](../compiler/game/web-test/README.md).
424
+ `std/game/headless` is tested by [`tests/port/game/screens.plum`](../tests/port/game/screens.plum) (presses through turned groups and overlays, dispatch order, navigation, transitions, frames on demand, record and replay, undo and rewind).
425
+
426
+ ## Beside master
427
+
428
+ The engine has master's shape (`Screen`, a slice per screen, `Game(screens: ..)`, `Control`, the view and its hit test, the kit), in the functional dialect. Where the signatures differ:
429
+
430
+ | Master | Here | Why |
431
+ |---|---|---|
432
+ | `trait Slice<A>[Screen]` | `trait ScreenSlice<A>[Screen]` | `Slice` is std's growable array here, and a trait can't share a type's name |
433
+ | `fun reduce(&self, a: A)` | `fun reduce(self, a: A) -> Self` | a value is not changed in place: the reducer returns the next screen |
434
+ | `fun dispatch(&self, a: A)` | `fun dispatch(self, a: A) -> Self` | the same; it returns the slice after `a` |
435
+ | `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
436
+ | `build(&self, io) -> SceneTree`, `draw(self, tree, io)` | no `build`; `draw(self, io, m, alpha, area)` | no tree: the game draws the view through the screen's viewport |
437
+ | `enter(&self, tree, from)`, `leave(&self, tree, to)`, `resize(&self, tree, w, h)` | `enter(self, from) -> Self`, `leave(self, to) -> Self`, `resize(self, w, h) -> Self` | no tree; each returns the next screen |
438
+ | `deliver(&self, tree, input, dt)`, `wants(self, input)` | `deliver(self, cam: Viewport, input, dt) -> Delivered`, `wants(self, input)` | std's; returns the next screen and the tick's effects |
439
+ | `name(self) -> Str` (and Orbit Runner's `"play"`) | the same | |
440
+ | `Actor`: `place`, `view`, `paint`, `step(&self, ctx, dt)`, `shown` | `place`, `view`, `paint`, `shown`; no `step` | an actor moves by its own methods returning its next version, called by the reducer (master's example games do this too, with `update(&self, dt)`) |
441
+ | actor fields with defaults (`Box(w:, h:)`) | every field given, or a static (`Box.of`, `Label.of`, `Sprite.cell`, `Overlay.of`) | no struct field defaults in this dialect |
442
+ | `Overlay(open: true, ..)` takes presses as an `InputHandler` | `Overlay` is `Sized` and `Enabled`, hit anywhere in it | no tree input phases |
443
+ | `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, view) -> Game` | the game is a value; `step` takes the screen size, which the host's `update` reads |
444
+ | `Control`: methods on `&self` | methods that push onto its `asked` slice | an effect returns nothing; this is the one thing a tick writes in place |
445
+ | `game.restart()` builds the trees again | every screen back as the game was made with it | a screen's state is the screen |
446
+ | `timeTravel(make: fn(Io) -> Game, cap)` | `timeTravel(cap) -> Game` | the game keeps the screens it was made with |
447
+ | `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
448
+ | the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
449
+ | a view literal's `if`, `for`, `..` elements | `append`, `map`, functions | not in this dialect's list literals |
450
+ | `ScreenView`, the one-actor tree that draws a view | none | the game draws and hit-tests the view itself |
451
+ | `Container` trait, `declared(self)` | `Actor.declared(self) -> List<Actor>`, empty by default | spares a type test per item drawn, and keeps every optimizer pass in a game with no container kind (the downcast had to stay valid with none) |
452
+
453
+ Not ported yet: master's frames-on-demand host call (`frameIdle`) and its development keys (`plum run --dev`, `remakeGame`), and `plum run` taking a game's folder; see the [backlog](backlog.md).
317
454
 
318
455
  ## Publishing
319
456
 
320
457
  ```sh
321
- plum build game.plum -o dist
458
+ plum build examples/games/orbitrunner/OrbitRunner.plum -o dist
322
459
  ```
323
460
 
324
461
  This writes a static site to `dist`, ready for any static file host. It leaves out the hot reload code.
docs/language.md CHANGED
@@ -688,7 +688,23 @@ struct Play[Screen<Int, Msg>](id: Int, score: Int) =
688
688
  - A type that lists `Screen<Int, Msg>` is an `Actor<Msg>` as well: listing `Screen<..>` implies `Actor<..>`, with the arguments carried over, so the type must define Actor's required methods too and takes Actor's defaults for the rest. An error about one of them names the `Actor` entry and where it comes from (`Play is missing method 'key' of Actor<Msg> (Screen<Int, Msg> extends Actor<Msg>)`). Writing `[Screen<Int, Msg>, Actor<Msg>]` is the same.
689
689
  - On a `Screen<S, M>` trait object you can call Actor's methods too (`s.key()`, `s.step(dt)`, which returns a `Screen<S, M>`), and so can Screen's defaults on `self`.
690
690
  - A `Screen<S, M>` is accepted wherever an `Actor<M>` is expected, with no cast and no runtime cost (both are the same reference). The other way is a downcast: `Screen<S, M> as s`.
691
- - A subtrait can't declare a method its supertrait has, and a trait can't extend itself.
691
+ - A trait can't extend itself.
692
+
693
+ A subtrait may give a method of its supertrait a default of its own, with the same signature (the supertrait's parameters written as the subtrait's arguments for them). A type that implements the subtrait and doesn't define the method takes the subtrait's default, whatever order its `[ ]` lists the traits in, and a call through the supertrait reaches it. Anything else that redeclares a supertrait's method is an error. This lets a generic trait do what its non-generic supertrait can't type: values of `Panel` with different `A`s go in one `List<Panel>`, and each one's `press` maps the key to its own `A`:
694
+
695
+ ```plum
696
+ trait Panel =
697
+ fun press(self, key: Int) -> Int = 0
698
+
699
+ trait Driven<A>[Panel] =
700
+ fun map(self, key: Int) -> Option<A>
701
+ fun apply(self, a: A) -> Int
702
+ fun press(self, key: Int) -> Int = match self.map(key) # the default every Driven<A> takes
703
+ Some(a) => self.apply(a)
704
+ None => -1
705
+ ```
706
+
707
+ std/game's `ScreenSlice<A>[Screen]` works this way: the game holds `List<Screen>`, and each slice screen's `deliver` delivers the tick as its own type of action ([tests/traits/subtrait_defaults.plum](../tests/traits/subtrait_defaults.plum)).
692
708
 
693
709
  ### Bounds
694
710
 
@@ -713,7 +729,7 @@ A value of an implementing type becomes a trait object, with no cast, where one
713
729
  - `Self` outside a trait;
714
730
  - a method that isn't in the trait called on a trait object, or a field read on one (match `Type as x` first);
715
731
  - a value used as a trait it doesn't implement, or a downcast to a type that doesn't implement it, or to a trait no type shares with it;
716
- - a supertrait that isn't a trait or has the wrong number of arguments, a trait that extends itself, or a subtrait that declares its supertrait's method again;
732
+ - a supertrait that isn't a trait or has the wrong number of arguments, a trait that extends itself, or a subtrait that declares its supertrait's method again other than as a default with the same signature;
717
733
  - a bound not met at a use, naming the missing trait;
718
734
  - a method whose `Self` inside a parameter or the result can't be checked with the trait object there (`xs: List<Rect> := ..; xs` as a `List<Self>`): build the value where it is returned.
719
735
 
@@ -776,7 +792,7 @@ It is an error to write `@native` anywhere else: inside an expression, in a bloc
776
792
 
777
793
  Each file is a module. A file starts with its imports. Nothing is implicit, not even `Int` or `Str` methods, and each file imports what it uses.
778
794
 
779
- `import a/b` reads `a/b.plum`, with the path counted from the folder that holds `std`: the checkout, or the folder passed with `--lib-path`. That module's functions and constants are reached through its name, which is the last part of the path in lowercase. Its types and enum variants need no prefix:
795
+ `import a/b` reads `a/b.plum`. An import of `std/..` is counted from the folder that holds `std`: the checkout, or the folder passed with `--lib-path`. Any other import is looked for beside the importing file, then in each folder above it, nearest first, and last from that same folder, so the files of a game import each other by their path from the game's folder (`import actors/Ship`, `import OrbitRunner`) whichever of its folders they are in, and two files may import each other. That module's functions and constants are reached through its name, which is the last part of the path in lowercase. Its types and enum variants need no prefix:
780
796
 
781
797
  ```plum
782
798
  # geo/shapes.plum
@@ -800,7 +816,7 @@ fun main() -> Int =
800
816
  shapes.clamp(500) + shapes.Limit + p.x
801
817
  ```
802
818
 
803
- This means two modules can each have a `clamp` without clashing, while two modules that define the same type name are an error. A module's own functions and constants need no prefix inside it, and a local with the same name as a module hides the module.
819
+ This means two modules can each have a `clamp` without clashing, while two modules that define the same type name are an error. The program's `main` is the entry file's; the `main` of an imported file (a benchmark driver importing a game's main file) is an ordinary function of that module. A module's own functions and constants need no prefix inside it, and a local with the same name as a module hides the module.
804
820
 
805
821
  Module-level constants can be any pure expression, and they may refer to each other in any order. The same goes for std: `import std/math/math` gives `math.sqrt(2.0)`, and `import std/game/gfx` gives `gfx.drawRect(io, ..)`.
806
822
 
docs/std.md CHANGED
@@ -18,7 +18,7 @@ The [game engine](game.md) has its own page.
18
18
  | [`Os`, `http`](#files-and-network) | files and the network |
19
19
  | [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `@sameRef`](#utilities) | utilities |
20
20
  | [`testing`](#testing) | helpers for tests |
21
- | [`game/Store`](#game-state-store) | a game's state as a `Reducer`, and its messages |
21
+ | [`game/Screen`, `game/ScreenSlice`](#game-screens-and-slices) | a game's screens, each with its own state, actions and reducer |
22
22
 
23
23
  ## Numbers
24
24
 
@@ -154,7 +154,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
154
154
  - **`FenwickTree`:** a prefix-sum tree: a segment tree specialised to `Int` sums, keeping only each node's left-half sum (what prefix queries read). The `i & -i` index trick needs an array, so it isn't used.
155
155
  - **`Quadtree`, `KdTree`, `Bvh`:** spatial trees over `Vec2` and `Aabb`. Leaf buckets and query results are cons lists. Balanced builds sort with a merge sort on `List` (`KdTree`) or pick medians with a quickselect (`Bvh`).
156
156
  - **`UnionFind`:** a persistent parent map (two `Map<Int, Int>`s: parents and set sizes) with union by size and no path compression. `find`, `union` and `connected` are O(log² n). `union` returns the new forest.
157
- - **`RoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`RoseEmpty`, `RoseNode(value, firstChild, nextSibling)`). `RoseTree.leaf(v)` and `RoseTree.of(v, kids)` build nodes, `RoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `filter`, `replace` and `update` return untouched subtrees as they were. std/game/SceneTree's `SceneTree<M>` is a `RoseTree<Actor<M>>`, a tree of trait objects. An actor the pointer can hit is `Clickable` as well (`struct Target[Actor<M>, Clickable](..)`), and the tree's pointer walk tells it from the others with a downcast (`Clickable as c`, one type-tag test).
157
+ - **`RoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`RoseEmpty`, `RoseNode(value, firstChild, nextSibling)`). `RoseTree.leaf(v)` and `RoseTree.of(v, kids)` build nodes, `RoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `filter`, `replace` and `update` return untouched subtrees as they were.
158
158
  - **`LeftistHeap`, `PairingHeap`:** priority queues with `fold` in place of an iterator. The pairing heap's two-pass `pop` is tail recursive, so a root with 100,000 children is fine.
159
159
 
160
160
  ## Option and Result
@@ -245,7 +245,7 @@ fun main(io: Io) =
245
245
  - **`Uuid`:** `Uuid.v4(rng)`, `Uuid.fromStr`, `Uuid.isValid`, `==` (case-insensitive: `fromStr` lowers the text)
246
246
  - **`Base64`** (`import std/encoding/Base64`): `Base64.encode(data)` and `Base64.decode(text)` (a `Result`; whitespace and missing padding are fine, data after padding and a last group of one character are `Err(InvalidBase64)`), the URL alphabet `Base64.encodeUrl(data)` (no padding unless `pad` is true) and `Base64.decodeUrl(text)`, and the line-wrapped `Base64.encodePem` and `Base64.encodeMime`
247
247
  - **`Aabb`:** an axis-aligned box, corners included: `Aabb.of(x, y, w, h)`, `width`, `height`, `center`, `overlaps`, `contains`, `containsPoint`, `union`, `distSq`, `rayEntry`
248
- - **Reference identity:** the built-in `@sameRef(a, b)` is true when `a` and `b` are the very same object, not just equal ones (see [Built-ins](language.md#built-ins)); there is nothing to import. A persistent structure uses it to keep what didn't change: the scene tree's `input` and `Game`'s tick return a node as it was when its actor came back as the same object (see [the game engine](game.md))
248
+ - **Reference identity:** the built-in `@sameRef(a, b)` is true when `a` and `b` are the very same object, not just equal ones (see [Built-ins](language.md#built-ins)); there is nothing to import. A persistent structure uses it to keep what didn't change, and a game's screen uses it to tell which of the actors it holds a press landed on (`@sameRef(target, self.box)`, see [the game engine](game.md))
249
249
  - **Linear memory:** the built-ins `@memSize`, `@memGrow`, `@memStoreI32`, `@memLoadI32`, `@memStoreU8`, `@memLoadU8`, `@memStoreF32` and `@memLoadF32` read and write the program's wasm memory (see [Built-ins](language.md#linear-memory))
250
250
  - **`io.args()`:** the program's arguments as a `Slice<Str>`: what follows `--` in `plum run app.plum -- a b`, or a built executable's own arguments (empty under `plum test` and in the browser)
251
251
  - **`io.nowMicros()`:** a wall clock in microseconds since the Unix epoch, as a `Float`, on every host
@@ -254,31 +254,29 @@ fun main(io: Io) =
254
254
 
255
255
  `assert` covers most tests. `std/testing` adds `testing.expectEq`, `expectNotEq`, `expectTrue`, `expectFalse`, `expectSuccess` and `expectFailure`.
256
256
 
257
- ## Game state: Store
257
+ ## Game screens and slices
258
258
 
259
- `std/game/Store` holds a game's state and the messages that change it. The state implements `trait Reducer<M>` (see [Traits](language.md#traits)): `update(self, msg: M) -> Self` is the rules, pure and with no `Io`, so the same messages from the same state give the same state; `handle(self, io: Io, msg: M)` is a message's effects (a sound, a save) and does nothing unless the state overrides it. `screen(self) -> Str` is the name of the screen to show (std/game/Game): `""` by default, the game's first screen, so a game of one screen leaves it out and a game of several keeps the name in its state (`State(..self, on: PlayScreen.name())`).
259
+ A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<Actor>`, what the frame shows, made again from its fields every frame; a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`): its fields are its state, `A` its actions, `reduce(self, a) -> Self` its reducer (pure, with no `Io`, so the same actions from the same state give the same state) and `effect(self, io, a, game)` what an action does after the tick (a sound, `game.goTo("play")`). std maps each tick's input to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
260
260
 
261
261
  ```plum
262
262
  import std/Int
263
- import std/Io
264
263
  import std/Str
264
+ import std/Option
265
265
  import std/collections/List
266
+ import std/game/input
266
- import std/game/Store
267
+ import std/game/Screen
268
+ import std/game/ScreenSlice
269
+
270
+ enum Act = Collected(points: Int) | Hurt
267
271
 
272
+ struct Run[ScreenSlice<Act>](score: Int, lives: Int) =
268
- enum Msg = Collected(points: Int) | Hurt
273
+ fun name(self) -> Str = "run"
269
274
 
270
- struct Run[Reducer<Msg>](score: Int, lives: Int) =
271
- fun update(self, msg: Msg) -> Run = match msg
275
+ fun reduce(self, a: Act) -> Run = match a
272
276
  Collected(p) => Run(..self, score: self.score + p)
273
277
  Hurt => Run(..self, lives: self.lives - 1)
274
278
 
275
- fun main(io: Io) =
279
+ test "the reducer alone plays the slice"
276
- s := Store.of(Run(score: 0, lives: 3)).dispatch(Collected(points: 5)).dispatch(Hurt)
280
+ r := Run(score: 0, lives: 3).reduce(Collected(points: 5)).reduce(Hurt)
277
- done := s.flush(io) # handle(io, msg) for each message, oldest first
278
- io.printLn("{done.state.score} {done.state.lives}")
281
+ assert r.score == 5 && r.lives == 2
279
282
  ```
280
-
281
- - **`Store<S: Reducer<M>, M>`**: `Store.of(state)`, `dispatch(msg)` (reduces now and queues the message), `dispatchAll(msgs)`, `pending()` (the queued messages, oldest first), `flush(io)` (calls `handle` on the state for each queued message in order, then empties the queue), and the field `state`. A store is a value: `dispatch` and `flush` return a new one.
282
- - **`store.reduceAll(s, msgs)`**: the state after `msgs`, with no store and no effects.
283
-
284
- Only `Game` ([`std/game/Game`](game.md#a-minimal-game)) drives a store: it dispatches each message its actors and screens send, flushes the store after the tick, and then shows the screen `state.screen()` names. A game writes its `Reducer`.