plum

#treesitter#compiler#wasm

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

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


b9032ec — Peter John 2026-11-16T12:55:28+05:30
std/game review R3 (leftovers, games by hand, docs): `[Steps]` steps a `List<View>` field with `Views.stepIn` (each item's type tested as it is stepped, the one place the stepping looks at a type at run time), so benchmarks/screen_views/scale.plum's `CrowdScreen` lists `Steps` and loses its `stepped` (update view 22.6-23.3 ms after, 22.4-22.8 ms before, a loaded machine; checksum unchanged); `[Show]` derives `toStr`: `trait Show = fun toStr(self) -> Str` in std/Str, and an enum or struct that lists it and writes no `toStr` gets one written out before checking (core/show_derive.rs, after `deriveSteps`): the variant's name and its fields' values in order (`Steer(1.0, -1.0)`, `Hit`, a struct `Spot(1, 2)`, one with no fields its name), an own `toStr` kept, an error at the type when a field's type is a struct or enum of the program with no `toStr` that doesn't list `Show`; the games' action enums list it and lose their hand-written `toStr`; leftovers: `Frames.onDemand` removed, `Game.onDemand` kept as the one copy (a match on `frames()`, the fusion re-check failure in the backlog), the `SizedTile` fixture moved from std/game/Sized to its test, `Replay.ticks` a `List<Input>` (`Replay.at` gone, `ticksText` a join, `decodeTicks` a reversed accumulator, `onScreen` a map), the `Ticker`'s `played` a `List` whose head is dropped each tick (no `cursor`), `dueInputs` a `List`, and the kit's recording a value (it pushed into the `Slice` its copies shared; `log` holds the ticks newest first, `recorded()` reverses them); `Views.stepIn` stays (a `Group`'s and an `Overlay`'s children, and now the derive); games: `primitive Arena` and `primitive Sheet`, `Blinks` and `holdStill` moved to the tests, `Hue.All` a const list (`Hue.of`'s if-chain and `count` gone), `Balloon` built by name with field defaults (`Balloon.at` gone), `Orb` and `Mine` hold their `Motion` as `at` with the place derived in `place()` (`create`, `motion()`, `put`, `vx`/`vy` gone; a mine's rotation is an accumulated `spin`, the same float ops), so the games are 71 lines removed, 28 added; Orbit Runner's checksum is unchanged, 946756219 (orbit update 11.96 ms over 14,400 ticks); not done: a std `Body` (the bounce is the game's rule and `Motion` is that body), the `PlayAgain` indirection kept; game_in_place_test: `Mine.step`, `Mine.put` and `Orb.put$unique` no longer expected (a step is one spread of the shared `self`, where it was that copy and one or two in-place writes to it); tests: tests/traits/show.plum, checker diagnostic `showNeedsEachFieldShown`, tests/std/game/View.plum's `Stage` with a `List<View>` field (a group's actor inside), tests/port/game/replay.plum on lists; docs: game.md (Stepping, the `Mine` sample, the walks, record and replay, the slice, "Beside master": two rows added, the duplicate `timeTravel` row and the removed input readers in "The same on both" gone), language.md (`[Show]`, the built-ins table), std.md (`Show`, the stale `@sameRef` press, the replay), backlog, the review plan, View.plum's doc comments
Files changed (38) hide show
  1. benchmarks/screen_views/orbit.plum +1 -1
  2. benchmarks/screen_views/scale.plum +3 -4
  3. compiler/checker/tests/checker/diagnostic_tests.rs +9 -0
  4. compiler/cli/tests/cli/game_in_place_test.rs +6 -3
  5. compiler/core/src/lib.rs +1 -0
  6. compiler/core/src/lower.rs +5 -0
  7. compiler/core/src/show_derive.rs +112 -0
  8. compiler/core/src/steps_derive.rs +11 -4
  9. docs/backlog.md +2 -2
  10. docs/game.md +13 -14
  11. docs/language.md +13 -0
  12. docs/plans/2026-11-13-std-game-review.md +1 -1
  13. docs/std.md +4 -2
  14. examples/games/balloonpop/BalloonPop.plum +11 -18
  15. examples/games/balloonpop/actors/Balloon.plum +4 -8
  16. examples/games/balloonpop/screens/PlaygroundScreen.plum +1 -7
  17. examples/games/orbitrunner/OrbitRunner.plum +2 -2
  18. examples/games/orbitrunner/actors/Mine.plum +3 -12
  19. examples/games/orbitrunner/actors/Orb.plum +3 -10
  20. examples/games/orbitrunner/actors/Ship.plum +0 -2
  21. examples/games/orbitrunner/screens/PlayingScreen.plum +4 -12
  22. std/Str.plum +6 -0
  23. std/game/Game.plum +17 -16
  24. std/game/Replay.plum +10 -22
  25. std/game/Screen.plum +0 -4
  26. std/game/Sized.plum +0 -3
  27. std/game/TestRig.plum +6 -7
  28. std/game/View.plum +6 -5
  29. tests/examples/games/balloonpop/actors/Balloon.plum +2 -2
  30. tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +1 -1
  31. tests/examples/games/orbitrunner/actors/Mine.plum +2 -2
  32. tests/examples/games/orbitrunner/actors/Orb.plum +2 -2
  33. tests/examples/games/orbitrunner/actors/Ship.plum +2 -0
  34. tests/examples/games/orbitrunner/screens/PlayingScreen.plum +6 -6
  35. tests/port/game/replay.plum +18 -23
  36. tests/std/game/Sized.plum +3 -0
  37. tests/std/game/View.plum +6 -3
  38. tests/traits/show.plum +61 -0
benchmarks/screen_views/orbit.plum CHANGED
@@ -50,7 +50,7 @@ primitive OrbitBench[App] =
50
50
  head := [p.score, p.best, p.lives, Timing.flag(p.over), p.rng.seed, p.ship.at.x.toBits(), p.ship.at.y.toBits(), p.ship.vx.toBits(), p.ship.vy.toBits(), p.orbs.length(), p.mines.length()]
51
51
  none: List<Int> := Nil
52
52
  orbs := p.orbs.fold(none, |acc, o| Cons(o.at.y.toBits(), Cons(o.at.x.toBits(), acc)))
53
- mines := p.mines.fold(none, |acc, m| Cons(m.at.rotation.toBits(), Cons(m.at.x.toBits(), acc)))
53
+ mines := p.mines.fold(none, |acc, m| Cons(m.spin.toBits(), Cons(m.at.x.toBits(), acc)))
54
54
  Timing.hash(head.append(orbs.reverse()).append(mines.reverse()))
55
55
 
56
56
  fun tickOnce(io: Io, g: Game, inp: Input, paint: Bool) -> Game =
benchmarks/screen_views/scale.plum CHANGED
@@ -3,7 +3,8 @@
3
3
  # one `Sprite`, made again at each draw; with `hand`, the same actors drawing the same
4
4
  # sprite with a hand-written `paintSelf` (`Sprite.draw`). Each is an `Actor`,
5
5
  # and the game steps every one each tick, before the tick action, through the screen's
6
+ # `stepped`, derived by `Steps` (`Views.stepIn` over its `List<View>`, or `Views.stepAll`
6
- # `stepped` (`Views.stepIn` over its list); the tick action does nothing. One difference
7
+ # over its `List<ViewDot>`); the tick action does nothing. One difference
7
8
  # from master: master's stepping walk makes each actor's view to look under it, and this
8
9
  # branch's does not (an actor found under another could not be put back into a value), so
9
10
  # `update view` makes 10,000 fewer one-`Sprite` lists a tick here. With `spread`, the
@@ -118,15 +119,13 @@ struct HandDot[Actor](i: Int, at: Place, clock: Float) =
118
119
 
119
120
  enum CrowdAct = CrowdTick(dt: Float)
120
121
 
121
- struct CrowdScreen[ScreenSlice<CrowdAct>](hand: Bool, dots: List<View>) =
122
+ struct CrowdScreen[ScreenSlice<CrowdAct>, Steps](hand: Bool, dots: List<View>) =
122
123
  fun of(hand: Bool, n: Int) -> CrowdScreen = CrowdScreen(hand: hand, dots: ScaleBench.dotsFrom(hand, 0, n))
123
124
 
124
125
  fun name(self) -> Str = "crowd"
125
126
 
126
127
  fun view(self) -> List<View> = self.dots
127
128
 
128
- fun stepped(self, dt: Float) -> CrowdScreen = CrowdScreen(..self, dots: Views.stepIn(self.dots, dt))
129
-
130
129
  fun tick(self, dt: Float) -> Option<CrowdAct> = Some(CrowdTick(dt: dt))
131
130
 
132
131
  fun reduce(self, a: CrowdAct) -> CrowdScreen = match a
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -409,6 +409,15 @@ fn stepsNeedsAScreenOrActorStructHoldingActors() {
409
409
  assert!(es[0].message.contains("`P` lists `Steps` but holds no actors"), "{es:?}");
410
410
  }
411
411
 
412
+ /// `[Show]` derives `toStr` only when each field of a type of the program can be shown.
413
+ #[test]
414
+ fn showNeedsEachFieldShown() {
415
+ let es = frontErrors("trait Show =\n fun toStr(self) -> Str\n\nstruct Opaque(n: Int)\n\nenum Bad[Show] =\n | Holds(o: Opaque)\n | Fine(n: Int)\n\nprimitive Main[App] =\n fun main() -> Int = 1\n");
416
+ assert_eq!(es.len(), 1, "{es:?}");
417
+ assert!(es[0].message.contains("`Bad` lists `Show`, but its field `o: Opaque` has no `toStr`"), "{es:?}");
418
+ assert_eq!(es[0].line, 6, "{es:?}");
419
+ }
420
+
412
421
  /// `@stepsWhen` goes on a field holding actors of a `[Steps]` type that derives its stepping.
413
422
  #[test]
414
423
  fn stepsWhenGoesOnAnActorFieldOfAStepsType() {
compiler/cli/tests/cli/game_in_place_test.rs CHANGED
@@ -8,6 +8,12 @@
8
8
  //! Since a slice's `act` returns its follow-ups (`then`), std's fold steps them
9
9
  //! (`Delivery.actIn<A, S>`), and the uniqueness pass makes no unique version of a generic
10
10
  //! instantiation, so they copy; the delivery's own trail is updated in place.
11
+ //!
12
+ //! `Mine.step` (1), `Mine.put` (1) and `Orb.put$unique` (1) went on 2026-11-16 (R3): an orb
13
+ //! and a mine hold their `Motion`, so a step is one spread of `self`
14
+ //! (`Mine(..self, clock: .., at: .., spin: ..)`), a copy as `self` is shared by the list
15
+ //! it is stepped in, where it was that copy and then one or two in-place writes to it
16
+ //! (`put`, the rotation): the same allocation a step, and nothing left to write in place.
11
17
 
12
18
  use std::collections::BTreeMap;
13
19
  use std::process::Command;
@@ -62,9 +68,6 @@ fn orbitRunnerKeepsItsInPlaceSpreads() {
62
68
  ("PlayingScreen.deal", 1),
63
69
  ("PlayingScreen.newOrb", 1),
64
70
  ("PlayingScreen.newMine", 1),
65
- ("Mine.step", 1),
66
- ("Mine.put", 1),
67
- ("Orb.put$unique", 1),
68
71
  ]);
69
72
  assertKept("examples/games/orbitrunner/OrbitRunner.plum", &want);
70
73
  }
compiler/core/src/lib.rs CHANGED
@@ -37,6 +37,7 @@ pub mod session;
37
37
  pub mod simplify;
38
38
  pub mod spread_paths;
39
39
  pub mod steps_derive;
40
+ pub mod show_derive;
40
41
  pub mod tail;
41
42
  pub mod trait_defaults;
42
43
  pub mod tests_lower;
compiler/core/src/lower.rs CHANGED
@@ -35,6 +35,11 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
35
35
  if !stepsErrors.is_empty() {
36
36
  return Err(stepsErrors);
37
37
  }
38
+ // The derived `toStr` of each `[Show]` type, an ordinary method too.
39
+ let showErrors = crate::show_derive::deriveShow(source);
40
+ if !showErrors.is_empty() {
41
+ return Err(showErrors);
42
+ }
38
43
  let blockFieldErrors = crate::children_block::nameBlockFields(source);
39
44
  if !blockFieldErrors.is_empty() {
40
45
  return Err(blockFieldErrors);
compiler/core/src/show_derive.rs ADDED
@@ -0,0 +1,112 @@
1
+ //! `[Show]` (std/Str): a type's `toStr`, derived.
2
+ //!
3
+ //! An enum or a struct that lists `Show` and writes no `toStr` of its own gets one, written
4
+ //! out here before the checker sees it as an ordinary method: the variant's name, and its
5
+ //! fields' values in order between parentheses, each as it interpolates (so each field's
6
+ //! type needs a `toStr`, or is an `Int`, a `Float`, a `Bool` or a `Str`):
7
+ //!
8
+ //! enum PlayAction[Show] = | Steer(ax: Float, ay: Float) | Hit
9
+ //!
10
+ //! fun toStr(self) -> Str = match self
11
+ //! Steer(v0, v1) => "Steer({v0}, {v1})"
12
+ //! Hit => "Hit"
13
+ //!
14
+ //! A struct's is `"Name({self.a}, {self.b})"`, and one with no fields is its name. A type
15
+ //! that writes its own `toStr` keeps it.
16
+ //!
17
+ //! Error, at the type: a field whose type is a struct or an enum of the program that has no
18
+ //! `toStr` and doesn't list `Show` (it couldn't be put in the string).
19
+
20
+ use crate::ast::*;
21
+ use crate::diag::{DiagKind, Diagnostic};
22
+ use crate::main_result::parseItems;
23
+
24
+ /// The trait a type lists to have its `toStr` derived.
25
+ pub const SHOW_TRAIT: &str = "Show";
26
+
27
+ /// Writes out the `toStr` of each type that lists `Show` and has none (see the module doc).
28
+ pub fn deriveShow(source: &mut Source) -> Vec<Diagnostic> {
29
+ let hasToStr = |ty: &str| {
30
+ source.items.iter().any(|i| match i {
31
+ Item::Fn(f) => f.name == "toStr" && f.has_self && f.type_param.as_deref() == Some(ty),
32
+ Item::Enum(e) => e.name == ty && e.implements.iter().any(|t| t.name == SHOW_TRAIT),
33
+ _ => false,
34
+ })
35
+ };
36
+ let declared = |ty: &str| source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == ty));
37
+ let mut errors: Vec<Diagnostic> = Vec::new();
38
+ let mut made: Vec<Item> = Vec::new();
39
+ for item in &source.items {
40
+ let Item::Enum(e) = item else { continue };
41
+ if !e.implements.iter().any(|t| t.name == SHOW_TRAIT) {
42
+ continue;
43
+ }
44
+ let name = &e.name;
45
+ let own = source
46
+ .items
47
+ .iter()
48
+ .any(|i| matches!(i, Item::Fn(f) if f.name == "toStr" && f.has_self && f.type_param.as_deref() == Some(name.as_str())));
49
+ if own {
50
+ continue;
51
+ }
52
+ let unshown: Vec<String> = e
53
+ .variants
54
+ .iter()
55
+ .flat_map(|v| v.field_names.iter().zip(&v.fields))
56
+ .filter(|(_, t)| declared(&t.name) && !hasToStr(&t.name))
57
+ .map(|(f, t)| format!("`{f}: {}`", t.name))
58
+ .collect();
59
+ if !unshown.is_empty() {
60
+ errors.push(Diagnostic::new(
61
+ DiagKind::Type,
62
+ e.file.clone(),
63
+ e.line,
64
+ e.column,
65
+ format!(
66
+ "`{name}` lists `Show`, but its field {} has no `toStr`: list `Show` on that type too, or give it `fun toStr(self) -> Str`",
67
+ unshown.join(" and ")
68
+ ),
69
+ ));
70
+ continue;
71
+ }
72
+ let gens = if e.generics.is_empty() {
73
+ String::new()
74
+ } else {
75
+ format!("<{}>", e.generics.iter().map(|g| g.name.clone()).collect::<Vec<_>>().join(", "))
76
+ };
77
+ let body = if e.isStruct() {
78
+ let v = &e.variants[0];
79
+ if v.field_names.is_empty() {
80
+ format!("\"{name}\"")
81
+ } else {
82
+ let parts: Vec<String> = v.field_names.iter().map(|f| format!("{{self.{f}}}")).collect();
83
+ format!("\"{name}({})\"", parts.join(", "))
84
+ }
85
+ } else {
86
+ let arms: Vec<String> = e
87
+ .variants
88
+ .iter()
89
+ .map(|v| {
90
+ if v.fields.is_empty() {
91
+ format!(" {} => \"{}\"", v.name, v.name)
92
+ } else {
93
+ let binds: Vec<String> = (0..v.fields.len()).map(|i| format!("v{i}")).collect();
94
+ let parts: Vec<String> = binds.iter().map(|b| format!("{{{b}}}")).collect();
95
+ format!(" {}({}) => \"{}({})\"", v.name, binds.join(", "), v.name, parts.join(", "))
96
+ }
97
+ })
98
+ .collect();
99
+ format!("match self\n{}", arms.join("\n"))
100
+ };
101
+ let text = format!("struct {name}{gens} =\n fun toStr(self) -> Str = {body}\n");
102
+ for it in parseItems(&text, &e.file) {
103
+ if let Item::Fn(f) = it {
104
+ if f.type_param.as_deref() == Some(name.as_str()) {
105
+ made.push(Item::Fn(f));
106
+ }
107
+ }
108
+ }
109
+ }
110
+ source.items.extend(made);
111
+ errors
112
+ }
compiler/core/src/steps_derive.rs CHANGED
@@ -2,8 +2,9 @@
2
2
  //!
3
3
  //! A struct that lists `Steps` gets, as an ordinary method written out here before the
4
4
  //! checker sees it, the stepping of each field that holds actors: a field whose type is an
5
- //! `Actor` (a type that implements it, or a trait type that is one), a `List` of actors or an
5
+ //! `Actor` (a type that implements it, or a trait type that is one), a `List` of actors, an
6
+ //! `Option` of one, or a `List<View>` (each `Actor` in it, through `Views.stepIn`: a type
6
- //! `Option` of one. Other fields are left as they are. What is made is what a screen would
7
+ //! test per item, as the list holds views of any kind). Other fields are left as they are. What is made is what a screen would
7
8
  //! write by hand, one static construction:
8
9
  //!
9
10
  //! fun stepped(self, dt: Float) -> PlayingScreen =
@@ -37,6 +38,7 @@ use crate::main_result::{parseItems, typeText};
37
38
  pub const STEPS_TRAIT: &str = "Steps";
38
39
  const ACTOR: &str = "Actor";
39
40
  const SCREEN: &str = "Screen";
41
+ const VIEW: &str = "View";
40
42
  /// An actor's own `step`, renamed when the derived `step` steps its fields after it.
41
43
  pub const OWN_STEP: &str = "step$own";
42
44
  /// The stepping of an actor's fields, called by the derived `step` after `step$own`.
@@ -48,6 +50,9 @@ enum Holds {
48
50
  One,
49
51
  List,
50
52
  Some_,
53
+ /// A `List<View>`: views of any kind, each `Actor` among them stepped
54
+ /// (`Views.stepIn`, a type test per item; a `Group` or an `Overlay` looked inside).
55
+ Views,
51
56
  }
52
57
 
53
58
  /// Writes out each `[Steps]` struct's stepping (see the module doc) and empties every
@@ -92,6 +97,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
92
97
  let holds = |t: &Type| -> Option<Holds> {
93
98
  let inner = |h: Holds| (t.generics.len() == 1 && isActor(&t.generics[0].name)).then_some(h);
94
99
  match t.name.as_str() {
100
+ "List" if t.generics.len() == 1 && t.generics[0].name == VIEW => Some(Holds::Views),
95
101
  "List" => inner(Holds::List),
96
102
  "Option" => inner(Holds::Some_),
97
103
  n if isActor(n) => Some(Holds::One),
@@ -151,7 +157,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
151
157
  errors.push(attrAt(
152
158
  c,
153
159
  format!(
154
- "`@stepsWhen` on `{name}.{}`, a `{}`: only a field holding actors is stepped (an `Actor`, a `List` of actors or an `Option` of one)",
160
+ "`@stepsWhen` on `{name}.{}`, a `{}`: only a field holding actors is stepped (an `Actor`, a `List` of actors, an `Option` of one or a `List<View>`)",
155
161
  v.field_names[*i],
156
162
  typeText(&v.fields[*i])
157
163
  ),
@@ -160,7 +166,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
160
166
  }
161
167
  if fields.is_empty() {
162
168
  errors.push(here(format!(
163
- "`{name}` lists `Steps` but holds no actors: no field is an `Actor`, a `List` of actors or an `Option` of one"
169
+ "`{name}` lists `Steps` but holds no actors: no field is an `Actor`, a `List` of actors, an `Option` of one or a `List<View>`"
164
170
  )));
165
171
  continue;
166
172
  }
@@ -191,6 +197,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
191
197
  Holds::One => format!("self.{f}.step(dt)"),
192
198
  Holds::List => format!("Views.stepAll(self.{f}, dt)"),
193
199
  Holds::Some_ => format!("Views.stepSome(self.{f}, dt)"),
200
+ Holds::Views => format!("Views.stepIn(self.{f}, dt)"),
194
201
  };
195
202
  match c {
196
203
  Some(c) => {
docs/backlog.md CHANGED
@@ -12,11 +12,11 @@ The retained scene tree was replaced by master's screen view in functional form:
12
12
  - **A program with no `Sized` or `Touch` view drops the dead code pass**: std's `Views.touchOf`, `sizedHit` and `missesArea` match `Touch as t` and `Sized as s` on a `View`, and once the pass has dropped every type that is one, the re-check calls each match impossible ("no type is both a View and a Touch"). Every game has such a view, so only a minimal test program meets it. A trait default's copy is told apart since 2026-11-16 (`defaultPositions` reads the trait's declarations), but these are statics.
13
13
  - **Master's other games** (`clockwork`, `menu`) are not ported.
14
14
  - **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. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
15
- - **Stepping without the screen naming its actors**: done at compile time on 2026-11-16: a screen or an actor that lists `Steps` (std/game/View) has its fields holding actors stepped by a derived `stepped` (or after its own `step`), one field paused by `@stepsWhen(cond)` (`docs/game.md`, "Stepping"). Still by hand: a `List<View>` field (`Views.stepIn`).
15
+ - **Stepping without the screen naming its actors**: done at compile time on 2026-11-16: a screen or an actor that lists `Steps` (std/game/View) has its fields holding actors stepped by a derived `stepped` (or after its own `step`), one field paused by `@stepsWhen(cond)` (`docs/game.md`, "Stepping"). A `List<View>` field is stepped by `Views.stepIn` since R3 (each item's type tested as it is stepped).
16
16
 
17
17
  ## Decided, not built
18
18
 
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`.
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`, `lerp`, JSON; `toStr` is `[Show]`, std/Str, since 2026-11-16), replay checksums with snapshot and rewind, easing and tweens in `Anim`.
20
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).
21
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.
22
22
 
docs/game.md CHANGED
@@ -149,18 +149,16 @@ trait Actor[View] = # acts: state that advan
149
149
  `place` is its `Place` (`std/game/Place`: position, rotation, scale, the origin it turns about and its `alpha`); `view` is what is under it, ready-made items placed in its coordinates; `visible` hides it, with what is under it, from the draw and from presses; `paintSelf` is what it draws itself, before its view, for what no ready-made view draws (an additive glow, a line): it draws with `Gfx` through `m`, its own coordinates to the world's, at `alpha` (Orbit Runner's `Orb`, Balloon Pop's `Balloon`, whose string is a line). Its other fields are plain and public. `step` returns the actor's next version, `dt` seconds on. The ready-made views (`Group`, `Box`, `Circle`, `Sprite`, `Label`, `Overlay`) are stateless and never stepped.
150
150
 
151
151
  ```plum
152
- struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture) =
152
+ struct Mine[Actor](at: Motion, spin: Float = 0.0, clock: Float = 0.0, tex: Texture) =
153
- fun place(self) -> Place = self.at
153
+ fun place(self) -> Place = Place.pivoted(self.at.x, self.at.y, Sheet.Size / 2.0, Sheet.Size / 2.0).rotateTo(self.spin)
154
154
 
155
155
  fun view(self) -> List<View> =
156
156
  [Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
157
157
 
158
- fun step(self, dt: Float) -> Mine =
159
- moved := Mine(..self, clock: self.clock + dt).put(self.motion().drifted(Mine.Radius, dt))
158
+ fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt, at: self.at.drifted(Mine.Radius, dt), spin: self.spin + 2.0 * dt)
160
- Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
161
159
  ```
162
160
 
163
- **Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen's own fields are stepped. A screen that lists `Steps` (std/game/View) has its `stepped` derived by the compiler: each field that is an `Actor`, a `List` of actors (of one type, or of a trait type that is an `Actor`) or an `Option` of one is stepped, and the other fields are as they are. `@stepsWhen(cond)` before a field steps it only while `cond`, read on `self`, holds. Orbit Runner's:
161
+ **Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen's own fields are stepped. A screen that lists `Steps` (std/game/View) has its `stepped` derived by the compiler: each field that is an `Actor`, a `List` of actors (of one type, or of a trait type that is an `Actor`), an `Option` of one or a `List<View>` is stepped, and the other fields are as they are. `@stepsWhen(cond)` before a field steps it only while `cond`, read on `self`, holds. Orbit Runner's:
164
162
 
165
163
  ```plum
166
164
  struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
@@ -180,9 +178,9 @@ fun stepped(self, dt: Float) -> PlayingScreen =
180
178
  rings: Views.stepAll(self.rings, dt))
181
179
  ```
182
180
 
183
- and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`), not a walk at run time, so it costs what the hand-written one did (`benchmarks/screen_views`: Orbit Runner's update 12.8-13.3 ms before and after, the 10,000 actors of `scale update spread` 19.0-19.9 ms before, 19.2 ms after). A screen that writes its own `stepped` keeps it, and `steps()` still pauses it as a whole; a field `@stepsWhen` pauses one field, so a screen that derives its stepping has no need of `steps()`. A screen holding no actors lists no `Steps` (the default `stepped` returns the screen as it is). A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick.
181
+ and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`, `Views.stepIn` for a `List<View>`), not a walk at run time, so it costs what the hand-written one did (`benchmarks/screen_views`: Orbit Runner's update 12.8-13.3 ms before and after, the 10,000 actors of `scale update spread` 19.0-19.9 ms before, 19.2 ms after). A screen that writes its own `stepped` keeps it, and `steps()` still pauses it as a whole; a field `@stepsWhen` pauses one field, so a screen that derives its stepping has no need of `steps()`. A screen holding no actors lists no `Steps` (the default `stepped` returns the screen as it is). A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick.
184
182
 
185
- An actor that lists `Steps` has its actor fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds. An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field is not stepped by `Steps` (it holds views, not actors): a screen holding one writes `stepped` with `Views.stepIn`. An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not. So the tick action only runs the rules on what has moved:
183
+ An actor that lists `Steps` has its actor fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds. An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field of a `Steps` type is stepped with `Views.stepIn`: it holds views of any kind, so each item is tested for being an `Actor` (or a `Group` or an `Overlay`) as it is stepped, the one place the stepping looks at an item's type at run time (`benchmarks/screen_views/scale.plum`'s `CrowdScreen`, 10,000 actors in a `List<View>`, lists `Steps`). An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not. So the tick action only runs the rules on what has moved:
186
184
 
187
185
  ```plum
188
186
  fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
@@ -220,7 +218,7 @@ Every kind is at the origin of what it is in unless given an `x` and a `y`: an a
220
218
 
221
219
  The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
222
220
 
223
- Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll` and `stepIn` for a screen's `stepped`.
221
+ Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll`, `stepSome` and `stepIn` for a screen's `stepped`.
224
222
 
225
223
  ## Fixed timestep and determinism
226
224
 
@@ -234,7 +232,7 @@ The maths is the same everywhere too. std's maths (`Math.sin`, `Math.sqrt`, ...)
234
232
 
235
233
  ## Record and replay
236
234
 
237
- 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.
235
+ 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)), a value holding the seed, the window's size and its ticks, `ticks: List<Input>`. Neither needs a change to the game.
238
236
 
239
237
  - **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.
240
238
  - **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.
@@ -367,7 +365,7 @@ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux
367
365
  | `held(self, h: Held) -> Option<A>` | None | the action for what is held after the tick's events, every tick |
368
366
  | `tick(self, dt) -> Option<A>` | None | the tick action |
369
367
 
370
- **What follows from an action** is a value `act` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`: a screen with nothing more to say writes `reduce` alone, and one that has writes `act` (and keeps `reduce` for the plain state changes, or not). Each action std delivers is acted on as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next mapping and the next action see what they did. Orbit Runner's rules return what happened as actions (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), and `PlayAgain` on the game over panel is followed by `StartOver` at once (`then: [if self.over then StartOver]`). The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). A test calls `reduce` or `act` itself: `s.act(Keyed).then`. 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)).
368
+ **What follows from an action** is a value `act` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`: a screen with nothing more to say writes `reduce` alone, and one that has writes `act` (and keeps `reduce` for the plain state changes, or not). Each action std delivers is acted on as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next mapping and the next action see what they did. Orbit Runner's rules return what happened as actions (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), and `PlayAgain` on the game over panel is followed by `StartOver` at once (`then: [if self.over then StartOver]`). The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). A test calls `reduce` or `act` itself: `s.act(Keyed).then`. An action enum that lists `Show` (std/Str) has its `toStr` derived, so a test can compare the actions sent as text (`"Steer(1.0, -1.0) Tick(0.016) Scored(10)"`). 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)).
371
369
 
372
370
  ## Input and the tick as actions
373
371
 
@@ -476,7 +474,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
476
474
  | Master | Here | Why |
477
475
  |---|---|---|
478
476
  | `trait Actor[View]` with `step(&self, dt)` | `step(self, dt) -> Self` | a value is not changed in place: `step` returns the actor's next version |
479
- | the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the game calls the screen's `stepped(dt) -> Self` (default: the screen as it is), which maps the fields that hold actors: derived by the compiler for a screen that lists `Steps`, a field paused by `@stepsWhen(cond)`, or written by hand (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. An actor that lists `Steps` has its actor fields stepped after its own `step`. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
477
+ | the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the game calls the screen's `stepped(dt) -> Self` (default: the screen as it is), which maps the fields that hold actors: derived by the compiler for a screen that lists `Steps` (an `Actor` field, a `List` or an `Option` of actors, a `List<View>`), a field paused by `@stepsWhen(cond)`, or written by hand (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. An actor that lists `Steps` has its actor fields stepped after its own `step`. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
480
478
  | `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 |
481
479
  | `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` | `fun reduce(self, a: A) -> Self`, and `fun act(self, a: A) -> Next<Self, A>` returning the actions that follow (`then`) with the next screen; no `dispatch` | the reducer returns the next screen, and what follows from an action is part of what it returns, not a call that queues it |
482
480
  | `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
@@ -492,16 +490,17 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
492
490
  | a `Label`'s width an estimate, 0.6 of its size a letter (master's backlog: real font metrics) | Arial's advance widths, in std (`Label.Advances`) and in the browser's layout (`ADVANCES`) | a host call that measured text would make a tick that hits a label read the host, and differ between hosts and in a replay; a table in std is the same everywhere, and the browser lays text out by it |
493
491
  | actor and view fields with defaults (`Box(w:, h:)`, `Held(buttons: [])`) | the same: struct fields with defaults (`Label(x:, y:, text:)`, `Held(keys: k)`, `Held()`) | master's `Box` and `Group` default their size too; here every kind defaults its place (`x: 0.0, y: 0.0`) and names its size |
494
492
  | `Tween` advanced in place | `tween.advance(dt) -> Tween` | a value |
493
+ | a replay's ticks and the ticker's in a growable array, read by index | `Replay.ticks: List<Input>`; the `Ticker` replaying holds the ticks not yet played (`played`), its head dropped each tick, with no cursor; the kit's recording is a value too (`t.recorded()`) | a replay is a value: the kit's rig, itself a value, no longer pushes into an array its copies share |
494
+ | an action enum writes its `toStr` for a test's names | `enum PlayAction[Show] = ..`: `[Show]` (std/Str) derives `toStr`, `Steer(1.0, -1.0)` ([language.md](language.md#structs), "Field attributes and derived methods") | the names a test compares are the variant and its fields; a derive writes them once |
495
495
  | `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
496
496
  | `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`) handed to an effect | `enum Cmd` (`GoTo`, `Exit`, `Undo`, `Redo`, `RewindTo`, `Play`, `Loop`, `Stop`) returned by `act` | commands are values: a test reads them (`t.cmds`), and a sound is one of them |
497
- | `timeTravel(make: fn(Io) -> Game, cap)` | `timeTravel(cap) -> Game` | the game keeps the screens it was made with |
498
497
  | `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
499
498
  | the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
500
499
  | a view literal's `if`, `for`, `..` elements | `if` and `..` items and children blocks (`Overlay(..) {` + an item a line + `}`); no `for` item: `..xs.map(..)` | a `for` item would be a second way to write a `map` |
501
500
  | std's test helper types private (`_ViewProbe`, `_KitScreen`, ..) | public names (`ViewProbe`, `Stepper`, ..) | a type's name here is the module's: a game's own `Stepper` beside std's compiles, so there is no clash to avoid (checked with a probe) |
502
501
  | `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
503
502
 
504
- The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `steps`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), no `restart`, pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, `Input.axis`, `isMouseDown(b)`, `isMousePressed(b)`, `isMouseReleased(b)`, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, frames on demand in the hosts (`frameIdle`, the browser waiting for input, `PlumGame::idle`), `plum run --dev` (its keys, its line, the page's Cmd key fixes), and `plum compile <folder>`. Orbit Runner's state checksum was master's (925878360) until its rules returned what happened as `then` actions (the mines are checked before more are added for the tick's points, and a restart starts at once); it is 946756219 now.
503
+ The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `steps`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), no `restart`, pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, frames on demand in the hosts (`frameIdle`, the browser waiting for input, `PlumGame::idle`), `plum run --dev` (its keys, its line, the page's Cmd key fixes), and `plum compile <folder>`. Orbit Runner's state checksum was master's (925878360) until its rules returned what happened as `then` actions (the mines are checked before more are added for the tick's points, and a restart starts at once); it is 946756219 now.
505
504
 
506
505
  Not ported: master's `clockwork` and `menu` games; see the [backlog](backlog.md). This branch keeps `examples/games/clicks.plum` and `two_screens.plum`, which master doesn't have.
507
506
 
docs/language.md CHANGED
@@ -235,6 +235,18 @@ primitive Demo[App] =
235
235
 
236
236
  **Field attributes and derived methods:** a field may start with an attribute, `@name(expr)`. The one there is is `@stepsWhen(cond)`, for std/game's `Steps` trait: a struct that lists `Steps` and is a `Screen` gets a `stepped(self, dt)` written out by the compiler before checking, which steps each field holding actors (an `Actor`, a `List` of actors or an `Option` of one, the others as they are); an `Actor` that lists it has those fields stepped after its own `step`. `@stepsWhen(cond)` steps its field only while `cond`, an expression on `self`, holds. What is derived is an ordinary method, the same static construction one would write (`Screen(..self, ship: self.ship.step(dt), ..)`), so it costs nothing at run time; a screen that writes its own `stepped` keeps it. Any other attribute name is an error, and so is `@stepsWhen` on a field holding no actors or of a type that doesn't list `Steps`. See docs/game.md, "Stepping".
237
237
 
238
+ A type that lists `Show` (std/Str, `trait Show = fun toStr(self) -> Str`) and writes no `toStr` gets one derived the same way: its variant's name and its fields' values in order, each as it interpolates (`Steer(1.0, -1.0)`, `Hit`; a struct `Spot(1, 2)`, one with no fields its name), so it interpolates (`"{a}"`) and meets a `T: Show` bound. A type that writes its own `toStr` keeps it. A field whose type is one of the program's structs or enums with no `toStr` that doesn't list `Show` either is an error at the type, since it couldn't go in the string:
239
+
240
+ ```plum
241
+ enum PlayAction[Show] =
242
+ | Steer(ax: Float, ay: Float)
243
+ | Hit
244
+
245
+ # PlayAction.toStr, as written out: match self
246
+ # Steer(v0, v1) => "Steer({v0}, {v1})"
247
+ # Hit => "Hit"
248
+ ```
249
+
238
250
  ```plum
239
251
  struct PlayingScreen[ScreenSlice<PlayAction>, Steps](over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>) =
240
252
  fun name(self) -> Str = "play"
@@ -904,6 +916,7 @@ primitive Demo[App] =
904
916
  | `@memLoadF32(addr)` | the 32-bit float at `addr` as a `Float`. |
905
917
  | `@native` | not a call: the whole body of a std function the compiler supplies. See [`@native`](#native). |
906
918
  | `@stepsWhen(cond)` | not a call: an attribute before a struct field. See [Structs](#structs), "Field attributes and derived methods". |
919
+ | `[Show]` | not a call: a trait (std/Str) whose `toStr` is derived for a type that lists it and writes none. See [Structs](#structs), "Field attributes and derived methods". |
907
920
 
908
921
  ### Reference identity
909
922
 
docs/plans/2026-11-13-std-game-review.md CHANGED
@@ -28,5 +28,5 @@ Events stay the only source of truth; std keeps held state as a pure fold of the
28
28
  - Per tick, not per actor: the 10,000-actor benchmark is unaffected. Pairs with the `Key` enum.
29
29
 
30
30
  ## Chosen (user 2026-11-16)
31
- - Building: R1 items 1+2 (done cfbc7a67), R2 item 3 + input addendum, R2b derived `stepped` (user: "Yes derived stepped is good"): a `[Steps]` trait on a screen or actor makes the compiler generate `stepped`/child stepping from Actor / List<Actor> / Option<Actor> fields at compile time; per-field pause by an attribute (e.g. `@stepsWhen(!self.over)`); a hand-written `stepped` still wins (done on `sl/steps`: `trait Steps` in std/game/View, `@stepsWhen(cond)` before a field, core/steps_derive.rs). Then R3 items 10-12.
31
+ - Building: R1 items 1+2 (done cfbc7a67), R2 item 3 + input addendum, R2b derived `stepped` (user: "Yes derived stepped is good"): a `[Steps]` trait on a screen or actor makes the compiler generate `stepped`/child stepping from Actor / List<Actor> / Option<Actor> fields at compile time; per-field pause by an attribute (e.g. `@stepsWhen(!self.over)`); a hand-written `stepped` still wins (done on `sl/steps`: `trait Steps` in std/game/View, `@stepsWhen(cond)` before a field, core/steps_derive.rs). Then R3 items 9-11 (done on `sl/cleanup`: `Game.onDemand` kept as std's one copy, `Frames.onDemand` removed; `SizedTile` moved to its test; `Replay.ticks` and the `Ticker`'s `played` are `List`s, the kit's recording a value; `[Steps]` steps a `List<View>` field with `Views.stepIn`, so `CrowdScreen` derives; `[Show]` (std/Str) derives `toStr`, the games' action enums list it; the games: `primitive Arena`/`Sheet`, `Blinks` and `holdStill` moved to the tests, `Hue.All` a const list, `Balloon` built by name with field defaults (`Balloon.at` gone), `Orb` and `Mine` hold their `Motion` (`motion()`, `put`, `create` gone); not done: a std `Body`, since the bounce is the game's rule and `Motion` is that body; the `PlayAgain` indirection kept).
32
32
  - Waiting: Key enum, one time model, Setup value, typed navigation.
docs/std.md CHANGED
@@ -77,6 +77,8 @@ primitive Demo[App] =
77
77
 
78
78
  `Str` has no `+`: join strings with interpolation, `"{a}{b}"`, or `a.concat(b)`. To build a string in steps, use `Buffer`: `write`, `writeByte`, `toStr`.
79
79
 
80
+ `trait Show` (`fun toStr(self) -> Str`) is what a type is shown as. A type that lists it and writes no `toStr` has it derived, its variant's name and its fields' values (`enum PlayAction[Show] = ..` gives `Steer(1.0, -1.0)`; [language.md](language.md#structs), "Field attributes and derived methods").
81
+
80
82
  ## Sequences
81
83
 
82
84
  Across std, positional access follows one rule: `at` gives the element and crashes when the position is out of range, and `get` gives an `Option`, `None` out of range. `List`, `Slice`, `Array`, `Grid`, `Deque`, `Set` and `Str` have both; on a `Map`, whose `get` takes a key, they are `entryAt(i)` and `getEntryAt(i)`.
@@ -259,7 +261,7 @@ primitive Demo[App] =
259
261
  - **`Uuid`:** `Uuid.v4(rng)`, `Uuid.fromStr`, `Uuid.isValid`, `==` (case-insensitive: `fromStr` lowers the text)
260
262
  - **`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`
261
263
  - **`Aabb`:** an axis-aligned box, corners included: `Aabb.of(x, y, w, h)`, `width`, `height`, `center`, `overlaps`, `contains`, `containsPoint`, `union`, `distSq`, `rayEntry`
262
- - **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))
264
+ - **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 test can use it to tell which of the actors a screen holds a press landed on (a game's pressable items say what a press means instead, `Presses<A>`; see [the game engine](game.md))
263
265
  - **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))
264
266
  - **`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)
265
267
  - **`io.nowMicros()`:** a wall clock in microseconds since the Unix epoch, as a `Float`, on every host
@@ -270,7 +272,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
270
272
 
271
273
  ## Game screens and slices
272
274
 
273
- A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`, derived for a screen that lists `Steps`), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); 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 `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
275
+ A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`, derived for a screen that lists `Steps` from its fields holding actors, a `List<View>` among them), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); 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 `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default) and keeps the screen each `reduce` returns. A run records as a `Replay` (`std/game/Replay`: the seed and a `List<Input>`, one a tick). All of it is in [the game engine](game.md).
274
276
 
275
277
  ```plum
276
278
  import std/Int
examples/games/balloonpop/BalloonPop.plum CHANGED
@@ -13,29 +13,22 @@ import std/game/Game
13
13
  import std/App
14
14
  import screens/PlaygroundScreen
15
15
 
16
- struct Arena =
16
+ primitive Arena =
17
17
  const W = 800.0
18
18
  const H = 600.0
19
19
 
20
20
  struct Hue(name: Str, color: Color) =
21
- fun of(i: Int) -> Hue =
22
- k := i % Hue.count()
23
- if k == 0
21
+ const All = [
24
- Hue(name: "Red", color: Color.rgb(0.93, 0.2, 0.22))
22
+ Hue(name: "Red", color: Color.rgb(0.93, 0.2, 0.22))
25
- else if k == 1
26
- Hue(name: "Blue", color: Color.rgb(0.2, 0.45, 0.95))
23
+ Hue(name: "Blue", color: Color.rgb(0.2, 0.45, 0.95))
27
- else if k == 2
28
- Hue(name: "Yellow", color: Color.rgb(1.0, 0.85, 0.15))
24
+ Hue(name: "Yellow", color: Color.rgb(1.0, 0.85, 0.15))
29
- else if k == 3
30
- Hue(name: "Green", color: Color.rgb(0.25, 0.75, 0.3))
25
+ Hue(name: "Green", color: Color.rgb(0.25, 0.75, 0.3))
31
- else if k == 4
32
- Hue(name: "Orange", color: Color.rgb(1.0, 0.55, 0.1))
26
+ Hue(name: "Orange", color: Color.rgb(1.0, 0.55, 0.1))
33
- else if k == 5
34
- Hue(name: "Purple", color: Color.rgb(0.6, 0.3, 0.85))
27
+ Hue(name: "Purple", color: Color.rgb(0.6, 0.3, 0.85))
35
- else
36
- Hue(name: "Pink", color: Color.rgb(1.0, 0.5, 0.75))
28
+ Hue(name: "Pink", color: Color.rgb(1.0, 0.5, 0.75))
29
+ ]
37
30
 
38
- fun count() -> Int = 7
31
+ fun of(i: Int) -> Hue = Hue.All.at(i % Hue.All.length())
39
32
 
40
33
  struct Assets(pop: Sound, party: Sound, music: Sound) =
41
34
  fun load(io: Io) -> Assets = Assets(pop: Sound.load(io, "pickup.wav"), party: Sound.load(io, "gameover.wav"), music: Sound.load(io, "music.wav"))
examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -23,30 +23,26 @@ import std/game/Button
23
23
  import BalloonPop
24
24
  import screens/PlaygroundScreen
25
25
 
26
+ struct Balloon[Actor, Sized, Touch, Presses<PopAction>](
26
- struct Balloon[Actor, Sized, Touch, Presses<PopAction>](id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, clock: Float, poppedAt: Float) =
27
+ id: Int, x: Float, y: Float, speed: Float = 0.0, hue: Int = 0, phase: Float = 0.0, clock: Float = 0.0, poppedAt: Float = -1.0) =
27
28
  const Radius = 40.0
28
29
  const MinSpeed = 35.0
29
30
  const MaxSpeed = 70.0
30
31
  const PopTime = 0.6
31
32
  const FirstId = 100
32
33
 
33
- fun at(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, clock: Float) -> Balloon =
34
- Balloon(id: id, x: x, y: y, speed: speed, hue: hue, phase: phase, clock: clock, poppedAt: -1.0)
35
-
36
34
  fun spawn(id: Int, rng: Random, depth: Float, clock: Float) -> Spawned =
37
35
  rx := rng.nextFloat()
38
36
  rs := rx.rng.nextFloat()
39
- rh := rs.rng.nextIntBelow(Hue.count())
37
+ rh := rs.rng.nextIntBelow(Hue.All.length())
40
38
  x := 60.0 + rx.value * {Arena.W - 120.0}
41
39
  speed := Balloon.MinSpeed + rs.value * {Balloon.MaxSpeed - Balloon.MinSpeed}
42
- Spawned(balloon: Balloon.at(id, x, Arena.H + Balloon.Radius + depth, speed, rh.value, rx.value * Float.Tau, clock), rng: rh.rng)
40
+ Spawned(balloon: Balloon(id: id, x: x, y: Arena.H + Balloon.Radius + depth, speed: speed, hue: rh.value, phase: rx.value * Float.Tau, clock: clock), rng: rh.rng)
43
41
 
44
42
  fun place(self) -> Place = Place.at(self.drawnX(), self.y)
45
43
 
46
44
  fun pop(self) -> Balloon = Balloon(..self, x: self.drawnX(), poppedAt: self.clock)
47
45
 
48
- fun holdStill(self, x: Float, y: Float) -> Balloon = Balloon(..self, x: x, y: y, speed: 0.0, phase: 0.0)
49
-
50
46
  fun popped(self) -> Bool = self.poppedAt >= 0.0
51
47
 
52
48
  fun drawnX(self) -> Float = if self.popped() then self.x else self.x + 14.0 * Math.sin(self.clock * 1.3 + self.phase)
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -26,18 +26,12 @@ import std/game/Game
26
26
  import actors/Balloon
27
27
  import BalloonPop
28
28
 
29
- enum PopAction =
29
+ enum PopAction[Show] =
30
30
  | Pop(id: Int)
31
31
  | Popped(at: Float)
32
32
  | TakeBack
33
33
  | Tick(dt: Float)
34
34
 
35
- fun toStr(self) -> Str = match self
36
- Pop(id) => "Pop({id})"
37
- Popped(at) => "Popped({at})"
38
- TakeBack => "TakeBack"
39
- Tick(dt) => "Tick({dt})"
40
-
41
35
  struct PlaygroundScreen[ScreenSlice<PopAction>, Steps](
42
36
  rng: Random, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
43
37
  const Count = 6
examples/games/orbitrunner/OrbitRunner.plum CHANGED
@@ -15,11 +15,11 @@ import std/game/Game
15
15
  import std/App
16
16
  import screens/PlayingScreen
17
17
 
18
- struct Arena =
18
+ primitive Arena =
19
19
  const W = 800.0
20
20
  const H = 600.0
21
21
 
22
- struct Sheet =
22
+ primitive Sheet =
23
23
  const Cell = 16.0
24
24
  const Size = 48.0
25
25
 
examples/games/orbitrunner/actors/Mine.plum CHANGED
@@ -9,23 +9,14 @@ import std/game/View
9
9
  import std/game/Sprite
10
10
  import OrbitRunner
11
11
 
12
- struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture) =
12
+ struct Mine[Actor](at: Motion, spin: Float = 0.0, clock: Float = 0.0, tex: Texture) =
13
13
  const Radius = 11.0
14
14
 
15
- fun create(start: Motion, tex: Texture) -> Mine =
16
- 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)
17
-
18
15
  fun countFor(score: Int) -> Int = {3 + score / 50}.min(8)
19
16
 
20
- fun place(self) -> Place = self.at
17
+ fun place(self) -> Place = Place.pivoted(self.at.x, self.at.y, Sheet.Size / 2.0, Sheet.Size / 2.0).rotateTo(self.spin)
21
18
 
22
19
  fun view(self) -> List<View> =
23
20
  [Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
24
21
 
25
- fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
26
-
27
- fun put(self, m: Motion) -> Mine = Mine(..self, at: self.at.moveTo(m.x, m.y), vx: m.vx, vy: m.vy)
22
+ fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt, at: self.at.drifted(Mine.Radius, dt), spin: self.spin + 2.0 * dt)
28
-
29
- fun step(self, dt: Float) -> Mine =
30
- moved := Mine(..self, clock: self.clock + dt).put(self.motion().drifted(Mine.Radius, dt))
31
- Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
examples/games/orbitrunner/actors/Orb.plum CHANGED
@@ -14,23 +14,16 @@ import std/game/View
14
14
  import std/game/Sprite
15
15
  import OrbitRunner
16
16
 
17
- struct Orb[Actor](at: Place, vx: Float, vy: Float, phase: Float, clock: Float, tex: Texture) =
17
+ struct Orb[Actor](at: Motion, phase: Float = 0.0, clock: Float = 0.0, tex: Texture) =
18
18
  const Radius = 10.0
19
19
  const Points = 10
20
20
 
21
- fun create(start: Motion, phase: Float, tex: Texture) -> Orb =
22
- Orb(at: Place.pivoted(start.x, start.y, Sheet.Size / 2.0, Sheet.Size / 2.0), vx: start.vx, vy: start.vy, phase: phase, clock: 0.0, tex: tex)
21
+ fun place(self) -> Place = Place.pivoted(self.at.x, self.at.y, Sheet.Size / 2.0, Sheet.Size / 2.0)
23
-
24
- fun place(self) -> Place = self.at
25
22
 
26
23
  fun view(self) -> List<View> =
27
24
  [Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock + self.phase, 8.0, 4))]
28
25
 
29
- fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
30
-
31
- fun put(self, m: Motion) -> Orb = Orb(..self, at: self.at.moveTo(m.x, m.y), vx: m.vx, vy: m.vy)
32
-
33
- fun step(self, dt: Float) -> Orb = Orb(..self, clock: self.clock + dt).put(self.motion().drifted(Orb.Radius, dt))
26
+ fun step(self, dt: Float) -> Orb = Orb(..self, clock: self.clock + dt, at: self.at.drifted(Orb.Radius, dt))
34
27
 
35
28
  fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
36
29
  c := m.apply(Vec2(x: Sheet.Size / 2.0, y: Sheet.Size / 2.0))
examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -53,5 +53,3 @@ struct Ship[Actor](tex: Texture, at: Place, vx: Float, vy: Float, ax: Float, ay:
53
53
  at: if vx * vx + vy * vy > 400.0 then moved.rotateTo(Math.atan2(vx, 0.0 - vy)) else moved)
54
54
 
55
55
  fun lit(self) -> Bool = !{self.hurt > 0.0 && Sprite.frameAt(self.clock, 10.0, 2) == 0}
56
-
57
- struct Blinks(ship: Ship, n: Int)
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -30,7 +30,7 @@ import actors/Ship
30
30
  import actors/Star
31
31
  import OrbitRunner
32
32
 
33
- enum PlayAction =
33
+ enum PlayAction[Show] =
34
34
  | Steer(ax: Float, ay: Float)
35
35
  | Tick(dt: Float)
36
36
  | PlayAgain
@@ -38,14 +38,6 @@ enum PlayAction =
38
38
  | Hit
39
39
  | StartOver
40
40
 
41
- fun toStr(self) -> Str = match self
42
- Steer(ax, ay) => "Steer({ax}, {ay})"
43
- Tick(dt) => "Tick({dt})"
44
- PlayAgain => "PlayAgain"
45
- Scored(points) => "Scored({points})"
46
- Hit => "Hit"
47
- StartOver => "StartOver"
48
-
49
41
  struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
50
42
  rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
51
43
  @stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
@@ -89,11 +81,11 @@ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
89
81
 
90
82
  fun newOrb(self, i: Int) -> PlayingScreen =
91
83
  sp := Motion.spawn(self.rng, self.ship.at.x, self.ship.at.y, 120.0, 40.0)
92
- PlayingScreen(..self, rng: sp.rng, orbs: self.orbs.append([Orb.create(sp.at, Float(i) * 0.1, self.assets.sheet)]))
84
+ PlayingScreen(..self, rng: sp.rng, orbs: self.orbs.append([Orb(at: sp.at, phase: Float(i) * 0.1, tex: self.assets.sheet)]))
93
85
 
94
86
  fun newMine(self) -> PlayingScreen =
95
87
  sp := Motion.spawn(self.rng, self.ship.at.x, self.ship.at.y, 220.0, 90.0)
96
- PlayingScreen(..self, rng: sp.rng, mines: self.mines.append([Mine.create(sp.at, self.assets.sheet)]))
88
+ PlayingScreen(..self, rng: sp.rng, mines: self.mines.append([Mine(at: sp.at, tex: self.assets.sheet)]))
97
89
 
98
90
  fun onKey(self, e: InputEvent) -> Option<PlayAction> = match e
99
91
  KeyDown(k) => if k == Key.Enter || k == Key.KeyR then Some(PlayAgain) else None
@@ -141,7 +133,7 @@ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
141
133
  caught := self.orbs.fold(Caught(orbs: Nil, rng: self.rng, points: 0), |c, orb|
142
134
  if overlaps(sh.at.x, sh.at.y, Ship.Radius, orb.at.x, orb.at.y, Orb.Radius)
143
135
  sp := Motion.spawn(c.rng, sh.at.x, sh.at.y, 120.0, 40.0)
144
- Caught(orbs: Cons(orb.put(sp.at), c.orbs), rng: sp.rng, points: c.points + Orb.Points)
136
+ Caught(orbs: Cons(Orb(..orb, at: sp.at), c.orbs), rng: sp.rng, points: c.points + Orb.Points)
145
137
  else
146
138
  Caught(..c, orbs: Cons(orb, c.orbs))
147
139
  )
std/Str.plum CHANGED
@@ -17,6 +17,12 @@ import std/Option
17
17
  # `split` parts) share their source's bytes instead of copying. Every way of
18
18
  # turning mutable bytes into a `Str` (`fromBytes`, `Buffer.toStr`) copies.
19
19
  # A small substring keeps its source's array alive; `clone()` detaches it.
20
+ # A type that is shown as text. One that lists `Show` and writes no `toStr` has it
21
+ # derived: its variant's name and its fields' values in order, `Steer(1.0, -1.0)`, `Hit`
22
+ # (docs/language.md, "Derived methods").
23
+ trait Show =
24
+ fun toStr(self) -> Str
25
+
20
26
  struct Str(data: Array<Byte>, start: Int, len: Int) =
21
27
 
22
28
  # Number of bytes in the string.
std/game/Game.plum CHANGED
@@ -448,7 +448,9 @@ struct Game(screens: List<Screen>) =
448
448
  else
449
449
  Viewport.of(Pixels, 1.0, 1.0)
450
450
 
451
- # Whether `s` sleeps through ticks with nothing to do (`frames()` is `OnDemand`).
451
+ # Whether `s` sleeps through ticks with nothing to do (`frames()` is `OnDemand`): a
452
+ # match on `frames()` here, not a method of `Frames` (docs/backlog.md, the fusion
453
+ # re-check failure).
452
454
  fun onDemand(s: Screen) -> Bool = match s.frames()
453
455
  OnDemand => true
454
456
  Always => false
@@ -491,14 +493,15 @@ struct Game(screens: List<Screen>) =
491
493
  #
492
494
  # Record and replay (std/game/Replay): `frame` asks the host each frame. Recording, it
493
495
  # hands the host the inputs of the ticks the frame runs. Replaying (`mode`), the ticks
494
- # take their input from `played`, from `cursor` on, on the recorded window, the host's
496
+ # take their input from `played` (those not yet replayed, the head dropped each tick), on
495
- # input is never read, and no tick runs once the replay is over.
497
+ # the recorded window, the host's input is never read, and no tick runs once the replay
498
+ # is over.
496
499
  #
497
500
  # A development run (`plum run --dev`, `ReplayMode.Dev`): `frame` reads the time travel
498
501
  # keys first (`keys`, std/game/History's `TravelKeys`), keeps them from the game's input
499
502
  # and leaves their commands in `travel` for the game (`Game.devFrame`).
500
503
  struct Ticker(
501
- pending: Input = Input(), acc: Float = 0.0, n: Int = 0, ticks: Int = 0, mode: Int = ReplayMode.Off, played: Slice<Input> = Slice<Input>(), cursor: Int = 0,
504
+ pending: Input = Input(), acc: Float = 0.0, n: Int = 0, ticks: Int = 0, mode: Int = ReplayMode.Off, played: List<Input> = Nil,
502
505
  keys: TravelKeys = TravelKeys(), travel: List<TravelCmd> = Nil) =
503
506
  # The tick length in seconds (1/60), the most ticks one frame runs (a longer stall drops
504
507
  # the rest, so the game slows down instead of falling further behind), and how much
@@ -555,32 +558,30 @@ struct Ticker(
555
558
 
556
559
  # Is another tick due this frame?
557
560
  fun due(self) -> Bool =
558
- self.acc >= Ticker.Tick - Ticker.Slack && self.n < Ticker.MaxTicks && {!self.replaying() || self.cursor < self.played.length()}
561
+ self.acc >= Ticker.Tick - Ticker.Slack && self.n < Ticker.MaxTicks && {!self.replaying() || !self.played.isEmpty()}
559
562
 
560
563
  # The input of the next tick.
561
564
  fun input(self) -> Input =
565
+ match self.played
562
- if self.replaying() then self.played.at(self.cursor) else self.pending
566
+ Cons(x, _) => if self.replaying() then x else self.pending
567
+ Nil => self.pending
563
568
 
564
569
  # After a tick: its time is spent and its events are used up.
565
570
  fun ticked(self) -> Ticker =
566
571
  p := self.pending
567
572
  pending := if self.replaying() then p else Input(..p, events: Nil)
573
+ played := match self.played
574
+ Cons(_, rest) => if self.replaying() then rest else self.played
575
+ Nil => Nil
568
- Ticker(..self, pending: pending, acc: self.acc - Ticker.Tick, n: self.n + 1, ticks: self.ticks + 1, cursor: if self.replaying() then self.cursor + 1 else self.cursor)
576
+ Ticker(..self, pending: pending, acc: self.acc - Ticker.Tick, n: self.n + 1, ticks: self.ticks + 1, played: played)
569
577
 
570
578
  # After the frame's last tick: a stall's leftover time is dropped.
571
579
  fun settled(self) -> Ticker =
572
580
  if self.acc >= Ticker.Tick then Ticker(..self, acc: 0.0) else self
573
581
 
574
582
  # The inputs of the ticks still due this frame, in order: what a recording hands the host.
575
- fun dueInputs(self) -> Slice<Input> =
583
+ fun dueInputs(self) -> List<Input> =
576
- self.collectDue(Slice<Input>())
577
-
578
- fun collectDue(self, out: Slice<Input>) -> Slice<Input> =
584
+ if self.due() then Cons(self.input(), self.ticked().dueInputs()) else Nil
579
- if self.due()
580
- out.push(self.input())
581
- self.ticked().collectDue(out)
582
- else
583
- out
584
585
 
585
586
  # What the host holds between frames: the game and its ticker. The compiler makes a
586
587
  # game's `main` return one, and its frame entry points (`update(state, dt)` and
std/game/Replay.plum CHANGED
@@ -7,7 +7,6 @@ import std/Bool
7
7
  import std/Option
8
8
  import std/Result
9
9
  import std/Slice
10
- import std/Buffer
11
10
  import std/collections/List
12
11
  import std/math/Vec2
13
12
  import std/Io
@@ -50,7 +49,7 @@ primitive ReplayMode =
50
49
 
51
50
  # A recorded run: the seed `io.randomSeed()` gave `main`, the screen size at the start,
52
51
  # and the input of every tick in order.
53
- struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
52
+ struct Replay(seed: Int, width: Int, height: Int, ticks: List<Input> = Nil) =
54
53
  # Whether the host is recording or replaying this run (a `ReplayMode`, asked once a frame).
55
54
  extern fun replayMode(io: Io) -> Int
56
55
  # The text of the replay the host is replaying.
@@ -59,25 +58,19 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
59
58
  extern fun replayAppend(io: Io, ticks: Str)
60
59
 
61
60
  fun create(seed: Int) -> Replay =
62
- Replay(seed: seed, width: 0, height: 0, ticks: Slice<Input>())
61
+ Replay(seed: seed, width: 0, height: 0)
63
62
 
64
63
  # How many ticks it holds.
65
64
  fun length(self) -> Int =
66
65
  self.ticks.length()
67
66
 
68
- fun at(self, i: Int) -> Input =
69
- self.ticks.at(i)
70
-
71
67
  # The text form (see the top of this file).
72
68
  fun encode(self) -> Str =
73
69
  "{Replay.header(self.seed, self.width, self.height)}{Replay.ticksText(self.ticks)}"
74
70
 
75
71
  # The tick lines alone, what a recording game hands the host.
76
- fun ticksText(ticks: Slice<Input>) -> Str =
72
+ fun ticksText(ticks: List<Input>) -> Str =
77
- b := Buffer()
78
- for i := range ticks.length()
79
- b.write(Replay.line(ticks.at(i)))
73
+ ticks.map(|t| Replay.line(t)).join("")
80
- b.toStr()
81
74
 
82
75
  # Reads the text form back, or says what is wrong with it.
83
76
  fun decode(text: Str) -> Result<Replay, Str> =
@@ -90,34 +83,29 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
90
83
  lo := Replay.headNumber(head, 2)?
91
84
  width := Replay.headNumber(head, 3)?
92
85
  height := Replay.headNumber(head, 4)?
93
- ticks := Replay.decodeTicks(lines, 1, Slice<Input>())?
86
+ ticks := Replay.decodeTicks(lines, 1, Nil)?
94
87
  Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks).onScreen(width, height))
95
88
 
96
89
  # The replay on a window `w` by `h` pixels, each tick's input in it (`Input.screen`): a
97
90
  # decoded replay is on the window of its header.
98
91
  fun onScreen(self, w: Int, h: Int) -> Replay =
99
- sized := Slice<Input>()
100
- for i := range self.ticks.length()
101
- sized.push(self.ticks.at(i).sized(Float(w), Float(h)))
102
- Replay(..self, width: w, height: h, ticks: sized)
92
+ Replay(..self, width: w, height: h, ticks: self.ticks.map(|t| t.sized(Float(w), Float(h))))
103
93
 
104
94
  # The whole number at `head.at(i)`, a field of the first line.
105
95
  fun headNumber(head: Slice<Str>, i: Int) -> Result<Int, Str> =
106
96
  Int.parse(head.at(i)).mapErr(|e| "line 1: `{head.at(i)}` is not a whole number")
107
97
 
108
- # The tick lines from `lines.at(i)` on, added to `out`.
98
+ # The tick lines from `lines.at(i)` on, after `out` (the lines before, the last first).
109
- fun decodeTicks(lines: Slice<Str>, i: Int, out: Slice<Input>) -> Result<Slice<Input>, Str> =
99
+ fun decodeTicks(lines: Slice<Str>, i: Int, out: List<Input>) -> Result<List<Input>, Str> =
110
100
  if i >= lines.length()
111
- Ok(out)
101
+ Ok(out.reverse())
112
102
  else
113
103
  l := lines.at(i).trim()
114
104
  if l.length() == 0
115
105
  Replay.decodeTicks(lines, i + 1, out)
116
106
  else
117
107
  match Replay.parseLine(l)
118
- Some(input) =>
119
- out.push(input)
120
- Replay.decodeTicks(lines, i + 1, out)
108
+ Some(input) => Replay.decodeTicks(lines, i + 1, Cons(input, out))
121
109
  None => Err("line {i + 1}: `{l}` is not a tick")
122
110
 
123
111
  fun header(seed: Int, width: Int, height: Int) -> Str =
std/game/Screen.plum CHANGED
@@ -139,10 +139,6 @@ enum Frames =
139
139
  | Always
140
140
  | OnDemand
141
141
 
142
- fun onDemand(self) -> Bool = match self
143
- OnDemand => true
144
- Always => false
145
-
146
142
  # How a screen comes in when the game goes to it: at once (`Cut`), fading in over the old
147
143
  # one (`Fade`), or sliding in from an edge, pushing the old one out of the other side
148
144
  # (`Slide`), over `secs` seconds.
std/game/Sized.plum CHANGED
@@ -14,6 +14,3 @@ trait Sized =
14
14
  fun bounds(self) -> Aabb
15
15
 
16
16
  fun hit(self, p: Vec2) -> Bool = self.bounds().containsPoint(p)
17
-
18
- struct SizedTile[Sized](w: Float) =
19
- fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, 5.0)
std/game/TestRig.plum CHANGED
@@ -206,9 +206,8 @@ struct TestRig<S>(
206
206
  if self.game.exited || self.game.paused
207
207
  self
208
208
  else
209
- if self.recording
210
- self.log.ticks.push(input)
209
+ logged := if self.recording then Replay(..self.log, ticks: Cons(input, self.log.ticks)) else self.log
211
- self.kept(self.game.step(self.io, input, dt, self.pixels))
210
+ TestRig(..self, log: logged).kept(self.game.step(self.io, input, dt, self.pixels))
212
211
 
213
212
  # The rig with `g`, keeping what its last tick gave.
214
213
  fun kept(self, g: Game) -> TestRig<S> =
@@ -298,12 +297,12 @@ struct TestRig<S>(
298
297
 
299
298
  fun showing(self) -> Str = self.game.showing()
300
299
 
301
- # Records the ticks from here as a replay of `seed`.
300
+ # Records the ticks from here as a replay of `seed` (`log` holds them the newest first).
302
301
  fun record(self, seed: Int) -> TestRig<S> =
303
- TestRig(..self, recording: true, log: Replay(seed: seed, width: Int(self.pixels.x), height: Int(self.pixels.y), ticks: Slice<Input>()))
302
+ TestRig(..self, recording: true, log: Replay(seed: seed, width: Int(self.pixels.x), height: Int(self.pixels.y)))
304
303
 
305
- fun recorded(self) -> Replay = self.log
304
+ fun recorded(self) -> Replay = Replay(..self.log, ticks: self.log.ticks.reverse())
306
305
 
307
306
  # Every tick of `r` played now (a game made from `r.seed`).
308
307
  fun replay(self, r: Replay) -> TestRig<S> =
309
- Range.until(0, r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i), Ticker.Tick))
308
+ r.ticks.fold(self.forget(), |t, input| t.ran1(input, Ticker.Tick))
std/game/View.plum CHANGED
@@ -82,9 +82,10 @@ import std/game/Overlay
82
82
  # worldIn where they draw a given view: its transform (std/game/TestRig's
83
83
  # `worldOf`)
84
84
  #
85
- # and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind)
85
+ # and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind),
86
- # and `stepIn` (each `Actor` of a list of views, what a `Group` or an `Overlay` holds,
86
+ # `stepSome` (an `Option` of one) and `stepIn` (each `Actor` of a list of views, what a
87
+ # `Group` or an `Overlay` holds, and the others as they are: a `[Steps]` type's
87
- # and the others as they are).
88
+ # `List<View>` field).
88
89
  trait View =
89
90
  fun place(self) -> Place
90
91
 
@@ -101,8 +102,8 @@ trait Actor[View] =
101
102
  fun step(self, dt: Float) -> Self
102
103
 
103
104
  # A screen or an actor whose fields holding actors the compiler steps: each field that is
104
- # an `Actor`, a `List` of actors or an `Option` of one, the others as they are, at compile
105
+ # an `Actor`, a `List` of actors, an `Option` of one or a `List<View>` (`Views.stepIn`, each
105
- # time (the same static construction a hand-written `stepped` is). On a `Screen` it derives
106
+ # item's type tested as it is stepped), the others as they are, at compile time (the same static construction a hand-written `stepped` is). On a `Screen` it derives
106
107
  # `stepped(dt)` (a screen that writes its own keeps it); on an `Actor` its fields are
107
108
  # stepped after its own `step`, which then holds only what is special about it.
108
109
  # `@stepsWhen(cond)` before a field steps it only while `cond` holds, read on `self`:
tests/examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -24,7 +24,7 @@ import std/Test
24
24
  primitive BalloonTest[UnitTest] =
25
25
  # a whole balloon is hit on its body, its knot and its string, and a burst one nowhere
26
26
  fun aWholeBalloonIsHitOnItsBody() =
27
- b := Balloon.at(1, 100.0, 100.0, 0.0, 0, 0.0, 0.0)
27
+ b := Balloon(id: 1, x: 100.0, y: 100.0)
28
28
  r := Balloon.Radius
29
29
  assert b.hit(Vec2(x: 0.0, y: 0.0))
30
30
  assert b.hit(Vec2(x: 0.0, y: r + 6.0))
@@ -35,7 +35,7 @@ primitive BalloonTest[UnitTest] =
35
35
 
36
36
  # a balloon rises and sways as the clock runs, and stays where it burst
37
37
  fun aBalloonRisesAndSwaysAsTheClock() =
38
- b := Balloon.at(1, 100.0, 500.0, 50.0, 0, 0.0, 0.0).step(1.0)
38
+ b := Balloon(id: 1, x: 100.0, y: 500.0, speed: 50.0).step(1.0)
39
39
  assert b.place().y == 450.0
40
40
  assert b.place().x != 100.0
41
41
  x := b.place().x
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -187,7 +187,7 @@ primitive PlaygroundScreenHelpers =
187
187
 
188
188
  fun stillAt(t: TestRig<PlaygroundScreen>, i: Int, x: Float, y: Float) -> TestRig<PlaygroundScreen> =
189
189
  s := t.screen
190
- poked(t, PlaygroundScreen(..s, balloons: s.balloons.map(|b| if b.id == Balloon.FirstId + i then b.holdStill(x, y) else b)))
190
+ poked(t, PlaygroundScreen(..s, balloons: s.balloons.map(|b| if b.id == Balloon.FirstId + i then Balloon(..b, x: x, y: y, speed: 0.0, phase: 0.0) else b)))
191
191
 
192
192
  fun centred(t: TestRig<PlaygroundScreen>) -> TestRig<PlaygroundScreen> = stillAt(t, 0, 400.0, 300.0)
193
193
 
tests/examples/games/orbitrunner/actors/Mine.plum CHANGED
@@ -11,8 +11,8 @@ import std/Test
11
11
 
12
12
  primitive MineTest[UnitTest] =
13
13
  fun aMineSpinsAsItDrifts() =
14
- mine := Mine.create(Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), Texture.none()).step(0.5)
14
+ mine := Mine(at: Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), tex: Texture.none()).step(0.5)
15
- assert Math.near(mine.at.rotation, 1.0, 0.01)
15
+ assert Math.near(mine.place().rotation, 1.0, 0.01)
16
16
  assert Math.near(mine.at.x, 405.0, 0.01)
17
17
 
18
18
  fun moreMinesAreOutAsTheScoreGrows() =
tests/examples/games/orbitrunner/actors/Orb.plum CHANGED
@@ -16,7 +16,7 @@ import std/Test
16
16
 
17
17
  primitive OrbTest[UnitTest] =
18
18
  fun anOrbDriftsAndBouncesOffTheWalls() =
19
- orb := Orb.create(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), 0.0, Texture.none()).step(0.1)
19
+ orb := Orb(at: Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), tex: Texture.none()).step(0.1)
20
- assert orb.vx == -100.0
20
+ assert orb.at.vx == -100.0
21
21
  assert orb.at.x == Arena.W - 10.0
22
22
  assert orb.clock == 0.1
tests/examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -39,3 +39,5 @@ primitive ShipTest[UnitTest] =
39
39
  next := b.ship.step(0.02)
40
40
  Blinks(ship: next, n: if next.visible() then b.n else b.n + 1))
41
41
  assert blinks.n > 0 && blinks.n < 60
42
+
43
+ struct Blinks(ship: Ship, n: Int)
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -150,7 +150,7 @@ primitive PlayingScreenTest[UnitTest] =
150
150
  fun afterGameOverTheFieldStandsStillThe() =
151
151
  t := PlayingScreenHelpers.emptied(io, 0, 1)
152
152
  s := t.screen
153
- started := PlayingScreenHelpers.poked(t, PlayingScreen(..s, mines: Cons(s.mines.at(0).put(Motion(x: s.ship.at.x, y: s.ship.at.y, vx: 10.0, vy: 0.0)), PlayingScreenHelpers.rest(s.mines)))).tick(0.016)
153
+ started := PlayingScreenHelpers.poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), at: Motion(x: s.ship.at.x, y: s.ship.at.y, vx: 10.0, vy: 0.0)), PlayingScreenHelpers.rest(s.mines)))).tick(0.016)
154
154
  p := started.screen
155
155
  assert p.over
156
156
  mine := p.mines.at(0)
@@ -159,7 +159,7 @@ primitive PlayingScreenTest[UnitTest] =
159
159
  later := Range.until(0, 10).fold(grown.hold(Key.Right), |r, i| r.tick(0.1))
160
160
  q := later.screen
161
161
  assert q.mines.at(0).at.x == mine.at.x
162
- assert q.mines.at(0).at.rotation == mine.at.rotation
162
+ assert q.mines.at(0).spin == mine.spin
163
163
  assert q.ship.at.x == Arena.W / 2.0
164
164
  assert q.mines.at(0).clock == mine.clock
165
165
  assert q.orbs.at(0).clock == p.orbs.at(0).clock
@@ -372,7 +372,7 @@ primitive PlayingScreenHelpers =
372
372
  fun mounted(io: Io, seed: Int, score: Int, lives: Int) -> TestRig<PlayingScreen> =
373
373
  TestRig.mount(io, PlayingScreen.at(Random.seeded(seed), Assets.none(), score, lives))
374
374
 
375
- fun cleared(s: PlayingScreen) -> PlayingScreen = PlayingScreen(..s, orbs: s.orbs.map(|o| o.put(away())), mines: s.mines.map(|m| m.put(away())))
375
+ fun cleared(s: PlayingScreen) -> PlayingScreen = PlayingScreen(..s, orbs: s.orbs.map(|o| Orb(..o, at: away())), mines: s.mines.map(|m| Mine(..m, at: away())))
376
376
 
377
377
  fun emptied(io: Io, score: Int, lives: Int) -> TestRig<PlayingScreen> =
378
378
  TestRig.mount(io, cleared(PlayingScreen.at(Random.seeded(7), Assets.none(), score, lives)))
@@ -383,15 +383,15 @@ primitive PlayingScreenHelpers =
383
383
 
384
384
  fun orbOnShip(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
385
385
  s := t.screen
386
- poked(t, PlayingScreen(..s, orbs: Cons(s.orbs.at(0).put(onShip(s.ship)), rest(s.orbs))))
386
+ poked(t, PlayingScreen(..s, orbs: Cons(Orb(..s.orbs.at(0), at: onShip(s.ship)), rest(s.orbs))))
387
387
 
388
388
  fun mineOnShip(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
389
389
  s := t.screen
390
- poked(t, PlayingScreen(..s, mines: Cons(s.mines.at(0).put(onShip(s.ship)), rest(s.mines))))
390
+ poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), at: onShip(s.ship)), rest(s.mines))))
391
391
 
392
392
  fun mineAway(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
393
393
  s := t.screen
394
- poked(t, PlayingScreen(..s, mines: Cons(s.mines.at(0).put(away()), rest(s.mines))))
394
+ poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), at: away()), rest(s.mines))))
395
395
 
396
396
  fun lastLife(io: Io) -> TestRig<PlayingScreen> = mineOnShip(emptied(io, 30, 1))
397
397
 
tests/port/game/replay.plum CHANGED
@@ -58,7 +58,7 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, presses: Int, held: Int,
58
58
  # The screen the tests run on.
59
59
 
60
60
  # The game, its clock and the ticks recorded so far, as a recording host holds them.
61
- struct Run(game: Game, clock: Ticker, log: Slice<Input>) =
61
+ struct Run(game: Game, clock: Ticker, log: List<Input>) =
62
62
  fun probe(self) -> Probe = match self.game.screen()
63
63
  Probe as p => p
64
64
  _ => Probe.seeded(-1)
@@ -66,27 +66,28 @@ struct Run(game: Game, clock: Ticker, log: Slice<Input>) =
66
66
  primitive ReplayTest[UnitTest] =
67
67
  # replay_roundtrip
68
68
  fun replayRoundtrip() =
69
- r := Replay(seed: -6917529027641081853, width: 800, height: 600, ticks: Slice<Input>())
70
- r.ticks.push(Input())
71
- r.ticks.push(Input(events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), Wheel(dy: -1.0), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)], held: Held(mouse: true, keys: [Key.Left, Key.Space], pointer: Vec2(x: 0.1, y: 1.0e-300))))
72
- r.ticks.push(Input(events: [Wheel(dy: 0.1)], held: Held(keys: [Key.Up], pointer: Vec2(x: 0.3, y: 0.7))))
73
- r.ticks.push(Input(events: [ButtonDown(button: Mouse.Right, x: 1.5, y: -2.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 3.0)], held: Held(mouse: true, buttons: [Mouse.Middle, Mouse.Right], pointer: Vec2(x: 1.5, y: -2.0))))
69
+ r := Replay(seed: -6917529027641081853, width: 800, height: 600, ticks: [
70
+ Input()
71
+ Input(events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), Wheel(dy: -1.0), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)], held: Held(mouse: true, keys: [Key.Left, Key.Space], pointer: Vec2(x: 0.1, y: 1.0e-300)))
72
+ Input(events: [Wheel(dy: 0.1)], held: Held(keys: [Key.Up], pointer: Vec2(x: 0.3, y: 0.7)))
73
+ Input(events: [ButtonDown(button: Mouse.Right, x: 1.5, y: -2.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 3.0)], held: Held(mouse: true, buttons: [Mouse.Middle, Mouse.Right], pointer: Vec2(x: 1.5, y: -2.0)))
74
+ ])
74
75
  text := r.encode()
75
76
  if Ok(back) := Replay.decode(text)
76
77
  assert back.seed == r.seed
77
78
  assert back.width == 800
78
79
  assert back.height == 600
79
80
  assert back.length() == 4
80
- assert back.at(3).held.isButtonDown(Mouse.Middle) && back.at(3).held.isButtonDown(Mouse.Right)
81
+ assert back.ticks.at(3).held.isButtonDown(Mouse.Middle) && back.ticks.at(3).held.isButtonDown(Mouse.Right)
81
- assert back.at(3).held.same(r.at(3).held)
82
+ assert back.ticks.at(3).held.same(r.ticks.at(3).held)
82
83
  for i := range 4
83
- assert Replay.sameInput(back.at(i), r.at(i))
84
+ assert Replay.sameInput(back.ticks.at(i), r.ticks.at(i))
84
- assert back.at(1).held.pointer.x == 0.1
85
+ assert back.ticks.at(1).held.pointer.x == 0.1
85
- assert back.at(1).held.pointer.y == 1.0e-300
86
+ assert back.ticks.at(1).held.pointer.y == 1.0e-300
86
- assert back.at(2).events.length() == 1 && back.at(2).events.any(|e| match e
87
+ assert back.ticks.at(2).events.length() == 1 && back.ticks.at(2).events.any(|e| match e
87
88
  Wheel(dy) => dy == 0.1
88
89
  _ => false)
89
- if Some(p) := back.at(1).events.at(5).position()
90
+ if Some(p) := back.ticks.at(1).events.at(5).position()
90
91
  assert p.x == 1.0e-300
91
92
  else
92
93
  assert false
@@ -112,10 +113,7 @@ primitive ReplayTest[UnitTest] =
112
113
 
113
114
  fun aReplayWithNoInputEndsElsewhere() =
114
115
  run := recorded(io, 5, 60)
115
- idle := Slice<Input>()
116
- for i := range run.log.length()
117
- idle.push(Input())
118
- still := replayed(io, Replay(seed: 5, width: 0, height: 0, ticks: idle), 80)
116
+ still := replayed(io, Replay(seed: 5, width: 0, height: 0, ticks: run.log.map(|t| Input())), 80)
119
117
  assert still.probe().ticks == run.probe().ticks
120
118
  assert !still.probe().same(run.probe())
121
119
 
@@ -231,10 +229,7 @@ primitive ReplayTest[UnitTest] =
231
229
  # `frame` as the polled input and the frame's ticks handed to the log.
232
230
  fun recordFrame(io: Io, r: Run, frame: Input, dt: Float) -> Run =
233
231
  c := r.clock.accept(frame, dt)
234
- due := c.dueInputs()
235
- for i := range due.length()
236
- r.log.push(due.at(i))
237
- ticks(io, Run(..r, clock: c))
232
+ ticks(io, Run(..r, clock: c, log: r.log.append(c.dueInputs())))
238
233
 
239
234
  # One replayed frame: the frame's time paces the ticks, its input is not read.
240
235
  fun replayFrame(io: Io, r: Run, dt: Float) -> Run =
@@ -260,9 +255,9 @@ primitive ReplayTest[UnitTest] =
260
255
  0.0166 + Float(i % 3) * 0.004 - 0.004
261
256
 
262
257
  fun recorded(io: Io, seed: Int, frames: Int) -> Run =
263
- start := Run(game: probeGame(seed), clock: Ticker(), log: Slice<Input>())
258
+ start := Run(game: probeGame(seed), clock: Ticker(), log: Nil)
264
259
  Range.until(0, frames).fold(start, |r, i| recordFrame(io, r, scripted(i), jitter(i)))
265
260
 
266
261
  fun replayed(io: Io, r: Replay, frames: Int) -> Run =
267
- start := Run(game: probeGame(r.seed), clock: Ticker.playing(r), log: Slice<Input>())
262
+ start := Run(game: probeGame(r.seed), clock: Ticker.playing(r), log: Nil)
268
263
  Range.until(0, frames).fold(start, |run, i| replayFrame(io, run, jitter(i + 1)))
tests/std/game/Sized.plum CHANGED
@@ -5,6 +5,9 @@ import std/math/Vec2
5
5
  import std/game/Sized
6
6
  import std/Test
7
7
 
8
+ struct SizedTile[Sized](w: Float) =
9
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, 5.0)
10
+
8
11
  primitive SizedTest[UnitTest] =
9
12
  # a sized actor is hit inside its bounds, edges included
10
13
  fun aSizedActorIsHitInsideItsBounds() =
tests/std/game/View.plum CHANGED
@@ -130,14 +130,17 @@ primitive ViewTest[UnitTest] =
130
130
 
131
131
  # A view that logs where it is painted (the x of its origin) and at what alpha.
132
132
 
133
- # a [Steps] screen's derived `stepped` steps each field holding actors, and leaves the others
133
+ # a [Steps] screen's derived `stepped` steps each field holding actors (the actors of a
134
+ # `List<View>`, a group's among them), and leaves the others
134
135
  fun aStepsScreenStepsItsActorFields() =
135
- s := Stage(n: 7, one: Stepper(time: 0.0), many: [Stepper(time: 1.0), Stepper(time: 2.0)], maybe: Some(Stepper(time: 3.0)), nothing: None, anyOne: Stepper(time: 4.0), anyMany: [Stepper(time: 5.0)], loose: Stepper(time: 6.0)).stepped(0.5)
136
+ s := Stage(n: 7, one: Stepper(time: 0.0), many: [Stepper(time: 1.0), Stepper(time: 2.0)], maybe: Some(Stepper(time: 3.0)), nothing: None, anyOne: Stepper(time: 4.0), anyMany: [Stepper(time: 5.0)], loose: Stepper(time: 6.0), scene: [Stepper(time: 7.0), Group() { Stepper(time: 8.0) }]).stepped(0.5)
136
137
  assert s.n == 7 && s.one.time == 0.5 && ViewHelpers.timeOf(s.loose) == 6.0
137
138
  assert s.many.map(|x| x.time) == [1.5, 2.5]
138
139
  assert s.maybe.map(|x| x.time) == Some(3.5) && s.nothing.isNone()
139
140
  assert ViewHelpers.timeOf(s.anyOne) == 4.5
140
141
  assert s.anyMany.map(|x| ViewHelpers.timeOf(x)) == [5.5]
142
+ assert s.scene.map(|x| ViewHelpers.timeOf(x)) == [7.5, -1.0]
143
+ assert s.scene.at(1).view().map(|x| ViewHelpers.timeOf(x)) == [8.5]
141
144
 
142
145
  # `@stepsWhen` steps a field only while its condition holds, the others always
143
146
  fun stepsWhenPausesOneField() =
@@ -227,7 +230,7 @@ primitive ViewHelpers =
227
230
  fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
228
231
 
229
232
  # A screen whose actors are stepped for it, of each kind a field can hold them in.
230
- struct Stage[Screen, Steps](n: Int, one: Stepper, many: List<Stepper>, maybe: Option<Stepper>, nothing: Option<Stepper>, anyOne: Actor, anyMany: List<Actor>, loose: View) =
233
+ struct Stage[Screen, Steps](n: Int, one: Stepper, many: List<Stepper>, maybe: Option<Stepper>, nothing: Option<Stepper>, anyOne: Actor, anyMany: List<Actor>, loose: View, scene: List<View>) =
231
234
  fun name(self) -> Str = "stage"
232
235
 
233
236
  # A walker paused with the screen, clocks that run on.
tests/traits/show.plum ADDED
@@ -0,0 +1,61 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/collections/List
6
+ import std/Option
7
+ import std/Test
8
+
9
+ # `[Show]`: a derived `toStr`, the variant's name and its fields' values in order.
10
+
11
+ enum Move[Show] =
12
+ | Step(dx: Float, dy: Float)
13
+ | Jump
14
+ | Say(text: Str, loud: Bool)
15
+ | Nested(m: Spot)
16
+
17
+ struct Spot[Show](x: Int, y: Int)
18
+
19
+ struct Nothing[Show]
20
+
21
+ enum Boxed<T>[Show] =
22
+ | Full(value: T)
23
+ | Empty
24
+
25
+ enum Own[Show] =
26
+ | A
27
+ | B
28
+
29
+ fun toStr(self) -> Str = "mine"
30
+
31
+ primitive ShowTest[UnitTest] =
32
+ # an enum's variants are their names and their fields' values
33
+ fun anEnumIsShownByItsVariants() =
34
+ assert Step(dx: 1.0, dy: -0.5).toStr() == "Step(1.0, -0.5)"
35
+ assert Jump.toStr() == "Jump"
36
+ assert Say(text: "hi", loud: true).toStr() == "Say(hi, true)"
37
+ assert Nested(m: Spot(x: 1, y: 2)).toStr() == "Nested(Spot(1, 2))"
38
+ m: Move := Jump
39
+ assert "{m}!" == "Jump!"
40
+
41
+ # a struct is its name and its fields' values; one with none is its name
42
+ fun aStructIsShownByItsFields() =
43
+ assert Spot(x: 3, y: -4).toStr() == "Spot(3, -4)"
44
+ assert Nothing().toStr() == "Nothing"
45
+
46
+ # a generic enum shows its type argument's values
47
+ fun aGenericEnumIsShown() =
48
+ assert Full(value: 5).toStr() == "Full(5)"
49
+ assert Full(value: Spot(x: 0, y: 0)).toStr() == "Full(Spot(0, 0))"
50
+ e: Boxed<Int> := Empty
51
+ assert e.toStr() == "Empty"
52
+
53
+ # a type that writes its own `toStr` keeps it
54
+ fun anOwnToStrWins() =
55
+ assert A.toStr() == "mine"
56
+
57
+ # a `Show` bound takes any type that lists it
58
+ fun aShowBoundTakesAnyShown() =
59
+ assert ShowTest.both(Spot(x: 1, y: 1), Jump) == "Spot(1, 1) Jump"
60
+
61
+ fun both<A: Show, B: Show>(a: A, b: B) -> Str = "{a.toStr()} {b.toStr()}"