plum

#treesitter#compiler#wasm

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

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


cfbc7a6 — Peter John 2026-11-16T11:20:12+05:30
reducers return their follow-ups, commands as data (std/game review items 1 and 2): a slice's `act(self, a: A) -> Next<Self, A>` (`struct Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`, std/game/ScreenSlice) is `Next(state: self.reduce(a))` by default and `reduce` is the screen as it is by default, so a screen writes the one it needs; named `act`, not `step`, which an `Actor` has (the uniqueness pass resolves methods by name); each action delivered is acted on and then each action of its `then`, in order, each with its own `then` first; the delivery is a pure fold (`Delivery.deliverTo` over `eventsInto`, `eventInto`, `heldInto`, `tickInto`, `actIn`, `actAll`, `done`; the slice passed as a parameter and the actions and commands in a `Trail<A>`, a `Folded<S, A>` taken apart by pattern each time) returning `Delivered(screen, cmds, sent, acted)`, with no `Slice` accumulators; `TestRig.dispatch` runs the same fold (`Delivery.dispatchTo<A, S>` on the rig's own screen type: `Next<Self, A>` can't be called on a trait object); `enum Cmd = GoTo(name) | Exit | Undo | Redo | RewindTo(tick) | Play(sound, volume) | Loop(sound, volume) | Stop(sound)` (std/game/Cmd, with `toStr`, `travels`, `sound(io)`, `Cmd.names`), done by the game after the tick in order (`Game.obey(io, c)`; the history moves once the tick is recorded); a tick played again by a rewind gives the same commands and the game does only its `GoTo`s (`Game.redone`), so no sound plays twice by construction, and `HistoryTick` no longer records asks; no escape hatch, as nothing needed one; removed: std/game/Control.plum (`Control`, `Ask`), std/game/Effects.plum (`Effects.Running`, the global slot, `startDispatch`, `queueAction`, `sent`, `Effect`, `Queued`, `Sink`, `ActionSink`), `ScreenSlice.effect` and `dispatch`, `Game.apply`/`redoAsks`, `Game.ran`/`asked` (now `sent`/`cmds`); the kit reads `t.actions<A>()` (`Dispatches.of`, a `Sent<A>` per action) and `t.cmds` as values; checker: a generic struct with no `mut` field is covariant in each generic its fields hold only as themselves or in a `List` or an `Option` (`upcasts::covariantStructs`, rebuilt field by field by a helper as `List`/`Option` are), which a `$dyn` copy of `act` needs (`Next<PlayingScreen, A>` where `Next<ScreenSlice<A>, A>` is expected); games: Orbit Runner's rules return what happened (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), `PlayAgain` is followed by `StartOver` at once (`again` gone), `act` is `self.reduce(a).followed(a)` with the sounds as commands, `startMusic` gone, mines grow with the score in `Scored`; Balloon Pop loses `popsHeard`, `partiesHeard`, `newPop`, `newParty`, `hearPop`, `hearParty` and `hear()`: `Pop` is followed by `Popped`, which plays the pop and every tenth the fanfare, `TakeBack` gives `Undo`; clicks and two_screens use `act` with `Exit`/`GoTo`; the games are 72 lines removed, 54 added; Orbit Runner's checksum is 946756219 (was master's 925878360: the mines are checked before more are added for the tick's points, a restart starts at once), stable run after run; benchmarks/screen_views: orbit update 14.0-14.4 ms before, 12.6-12.8 ms after, paint 130.8-131.6 ms before, 129.5-130.2 ms after, scale update view about 22 ms and paint about 330 ms, spread 15.5 ms, both unchanged; game_in_place_test: Orbit Runner's `reduce$unique` (3) and `newMine$unique` (1) are gone (they were reductions dispatched from inside its own `reduce`; std's generic fold gets no unique version), `Delivery.actIn` is in place in both games; tests: tests/std/game/Cmd.plum (replaces Control), tests/port/game/screens.plum (an `act`'s `then` order, commands read back, the kit's undo through `TakeBack`), the games' tests assert commands (`Cmd.names(t.cmds) == "stop(-1) play(-1, 1.0)"`), tests/traits/covariance.plum and a checker test for covariant structs, host_test's seed replay takes no seed in a tick, camera_fixture and game_entry_test on `act`; docs: game.md (the slice table, what follows from an action, commands for sound and navigation, rewinds and commands, undo, the kit, the "Beside master" rows for Effects/Control/dispatch, the checksum), language.md (covariant structs), std.md, backlog, the review plan
benchmarks/screen_views/orbit.plum CHANGED
@@ -2,8 +2,8 @@
2
2
  # input of benchmarks/screen_views/timing (as master's benchmarks/screen_views/orbit.plum),
3
3
  # restarts on.
4
4
  #
5
- # update each tick through the game (`Game.update`: the screen's mapping, its reducer,
5
+ # update each tick through the game (`Game.update`: the screen's mapping, its steps,
6
- # the effects)
6
+ # the commands)
7
7
  # paint each tick, then the frame (`Game.draw`: the clear, the viewport, the screen's
8
8
  # view made and drawn). Run with PLUM_NULL_GFX=1: there is no host, and the draw
9
9
  # calls reach nothing.
compiler/checker/src/program.rs CHANGED
@@ -283,6 +283,8 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
283
283
  let primitive_generics = buildPrimitiveGenerics(source);
284
284
  let (mut global_env, methods, enum_variants) = buildGlobalTablesWith(source, &traits, &primitive_generics);
285
285
  withCheck(|s| *s.traits.borrow_mut() = traits.clone());
286
+ let covariant = std::rc::Rc::new(crate::upcasts::covariantStructs(source, &enum_variants));
287
+ withCheck(|s| *s.covariant.borrow_mut() = covariant);
286
288
  withCheck(|s| {
287
289
  *s.fn_generics.borrow_mut() = source
288
290
  .items
compiler/checker/src/state.rs CHANGED
@@ -93,6 +93,8 @@ pub(crate) struct CheckState {
93
93
  pub(crate) scope_site: RefCell<Option<(String, usize, String)>>,
94
94
  /// The traits of the program being checked (`traits::buildTraits`).
95
95
  pub(crate) traits: RefCell<std::rc::Rc<crate::traits::Traits>>,
96
+ /// The program's covariant structs, by name (`upcasts::covariantStructs`).
97
+ pub(crate) covariant: RefCell<std::rc::Rc<HashMap<String, crate::upcasts::CovStruct>>>,
96
98
  /// The bounds of the generics in scope of the body being checked (`[T: Show]`).
97
99
  pub(crate) cur_bounds: RefCell<BTreeMap<String, Vec<PlumType>>>,
98
100
  /// Instantiations whose type arguments don't meet a bound, found as they are registered.
compiler/checker/src/upcasts.rs CHANGED
@@ -5,6 +5,11 @@
5
5
  //! place; a `Slice` or an `Array` is written through, so it stays invariant). Inside a
6
6
  //! function type nothing is covariant: a `fn(List<View>)` takes no `fn(List<Ship>)`.
7
7
  //!
8
+ //! A generic struct with no `mut` field is covariant in each generic that its fields hold
9
+ //! only as themselves or inside a `List` or an `Option` (`covariantStructs`): a
10
+ //! `Next<Ship, A>` (`struct Next<S, A>(state: S, then: List<A>)`) is a `Next<View, A>`, built
11
+ //! again field by field.
12
+ //!
8
13
  //! A trait object is a reference to the value itself (`plum_wasm_codegen::traits`), but each
9
14
  //! instance of a generic enum is its own wasm-gc type: a `List<Ship>`'s cells hold `Ship`s and
10
15
  //! a `List<View>`'s hold trait objects. So an upcast builds the list again: the check records
@@ -36,6 +41,72 @@ fn isCovariant(n: &str) -> bool {
36
41
  COVARIANT.contains(&n)
37
42
  }
38
43
 
44
+ /// A covariant struct (see the module doc): its variant, its generics, which of them are
45
+ /// covariant, and its fields' names and types (in terms of the generics).
46
+ #[derive(Debug, Clone)]
47
+ pub(crate) struct CovStruct {
48
+ variant: String,
49
+ generics: Vec<String>,
50
+ covariant: Vec<bool>,
51
+ field_names: Vec<String>,
52
+ field_types: Vec<PlumType>,
53
+ }
54
+
55
+ /// The program's generic structs with no `mut` field that are covariant in at least one of
56
+ /// their generics: each such generic is held by the fields only as itself or inside a `List`
57
+ /// or an `Option`.
58
+ pub(crate) fn covariantStructs(source: &ast::Source, variants: &EnumVariants) -> HashMap<String, CovStruct> {
59
+ // Whether the generic `g` occurs in `t` only where a value of a narrower type can stand.
60
+ fn onlyCovariant(t: &PlumType, g: &str) -> bool {
61
+ match t {
62
+ PlumType::TApp(n, args) if isCovariant(n) => args.iter().all(|a| onlyCovariant(a, g)),
63
+ PlumType::TApp(_, args) => !args.iter().any(|a| mentions(a, g)),
64
+ PlumType::TFun(ps, r) => !ps.iter().any(|p| mentions(p, g)) && !mentions(r, g),
65
+ _ => true,
66
+ }
67
+ }
68
+ fn mentions(t: &PlumType, g: &str) -> bool {
69
+ match t {
70
+ PlumType::TParam(n) => n == g,
71
+ PlumType::TApp(_, args) => args.iter().any(|a| mentions(a, g)),
72
+ PlumType::TFun(ps, r) => ps.iter().any(|p| mentions(p, g)) || mentions(r, g),
73
+ _ => false,
74
+ }
75
+ }
76
+ let mut out = HashMap::new();
77
+ for item in &source.items {
78
+ let ast::Item::Enum(e) = item else { continue };
79
+ if !e.isStruct() || e.variants.len() != 1 || isCovariant(&e.name) {
80
+ continue;
81
+ }
82
+ let v = &e.variants[0];
83
+ let Some(info) = variants.get(&v.name) else { continue };
84
+ if info.generics.is_empty() || info.mut_fields.iter().any(|m| *m) || info.field_names.len() != info.field_types.len() {
85
+ continue;
86
+ }
87
+ let covariant: Vec<bool> = info.generics.iter().map(|g| info.field_types.iter().all(|t| onlyCovariant(t, g))).collect();
88
+ if !covariant.iter().any(|c| *c) {
89
+ continue;
90
+ }
91
+ out.insert(
92
+ e.name.clone(),
93
+ CovStruct {
94
+ variant: v.name.clone(),
95
+ generics: info.generics.clone(),
96
+ covariant,
97
+ field_names: info.field_names.clone(),
98
+ field_types: info.field_types.clone(),
99
+ },
100
+ );
101
+ }
102
+ out
103
+ }
104
+
105
+ /// The covariant struct `n`, if it is one.
106
+ fn covStruct(n: &str) -> Option<CovStruct> {
107
+ withCheck(|s| s.covariant.borrow().get(n).cloned())
108
+ }
109
+
39
110
  /// No open variable and no generic parameter: an upcast is made for concrete types only (a
40
111
  /// generic body's erased pass keeps the old rule).
41
112
  fn closed(t: &PlumType) -> bool {
@@ -47,15 +118,19 @@ fn closed(t: &PlumType) -> bool {
47
118
  /// at least one argument differs.
48
119
  pub(crate) fn upcastable(to: &PlumType, from: &PlumType) -> bool {
49
120
  let (PlumType::TApp(a, xs), PlumType::TApp(b, ys)) = (to, from) else { return false };
50
- if a != b || !isCovariant(a) || xs.len() != ys.len() {
121
+ if a != b || xs.len() != ys.len() {
122
+ return false;
123
+ }
124
+ let st = if isCovariant(a) { None } else { covStruct(a) };
125
+ if !isCovariant(a) && st.is_none() {
51
126
  return false;
52
127
  }
53
128
  let mut differs = false;
54
- for (x, y) in xs.iter().zip(ys) {
129
+ for (i, (x, y)) in xs.iter().zip(ys).enumerate() {
55
130
  if x == y {
56
131
  continue;
57
132
  }
58
- if !elemUpcast(x, y) {
133
+ if st.as_ref().is_some_and(|c| !c.covariant.get(i).copied().unwrap_or(false)) || !elemUpcast(x, y) {
59
134
  return false;
60
135
  }
61
136
  differs = true;
@@ -357,6 +432,9 @@ impl Helpers<'_> {
357
432
  let (PlumType::TApp(kind, tos), PlumType::TApp(_, froms)) = (to, from) else {
358
433
  unreachable!("an upcast is between two instances of one container")
359
434
  };
435
+ if let Some(st) = covStruct(kind).filter(|_| !isCovariant(kind)) {
436
+ return self.structHelper(name, &st, to, from, tos, froms);
437
+ }
360
438
  // Each argument as the value of the other: itself, or the nested helper's call.
361
439
  let elem = |me: &mut Self, v: &str| -> ast::Expr {
362
440
  let (t, f) = (&tos[0], &froms[0]);
@@ -408,6 +486,47 @@ impl Helpers<'_> {
408
486
  name
409
487
  }
410
488
 
489
+ /// The helper of a covariant struct: the struct built again, each field the value of the
490
+ /// other (itself, or the nested helper's call).
491
+ fn structHelper(&mut self, name: String, st: &CovStruct, to: &PlumType, from: &PlumType, tos: &[PlumType], froms: &[PlumType]) -> String {
492
+ let toSubst: BTreeMap<String, PlumType> = st.generics.iter().cloned().zip(tos.iter().cloned()).collect();
493
+ let fromSubst: BTreeMap<String, PlumType> = st.generics.iter().cloned().zip(froms.iter().cloned()).collect();
494
+ let binders: Vec<String> = (0..st.field_names.len()).map(|i| format!("__f{i}")).collect();
495
+ let mut values = Vec::new();
496
+ for (i, ft) in st.field_types.iter().enumerate() {
497
+ let (t, f) = (types::substitute(ft, &toSubst), types::substitute(ft, &fromSubst));
498
+ let x = ast::Expr::Var(binders[i].clone());
499
+ values.push(if t != f && upcastable(&t, &f) { call(&self.helper(&t, &f), x) } else { x });
500
+ }
501
+ let variant = (st.variant.clone(), st.field_names.clone());
502
+ let cases = vec![case(&st.variant, binders.iter().map(|b| b.as_str()).collect(), build(&variant, values))];
503
+ let x = ast::Expr::Var("__xs".to_string());
504
+ let body = ast::Block { stmts: vec![ast::Stmt::Match(ast::Match { subjects: vec![x], cases })] };
505
+ let mut generics = Vec::new();
506
+ self.items.push(ast::Item::Fn(ast::Fn {
507
+ name: name.clone(),
508
+ file: self.source.file.clone(),
509
+ line: 0,
510
+ column: 0,
511
+ type_param: None,
512
+ generics: vec![],
513
+ bounds: vec![],
514
+ is_extern: false,
515
+ is_export: false,
516
+ is_test: false,
517
+ is_fip: false,
518
+ has_self: false,
519
+ params: vec![ast::Param {
520
+ name: "__xs".to_string(),
521
+ ty: ast::ParamType::Type(astTypeOf(from, &mut generics).expect("an upcast's types are closed")),
522
+ default: None,
523
+ }],
524
+ returns: Some(astTypeOf(to, &mut generics).expect("an upcast's types are closed")),
525
+ body: ast::FnBody::Block(body),
526
+ }));
527
+ name
528
+ }
529
+
411
530
  /// The helper that puts the cells of a `from` list, each made a `to`'s, in front of a `to`
412
531
  /// list (a spread of an upcast list; see the module doc), made if new.
413
532
  fn onto(&mut self, to: &PlumType, from: &PlumType) -> String {
compiler/checker/tests/checker/traits_tests.rs CHANGED
@@ -714,6 +714,33 @@ primitive Main =
714
714
  );
715
715
  }
716
716
 
717
+ #[test]
718
+ fn immutableStructsAreCovariant() {
719
+ // a generic struct with no `mut` field is covariant in each generic its fields hold as
720
+ // themselves or in a `List` or an `Option`: rebuilt field by field, a nested pair by its
721
+ // own helper
722
+ let info = ok(&format!(
723
+ "{ACTOR}struct Held<S, A>(state: S, more: List<S>, tag: A)
724
+
725
+ primitive Main =
726
+ fun f(h: Held<Orb, Int>) -> Held<Actor, Int> = h
727
+
728
+ fun made(o: Orb) -> Held<Orb, Int> = Held(state: o, more: [o], tag: 1)
729
+
730
+ fun g(o: Orb) -> Held<Actor, Int> = Main.made(o)
731
+ "
732
+ ));
733
+ assert_eq!(upcastsOf(&info), vec!["Held<Orb, Int> -> Held<Actor, Int>", "List<Orb> -> List<Actor>"]);
734
+ // a generic held inside a function type or another struct is not covariant, nor is a
735
+ // struct with a `mut` field
736
+ for decl in ["struct Held<S>(state: S, f: fn(S) -> Int)", "struct Cell<T>(mut v: T)\nstruct Held<S>(state: S, c: Cell<S>)", "struct Held<S>(mut state: S)"] {
737
+ fails(
738
+ &format!("{ACTOR}{decl}\n\nprimitive Main =\n fun f(h: Held<Orb>) -> Held<Actor> = h\n"),
739
+ "type mismatch",
740
+ );
741
+ }
742
+ }
743
+
717
744
  #[test]
718
745
  fn joinsWithNoExpectedType() {
719
746
  // a literal of several implementers is a list of their trait, and so are branches of two;
compiler/cli/tests/cli/game_entry_test.rs CHANGED
@@ -129,9 +129,9 @@ fn screensGame(names: &[&str], to: &str) -> String {
129
129
  let made: Vec<String> = names.iter().enumerate().map(|(i, n)| format!(" s{i}: Screen := Named(n: \"{n}\")\n")).collect();
130
130
  format!(
131
131
  "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Input\nimport std/App\n\
132
- import std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
132
+ import std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
133
133
  struct Named[ScreenSlice<Int>](n: Str) =\n fun name(self) -> Str = self.n\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n \
134
- fun reduce(self, a: Int) -> Named = self\n fun effect(self, io: Io, a: Int, game: Control) = game.goTo(\"{to}\")\n\nprimitive Main[App] =\n \
134
+ fun act(self, a: Int) -> Next<Named, Int> = Next(state: self, cmds: [GoTo(name: \"{to}\")])\n\nprimitive Main[App] =\n \
135
135
  fun main(io: Io) =\n{} g := Game(screens: [{}])\n g1 := g.step(io, Input.create(), 0.1, Vec2(x: 800.0, y: 600.0))\n io.printLn(\"showing {{g1.showing()}}\")\n",
136
136
  made.join(""),
137
137
  screens.join(", ")
compiler/cli/tests/cli/game_in_place_test.rs CHANGED
@@ -2,6 +2,12 @@
2
2
  //! in Orbit Runner and Balloon Pop when their screens became views (branch sl/view) is still
3
3
  //! proved. A change that makes the game, a screen or the tick's values shared (another
4
4
  //! reference kept across a tick) turns one of them into a copy and fails here, naming it.
5
+ //!
6
+ //! Orbit Runner's `reduce$unique` (3) and `newMine$unique` (1) are no longer here: they were
7
+ //! the reductions its rules dispatched from inside its own `reduce` (`self.dispatch(Hit)`).
8
+ //! Since a slice's `act` returns its follow-ups (`then`), std's fold steps them
9
+ //! (`Delivery.actIn<A, S>`), and the uniqueness pass makes no unique version of a generic
10
+ //! instantiation, so they copy; the delivery's own trail is updated in place.
5
11
 
6
12
  use std::collections::BTreeMap;
7
13
  use std::process::Command;
@@ -46,16 +52,16 @@ const TICK: &[(&str, usize)] = &[
46
52
  ("Game.run", 1),
47
53
  ("Game.obey", 2),
48
54
  ("Viewport.update", 2),
55
+ ("Delivery.actIn", 1),
49
56
  ];
50
57
 
51
58
  #[test]
52
59
  fn orbitRunnerKeepsItsInPlaceSpreads() {
53
60
  let mut want = TICK.to_vec();
54
61
  want.extend([
55
- ("PlayingScreen.reduce$unique", 3),
56
62
  ("PlayingScreen.deal", 1),
57
63
  ("PlayingScreen.newOrb", 1),
58
- ("PlayingScreen.newMine$unique", 1),
64
+ ("PlayingScreen.newMine", 1),
59
65
  ("Mine.step", 1),
60
66
  ("Mine.put", 1),
61
67
  ("Orb.put$unique", 1),
compiler/game/tests/fixtures/camera_fixture.plum CHANGED
@@ -12,7 +12,7 @@ import std/game/Input
12
12
  import std/game/View
13
13
  import std/game/Box
14
14
  import std/game/Viewport
15
- import std/game/Control
15
+ import std/game/Cmd
16
16
  import std/game/Screen
17
17
  import std/game/ScreenSlice
18
18
  import std/game/Game
@@ -49,9 +49,9 @@ struct CamScreen[ScreenSlice<CamAct>](scaling: Scaling) =
49
49
  Use(s) => CamScreen(scaling: s)
50
50
  Go => self
51
51
 
52
- fun effect(self, io: Io, a: CamAct, game: Control) = match a
52
+ fun act(self, a: CamAct) -> Next<CamScreen, CamAct> = match a
53
- Go => game.goTo("two")
53
+ Go => Next(state: self, cmds: [GoTo(name: "two")])
54
- _ => Unit
54
+ _ => Next(state: self.reduce(a))
55
55
 
56
56
  # A culled 400 by 300 world, fitted: a green box at (10, 100) and a white one at (300, 100).
57
57
  struct TwoScreen[Screen](n: Int) =
compiler/game/tests/host_test.rs CHANGED
@@ -151,7 +151,7 @@ fn unknownImportTraps() {
151
151
  let path = dir.join("m.plum");
152
152
  std::fs::write(
153
153
  &path,
154
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
154
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
155
155
  )
156
156
  .unwrap();
157
157
  let wasm = compile(&path);
@@ -364,7 +364,7 @@ fn randomSeedProvidedByHost() {
364
364
  let path = dir.join("m.plum");
365
365
  std::fs::write(
366
366
  &path,
367
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
367
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
368
368
  )
369
369
  .unwrap();
370
370
  let wasm = compile(&path);
@@ -388,7 +388,7 @@ fn seedGame(name: &str) -> Vec<u8> {
388
388
  let path = dir.join("m.plum");
389
389
  std::fs::write(
390
390
  &path,
391
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float) =\n fun name(self) -> Str = \"page\"\n fun hud(self, window: Vec2) -> List<View> = [StateDrawing(s: self, w: window.x)]\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `Gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
391
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float) =\n fun name(self) -> Str = \"page\"\n fun hud(self, window: Vec2) -> List<View> = [StateDrawing(s: self, w: window.x)]\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `Gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
392
392
  )
393
393
  .unwrap();
394
394
  let wasm = compile(&path);
@@ -454,8 +454,8 @@ fn derivedHalvesMatchTheBrowsers() {
454
454
  assert_eq!(derived_half(1, 2, 1000000), 1266057807);
455
455
  }
456
456
 
457
- /// A game that takes a seed twice in `main` and once more in each tick (in the effects of the
457
+ /// A game that takes a seed twice in `main` and works its ticks from both replays them all (a
458
- /// tick's action, `effect`) replays all of them.
458
+ /// tick takes nothing from `io` but its sounds, std/game/Cmd).
459
459
  #[test]
460
460
  fn everySeedOfARecordedRunReplays() {
461
461
  let dir = std::env::temp_dir().join(format!("plum_game_replayseeds_{}", std::process::id()));
@@ -463,7 +463,7 @@ fn everySeedOfARecordedRunReplays() {
463
463
  let path = dir.join("m.plum");
464
464
  std::fs::write(
465
465
  &path,
466
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct Seeds(mut c: Int)\nstruct State[ScreenSlice<Int>](a: Int, b: Int, seeds: Seeds) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = self\n fun effect(self, io: Io, n: Int, game: Control) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"{self.s.a} {self.s.b} {self.s.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n only: Screen := State(a: a, b: io.randomSeed(), seeds: seeds)\n Game(screens: [only])\n",
466
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](a: Int, b: Int, c: Int) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = State(..self, c: self.c * 31 + self.a ^ self.b)\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"{self.s.a} {self.s.b} {self.s.c}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n a := io.randomSeed()\n only: Screen := State(a: a, b: io.randomSeed(), c: 0)\n Game(screens: [only])\n",
467
467
  )
468
468
  .unwrap();
469
469
  let wasm = compile(&path);
@@ -800,7 +800,7 @@ fn countingGame(name: &str, frames: &str) -> Vec<u8> {
800
800
  std::fs::write(
801
801
  &path,
802
802
  format!(
803
- "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Color\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Label\nimport std/App\nenum Count = Bump | Tock\nstruct Counting[ScreenSlice<Count>](ticks: Int, bumps: Int) =\n fun name(self) -> Str = \"main\"\n fun frames(self) -> Frames = {frames}\n fun hud(self, window: Vec2) -> List<View> = [Label(text: \"ticks {{self.ticks}} bumps {{self.bumps}} w {{window.x}}\", size: 8.0)]\n fun onKey(self, e: InputEvent) -> Option<Count> = match e\n KeyDown(k) => if k == Key.Space then Some(Bump) else None\n _ => None\n fun tick(self, dt: Float) -> Option<Count> = Some(Tock)\n fun reduce(self, a: Count) -> Counting = match a\n Bump => Counting(..self, bumps: self.bumps + 1)\n Tock => Counting(..self, ticks: self.ticks + 1)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := Counting(ticks: 0, bumps: 0)\n Game(screens: [only])\n"
803
+ "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Color\nimport std/game/Input\nimport std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Label\nimport std/App\nenum Count = Bump | Tock\nstruct Counting[ScreenSlice<Count>](ticks: Int, bumps: Int) =\n fun name(self) -> Str = \"main\"\n fun frames(self) -> Frames = {frames}\n fun hud(self, window: Vec2) -> List<View> = [Label(text: \"ticks {{self.ticks}} bumps {{self.bumps}} w {{window.x}}\", size: 8.0)]\n fun onKey(self, e: InputEvent) -> Option<Count> = match e\n KeyDown(k) => if k == Key.Space then Some(Bump) else None\n _ => None\n fun tick(self, dt: Float) -> Option<Count> = Some(Tock)\n fun reduce(self, a: Count) -> Counting = match a\n Bump => Counting(..self, bumps: self.bumps + 1)\n Tock => Counting(..self, ticks: self.ticks + 1)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := Counting(ticks: 0, bumps: 0)\n Game(screens: [only])\n"
804
804
  ),
805
805
  )
806
806
  .unwrap();
docs/backlog.md CHANGED
@@ -4,7 +4,7 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
4
4
 
5
5
  ## Screen views (branch `sl/view`, 2026-11-12)
6
6
 
7
- The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, `Control` for effects, undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks is master's (925878360). On 2026-11-13 it was brought up to master at e91c40ce (stages 24 and 25 and the review after 24): `View` and `Actor[View]`, actors stepped by the game through the screen's `stepped(dt)`, `Screen.hud`, `steps` and `camera`, one walk over `view`, turned boxes and text, the other mouse buttons and keys, the per-screen backgrounds and dropped pointer events of a transition (the "Beside master" table has what still differs). On 2026-11-13 (branch `sl/game-ports`) master's later framework work followed: the stepping of what a `Group` or an `Overlay` holds, frames on demand in the hosts (`frameIdle`), `plum run --dev` and its time travel keys, the window's size on the tick's input, the `Ticker`, a `Label`'s width from Arial's advance widths (in std and the browser's layout; master still estimates it) and `plum compile <folder>`. Open:
7
+ The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, commands as values for sounds and navigation (`std/game/Cmd`, returned by a slice's `act` beside its `then` actions, since 2026-11-16), undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks was master's (925878360) until its rules returned their follow-ups as `then` actions on 2026-11-16; it is 946756219 since. On 2026-11-13 it was brought up to master at e91c40ce (stages 24 and 25 and the review after 24): `View` and `Actor[View]`, actors stepped by the game through the screen's `stepped(dt)`, `Screen.hud`, `steps` and `camera`, one walk over `view`, turned boxes and text, the other mouse buttons and keys, the per-screen backgrounds and dropped pointer events of a transition (the "Beside master" table has what still differs). On 2026-11-13 (branch `sl/game-ports`) master's later framework work followed: the stepping of what a `Group` or an `Overlay` holds, frames on demand in the hosts (`frameIdle`), `plum run --dev` and its time travel keys, the window's size on the tick's input, the `Ticker`, a `Label`'s width from Arial's advance widths (in std and the browser's layout; master still estimates it) and `plum compile <folder>`. Open:
8
8
 
9
9
  - **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
10
10
  - **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
docs/game.md CHANGED
@@ -20,8 +20,8 @@ A game is a folder: the file with `main`, its `assets`, and the rest of its sour
20
20
  examples/games/orbitrunner/
21
21
  OrbitRunner.plum main, the Assets, and what several files share
22
22
  screens/PlayingScreen.plum one file per screen: the screen, its slice (its state in
23
- its fields, its actions, reducer, effects, input mapping
23
+ its fields, its actions, reducer and steps, input
24
- and view)
24
+ mapping and view)
25
25
  actors/Ship.plum one file per kind of actor (Orb.plum, Mine.plum, Star.plum,
26
26
  Ring.plum)
27
27
  assets/
@@ -70,9 +70,9 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
70
70
  Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
71
71
  Quit => self
72
72
 
73
- fun effect(self, io: Io, a: TapAction, game: Control) = match a
73
+ fun act(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
74
- Quit => game.exit()
74
+ Quit => Next(state: self, cmds: [Exit])
75
- _ => Unit
75
+ _ => Next(state: self.reduce(a))
76
76
 
77
77
  primitive Clicks[App] =
78
78
  fun main(io: Io) -> Game =
@@ -170,11 +170,10 @@ fun stepped(self, dt: Float) -> PlayingScreen =
170
170
  That is the only line a game writes for stepping, one per screen that holds actors; the default 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. An actor steps what it holds itself, in its own `step` (`Views.stepIn` doesn't look inside an actor, nor make its view); a `Group` or an `Overlay` is made again with its actors stepped; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. An actor the screen leaves out of `stepped` is not stepped, whether it is in the view or not, and one stepped there moves whether it is visible or not. So the tick action only runs the rules on what has moved:
171
171
 
172
172
  ```plum
173
- fun advance(self, dt: Float) -> PlayingScreen =
173
+ fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
174
174
  rings := if self.over then Views.stepAll(self.rings, dt) else self.rings
175
175
  moved := PlayingScreen(..self, clock: self.clock + dt, rings: rings.filter(|r| !r.done()))
176
- ruled := if self.over then moved else moved.rules()
176
+ if self.over then Next(state: moved) else moved.rules()
177
- if ruled.again then PlayingScreen(..ruled, again: false).dispatch(StartOver) else ruled
178
177
  ```
179
178
 
180
179
  Once Orbit Runner's run is over the screen steps nothing, so the mines and orbs stand still under the game over panel, while the stars, which read the screen's clock, keep twinkling, and the ship is left out of the view. What should move while the rest is held, the reducer still steps by hand: here the ripple of the last hit grows on under the panel.
@@ -212,7 +211,7 @@ The host adds up the time between frames and runs one tick (`Game.update`) for e
212
211
 
213
212
  The tick's `Input` is read from the host once per frame, before the ticks, with the window's size (`input.screen`, which the game takes its window from: `Game.update` is `step` with `input.screen`). A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. A slice gets it through its mapping (`onKey`, `held`, ..); don't read input any other way.
214
213
 
215
- Keep randomness in the screen: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, threaded through each draw (`r := self.rng.nextFloat()`, then keep `r.rng` in the next screen). Then the same seed and the same inputs give the same game, tick for tick. Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has the same checksum as master's imperative Orbit Runner (`benchmarks/screen_views/orbit.plum`).
214
+ Keep randomness in the screen: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, threaded through each draw (`r := self.rng.nextFloat()`, then keep `r.rng` in the next screen). Then the same seed and the same inputs give the same game, tick for tick. Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has one checksum, run after run (`benchmarks/screen_views/orbit.plum`; it was master's imperative Orbit Runner's until the rules returned their follow-ups as actions).
216
215
 
217
216
  The maths is the same everywhere too. std's maths (`Math.sin`, `Math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick gets is the window's size, on its input, and a replay records it.
218
217
 
@@ -256,15 +255,15 @@ primitive BalloonPop[App] =
256
255
 
257
256
  A move that can't be made (no history, a full one, a tick out of reach) leaves the game as it was with `moved` false. After a move the game plays on from there: the ticks undone stay as the future, for `redo`, until a user action cuts them.
258
257
 
259
- **What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length, whether it was a user action, and what its effects asked of the game. Not actions: an action may hold an actor (`onPress(target, ..)`), and the recorded input is mapped again into fresh actions against the state made again.
258
+ **What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length and whether it was a user action. Not actions: an action may hold an actor (`onPress(target, ..)`), and the recorded input is mapped again into fresh actions against the state made again.
260
259
 
261
- **What a rewind does with effects.** It runs none: no sound plays. What the effects of a tick asked of the screens (`goTo`) is done again at the same point; an `exit` is not, nor an undo, a redo or a rewind.
260
+ **What a rewind does with commands.** A tick played again gives the commands it gave the first time, as it is the same tick on the same state; of those the game does only the `GoTo`s again, at the same point. No sound plays, and no `Exit`, undo, redo or rewind is done again.
262
261
 
263
- **A user action** is a tick in which the shown slice screen's mapping gave an action for one of the tick's events (`onKey`, `onPointer`, `onPress`), or `held` gave an action while what is held (the keys and the mouse buttons) differs from that screen's tick before. The `tick` action is not one, nor an unchanged `held`, nor what a reducer dispatches. A tick whose effects asked for an undo, a redo or a rewind is not one either. `undo` lands just before the last user action; again, just before the one before.
262
+ **A user action** is a tick in which the shown slice screen's mapping gave an action for one of the tick's events (`onKey`, `onPointer`, `onPress`), or `held` gave an action while what is held (the keys and the mouse buttons) differs from that screen's tick before. The `tick` action is not one, nor an unchanged `held`, nor an action a step's `then` gives. A tick whose commands asked for an undo, a redo or a rewind is not one either. `undo` lands just before the last user action; again, just before the one before.
264
263
 
265
- **Offering undo in a game.** An effect asks through its `Control`: `game.undo()`, `game.redo()`, `game.rewindTo(tick)`, done once the tick is over. Balloon Pop maps Z and Backspace to `TakeBack`, whose effect is `game.undo()`: the last press is taken back, and the balloon it popped is whole again.
264
+ **Offering undo in a game.** A slice's `act` asks with a command: `Undo`, `Redo`, `RewindTo(tick: k)` (`std/game/Cmd`), done once the tick is recorded. Balloon Pop maps Z and Backspace to `TakeBack`, whose `act` is `Next(state: self, cmds: [Undo])`: the last press is taken back, and the balloon it popped is whole again.
266
265
 
267
- **What it costs.** A rewind back costs the ticks it plays: `rewindTo(k)` plays `k` ticks from the start, with no drawing and no effects. A move forward plays only the ticks ahead. The history is a list of ticks; `timeTravel(cap)` bounds it (`History.Cap` is 30 minutes of ticks). Once full, the history lets its ticks go and every move is refused from then on; the game plays on.
266
+ **What it costs.** A rewind back costs the ticks it plays: `rewindTo(k)` plays `k` ticks from the start, with no drawing and no sound. A move forward plays only the ticks ahead. The history is a list of ticks; `timeTravel(cap)` bounds it (`History.Cap` is 30 minutes of ticks). Once full, the history lets its ticks go and every move is refused from then on; the game plays on.
268
267
 
269
268
  **The development keys.** `plum run --dev` serves the game for development: the game keeps its history from the first frame, whether or not it calls `timeTravel`, and the keyboard moves through it:
270
269
 
@@ -312,7 +311,7 @@ A missing file stops the game and names the file, so typos show up straight away
312
311
 
313
312
  A game with more than one screen (a title, a level select, the play) gives each its own `Screen`, with its own name, its own state and its own view. What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of the view of the screen it sits on, drawn while the state says so, as Orbit Runner's game over `Overlay`. The keys still go to the screen's mapping, so Enter can play again while the game over shows.
314
313
 
315
- The first screen of the list shows first. A screen never gets the game: it changes screen through its effects (below). A screen says how it comes in with `transition(self, from: Str) -> Transition`: `Cut` (the default), `Fade(secs: 0.5)` or `Slide(from: FromRight, secs: 0.4)`. While a transition runs, the game draws both screens, the one going out and then the one coming in, each on its own `background()`, moved and faded. Only the screen coming in gets ticks, and its pointer events are dropped until the transition is over (a press on a screen still sliding in lands nowhere); keys still come.
314
+ The first screen of the list shows first. A screen never gets the game: it changes screen with a command (below). A screen says how it comes in with `transition(self, from: Str) -> Transition`: `Cut` (the default), `Fade(secs: 0.5)` or `Slide(from: FromRight, secs: 0.4)`. While a transition runs, the game draws both screens, the one going out and then the one coming in, each on its own `background()`, moved and faded. Only the screen coming in gets ticks, and its pointer events are dropped until the transition is over (a press on a screen still sliding in lands nowhere); keys still come.
316
315
 
317
316
  A screen left and shown again is as it was left: its state is its fields, which the game keeps. A screen has no `update`, and no hooks for going to it, leaving it or a resize: a slice screen gets its ticks as actions, a plain `Screen` (no rules) gets none and draws what it was made with, its actors stepped, and starting a run over is the reducer's (Orbit Runner's `StartOver` deals the new run into the screen's fields). [`examples/games/two_screens.plum`](../examples/games/two_screens.plum) is a title that fades into a play.
318
317
 
@@ -324,10 +323,10 @@ Most screens change every tick, but a title, a menu or a level select only chang
324
323
  fun frames(self) -> Frames = OnDemand
325
324
  ```
326
325
 
327
- `Always`, the default, ticks the screen every tick. An `OnDemand` screen sleeps through every tick in which nothing needs doing: the game delivers it no tick (no action, no effect). Something needs doing, and the screen ticks, when any of these holds:
326
+ `Always`, the default, ticks the screen every tick. An `OnDemand` screen sleeps through every tick in which nothing needs doing: the game delivers it no tick (no action, no command). Something needs doing, and the screen ticks, when any of these holds:
328
327
 
329
328
  - the tick's input has an event: a key, a press, a pointer that moved (a move to where it already was doesn't count), or what is held maps to an action (its `held` gives one);
330
- - the tick before left the screen `busy()`, ran an effect that asked the game for something, or a transition is in progress;
329
+ - the tick before left the screen `busy()`, gave a command, or a transition is in progress;
331
330
  - the screen was just entered, or the screen's size changed.
332
331
 
333
332
  It then ticks as an `Always` screen until it goes quiet again. A tick it sleeps through is still a tick of the run: a recording keeps its input, and whether the screen sleeps is worked out from that input and the screen's state alone, so a replay sleeps through the same ticks. `Game.delivered` and `Game.skipped` count the ticks delivered and slept through. `Game.idle()` is true when the shown screen is `OnDemand`, no transition runs and no tick has run since the last frame drawn (`frameDrawn()`, which a test calls).
@@ -336,20 +335,19 @@ It then ticks as an `Always` screen until it goes quiet again. A tick it sleeps
336
335
 
337
336
  ## The slice
338
337
 
339
- A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux Toolkit: one slice per screen, its state, an enum `A` of its actions, a reducer and an effect handler. (Master calls the trait `Slice<A>`; here `Slice` is std's growable array, and a trait can't share a type's name.) `ScreenSlice<A>` extends `Screen`, so the screen is the slice: its own fields are the state, plain values and the actors it holds.
338
+ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux Toolkit: one slice per screen, its state, an enum `A` of its actions, and a reducer that may say what follows from an action. (Master calls the trait `Slice<A>`; here `Slice` is std's growable array, and a trait can't share a type's name.) `ScreenSlice<A>` extends `Screen`, so the screen is the slice: its own fields are the state, plain values and the actors it holds.
340
339
 
341
340
  | A `ScreenSlice<A>`'s method | Default | What it does |
342
341
  |---|---|---|
343
- | `reduce(self, a: A) -> Self` | required | applies `a`: the next version of the screen. An exhaustive `match`, with no `Io` |
344
- | `dispatch(self, a: A) -> Self` | std's | dispatches `a` from the slice's own reducer (below) |
345
- | `effect(self, io, a: A, game: Control)` | nothing | what `a` does after the tick (a sound, a change of screen); it only reads the slice |
342
+ | `reduce(self, a: A) -> Self` | the screen as it is | applies `a`: the next version of the screen. An exhaustive `match`, with no `Io` |
343
+ | `act(self, a: A) -> Next<Self, A>` | `Next(state: self.reduce(a))` | applies `a` and says what follows from it: `Next(state, then, cmds)`, the next screen, the actions that follow (`then`) and the commands for the game (`cmds`, below) |
346
344
  | `onKey(self, e) -> Option<A>` | None | the action for a key event |
347
345
  | `onPointer(self, e, at: Vec2) -> Option<A>` | None | the action for a pointer event, `at` its point in the world |
348
346
  | `onPress(self, target: View, at: Vec2) -> Option<A>` | None | the action for a press on an item that takes presses ([Clicks](#clicks)) |
349
347
  | `held(self, input) -> Option<A>` | None | the action for what is held, every tick |
350
348
  | `tick(self, dt) -> Option<A>` | None | the tick action |
351
349
 
352
- **Dispatch** reduces at once and queues (the queue of the dispatch running sits in one slot of `std/game/Effects`, set around a screen's delivery and the kit's `dispatch`). Each action std delivers is reduced as it is made, so the next mapping and the next action see what it did, and it is queued for its effect after the tick. A reducer dispatches more with `self.dispatch(a)`, which returns the slice after it (Orbit Runner's rules: `scored := if caught.points > 0 then collected.dispatch(Scored(points: caught.points)) else collected`): reduced at once, and queued before the action that dispatched it. Called outside a tick (a test calling `reduce` itself), `dispatch` only reduces. How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
350
+ **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)).
353
351
 
354
352
  ## Input and the tick as actions
355
353
 
@@ -360,9 +358,9 @@ Each tick, std delivers to the shown screen's slice, in this order:
360
358
  3. **The step**: the screen's `stepped(dt)`, unless `steps()` is false ([Views and actors](#views-and-actors)).
361
359
  4. **`tick(dt)`**: the tick action, which sees the actors moved and runs the rules.
362
360
 
363
- A mapping that gives None sends nothing. Then the transition in progress moves on, and the effects run.
361
+ A mapping that gives None sends nothing. Then the transition in progress moves on, and the game does the commands.
364
362
 
365
- The input comes before the tick, so a rule that must see the tick's motion first notes the action and acts on it in the tick: Orbit Runner's `PlayAgain` notes that the run is to start over (`again`), and its `Tick` dispatches `StartOver` once the actors have moved. Orbit Runner steers with `input.axis`: `Steer(ax: {input.axis(Key.Left, Key.Right) + input.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`.
363
+ Orbit Runner steers with `input.axis`: `Steer(ax: {input.axis(Key.Left, Key.Right) + input.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`.
366
364
 
367
365
  ## Clicks
368
366
 
@@ -378,21 +376,22 @@ fun onPress(self, target: View, at: Vec2) -> Option<PopAction> = match target
378
376
 
379
377
  and `Pop(b)` bursts the balloon of `self.balloons` with `b`'s id. A balloon that has burst says `Disabled`, so a press goes through it to one behind. An item made inside `view` (Orbit Runner's game over panel) can be hit, and so keeps a press from what is under it, but it is a new object each time: compare its kind (`Overlay as o`), not its identity.
380
378
 
381
- ## Effects that outlive a tick
379
+ ## What outlives a tick
382
380
 
383
381
  A flash, a ripple, a slide: something that runs for a while after what started it is plain state too. The reducer adds it, the step ages it, the tick action drops it once it is done; the view draws it at its age. Orbit Runner's ripple where the ship is hit is a `Ring`, an actor with its age: `Hit` appends one to `rings` where the ship is; the screen's `stepped` ages them; each `Tick` keeps those not done; the view appends them. A value that goes from one number to another over a while is a `Tween` (`std/game/Tween`, `Tween(from: 0.0, to: 1.0, secs: 0.5, ease: QuadOut)`, `Linear` unless given), which the screen advances on its tick action and reads in its view.
384
382
 
385
- ## Effects and navigation
383
+ ## Commands: sound and navigation
386
384
 
387
- After the tick, the game runs `effect(io, a, game)` for every action dispatched in it, in the order dispatched, each with the slice as the tick left it, and right after each effect what it asked of `game`, a `Control` (`std/game/Control`):
385
+ What a slice's `act` asks of the game is data, an `enum Cmd` (`std/game/Cmd`) in its `Next`'s `cmds`. After the tick (and the transition's step) the game does every command the tick's actions gave, in the order given, with the `Io` the tick has:
388
386
 
389
- | `Control` | What the game does |
387
+ | `Cmd` | What the game does |
390
388
  |---|---|
391
- | `game.goTo("over")` | shows the screen of that name from the next tick on, as it was left, coming in by its `transition(from)`. A name no screen has stops the program and lists the screens. |
389
+ | `GoTo(name: "over")` | shows the screen of that name from the next tick on, as it was left, coming in by its `transition(from)`. A name no screen has stops the program and lists the screens. |
392
- | `game.exit()` | no tick runs after this one. |
390
+ | `Exit` | no tick runs after this one. |
393
- | `game.undo()`, `game.redo()`, `game.rewindTo(tick)` | once the tick is over, a move through the game's history ([Undo and time travel](#undo-and-time-travel)); nothing if the game keeps none |
391
+ | `Undo`, `Redo`, `RewindTo(tick: k)` | once the tick is recorded, a move through the game's history ([Undo and time travel](#undo-and-time-travel)); nothing if the game keeps none |
392
+ | `Play(sound: s, volume: v)`, `Loop(sound: s, volume: v)`, `Stop(sound: s)` | plays the sound once, starts it looping, or stops it (`Sound.Silent`, a test's, calls no host) |
394
393
 
395
- An effect returns nothing; a `Control` is the one thing a tick writes in place. Navigation is the game's own actions: std has none. Orbit Runner's effects play the sounds, and `StartOver`'s starts the music again (its reducer has dealt the new run already).
394
+ A tick reads nothing from `io` and writes to it only through these, so a rewind plays the tick again with no sound by construction (it does only the `GoTo`s again), and a test reads the commands as values (`t.cmds`, `Cmd.names(t.cmds) == "goTo(play) exit"`). Navigation is the game's own actions: std has none. Orbit Runner's `act` reduces first and then says what follows from the screen the action left (`_ => self.reduce(a).followed(a)`): `Hit` plays the hit, or stops the music for the game over sound once the run is over (`Hit => Next(state: self, cmds: if self.over then [Stop(sound: self.assets.music), Play(sound: self.assets.over, volume: 1.0)] else [Play(..)])`), and `StartOver` starts the music again; Balloon Pop's `Popped` plays a pop, and the fanfare on every tenth, in the tick of the press.
396
395
 
397
396
  ## Assets
398
397
 
@@ -404,11 +403,11 @@ While `plum run` serves a game, it watches your code and assets, the game's own
404
403
 
405
404
  ## Testing a game
406
405
 
407
- Put your rules in code that takes no `Io`, test them from a `primitive XTest[UnitTest]` in the `tests/` mirror ([Tests](language.md#tests)), and `plum test` runs them with no browser. An actor's own methods are tested by calling them (`ship.step(0.1)`); a reducer the same way (`s.reduce(a)`); a screen, or a whole game, with the kit below. To check a game actually renders, the browser test tool runs it in headless Chromium. See [its README](../compiler/game/web-test/README.md).
406
+ Put your rules in code that takes no `Io`, test them from a `primitive XTest[UnitTest]` in the `tests/` mirror ([Tests](language.md#tests)), and `plum test` runs them with no browser. An actor's own methods are tested by calling them (`ship.step(0.1)`); a reducer the same way (`s.reduce(a)`, `s.act(a).cmds`); a screen, or a whole game, with the kit below. To check a game actually renders, the browser test tool runs it in headless Chromium. See [its README](../compiler/game/web-test/README.md).
408
407
 
409
408
  ### Testing a screen
410
409
 
411
- `std/game/TestRig` runs a screen, or a whole game, with no host: the test sends input, runs ticks through the game's own tick, and reads back the screen, what its view draws and what its effects did. A rig is a value, like the game in it: each input and tick returns the next rig.
410
+ `std/game/TestRig` runs a screen, or a whole game, with no host: the test sends input, runs ticks through the game's own tick, and reads back the screen, what its view draws, the actions stepped and the commands they gave. A rig is a value, like the game in it: each input and tick returns the next rig.
412
411
 
413
412
  ```plum
414
413
  # tests/examples/games/orbitrunner/screens/PlayingScreen.plum
@@ -426,10 +425,10 @@ primitive PlayingScreenTest[UnitTest] =
426
425
  | | |
427
426
  |---|---|
428
427
  | Input, for the next tick | `press(key)` (down and up within the tick: one key down for the mapping, not held after), `hold(key)`, `release(key)`, `click(actor)` (a press and release at the actor's centre, its bounds' if it is `Sized`, in screen pixels through the camera, or one unit a pixel for an item of the hud, so it goes through the real hit test: a panel in front gets it), `clickAt(x, y)`, `pointerMove(x, y)`, `send(e)`, `next(held, events)` |
429
- | Time | `tick()` (the game's own tick: mapping, the step, reducer, transition, effects and what they ask), `ticks(n)` (`n` ticks, the input going to the first), `tick(dt)` for a tick of another length, `frame(input, frameDt)` for the host's frame with the `Ticker` turning wall time into ticks |
430
- | An action | `dispatch(a)`: reduced into the screen as its reducer would dispatch it, then what ends a tick: its effects with what they ask, an undo, a redo or a rewind done at once |
428
+ | Time | `tick()` (the game's own tick: mapping, the actors' step, the slice's steps, transition and commands), `ticks(n)` (`n` ticks, the input going to the first), `tick(dt)` for a tick of another length, `frame(input, frameDt)` for the host's frame with the `Ticker` turning wall time into ticks |
429
+ | An action | `dispatch(a)`: stepped into the rig's screen as a delivery steps it (with its `then`), then what ends a tick: its commands, an undo, a redo or a rewind done at once |
431
430
  | Reading, the view's then the hud's | `find<T>()` (the items of type `T` the view and the hud draw, in the order drawn, an item before what is under it), `first<T>()` (none stops the test: "headless: first: no actor of the type asked for is in the view"), `count<T>()`, `text(label)`, `shown(actor)` (the view or the hud draws it), `hit(x, y)` (what a press at that screen pixel lands on, the hud first), `worldOf(actor)` (its transform), `toWorld(x, y)` (a screen pixel in the world, through the camera), `drawn()` (what the frame draws, `Game.drawList()`) |
432
- | What came out of the last `tick` or `ticks` | `effects<A>()` (the actions of type `A` whose effects ran, in order), `wentTo()` (an `Option`), `exited()`; `showing()` names the screen shown |
431
+ | What came out of the last `tick` or `ticks` | `actions<A>()` (the actions of type `A` stepped, in order), `cmds` (the commands, in order), `wentTo()` (the last `GoTo`'s name, an `Option`), `exited()`; `showing()` names the screen shown |
433
432
  | A whole run | `record(seed)`, `recorded()`, `replay(r)`, and `game` (its counters) |
434
433
  | Time travel | `TestRig.mountWith(io, screen)` and `TestRig.playWith(io, game)` keep the history; then `rewindTo(k)`, `undo()`, `redo()`, `stepBack()`, `stepForward()`, `pause()`, `resume()`, with `moved()`, and `t.screen` is the one made again |
435
434
 
@@ -438,32 +437,33 @@ Orbit Runner's game over test:
438
437
  ```plum
439
438
  # tests/examples/games/orbitrunner/screens/PlayingScreen.plum
440
439
  primitive PlayingScreenTest[UnitTest] =
441
- # while the game over panel shows, Enter or R plays again: the run starts over after the tick
440
+ # while the game over panel shows, Enter or R plays again: StartOver follows it at once and starts the music again
442
441
  fun whileTheGameOverPanelShowsEnterOr() =
443
- t := playingscreen.lastLife(io).press(Key.Enter).tick()
442
+ t := PlayingScreenHelpers.lastLife(io).press(Key.Enter).tick()
444
- assert playingscreen.names(playingscreen.ruledLast(t)) == "PlayAgain Hit"
443
+ assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "PlayAgain Hit"
445
444
  u := t.press(Key.Space).tick()
446
445
  assert u.screen.over
447
446
  v := u.press(Key.Enter).tick()
448
- assert playingscreen.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({Ticker.Tick})"
447
+ assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "PlayAgain StartOver Steer(0.0, 0.0) Tick({Ticker.Tick})"
448
+ assert Cmd.names(v.cmds) == "stop(-1) loop(-1, 0.3)"
449
449
  assert !v.screen.over
450
450
  ```
451
451
 
452
- `std/game/TestRig` is tested by [`tests/port/game/screens.plum`](../tests/port/game/screens.plum) (presses through turned groups and overlays, dispatch order, navigation, transitions and the presses they drop, frames on demand, record and replay, undo and rewind, the stepping and `steps()`, the hud, a camera that follows). `compiler/game/tests/host_test.rs` checks what the native host draws: each scaling's placing and culling, a slide's offsets and backgrounds on both screens, a turned box and label and the hud.
452
+ `std/game/TestRig` is tested by [`tests/port/game/screens.plum`](../tests/port/game/screens.plum) (presses through turned groups and overlays, the order of an `act`'s `then`, commands, navigation, transitions and the presses they drop, frames on demand, record and replay, undo and rewind, the stepping and `steps()`, the hud, a camera that follows). `compiler/game/tests/host_test.rs` checks what the native host draws: each scaling's placing and culling, a slide's offsets and backgrounds on both screens, a turned box and label and the hud.
453
453
 
454
454
  ## Beside master
455
455
 
456
- The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its `hud`, `steps` and `camera`, a slice per screen, `Game(screens: ..)`, `Control`, the walks over a view, the kit), in the functional dialect. Where the signatures or the behaviour differ:
456
+ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its `hud`, `steps` and `camera`, a slice per screen, `Game(screens: ..)`, the walks over a view, the kit), in the functional dialect. Where the signatures or the behaviour differ:
457
457
 
458
458
  | Master | Here | Why |
459
459
  |---|---|---|
460
460
  | `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 |
461
461
  | 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 (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. `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 |
462
462
  | `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 |
463
- | `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` | `fun reduce(self, a: A) -> Self`, `fun dispatch(self, a: A) -> Self` | the reducer returns the next screen |
463
+ | `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 |
464
464
  | `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
465
- | `deliver(&self, d: Delivery)`, the delivery noting `acted` | `deliver(self, d: Delivery) -> Delivered` (the next screen, the tick's effects, whether it was a user action) | the delivery returns what it made |
466
- | `Effects`, one queue of `Queued<A>` holding each action with its slice, set in one slot around a delivery | one slot too (`Effects.startDispatch`), holding the delivery's queue of its own action type; after the tick each action is held with the slice as the tick left it (`Queued<A>`), and `Effects.sent<A>(list)` reads them | an effect must see the slice the tick left, which is a new value, not the one the action was reduced into |
465
+ | `deliver(&self, d: Delivery)`, the delivery noting `acted` | `deliver(self, d: Delivery) -> Delivered` (the next screen, the tick's commands, the actions stepped, whether it was a user action), a fold with no queue | the delivery returns what it made |
466
+ | `Effects`, one queue of `Queued<A>` holding each action with its slice, set in one slot around a delivery, and `effect(a, game)` run for each after the tick | no `Effects` and no slot: a step returns its commands (`Next.cmds`), and the game does them after the tick | nothing in a tick is written in place or kept in a global, and a rewind skips the sounds by construction |
467
467
  | `Viewport` updated in place (`v.update(w, h)`), `lookAt(x, y, zoom = 1.0)` | `Viewport.of(..).update(w, h) -> Viewport`, the same `lookAt` and `moved` | a value |
468
468
  | the frame sets the host's camera (`setCamera`) for a camera with one scale, and puts a `Stretch` camera into the transform | every camera goes into the transform the view is drawn through, in window pixels, and culling maps its area through it | this branch's draw has always gone through the transform; the host sees no `setCamera`/`resetCamera` in a frame, so the recorder's calls differ (`compiler/game/tests/host_test.rs` checks the pixels) |
469
469
  | the window's size on each tick's input (`input.screen`, `Input.sized`) | the same; `Game.step(io, input, dt, pixels)` takes it from a test, and an input of 0 by 0 leaves the window as it was | |
@@ -473,7 +473,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
473
473
  | 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 |
474
474
  | `Tween` advanced in place | `tween.advance(dt) -> Tween` | a value |
475
475
  | `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
476
- | `Control`: methods on `&self` | methods that push onto its `asked` slice | an effect returns nothing; this is the one thing a tick writes in place |
476
+ | `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 |
477
477
  | `timeTravel(make: fn(Io) -> Game, cap)` | `timeTravel(cap) -> Game` | the game keeps the screens it was made with |
478
478
  | `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
479
479
  | the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
@@ -481,7 +481,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
481
481
  | 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) |
482
482
  | `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
483
483
 
484
- 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`), `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`; 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), `plum compile <folder>`, and Orbit Runner's state checksum (925878360).
484
+ 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.
485
485
 
486
486
  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.
487
487
 
docs/language.md CHANGED
@@ -833,7 +833,7 @@ Each use is checked to meet the bound. Generics are compiled per type, so a call
833
833
 
834
834
  A value of an implementing type becomes a trait object, with no cast, where one is expected: an argument, an annotated local, a field, a list element, a returned value.
835
835
 
836
- `List` and `Option` are covariant: a `List<Rect>` is a `List<Shape>` wherever one is expected, and an `Option<Rect>` an `Option<Shape>`, nested too (`List<List<Rect>>`). Each instance is stored as its own type, so the value is rebuilt there: a loop over the list, the work `rects.map(|r| r)` does. A list that is already a `List<Shape>` costs nothing. Nothing else is covariant: a `Slice` or an `Array` is written in place (a `Slice<Rect>` taken as a `Slice<Shape>` could be given a `Circle`), a `fn(List<Rect>) -> Int` is not a `fn(List<Shape>) -> Int`, and a generic body's `List<T>` is not a `List<Shape>`, since its one code serves every `T`.
836
+ `List` and `Option` are covariant: a `List<Rect>` is a `List<Shape>` wherever one is expected, and an `Option<Rect>` an `Option<Shape>`, nested too (`List<List<Rect>>`). Each instance is stored as its own type, so the value is rebuilt there: a loop over the list, the work `rects.map(|r| r)` does. A list that is already a `List<Shape>` costs nothing. A generic struct with no `mut` field is covariant too, in each generic its fields hold only as themselves or in a `List` or an `Option`: with `struct Next<S, A>(state: S, then: List<A>)`, a `Next<Rect, A>` is a `Next<Shape, A>`, built again field by field (a generic held in a function type, a `Slice` or another struct keeps it invariant). Nothing else is covariant: a `Slice` or an `Array` is written in place (a `Slice<Rect>` taken as a `Slice<Shape>` could be given a `Circle`), a `fn(List<Rect>) -> Int` is not a `fn(List<Shape>) -> Int`, and a generic body's `List<T>` is not a `List<Shape>`, since its one code serves every `T`.
837
837
 
838
838
  So a value needs no annotation where its type is known:
839
839
 
docs/plans/2026-11-13-std-game-review.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # std/game review (simpler-language @ 257d46e6), 2026-11-13
2
2
 
3
- User: "one general review on the std/game and how it can be improved, made more declarative and functional please". Read-only review by a fresh agent; items in priority order. Not yet chosen for building.
3
+ User: "one general review on the std/game and how it can be improved, made more declarative and functional please". Read-only review by a fresh agent; items in priority order. Not yet chosen for building. Items 1 and 2 built on 2026-11-16 (branch `sl/next-cmd`: `Next`, `act` (not `step`, which an `Actor` has), the delivery as a fold, `enum Cmd`; no escape hatch, as nothing needed one).
4
4
 
5
5
  1. Reducers return their follow-ups: `Next<S, A>(state, then: List<A>, cmds: List<Cmd>)`, `step(a) -> Next` defaulting to `reduce`; `deliverTo` a pure fold; removes the global `Effects.Running` slot (Effects.plum:43) and the mutable `q`/`acted` Slices (ScreenSlice.plum:114-160); TestRig.dispatch reuses the fold. M, std.
6
6
  2. Effects as data, `Control` removed: `enum Cmd = GoTo | Exit | Undo | Redo | RewindTo | Play | Loop | Stop` (+ `Run(fn(Io))` escape hatch); the game interprets them; rewinds skip sounds by construction; Balloon Pop loses its six "heard" fields (~25 lines); `Effects.sent`/`Queued`/`Sink`/`ActionSink` go. M, std.
docs/std.md CHANGED
@@ -270,7 +270,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
270
270
 
271
271
  ## Game screens and slices
272
272
 
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)`), 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 `effect(self, io, a, game)` what an action does after the tick (a sound, `game.goTo("play")`). std maps each tick's input to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
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)`), 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 to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
274
274
 
275
275
  ```plum
276
276
  import std/Int
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -18,7 +18,8 @@ import std/game/Box
18
18
  import std/game/Circle
19
19
  import std/game/Group
20
20
  import std/game/Label
21
- import std/game/Control
21
+ import std/game/Audio
22
+ import std/game/Cmd
22
23
  import std/game/Screen
23
24
  import std/game/ScreenSlice
24
25
  import std/game/Game
@@ -38,17 +39,14 @@ enum PopAction =
38
39
  Tick(dt) => "Tick({dt})"
39
40
 
40
41
  struct PlaygroundScreen[ScreenSlice<PopAction>](
41
- rng: Random, assets: Assets, pops: Int, partyAt: Float, popsHeard: Int, partiesHeard: Int, newPop: Bool, newParty: Bool,
42
- hearPop: Bool, hearParty: Bool, clock: Float, balloons: List<Balloon>) =
42
+ rng: Random, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
43
43
  const Count = 6
44
44
  const PartyEvery = 10
45
45
  const PartyTime = 2.5
46
46
  const Confetti = 30
47
47
 
48
48
  fun seeded(seed: Int, assets: Assets) -> PlaygroundScreen =
49
- empty := PlaygroundScreen(
50
- rng: Random.seeded(seed), assets: assets, pops: 0, partyAt: -100.0, popsHeard: 0, partiesHeard: 0, newPop: false, newParty: false,
49
+ empty := PlaygroundScreen(rng: Random.seeded(seed), assets: assets, pops: 0, partyAt: -100.0, clock: 0.0, balloons: Nil)
51
- hearPop: false, hearParty: false, clock: 0.0, balloons: Nil)
52
50
  Range.until(0, PlaygroundScreen.Count).fold(empty, |s, i|
53
51
  sp := Balloon.spawn(Balloon.FirstId + i, s.rng, Float(i) * 110.0 - Arena.H * 0.6, 0.0)
54
52
  PlaygroundScreen(..s, rng: sp.rng, balloons: s.balloons.append([sp.balloon])))
@@ -89,19 +87,21 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
89
87
  fun tick(self, dt: Float) -> Option<PopAction> = Some(Tick(dt: dt))
90
88
 
91
89
  fun reduce(self, a: PopAction) -> PlaygroundScreen = match a
92
- Pop(b) => PlaygroundScreen(..self, balloons: self.balloons.map(|x| if x.id == b.id then x.pop() else x)).dispatch(Popped(at: self.clock))
90
+ Pop(b) => PlaygroundScreen(..self, balloons: self.balloons.map(|x| if x.id == b.id then x.pop() else x))
93
91
  Popped(at) => self.popped(at)
94
92
  TakeBack => self
95
- Tick(dt) => self.hear().advance(dt)
93
+ Tick(dt) => self.advance(dt)
96
-
94
+
97
- fun effect(self, io: Io, a: PopAction, game: Control) = match a
95
+ fun act(self, a: PopAction) -> Next<PlaygroundScreen, PopAction> = match a
98
- TakeBack => game.undo()
96
+ Pop(_) => Next(state: self.reduce(a), then: [Popped(at: self.clock)])
99
- Tick(_) =>
97
+ Popped(_) =>
100
- if self.hearPop
98
+ p := self.reduce(a)
99
+ Next(state: p, cmds: [
101
- self.assets.pop.play(io, 0.9)
100
+ Play(sound: self.assets.pop, volume: 0.9)
101
+ if p.pops % PlaygroundScreen.PartyEvery == 0 then Play(sound: self.assets.party, volume: 0.6)
102
+ ])
102
- if self.hearParty
103
+ TakeBack => Next(state: self, cmds: [Undo])
103
- self.assets.party.play(io, 0.6)
104
+ _ => Next(state: self.reduce(a))
104
- _ => Unit
105
105
 
106
106
  fun advance(self, dt: Float) -> PlaygroundScreen =
107
107
  clock := self.clock + dt
@@ -116,12 +116,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
116
116
  fun popped(self, at: Float) -> PlaygroundScreen =
117
117
  pops := self.pops + 1
118
118
  party := pops % PlaygroundScreen.PartyEvery == 0
119
- PlaygroundScreen(..self, pops: pops, newPop: true, partyAt: if party then at else self.partyAt, newParty: self.newParty || party)
119
+ PlaygroundScreen(..self, pops: pops, partyAt: if party then at else self.partyAt)
120
-
121
- fun hear(self) -> PlaygroundScreen =
122
- PlaygroundScreen(
123
- ..self, hearPop: self.newPop, hearParty: self.newParty, popsHeard: if self.newPop then self.popsHeard + 1 else self.popsHeard,
124
- partiesHeard: if self.newParty then self.partiesHeard + 1 else self.partiesHeard, newPop: false, newParty: false)
125
120
 
126
121
  fun partying(self) -> Bool = self.partyingAt(self.clock)
127
122
 
examples/games/clicks.plum CHANGED
@@ -14,7 +14,7 @@ import std/game/View
14
14
  import std/game/Box
15
15
  import std/game/Circle
16
16
  import std/game/Label
17
- import std/game/Control
17
+ import std/game/Cmd
18
18
  import std/game/Screen
19
19
  import std/game/ScreenSlice
20
20
  import std/game/Game
@@ -55,9 +55,9 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
55
55
  Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
56
56
  Quit => self
57
57
 
58
- fun effect(self, io: Io, a: TapAction, game: Control) = match a
58
+ fun act(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
59
- Quit => game.exit()
59
+ Quit => Next(state: self, cmds: [Exit])
60
- _ => Unit
60
+ _ => Next(state: self.reduce(a))
61
61
 
62
62
  primitive Clicks[App] =
63
63
  fun main(io: Io) -> Game =
examples/games/orbitrunner/OrbitRunner.plum CHANGED
@@ -66,13 +66,9 @@ struct Assets(sheet: Texture, pickup: Sound, hit: Sound, over: Sound, music: Sou
66
66
 
67
67
  fun none() -> Assets = Assets(sheet: Texture.none(), pickup: Sound.none(), hit: Sound.none(), over: Sound.none(), music: Sound.none())
68
68
 
69
- fun startMusic(self, io: Io) =
70
- self.music.stop(io)
71
- self.music.loop(io, Assets.MusicVolume)
72
-
73
69
  primitive OrbitRunner[App] =
74
70
  fun main(io: Io) -> Game =
75
71
  assets := Assets.load(io)
76
- assets.startMusic(io)
72
+ assets.music.loop(io, Assets.MusicVolume)
77
73
  play: Screen := PlayingScreen.start(Random.seeded(io.randomSeed()), assets)
78
74
  Game(screens: [play])
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -18,7 +18,8 @@ import std/game/Box
18
18
  import std/game/Label
19
19
  import std/game/Sprite
20
20
  import std/game/Overlay
21
- import std/game/Control
21
+ import std/game/Audio
22
+ import std/game/Cmd
22
23
  import std/game/Screen
23
24
  import std/game/ScreenSlice
24
25
  import std/game/Game
@@ -46,18 +47,18 @@ enum PlayAction =
46
47
  StartOver => "StartOver"
47
48
 
48
49
  struct PlayingScreen[ScreenSlice<PlayAction>](
49
- rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, again: Bool, clock: Float,
50
+ rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
50
51
  ship: Ship, orbs: List<Orb>, mines: List<Mine>, rings: List<Ring>) =
51
52
  const OrbCount = 3
52
53
  const StartLives = 3
53
54
 
54
55
  fun start(rng: Random, assets: Assets) -> PlayingScreen =
55
56
  PlayingScreen(
56
- rng: rng, assets: assets, score: 0, best: 0, lives: PlayingScreen.StartLives, over: false, again: false, clock: 0.0,
57
+ rng: rng, assets: assets, score: 0, best: 0, lives: PlayingScreen.StartLives, over: false, clock: 0.0,
57
58
  ship: Ship.create(assets.sheet), orbs: Nil, mines: Nil, rings: Nil).deal()
58
59
 
59
60
  fun at(rng: Random, assets: Assets, score: Int, lives: Int) -> PlayingScreen =
60
- PlayingScreen(..PlayingScreen.start(rng, assets), score: score, lives: lives)
61
+ PlayingScreen(..PlayingScreen.start(rng, assets), score: score, lives: lives).grown()
61
62
 
62
63
  fun name(self) -> Str = "play"
63
64
 
@@ -112,26 +113,36 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
112
113
 
113
114
  fun reduce(self, a: PlayAction) -> PlayingScreen = match a
114
115
  Steer(ax, ay) => PlayingScreen(..self, ship: self.ship.steer(ax, ay))
115
- Tick(dt) => self.advance(dt)
116
+ Tick(dt) => self.advance(dt).state
116
- PlayAgain => if self.over then PlayingScreen(..self, again: true) else self
117
+ PlayAgain => self
117
- Scored(points) => PlayingScreen(..self, score: self.score + points)
118
+ Scored(points) => PlayingScreen(..self, score: self.score + points).grown()
118
119
  Hit =>
119
120
  lives := self.lives - 1
120
121
  ring := Ring.at(self.ship.at.x + Sheet.Size / 2.0, self.ship.at.y + Sheet.Size / 2.0)
121
122
  ended := lives <= 0
122
123
  PlayingScreen(
123
- ..self, lives: lives, rings: self.rings.append([ring]), over: self.over || ended,
124
+ ..self, lives: lives, rings: self.rings.append([ring]), over: self.over || ended, ship: self.ship.hurtFor(Ship.HurtTime),
124
125
  best: if ended then self.best.max(self.score) else self.best)
125
126
  StartOver =>
126
127
  PlayingScreen(..self, best: self.best.max(self.score), score: 0, lives: PlayingScreen.StartLives, over: false).deal()
127
128
 
129
+ fun act(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
130
+ Tick(dt) => self.advance(dt)
131
+ _ => self.reduce(a).followed(a)
132
+
133
+ fun followed(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
134
+ PlayAgain => Next(state: self, then: [if self.over then StartOver])
135
+ Scored(_) => Next(state: self, cmds: [Play(sound: self.assets.pickup, volume: 0.8)])
136
+ Hit => Next(state: self, cmds: if self.over then [Stop(sound: self.assets.music), Play(sound: self.assets.over, volume: 1.0)] else [Play(sound: self.assets.hit, volume: 1.0)])
137
+ StartOver => Next(state: self, cmds: [Stop(sound: self.assets.music), Loop(sound: self.assets.music, volume: Assets.MusicVolume)])
138
+ _ => Next(state: self)
139
+
128
- fun advance(self, dt: Float) -> PlayingScreen =
140
+ fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
129
141
  rings := if self.over then Views.stepAll(self.rings, dt) else self.rings
130
142
  moved := PlayingScreen(..self, clock: self.clock + dt, rings: rings.filter(|r| !r.done()))
131
- ruled := if self.over then moved else moved.rules()
143
+ if self.over then Next(state: moved) else moved.rules()
132
- if ruled.again then PlayingScreen(..ruled, again: false).dispatch(StartOver) else ruled
133
144
 
134
- fun rules(self) -> PlayingScreen =
145
+ fun rules(self) -> Next<PlayingScreen, PlayAction> =
135
146
  sh := self.ship
136
147
  caught := self.orbs.fold(Caught(orbs: Nil, rng: self.rng, points: 0), |c, orb|
137
148
  if overlaps(sh.at.x, sh.at.y, Ship.Radius, orb.at.x, orb.at.y, Orb.Radius)
@@ -140,30 +151,14 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
140
151
  else
141
152
  Caught(..c, orbs: Cons(orb, c.orbs))
142
153
  )
154
+ hit := sh.hurt <= 0.0 && self.mines.any(|m| overlaps(sh.at.x, sh.at.y, Ship.Radius, m.at.x, m.at.y, Mine.Radius))
143
- collected := PlayingScreen(..self, orbs: caught.orbs.reverse(), rng: caught.rng)
155
+ Next(state: PlayingScreen(..self, orbs: caught.orbs.reverse(), rng: caught.rng), then: [
144
- scored := if caught.points > 0 then collected.dispatch(Scored(points: caught.points)) else collected
156
+ if caught.points > 0 then Scored(points: caught.points)
145
- grown := scored.grown()
146
- grown.mines.fold(grown, |s, mine|
147
- if s.ship.hurt <= 0.0 && overlaps(s.ship.at.x, s.ship.at.y, Ship.Radius, mine.at.x, mine.at.y, Mine.Radius)
148
- h := s.dispatch(Hit)
157
+ if hit then Hit
149
- PlayingScreen(..h, ship: h.ship.hurtFor(Ship.HurtTime))
150
- else
151
- s
152
- )
158
+ ])
153
159
 
154
160
  fun grown(self) -> PlayingScreen = if self.mines.length() < Mine.countFor(self.score) then self.newMine().grown() else self
155
161
 
156
- fun effect(self, io: Io, a: PlayAction, game: Control) = match a
157
- Scored(_) => self.assets.pickup.play(io, 0.8)
158
- Hit =>
159
- if self.over
160
- self.assets.music.stop(io)
161
- self.assets.over.play(io, 1.0)
162
- else
163
- self.assets.hit.play(io, 1.0)
164
- StartOver => self.assets.startMusic(io)
165
- _ => Unit
166
-
167
162
  fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool = Math.hypot(ax - bx, ay - by) < ra + rb
168
163
 
169
164
  struct Caught(orbs: List<Orb>, rng: Random, points: Int)
examples/games/two_screens.plum CHANGED
@@ -10,7 +10,7 @@ import std/game/Color
10
10
  import std/game/Input
11
11
  import std/game/View
12
12
  import std/game/Label
13
- import std/game/Control
13
+ import std/game/Cmd
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
@@ -32,9 +32,7 @@ struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
32
32
  KeyDown(k) => if k == Key.Enter then Some(Start) else None
33
33
  _ => None
34
34
 
35
- fun reduce(self, a: TitleAction) -> TitleScreen = TitleScreen(starts: self.starts + 1)
35
+ fun act(self, a: TitleAction) -> Next<TitleScreen, TitleAction> = Next(state: TitleScreen(starts: self.starts + 1), cmds: [GoTo(name: "play")])
36
-
37
- fun effect(self, io: Io, a: TitleAction, game: Control) = game.goTo("play")
38
36
 
39
37
  struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
40
38
  fun name(self) -> Str = "play"
@@ -47,9 +45,7 @@ struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
47
45
  KeyDown(k) => if k == Key.Escape then Some(Back) else None
48
46
  _ => None
49
47
 
50
- fun reduce(self, a: PlayAction) -> PlayScreen = PlayScreen(runs: self.runs + 1)
48
+ fun act(self, a: PlayAction) -> Next<PlayScreen, PlayAction> = Next(state: PlayScreen(runs: self.runs + 1), cmds: [GoTo(name: "title")])
51
-
52
- fun effect(self, io: Io, a: PlayAction, game: Control) = game.goTo("title")
53
49
 
54
50
  primitive TwoScreens[App] =
55
51
  fun game() -> Game =
std/game/Audio.plum CHANGED
@@ -24,7 +24,7 @@ primitive Audio =
24
24
  extern fun soundSetVolume(io: Io, s: Int, volume: Float)
25
25
 
26
26
  # A sound handle; the id is the host's. `Sound.Silent` (id -1) is no sound: it plays
27
- # nothing and never calls the host, so a test can run a game's effects.
27
+ # nothing and never calls the host, so a test can run a game's sounds.
28
28
  struct Sound(id: Int) =
29
29
  const Silent = Sound(id: -1)
30
30
 
std/game/Cmd.plum ADDED
@@ -0,0 +1,72 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Bool
7
+ import std/Io
8
+ import std/collections/List
9
+ import std/game/Audio
10
+
11
+ # What a reducer asks of the game, as a value: a slice's `act(a)` returns its commands
12
+ # with its next state (std/game/ScreenSlice's `Next`), and the game does them once the tick
13
+ # is over, in the order given, with the `Io` the tick has (std/game/Game):
14
+ #
15
+ # fun act(self, a: MenuAction) -> Next<MenuScreen, MenuAction> = match a
16
+ # Start => Next(state: self, cmds: [GoTo(name: "play"), Play(sound: self.assets.click, volume: 1.0)])
17
+ # Quit => Next(state: self, cmds: [Exit])
18
+ # _ => Next(state: self.reduce(a))
19
+ #
20
+ # GoTo shows the screen of that name from the next tick on, as it was left, coming
21
+ # in by its `transition(from)`. A name no screen has stops the program and
22
+ # lists the screens.
23
+ # Exit no tick runs after this one.
24
+ # Undo goes back to just before the last user action (docs/game.md, "Undo and time
25
+ # travel"); nothing if there is none, or the game keeps no history
26
+ # (`Game.timeTravel`).
27
+ # Redo goes forward again to the next user action undone.
28
+ # RewindTo puts the game in the state it was in after `tick` ticks.
29
+ # Play plays the sound once at `volume` (0..1).
30
+ # Loop starts the sound looping at `volume`.
31
+ # Stop stops every play and loop of the sound.
32
+ #
33
+ # A tick played again by a rewind gives the same commands, as it is the same tick: the game
34
+ # then does its `GoTo`s again and nothing else, so no sound plays twice and no rewind
35
+ # rewinds again.
36
+ enum Cmd =
37
+ | GoTo(name: Str)
38
+ | Exit
39
+ | Undo
40
+ | Redo
41
+ | RewindTo(tick: Int)
42
+ | Play(sound: Sound, volume: Float)
43
+ | Loop(sound: Sound, volume: Float)
44
+ | Stop(sound: Sound)
45
+
46
+ fun toStr(self) -> Str = match self
47
+ GoTo(name) => "goTo({name})"
48
+ Exit => "exit"
49
+ Undo => "undo"
50
+ Redo => "redo"
51
+ RewindTo(tick) => "rewindTo({tick})"
52
+ Play(s, v) => "play({s.id}, {v})"
53
+ Loop(s, v) => "loop({s.id}, {v})"
54
+ Stop(s) => "stop({s.id})"
55
+
56
+ # Whether it moves the game through its history (undo, redo, rewindTo): what the game
57
+ # does once the tick is recorded.
58
+ fun travels(self) -> Bool = match self
59
+ Undo => true
60
+ Redo => true
61
+ RewindTo(_) => true
62
+ _ => false
63
+
64
+ # Plays, loops or stops its sound; any other command is the game's own.
65
+ fun sound(self, io: Io) = match self
66
+ Play(s, v) => s.play(io, v)
67
+ Loop(s, v) => s.loop(io, v)
68
+ Stop(s) => s.stop(io)
69
+ _ => Unit
70
+
71
+ # The commands of `cmds` as one line, for tests: "goTo(play) exit".
72
+ fun names(cmds: List<Cmd>) -> Str = cmds.map(|c| c.toStr()).join(" ")
std/game/Control.plum DELETED
@@ -1,69 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Str
5
- import std/Bool
6
- import std/Slice
7
- import std/collections/List
8
-
9
- # What an effect may ask of the game: show another screen, or stop, or move through its
10
- # history. A slice's
11
- # `effect(io, a, game)` is handed one; the game does what it asks once that effect has
12
- # run, before the next action's effect, in the order asked:
13
- #
14
- # fun effect(self, io: Io, a: MenuAction, game: Control) = match a
15
- # Start => game.goTo("play")
16
- # Quit => game.exit()
17
- # _ => Unit
18
- #
19
- # goTo shows the screen of that name from the next tick on, as it was left, coming
20
- # in by its `transition(from)`. A name no screen has stops the program and
21
- # lists the screens.
22
- # exit no tick runs after this one.
23
- # undo after the tick, goes back to just before the last user action
24
- # (docs/game.md, "Undo and time travel"); nothing if there is none, or the
25
- # game keeps no history (`Game.timeTravel`).
26
- # redo after the tick, goes forward again to the next user action undone.
27
- # rewindTo after the tick, puts the game in the state it was in after `tick` ticks.
28
- #
29
- # It holds only what was asked, not the game: a slice keeps no link to the `Game`. An
30
- # effect returns nothing, so a `Control` is the one thing in a tick that is written in
31
- # place: `goTo` and the others push onto `asked`.
32
- struct Control(asked: Slice<Ask>) =
33
- fun create() -> Control = Control(asked: Slice<Ask>())
34
-
35
- fun goTo(self, name: Str) = self.asked.push(AskGoTo(name: name))
36
-
37
- fun exit(self) = self.asked.push(AskExit)
38
-
39
- fun undo(self) = self.asked.push(AskUndo)
40
-
41
- fun redo(self) = self.asked.push(AskRedo)
42
-
43
- fun rewindTo(self, tick: Int) = self.asked.push(AskRewind(tick: tick))
44
-
45
- # What was asked, in order.
46
- fun take(self) -> List<Ask> = List.fromSlice(self.asked)
47
-
48
- # One thing an effect asked of the game.
49
- enum Ask =
50
- | AskGoTo(name: Str)
51
- | AskExit
52
- | AskUndo
53
- | AskRedo
54
- | AskRewind(tick: Int)
55
-
56
- fun toStr(self) -> Str = match self
57
- AskGoTo(name) => "goTo({name})"
58
- AskExit => "exit"
59
- AskUndo => "undo"
60
- AskRedo => "redo"
61
- AskRewind(tick) => "rewindTo({tick})"
62
-
63
- # Whether it moves the game through its history (undo, redo, rewindTo): what the game
64
- # does after the tick, never again when a rewind plays the tick over.
65
- fun travels(self) -> Bool = match self
66
- AskUndo => true
67
- AskRedo => true
68
- AskRewind(_) => true
69
- _ => false
std/game/Effects.plum DELETED
@@ -1,67 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Io
5
- import std/Slice
6
- import std/collections/List
7
- import std/game/Control
8
- import std/game/ScreenSlice
9
-
10
- # The actions dispatched in a tick, waiting for their effects. A delivery
11
- # (std/game/ScreenSlice's `Delivery.deliverTo`) queues each action of its slice as it is
12
- # dispatched, on a queue of the slice's action type (`ActionSink<A>`); after the tick each
13
- # is held with the slice as the tick left it (`Queued<A>`), so one list holds the actions
14
- # of every screen whatever their types, and the game runs each one's effect (the slice's
15
- # `effect(io, a, game)`), in the order dispatched. A test reads the ones that ran with
16
- # `Effects.sent<A>(game.ran)` (std/game/TestRig's `effects<A>()`).
17
- #
18
- # The queue of the dispatch running sits in one slot (`Effects.Running`): the game sets it around
19
- # a screen's `deliver`, std/game/TestRig around its own `dispatch`, and a slice's own
20
- # `dispatch` (a reducer dispatching what happened) queues there. Outside them it is empty
21
- # and `dispatch` only reduces.
22
-
23
- # One waiting action and the slice whose effect runs it.
24
- trait Effect =
25
- fun apply(self, io: Io, game: Control)
26
-
27
- struct Queued<A>[Effect](slice: ScreenSlice<A>, action: A) =
28
- fun apply(self, io: Io, game: Control) = self.slice.effect(io, self.action, game)
29
-
30
- # `a`, to run with the effect of the slice `s`.
31
- fun of(s: ScreenSlice<A>, a: A) -> Effect = Queued(slice: s, action: a)
32
-
33
- # A delivery's queue, of the slice's action type.
34
- trait Sink =
35
- fun size(self) -> Int
36
-
37
- struct ActionSink<A>[Sink](queue: Slice<A>) =
38
- fun size(self) -> Int = self.queue.length()
39
-
40
- # The dispatch slot and reading what ran.
41
- primitive Effects =
42
- # The queue of the dispatch running: empty outside any, one queue inside one.
43
- const Running = Slice<Sink>()
44
-
45
- # The actions of type `A` among `fx`, in order: `Effects.sent<PlayAction>(game.ran)`.
46
- fun sent<A>(fx: List<Effect>) -> List<A> =
47
- none: List<A> := Nil
48
- fx.fold(none, |acc, e| match e
49
- Queued<A> as q => Cons(q.action, acc)
50
- _ => acc).reverse()
51
-
52
- # From here to `endDispatch()`, what a slice dispatches is queued on `s`.
53
- fun startDispatch(s: Sink) =
54
- Effects.Running.clear()
55
- Effects.Running.push(s)
56
-
57
- fun endDispatch() = Effects.Running.clear()
58
-
59
- # Whether a dispatch is running.
60
- fun dispatching() -> Bool = !Effects.Running.isEmpty()
61
-
62
- # Queues `a` on the dispatch running, if it queues actions of `a`'s type.
63
- fun queueAction<A>(a: A) =
64
- if !Effects.Running.isEmpty()
65
- match Effects.Running.at(0)
66
- ActionSink<A> as k => k.queue.push(a)
67
- _ => Unit
std/game/Game.plum CHANGED
@@ -17,10 +17,9 @@ import std/game/Color
17
17
  import std/game/Gfx
18
18
  import std/game/Input
19
19
  import std/game/View
20
- import std/game/Effects
21
20
  import std/game/ScreenSlice
22
21
  import std/game/Viewport
23
- import std/game/Control
22
+ import std/game/Cmd
24
23
  import std/game/Screen
25
24
  import std/game/History
26
25
  import std/game/Replay
@@ -34,7 +33,7 @@ import std/game/Replay
34
33
  # Game(screens: [TitleScreen(..), PlayingScreen.start(Random.seeded(io.randomSeed()), Assets.load(io))])
35
34
  #
36
35
  # The first screen shows first. Each screen has a name, and the game goes to another when
37
- # an effect asks it to (`game.goTo(name)`, std/game/Control), after the tick, coming in by
36
+ # a slice's step asks it to (`GoTo(name)`, std/game/Cmd), after the tick, coming in by
38
37
  # that screen's `transition`. A name no screen has stops the program and names the
39
38
  # screens there are, as two screens of one name do when the game is made.
40
39
  #
@@ -57,9 +56,10 @@ import std/game/Replay
57
56
  # current screen gets the tick (`deliver`, with a `Delivery`: the tick's input, its
58
57
  # camera, what was held at its tick before, and no `Io`), as actions for a slice screen,
59
58
  # with its `Actor`s stepped before its tick action (a plain screen's are stepped alone);
60
- # then the transition in progress moves on; then, for each action dispatched in the tick,
59
+ # then the transition in progress moves on; then the game does the commands the tick's
61
- # in order, its slice's `effect(io, a, game)` and right after it what that effect asked of
60
+ # actions gave (std/game/Cmd), in order, with `io`: a sound, a `GoTo`, an `Exit`; an undo,
61
+ # a redo or a rewind once the tick is recorded. A tick takes nothing from `io` but its
62
- # `game` (`goTo`, `exit`; an undo, a redo or a rewind once the tick is over). Keep any randomness in a screen as a `Random` seeded once
62
+ # sounds, so keep any randomness in a screen as a `Random` seeded once
63
63
  # in `main` from `io.randomSeed()`: then the same seed and the same inputs give the same
64
64
  # game, which is what record and replay use.
65
65
  #
@@ -75,8 +75,8 @@ import std/game/Replay
75
75
  # frame then tells the host so (`hostFrame`, the `frameIdle` host call): it skips the
76
76
  # draw, keeps the last frame shown and, in a browser, waits for input. `delivered`,
77
77
  # `skipped` and `draws` count the ticks delivered, the ticks slept through and the frames
78
- # drawn, for tests; `ran` and `asked` are the effects that ran in the last tick and what
78
+ # drawn, for tests; `sent` and `cmds` are the actions the last tick stepped and the
79
- # they asked of the game (std/game/TestRig reads them).
79
+ # commands it gave (std/game/TestRig reads them).
80
80
  #
81
81
  # Undo and time travel (docs/game.md): `timeTravel(cap)` keeps the game's history from its
82
82
  # start (std/game/History), and the game can then go back to any tick it played and
@@ -84,8 +84,8 @@ import std/game/Replay
84
84
  # `stepBack(io)`, `stepForward(io)`, with `canUndo()`, `canRedo()`, `tickNow()` and
85
85
  # `ticksRecorded()`; each move returns the game moved, `moved` saying whether it could.
86
86
  # Going back makes the game again from `initial` and plays the recorded ticks into it,
87
- # through the same tick as ever (`run`), with no effects run: what they asked of the game
87
+ # through the same tick as ever (`run`), which gives the same commands: of those only a
88
- # (a `goTo`) is recorded and done again, an `exit` is not. `pause()` holds
88
+ # `GoTo` is done again, so no sound plays and no `Exit` or rewind is done twice. `pause()` holds
89
89
  # the game still until `resume()`, which drops what could be redone. `rewound` is how many
90
90
  # ticks the last move played. A development run (`plum run --dev`) does this from the
91
91
  # first frame and moves with the time travel keys (`devFrame`, std/game/History's
@@ -109,12 +109,12 @@ struct Game(screens: List<Screen>) =
109
109
  self.delivered: Int = 0
110
110
  self.skipped: Int = 0
111
111
  self.draws: Int = 0
112
- self.ran: List<Effect> = Nil
112
+ self.sent: List<Dispatched> = Nil
113
- self.asked: List<Ask> = Nil
113
+ self.cmds: List<Cmd> = Nil
114
114
  # The undo, redo or rewind asked this tick, whether the tick was a user action, the
115
115
  # history (none until `timeTravel`), whether the game is held still, how many ticks
116
116
  # the last move played, and whether it could move.
117
- self.travel: List<Ask> = Nil
117
+ self.travel: List<Cmd> = Nil
118
118
  self.acted: Bool = false
119
119
  self.history: Option<History> = None
120
120
  self.paused: Bool = false
@@ -160,39 +160,37 @@ struct Game(screens: List<Screen>) =
160
160
 
161
161
  # One tick of `dt` seconds with `input` in a window of `pixels` (see the top of this
162
162
  # file); a test runs ticks with it. With a history, the tick is added to it, and then
163
- # what its effects asked of the history is done. An exited or paused game stays as it is.
163
+ # the undo, redo or rewind its commands asked for is done. An exited or paused game stays as it is.
164
164
  fun step(self, io: Io, input: Input, dt: Float, pixels: Vec2) -> Game =
165
165
  if self.exited || self.paused
166
166
  self
167
167
  else
168
- ran := self.run(io, input, dt, pixels, None)
168
+ ran := self.run(io, input, dt, pixels, false)
169
- travel := ran.travel
170
169
  noted := match ran.history
171
- Some(h) => Game(..ran, history: Some(h.push(HistoryTick(input: input, pixels: pixels, dt: dt, user: ran.acted && travel.isEmpty(), asks: ran.asked))))
170
+ Some(h) => Game(..ran, history: Some(h.push(HistoryTick(input: input, pixels: pixels, dt: dt, user: ran.acted && ran.travel.isEmpty()))))
172
171
  None => ran
173
172
  noted.travelAsked(io)
174
173
 
175
- # The game after the undos, redos and rewinds the effects asked for, in order (`obey`
174
+ # The game after the undos, redos and rewinds the tick's commands asked for, in order
176
- # keeps them for the end of the tick), which it then forgets: what ends a tick, and the
175
+ # (`obey` keeps them for the end of the tick), which it then forgets: what ends a tick,
177
- # kit's `dispatch` (std/game/TestRig).
176
+ # and the kit's `dispatch` (std/game/TestRig).
178
- fun travelAsked(self, io: Io) -> Game = self.travel.fold(Game(..self, travel: Nil), |g, a| g.travelled(io, a))
177
+ fun travelAsked(self, io: Io) -> Game = self.travel.fold(Game(..self, travel: Nil), |g, c| g.travelled(io, c))
179
178
 
180
- # The game after a move through its history that an effect asked for.
179
+ # The game after a move through its history that a command asked for.
181
- fun travelled(self, io: Io, a: Ask) -> Game = match a
180
+ fun travelled(self, io: Io, c: Cmd) -> Game = match c
182
- AskUndo => self.undo(io)
181
+ Undo => self.undo(io)
183
- AskRedo => self.redo(io)
182
+ Redo => self.redo(io)
184
- AskRewind(k) => self.rewindTo(io, k)
183
+ RewindTo(k) => self.rewindTo(io, k)
185
184
  _ => self
186
185
 
187
186
  # The tick itself: what `step` does live, and what a rewind does for each tick it plays
188
- # again, with `replayed` the asks the tick's effects made when it was played: then no
187
+ # again (`replayed`): then of the tick's commands only a `GoTo` is done again.
189
- # effect runs, and only what they asked of the screens (`goTo`) is done again.
190
188
  # `acted` says whether the tick was a user action (std/game/History).
191
- fun run(self, io: Io, input: Input, dt: Float, pixels: Vec2, replayed: Option<List<Ask>>) -> Game =
189
+ fun run(self, io: Io, input: Input, dt: Float, pixels: Vec2, replayed: Bool) -> Game =
192
190
  sized := if pixels.x > 0.0 && pixels.y > 0.0 && {pixels.x != self.pixels.x || pixels.y != self.pixels.y} then self.resized(pixels) else self
193
191
  news := Game.heardIn(input, sized.pointer)
194
192
  s := sized.screen()
195
- base := Game(..sized, pointer: Game.lastPointer(input, sized.pointer), ticks: sized.ticks + 1, ran: Nil, asked: Nil, acted: false)
193
+ base := Game(..sized, pointer: Game.lastPointer(input, sized.pointer), ticks: sized.ticks + 1, sent: Nil, cmds: Nil, acted: false)
196
194
  if Game.onDemand(s) && !sized.wake && sized.shift.isNone() && !news && !s.wants(input)
197
195
  Game(..base, skipped: base.skipped + 1)
198
196
  else
@@ -202,42 +200,30 @@ struct Game(screens: List<Screen>) =
202
200
  None => None
203
201
  ticked := Game(
204
202
  ..base, screens: Game.setAt(base.screens, base.current, d.screen), helds: Game.setAt(base.helds, base.current, input.held), shift: shift,
205
- delivered: base.delivered + 1, dirty: true, acted: d.acted)
203
+ delivered: base.delivered + 1, dirty: true, acted: d.acted, sent: d.sent, cmds: d.cmds)
206
- after := match replayed
207
- Some(asks) => ticked.redoAsks(asks)
204
+ after := if replayed then ticked.redone(d.cmds) else d.cmds.fold(ticked, |g, c| g.obey(io, c))
208
- None => ticked.apply(io, d.effects)
209
- Game(..after, wake: !after.asked.isEmpty() || after.shift.isSome() || after.screen().busy())
205
+ Game(..after, wake: !d.cmds.isEmpty() || after.shift.isSome() || after.screen().busy())
210
206
 
211
207
  # The window is `pixels` from now on.
212
208
  fun resized(self, pixels: Vec2) -> Game = Game(..self, pixels: pixels, wake: true, dirty: true)
213
209
 
214
- # Runs the effects `fx` of the tick, in order, each followed by what it asked of the
215
- # game.
216
- fun apply(self, io: Io, fx: List<Effect>) -> Game =
217
- fx.fold(Game(..self, ran: fx), |g, e|
218
- c := Control.create()
219
- e.apply(io, c)
220
- c.take().fold(g, |h, a| h.obey(a))
221
- )
222
-
223
- # Does what an effect asked; an undo, a redo or a rewind waits for the end of the tick
210
+ # Does a command of the tick (std/game/Cmd); an undo, a redo or a rewind waits for the
224
- # (`step`).
211
+ # end of the tick (`step`).
225
- fun obey(self, a: Ask) -> Game =
226
- g := Game(..self, asked: self.asked.append([a]))
227
- match a
228
- AskGoTo(name) => g.goTo(name)
229
- AskExit => Game(..g, exited: true)
230
- _ => Game(..g, travel: g.travel.append([a]))
231
-
232
- # A tick played again by a rewind: its effects don't run, but what they asked of the
233
- # screens is done again, in order; an exit is not, nor a move through the history.
234
- fun redoAsks(self, asks: List<Ask>) -> Game =
235
- asks.fold(Game(..self, asked: asks), |g, a| g.redone(a))
236
-
237
- # What a tick played again asked of the screens, done again.
238
- fun redone(self, a: Ask) -> Game = match a
212
+ fun obey(self, io: Io, c: Cmd) -> Game = match c
239
- AskGoTo(name) => self.goTo(name)
213
+ GoTo(name) => self.goTo(name)
214
+ Exit => Game(..self, exited: true)
215
+ Undo => Game(..self, travel: self.travel.append([c]))
216
+ Redo => Game(..self, travel: self.travel.append([c]))
217
+ RewindTo(_) => Game(..self, travel: self.travel.append([c]))
218
+ _ =>
219
+ c.sound(io)
220
+ self
221
+
222
+ # The commands of a tick played again by a rewind: its `GoTo`s are done again, in order,
223
+ # and nothing else (no sound, no exit, no move through the history).
224
+ fun redone(self, cmds: List<Cmd>) -> Game = cmds.fold(self, |g, c| match c
225
+ GoTo(name) => g.goTo(name)
240
- _ => self
226
+ _ => g)
241
227
 
242
228
  # Shows the screen named `name` from the next tick on, as it was left, coming in by its
243
229
  # `transition`. The screen shown already stays as it is.
@@ -435,10 +421,10 @@ struct Game(screens: List<Screen>) =
435
421
  sized := if h.pixels.x > 0.0 && h.pixels.y > 0.0 then fresh.resized(h.pixels) else fresh
436
422
  Game(..sized, history: Some(h), paused: self.paused, dev: self.dev).playOn(io, h.played())
437
423
 
438
- # `recs` played again from the state the game is in, with no effects run.
424
+ # `recs` played again from the state the game is in, doing only their `GoTo`s.
439
425
  fun playOn(self, io: Io, recs: List<HistoryTick>) -> Game =
440
- played := recs.fold(self, |g, r| g.run(io, r.input, r.dt, r.pixels, Some(r.asks)))
426
+ played := recs.fold(self, |g, r| g.run(io, r.input, r.dt, r.pixels, true))
441
- Game(..played, rewound: recs.length(), ran: Nil, asked: Nil, dirty: true, moved: true)
427
+ Game(..played, rewound: recs.length(), sent: Nil, cmds: Nil, dirty: true, moved: true)
442
428
 
443
429
  # The camera the screen `s` is seen through in a window of `pixels` (0 by 0 while the
444
430
  # game doesn't know it): its world (`size()`) put on the window by its `viewport()`, or,
std/game/History.plum CHANGED
@@ -7,19 +7,17 @@ import std/collections/List
7
7
  import std/Io
8
8
  import std/math/Vec2
9
9
  import std/game/Input
10
- import std/game/Control
11
10
 
12
11
  # A game's own history, for undo and time travel (docs/game.md, "Undo and time travel").
13
12
  #
14
13
  # A game is a value, so an old game could be kept as it is; but a game of a long run kept
15
14
  # at every tick would keep every state. What is kept instead is what entered the game: the
16
15
  # game goes back by being made again from the screens it was made with (`Game.initial`)
17
- # and having the recorded ticks played into it, with no effects run. So a history is one
16
+ # and having the recorded ticks played into it. So a history is one `HistoryTick` per
18
- # `HistoryTick` per tick: its `Input`, the screen's size, its length, whether it was a
17
+ # tick: its `Input`, the screen's size, its length and whether it was a user action. A
19
- # user action, and what its effects asked of the game (a `goTo` changes
20
- # which screen gets the next ticks, so a rewind does it again without running the
18
+ # tick played again gives the same commands (std/game/Cmd), of which the game does only
21
- # effect). It records input, not actions: an action may hold an actor of the view, which
19
+ # the `GoTo`s again. It records input, not actions: an action may hold an actor of the
22
- # the input mapped again makes anew.
20
+ # view, which the input mapped again makes anew.
23
21
  #
24
22
  # The timeline is `ticks` (the newest first, `count` of them), the ticks played to reach
25
23
  # the state now. Going back moves the ticks after the point gone to into `future`, which
@@ -30,12 +28,12 @@ import std/game/Control
30
28
  #
31
29
  # A user action tick is one in which the shown slice screen's input mapping gave an
32
30
  # action for one of the tick's events, or `held` gave an action while what is held
33
- # differs from the tick before (std/game/Game, `run`). A tick whose effects asked for an
31
+ # differs from the tick before (std/game/Game, `run`). A tick whose commands asked for an
34
32
  # undo, a redo or a rewind is the command, not something to undo.
35
33
  #
36
34
  # `cap` bounds it: once the timeline would hold `cap` ticks the history is full, lets its
37
35
  # ticks go, and every rewind, undo and step is refused from then on (the game plays on).
38
- struct HistoryTick(input: Input, pixels: Vec2, dt: Float, user: Bool, asks: List<Ask>)
36
+ struct HistoryTick(input: Input, pixels: Vec2, dt: Float, user: Bool)
39
37
 
40
38
  struct History(cap: Int, pixels: Vec2, ticks: List<HistoryTick>, count: Int, future: List<HistoryTick>, fork: Int, full: Bool, over: Int) =
41
39
  # 30 minutes of ticks.
std/game/Screen.plum CHANGED
@@ -14,13 +14,12 @@ import std/game/Color
14
14
  import std/game/Input
15
15
  import std/game/View
16
16
  import std/game/Viewport
17
- import std/game/Control
17
+ import std/game/Cmd
18
- import std/game/Effects
19
18
  import std/game/ScreenSlice
20
19
 
21
20
  # One screen of a game (a title, the play, a level select): a name, its state, and the
22
21
  # `view` that draws it. The game shows one screen at a time (std/game/Game) and goes to
23
- # another by name, when an effect asks it to (`game.goTo(name)`, std/game/Control).
22
+ # another by name, when a slice's step asks it to (`GoTo(name)`, std/game/Cmd).
24
23
  #
25
24
  # A screen with rules is a `ScreenSlice<A>` (std/game/ScreenSlice), which extends
26
25
  # `Screen`: its fields are its state, `A` its actions, and std delivers the tick's input
@@ -117,15 +116,15 @@ trait Screen =
117
116
 
118
117
  fun frames(self) -> Frames = Always
119
118
 
120
- fun deliver(self, d: Delivery) -> Delivered = Delivered(screen: d.stepScreen(self), effects: Nil, acted: false)
119
+ fun deliver(self, d: Delivery) -> Delivered = Delivered(screen: d.stepScreen(self))
121
120
 
122
121
  fun wants(self, input: Input) -> Bool = false
123
122
 
124
- # One tick of a screen, delivered: the screen after it, the effects waiting to run (each
123
+ # One tick of a screen, delivered: the screen after it, the commands its actions gave for
125
- # action dispatched, with the slice as the tick left it), and whether the tick was a user
124
+ # the game (std/game/Cmd), in order, the actions stepped, and whether the tick was a user
126
125
  # action (std/game/History): the mapping gave an action for one of its events, or `held`
127
126
  # gave one while what is held differs from the screen's tick before.
128
- struct Delivered(screen: Screen, effects: List<Effect>, acted: Bool)
127
+ struct Delivered(screen: Screen, cmds: List<Cmd> = Nil, sent: List<Dispatched> = Nil, acted: Bool = false)
129
128
 
130
129
  # How often a screen gets its ticks and is drawn: every frame (`Always`), or only when
131
130
  # something happened (`OnDemand`).
std/game/ScreenSlice.plum CHANGED
@@ -6,22 +6,19 @@ import std/Bool
6
6
  import std/Str
7
7
  import std/Io
8
8
  import std/Option
9
- import std/Slice
10
9
  import std/collections/List
11
10
  import std/math/Vec2
12
11
  import std/game/Input
13
12
  import std/game/View
14
- import std/game/Effects
15
13
  import std/game/Viewport
16
- import std/game/Control
14
+ import std/game/Cmd
17
15
  import std/game/Screen
18
16
 
19
17
  # A screen with a slice of the game, as in Redux Toolkit (master's `Slice<A>`; here the
20
18
  # name `Slice` is std's growable array): the screen's own fields are the slice's state,
21
- # `A` (an enum, usually) its actions, `reduce` its reducer and `effect` what an action
19
+ # `A` (an enum, usually) its actions, and `reduce` its reducer. The screen declares how the
22
- # does after the tick. The screen declares how the tick's input becomes its actions and
20
+ # tick's input becomes its actions and what its tick action is; std delivers them, so a
23
- # what its tick action is; std delivers them, so a slice screen has no `update` of its
21
+ # slice screen has no `update` of its own:
24
- # own:
25
22
  #
26
23
  # enum Act = Bump | Tick(dt: Float)
27
24
  #
@@ -38,6 +35,17 @@ import std/game/Screen
38
35
  #
39
36
  # The slice is a value: `reduce` returns its next version, and std keeps that one.
40
37
  #
38
+ # A reducer that has more to say than its next state writes `act` instead (or as well):
39
+ # it returns a `Next`, the next state with the actions that follow from this one (`then`)
40
+ # and what it asks of the game (`cmds`, std/game/Cmd: a sound, another screen, an undo):
41
+ #
42
+ # fun act(self, a: Act) -> Next<CountScreen, Act> = match a
43
+ # Bump => Next(state: CountScreen(count: self.count + 1), cmds: [Play(sound: self.click, volume: 1.0)])
44
+ # _ => Next(state: self.reduce(a))
45
+ #
46
+ # `act` is `Next(state: self.reduce(a))` by default, and `reduce` the slice as it is, so
47
+ # a screen writes the one it needs.
48
+ #
41
49
  # Each tick of the screen, std delivers, in this order:
42
50
  #
43
51
  # 1. each of the tick's events, in the order they came:
@@ -55,27 +63,15 @@ import std/game/Screen
55
63
  # its `steps()` is false.
56
64
  # 4. `tick(dt)`: the tick action, which sees the actors stepped and runs the rules.
57
65
  #
58
- # A mapping that gives None sends nothing. Each action is dispatched as it is made:
66
+ # A mapping that gives None sends nothing. Each action is stepped as it is made, and then
67
+ # each action of its `then`, in order, each with its own `then` first: so the next
68
+ # mapping and action see what they did. The delivery is a fold (`Delivery.deliverTo`): the
59
- # `reduce(a)` runs at once, so the next mapping and action see what it did, and `a` is
69
+ # screen after the tick, the actions stepped, in order, and their commands, which the game
60
- # queued; after the tick (and the transition's step) the game runs `effect(io, a, game)`
70
+ # does after the tick (and the transition's step).
61
- # for every queued action, in the order dispatched, with the slice as the tick left it,
62
- # and then what each effect asked of `game` (std/game/Control).
63
- #
64
- # A reducer dispatches more with `self.dispatch(a)`: reduced at once (it returns the
65
- # slice after it) and queued for its effect before the action being reduced.
66
71
  trait ScreenSlice<A>[Screen] =
67
- fun reduce(self, a: A) -> Self
72
+ fun reduce(self, a: A) -> Self = self
68
-
69
- # Dispatches `a` from this slice's own reducer (the rules dispatching what happened):
70
- # reduced at once, and queued for its effect after the tick, before the action being
71
- # reduced. Called outside a dispatch (a test calling `reduce` itself), it only reduces.
72
- fun dispatch(self, a: A) -> Self =
73
- next := self.reduce(a)
74
- Effects.queueAction(a)
75
- next
76
73
 
77
- # The effects of `a`, after the tick: a sound, a change of screen. Nothing by default.
78
- fun effect(self, io: Io, a: A, game: Control) = Unit
74
+ fun act(self, a: A) -> Next<Self, A> = Next(state: self.reduce(a))
79
75
 
80
76
  fun onKey(self, e: InputEvent) -> Option<A> = None
81
77
 
@@ -94,68 +90,124 @@ trait ScreenSlice<A>[Screen] =
94
90
  # std's: one tick of the screen, delivered as actions (see the top of this file).
95
91
  fun deliver(self, d: Delivery) -> Delivered = Delivery.deliverTo<A, Self>(self, d)
96
92
 
93
+ # What a slice's `act` gives: its next state, the actions that follow from the one stepped
94
+ # (stepped next, in order, before anything else), and the commands for the game.
95
+ struct Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)
96
+
97
+ # An action stepped in a tick, of whichever slice's type: what a test reads back
98
+ # (`Dispatches.of<A>(xs)`, std/game/TestRig's `actions<A>()`).
99
+ trait Dispatched
100
+
101
+ struct Sent<A>[Dispatched](action: A)
102
+
103
+ primitive Dispatches =
104
+ # The actions of type `A` among `xs`, in order.
105
+ fun of<A>(xs: List<Dispatched>) -> List<A> =
106
+ none: List<A> := Nil
107
+ xs.fold(none, |acc, d| match d
108
+ Sent<A> as s => Cons(s.action, acc)
109
+ _ => acc).reverse()
110
+
111
+ # A tick's delivery so far: the slice, and what its steps gave (`Trail`). The fold takes
112
+ # the slice out of it by pattern each time, so it stays the one reference to the slice.
113
+ struct Folded<S, A>(state: S, trail: Trail<A>)
114
+
115
+ # What a tick's steps gave so far: the actions stepped (the last first), the commands they
116
+ # gave (the last first), and whether one of them came from the user.
117
+ struct Trail<A>(actions: List<A> = Nil, cmds: List<Cmd> = Nil, acted: Bool = false) =
118
+ fun user(self, acted: Bool) -> Trail<A> = if acted then Trail(..self, acted: true) else self
119
+
97
120
  # One tick as the game hands it to a screen's `deliver`: the tick's input and length, what
98
121
  # was held at the screen's tick before (`before`), the camera the screen is seen through
99
122
  # (window pixels to the world's coordinates), the window's size in pixels, and whether a
100
123
  # transition runs.
101
124
  struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels: Vec2, shifting: Bool) =
102
125
  # The item a press at the window pixel `p`, the world point `at`, lands on: in the
103
- # screen's `hud`, else in its view; None for none.
126
+ # screen's `hud`, else in its `view`; None for none.
104
- fun pressed(self, s: Screen, p: Vec2, at: Vec2) -> Option<View> =
127
+ fun pressed(hud: List<View>, view: List<View>, p: Vec2, at: Vec2) -> Option<View> =
105
- h := Views.hitIn(s.hud(self.pixels), p)
128
+ h := Views.hitIn(hud, p)
106
- if h.isSome() then h else Views.hitIn(s.view(), at)
129
+ if h.isSome() then h else Views.hitIn(view, at)
107
130
 
108
131
  # `s` with its actors stepped (`stepped(dt)`), unless it says it `steps()` none this
109
132
  # tick.
110
133
  fun stepScreen<S: Screen>(self, s: S) -> S = if s.steps() then s.stepped(self.dt) else s
111
134
 
112
- # One tick of the slice `s`, as `deliver` describes.
135
+ # One tick of the slice `s`, as `deliver` describes: a fold of its events, its `held`
136
+ # and its `tick` over the slice.
113
137
  fun deliverTo<A, S: ScreenSlice<A>>(s: S, d: Delivery) -> Delivered =
114
- q := Slice<A>()
138
+ none: Trail<A> := Trail()
115
- acted := Slice<Bool>()
139
+ afterEvents := d.eventsInto<A, S>(s, none, 0)
116
- Effects.startDispatch(ActionSink(queue: q))
117
- evs := d.input.events
140
+ match afterEvents
141
+ Folded(cur, trail) => d.heldInto<A, S>(cur, trail)
142
+
143
+ # The slice `s` after its `held`, its actors' step and its `tick`, delivered.
118
- afterEvents := Range.until(0, evs.length()).fold(s, |cur, i| Delivery.eventInto<A, S>(cur, d, evs.at(i), q, acted))
144
+ fun heldInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>) -> Delivered =
119
- h := afterEvents.held(d.input)
145
+ h := s.held(self.input)
120
146
  afterHeld := match h
121
- Some(a) =>
122
- if !d.before.same(d.input.held)
123
- acted.push(true)
124
- Delivery.reduced<A, S>(afterEvents, a, q)
125
- None => afterEvents
126
- stepped := d.stepScreen(afterHeld)
127
- afterTick := match stepped.tick(d.dt)
128
- Some(a) => Delivery.reduced<A, S>(stepped, a, q)
129
- None => stepped
130
- Effects.endDispatch()
131
- final: ScreenSlice<A> := afterTick
132
- fx: List<Effect> := List.fromSlice(q).map(|a| Queued.of(final, a))
133
- Delivered(screen: afterTick, effects: fx, acted: acted.length() > 0)
134
-
135
- # `s` after the event `e`, mapped to its action; a pointer event while a transition runs
136
- # is dropped.
137
- fun eventInto<A, S: ScreenSlice<A>>(s: S, d: Delivery, e: InputEvent, q: Slice<A>, acted: Slice<Bool>) -> S = match e.position()
138
- Some(p) =>
139
- if d.shifting
140
- s
141
- else
142
- at := d.camera.toWorld(p.x, p.y)
143
- target := if e.isPointerDown() then d.pressed(s, p, at) else None
144
- pressed := match target
145
- Some(t) => s.onPress(t, at)
146
- None => None
147
- act := if pressed.isSome() then pressed else s.onPointer(e, at)
148
- Delivery.actedOn<A, S>(s, act, q, acted)
149
- None => Delivery.actedOn<A, S>(s, s.onKey(e), q, acted)
150
-
151
- fun actedOn<A, S: ScreenSlice<A>>(s: S, act: Option<A>, q: Slice<A>, acted: Slice<Bool>) -> S = match act
152
- Some(a) =>
153
- acted.push(true)
154
- Delivery.reduced<A, S>(s, a, q)
155
- None => s
156
-
157
- # `s` with `a` reduced into it, and `a` queued after what its reducer dispatched.
158
- fun reduced<A, S: ScreenSlice<A>>(s: S, a: A, q: Slice<A>) -> S =
159
- next := s.reduce(a)
160
- q.push(a)
161
- next
147
+ Some(a) => Delivery.actIn<A, S>(s, trail.user(!self.before.same(self.input.held)), a)
148
+ None => Folded(state: s, trail: trail)
149
+ match afterHeld
150
+ Folded(held, heldTrail) => self.tickInto<A, S>(self.stepScreen(held), heldTrail)
151
+
152
+ # The slice `s`, its actors stepped, after its `tick`, delivered.
153
+ fun tickInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>) -> Delivered =
154
+ t := s.tick(self.dt)
155
+ match t
156
+ Some(a) => Delivery.done<A, S>(Delivery.actIn<A, S>(s, trail, a))
157
+ None => Delivery.done<A, S>(Folded(state: s, trail: trail))
158
+
159
+ # The slice `s` after the tick's events from the `i`th on.
160
+ fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, i: Int) -> Folded<S, A> =
161
+ if i >= self.input.events.length()
162
+ Folded(state: s, trail: trail)
163
+ else
164
+ f := self.eventInto<A, S>(s, trail, self.input.events.at(i))
165
+ match f
166
+ Folded(next, after) => self.eventsInto<A, S>(next, after, i + 1)
167
+
168
+ # The slice `s` after the event `e`, mapped to its action; a pointer event while a
169
+ # transition runs is dropped.
170
+ fun eventInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, e: InputEvent) -> Folded<S, A> =
171
+ act := match e.position()
172
+ Some(p) =>
173
+ if self.shifting
174
+ None
175
+ else
176
+ at := self.camera.toWorld(p.x, p.y)
177
+ target := if e.isPointerDown() then Delivery.pressed(s.hud(self.pixels), s.view(), p, at) else None
178
+ pressed := match target
179
+ Some(t) => s.onPress(t, at)
180
+ None => None
181
+ if pressed.isSome() then pressed else s.onPointer(e, at)
182
+ None => s.onKey(e)
183
+ match act
184
+ Some(a) => Delivery.actIn<A, S>(s, trail.user(true), a)
185
+ None => Folded(state: s, trail: trail)
186
+
187
+ # `a` stepped into the slice `s`, with its `then`, as a delivery steps an action: what
188
+ # std/game/TestRig's `dispatch` runs.
189
+ fun dispatchTo<A, S: ScreenSlice<A>>(s: S, a: A) -> Delivered =
190
+ none: Trail<A> := Trail()
191
+ Delivery.done<A, S>(Delivery.actIn<A, S>(s, none, a))
192
+
193
+ # The slice `s` with `a` stepped into it, and then each action of its `then`.
194
+ fun actIn<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, a: A) -> Folded<S, A> =
195
+ n := s.act(a)
196
+ match n
197
+ Next(next, then, cmds) =>
198
+ after := Trail(..trail, actions: Cons(a, trail.actions), cmds: cmds.fold(trail.cmds, |acc, c| Cons(c, acc)))
199
+ Delivery.actAll<A, S>(next, after, then)
200
+
201
+ # The slice `s` with each of `xs` stepped in, in order.
202
+ fun actAll<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, xs: List<A>) -> Folded<S, A> = match xs
203
+ Nil => Folded(state: s, trail: trail)
204
+ Cons(a, rest) =>
205
+ f := Delivery.actIn<A, S>(s, trail, a)
206
+ match f
207
+ Folded(next, after) => Delivery.actAll<A, S>(next, after, rest)
208
+
209
+ # The tick delivered: the slice, its actions and commands in order.
210
+ fun done<A, S: ScreenSlice<A>>(f: Folded<S, A>) -> Delivered = match f
211
+ Folded(s, trail) =>
212
+ sent: List<Dispatched> := trail.actions.fold(Nil, |acc, a| Cons(Sent(action: a), acc))
213
+ Delivered(screen: s, cmds: trail.cmds.reverse(), sent: sent, acted: trail.acted)
std/game/TestRig.plum CHANGED
@@ -14,11 +14,10 @@ import std/math/Aabb
14
14
  import std/game/Input
15
15
  import std/game/Replay
16
16
  import std/game/View
17
- import std/game/Effects
18
17
  import std/game/Sized
19
18
  import std/game/Label
20
19
  import std/game/Viewport
21
- import std/game/Control
20
+ import std/game/Cmd
22
21
  import std/game/Screen
23
22
  import std/game/ScreenSlice
24
23
  import std/game/History
@@ -57,11 +56,11 @@ import std/game/Game
57
56
  # send(e) any `InputEvent`, raw; what is held follows it
58
57
  # next(held, evs) the next tick's input is exactly that
59
58
  #
60
- # `dispatch(a)` dispatches an action to the shown screen as its reducer would, then runs
59
+ # `dispatch(a)` steps an action into the shown screen (the rig's screen) as a delivery
61
- # what ends a tick: its effects with what they ask, an undo, a redo or a rewind included.
60
+ # would (with its `then`), then does what ends a tick: its commands, an undo, a redo or a rewind included.
62
61
  #
63
62
  # Time: `tick()` runs one tick of the game's own path (`Game.step`: the screen's mapping,
64
- # its reducer, the transition, the effects and what they ask of the game), with the input
63
+ # its steps, the transition and the commands they gave), with the input
65
64
  # waiting and what is held; `ticks(n)` runs `n`, the input waiting going to the first.
66
65
  # `tick(dt)` runs one of `dt` seconds instead. `frame(input, frameDt)` is the host's
67
66
  # frame, the `Ticker` turning wall time into ticks, for scripted runs.
@@ -74,8 +73,9 @@ import std/game/Game
74
73
  # `worldOf(actor)` where the view draws it, `toWorld(x, y)` a screen pixel in the world,
75
74
  # `drawn()` what the frame draws (`Game.drawList`).
76
75
  #
77
- # What came out of the last `tick` or `ticks`: `effects<A>()` lists the actions of type `A`
76
+ # What came out of the last `tick` or `ticks`: `actions<A>()` lists the actions of type `A`
77
+ # stepped, in order; `cmds` the commands they gave (std/game/Cmd), in order, as values;
78
- # whose effects ran, in order; `wentTo()` the screen one asked to go to last, `exited()` whether the game has exited.
78
+ # `wentTo()` the screen a `GoTo` asked for last, `exited()` whether the game has exited.
79
79
  # `showing()` names the screen shown. `record(seed)`, `recorded()` and `replay(r)` record
80
80
  # and replay the game (std/game/Replay).
81
81
  #
@@ -84,11 +84,11 @@ import std/game/Game
84
84
  # `stepBack()`, `stepForward()`, `pause()` and `resume()` move the game through it, and
85
85
  # `moved()` says whether the last move could.
86
86
  # A game run headless (see the top of this file): the window's size, what is held, the input
87
- # waiting for the next tick, the pointer, what the last ticks gave (the effects that ran,
87
+ # waiting for the next tick, the pointer, what the last ticks gave (the actions stepped,
88
- # what they asked of the game), and the ticker and recording of `frame` and `record`.
88
+ # the commands they gave), and the ticker and recording of `frame` and `record`.
89
89
  struct TestRig<S>(
90
90
  io: Io, game: Game, screen: S, pixels: Vec2, held: Held, events: List<InputEvent>, pos: Vec2,
91
- ran: List<Effect>, asks: List<Ask>, ticker: Ticker, recording: Bool, log: Replay) =
91
+ sent: List<Dispatched>, cmds: List<Cmd>, ticker: Ticker, recording: Bool, log: Replay) =
92
92
  const DefaultW = 800.0
93
93
 
94
94
  const DefaultH = 600.0
@@ -113,7 +113,7 @@ struct TestRig<S>(
113
113
  pixels := Vec2(x: TestRig.DefaultW, y: TestRig.DefaultH)
114
114
  TestRig(
115
115
  io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
116
- ran: Nil, asks: Nil, ticker: Ticker(), recording: false, log: Replay.create(0))
116
+ sent: Nil, cmds: Nil, ticker: Ticker(), recording: false, log: Replay.create(0))
117
117
 
118
118
  # Stops a test that clicks an actor in neither the view nor the hud.
119
119
  fun notInView() -> Vec2 =
@@ -179,28 +179,22 @@ struct TestRig<S>(
179
179
 
180
180
  fun tickerTicked(self) -> TestRig<S> = TestRig(..self, ticker: self.ticker.ticked())
181
181
 
182
- # Dispatches `a` to the shown screen as its reducer would dispatch it (reduced at once,
182
+ # Steps `a` into the shown screen, which must be the rig's screen, as a delivery steps
183
- # with what its reducer dispatches), then runs what ends a tick: the effects with what
183
+ # an action (with its `then`: std/game/ScreenSlice's `Delivery.dispatchTo`), then does
184
- # they ask of the game, an undo, a redo or a rewind included. What it gave is read as a
184
+ # what ends a tick: its commands, an undo, a redo or a rewind included. What it gave is
185
- # tick's. An `OnDemand` screen is woken for the next tick.
185
+ # read as a tick's. An `OnDemand` screen is woken for the next tick.
186
186
  fun dispatch<A>(self, a: A) -> TestRig<S> =
187
187
  g := self.game
188
188
  match g.screen()
189
- ScreenSlice<A> as sl =>
189
+ S as sl =>
190
- q := Slice<A>()
190
+ d := Delivery.dispatchTo<A, S>(sl, a)
191
- Effects.startDispatch(ActionSink(queue: q))
192
- next := sl.reduce(a)
193
- q.push(a)
194
- Effects.endDispatch()
195
- final: ScreenSlice<A> := next
196
- fx: List<Effect> := List.fromSlice(q).map(|x| Queued.of(final, x))
197
- withScreen := Game(..g, screens: Game.setAt(g.screens, g.current, next), wake: true, dirty: true, ran: Nil, asked: Nil)
191
+ withScreen := Game(..g, screens: Game.setAt(g.screens, g.current, d.screen), wake: true, dirty: true, sent: d.sent, cmds: d.cmds)
198
- TestRig(..self.forget(), game: withScreen).kept(withScreen.apply(self.io, fx).travelAsked(self.io))
192
+ TestRig(..self.forget(), game: withScreen).kept(d.cmds.fold(withScreen, |w, c| w.obey(self.io, c)).travelAsked(self.io))
199
193
  _ =>
200
- crash "headless: dispatch: the screen shown takes no actions of that type"
194
+ crash "headless: dispatch: the screen shown is not the rig's screen"
201
195
 
202
196
  # Forgets what the last ticks gave.
203
- fun forget(self) -> TestRig<S> = TestRig(..self, ran: Nil, asks: Nil)
197
+ fun forget(self) -> TestRig<S> = TestRig(..self, sent: Nil, cmds: Nil)
204
198
 
205
199
  # One tick with the input waiting, keeping what it gave.
206
200
  fun step(self, dt: Float) -> TestRig<S> =
@@ -218,7 +212,7 @@ struct TestRig<S>(
218
212
 
219
213
  # The rig with `g`, keeping what its last tick gave.
220
214
  fun kept(self, g: Game) -> TestRig<S> =
221
- TestRig(..self, game: g, ran: self.ran.append(g.ran), asks: self.asks.append(g.asked)).follow()
215
+ TestRig(..self, game: g, sent: self.sent.append(g.sent), cmds: self.cmds.append(g.cmds)).follow()
222
216
 
223
217
  # The screen is the game's first screen now.
224
218
  fun follow(self) -> TestRig<S> = match self.game.screens.at(0)
@@ -292,12 +286,12 @@ struct TestRig<S>(
292
286
  # A screen pixel in the world's coordinates, through the screen's camera.
293
287
  fun toWorld(self, x: Float, y: Float) -> Vec2 = self.game.toWorld(x, y)
294
288
 
295
- fun effects<A>(self) -> List<A> = Effects.sent<A>(self.ran)
289
+ fun actions<A>(self) -> List<A> = Dispatches.of<A>(self.sent)
296
290
 
297
291
  fun wentTo(self) -> Option<Str> =
298
292
  none: Option<Str> := None
299
- self.asks.fold(none, |w, a| match a
293
+ self.cmds.fold(none, |w, c| match c
300
- AskGoTo(name) => Some(name)
294
+ GoTo(name) => Some(name)
301
295
  _ => w)
302
296
 
303
297
  fun exited(self) -> Bool = self.game.exited
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -16,7 +16,7 @@ import std/game/View
16
16
  import std/game/Box
17
17
  import std/game/Circle
18
18
  import std/game/Label
19
- import std/game/Control
19
+ import std/game/Cmd
20
20
  import std/game/Screen
21
21
  import std/game/ScreenSlice
22
22
  import std/game/Game
@@ -44,10 +44,11 @@ primitive PlaygroundScreenTest[UnitTest] =
44
44
  assert u.screen.balloons.at(0).y < t.screen.balloons.at(0).y
45
45
  assert u.screen.clock == 1.0
46
46
 
47
- # a press on a balloon is a Pop of it, which bursts it and dispatches Popped; a burst one takes no press
47
+ # a press on a balloon is a Pop of it, which bursts it and is followed by Popped, which plays the pop; a burst one takes no press
48
48
  fun aPressOnABalloonIsAPop() =
49
49
  t := PlaygroundScreenHelpers.centred(PlaygroundScreenHelpers.field(io, 3)).clickAt(400.0, 300.0).tick(0.0)
50
- assert PlaygroundScreenHelpers.names(t) == "Popped(0.0) Pop(100) Tick(0.0)"
50
+ assert PlaygroundScreenHelpers.names(t) == "Pop(100) Popped(0.0) Tick(0.0)"
51
+ assert Cmd.names(t.cmds) == "play(-1, 0.9)"
51
52
  assert t.screen.pops == 1
52
53
  assert t.screen.balloons.at(0).popped()
53
54
  u := t.clickAt(400.0, 300.0).tick(0.0)
@@ -58,7 +59,8 @@ primitive PlaygroundScreenTest[UnitTest] =
58
59
  t := PlaygroundScreenHelpers.centred(PlaygroundScreenHelpers.field(io, 3))
59
60
  assert t.hit(50.0, 560.0).isNone()
60
61
  u := t.clickAt(50.0, 560.0).tick(0.0)
61
- assert u.effects<PopAction>().length() == 1
62
+ assert u.actions<PopAction>().length() == 1
63
+ assert u.cmds.isEmpty()
62
64
  assert u.screen.pops == 0
63
65
 
64
66
  fun aPoppedBalloonComesBackAtTheBottom() =
@@ -77,21 +79,19 @@ primitive PlaygroundScreenTest[UnitTest] =
77
79
  assert PlaygroundScreenHelpers.lines(u) == "Yellow!, Hooray!, 10 balloons!, 10"
78
80
  assert !u.tick(PlaygroundScreen.PartyTime + 0.1).screen.partying()
79
81
 
80
- # the game counts pops as they are dispatched and plays one pop a tick, and the fanfare
82
+ # each pop plays the pop sound and the tenth the fanfare too, in the tick of the press
81
- fun theGameCountsPopsAsTheyAreDispatched() =
83
+ fun eachPopPlaysThePopSoundAndThe() =
82
84
  t := PlaygroundScreenHelpers.field(io, 3)
83
85
  f := Range.until(0, 8).fold(t.screen, |s, i| s.popped(-50.0))
84
86
  u := PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.poked(t, f), 0, 200.0, 300.0), 1, 400.0, 300.0), 2, 600.0, 300.0)
85
87
  v := u.clickAt(200.0, 300.0).clickAt(400.0, 300.0).tick()
86
88
  assert v.screen.pops == 10
87
89
  assert v.screen.partying()
88
- assert v.screen.popsHeard == 1
89
- assert v.screen.partiesHeard == 1
90
+ assert Cmd.names(v.cmds) == "play(-1, 0.9) play(-1, 0.9) play(-1, 0.6)"
90
91
  w := v.clickAt(600.0, 300.0).tick()
91
92
  assert w.screen.pops == 11
92
- assert w.screen.popsHeard == 2
93
- assert w.screen.partiesHeard == 1
93
+ assert Cmd.names(w.cmds) == "play(-1, 0.9)"
94
- assert w.tick().screen.popsHeard == 2
94
+ assert w.tick().cmds.isEmpty()
95
95
 
96
96
  # after a resize the press is found through the camera
97
97
  fun afterAResizeThePressIsFoundThrough() =
@@ -113,7 +113,7 @@ primitive PlaygroundScreenTest[UnitTest] =
113
113
  assert {PlaygroundScreen.partyScale(0.65) - 1.4 * 0.85}.abs() < 0.0001
114
114
  assert {PlaygroundScreen.partyScale(1.05) - 1.4}.abs() < 0.0001
115
115
 
116
- # the screen counts pops, every tenth starts a party, and a tick hears them once
116
+ # the screen counts pops, every tenth starts a party, and a pop's step plays its sounds
117
117
  fun theScreenCountsPopsEveryTenthStartsA() =
118
118
  s := Range.until(0, 9).fold(PlaygroundScreenHelpers.field(io, 3).screen, |p, i| p.popped(Float(i)))
119
119
  assert s.pops == 9
@@ -123,11 +123,9 @@ primitive PlaygroundScreenTest[UnitTest] =
123
123
  assert t.partyAt == 12.0
124
124
  assert t.partyingAt(12.0)
125
125
  assert !t.partyingAt(12.0 + PlaygroundScreen.PartyTime + 0.1)
126
- h := t.hear()
126
+ assert Cmd.names(s.act(Popped(at: 12.0)).cmds) == "play(-1, 0.9) play(-1, 0.6)"
127
- assert h.hearPop && h.hearParty
127
+ assert Cmd.names(t.act(Popped(at: 13.0)).cmds) == "play(-1, 0.9)"
128
- h2 := h.hear()
129
- assert !h2.hearPop && !h2.hearParty
128
+ assert Cmd.names(t.act(TakeBack).cmds) == "undo"
130
- assert h2.popsHeard == 1
131
129
 
132
130
  fun aRecordedRunReplaysToTheSameBalloons() =
133
131
  a := Range.until(0, 900).fold(PlaygroundScreenHelpers.field(io, 21).record(21), |r, f| r.frame(PlaygroundScreenHelpers.runInput(f), 0.0166 + Float(f % 3) * 0.004 - 0.004))
@@ -193,11 +191,11 @@ primitive PlaygroundScreenHelpers =
193
191
 
194
192
  fun centred(t: TestRig<PlaygroundScreen>) -> TestRig<PlaygroundScreen> = stillAt(t, 0, 400.0, 300.0)
195
193
 
196
- fun pops(t: TestRig<PlaygroundScreen>) -> List<PopAction> = t.effects<PopAction>().filter(|a| match a
194
+ fun pops(t: TestRig<PlaygroundScreen>) -> List<PopAction> = t.actions<PopAction>().filter(|a| match a
197
195
  Popped(_) => true
198
196
  _ => false)
199
197
 
200
- fun names(t: TestRig<PlaygroundScreen>) -> Str = t.effects<PopAction>().map(|a| a.toStr()).join(" ")
198
+ fun names(t: TestRig<PlaygroundScreen>) -> Str = t.actions<PopAction>().map(|a| a.toStr()).join(" ")
201
199
 
202
200
  fun lines(t: TestRig<PlaygroundScreen>) -> Str = t.find<Label>().map(|l| l.text).join(", ")
203
201
 
tests/examples/games/clicks.plum CHANGED
@@ -12,7 +12,6 @@ import std/game/View
12
12
  import std/game/Box
13
13
  import std/game/Circle
14
14
  import std/game/Label
15
- import std/game/Control
16
15
  import std/game/Screen
17
16
  import std/game/ScreenSlice
18
17
  import std/game/Game
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -17,7 +17,7 @@ import std/game/Box
17
17
  import std/game/Label
18
18
  import std/game/Sprite
19
19
  import std/game/Overlay
20
- import std/game/Control
20
+ import std/game/Cmd
21
21
  import std/game/Screen
22
22
  import std/game/ScreenSlice
23
23
  import std/game/Game
@@ -47,16 +47,17 @@ primitive PlayingScreenTest[UnitTest] =
47
47
  assert t.count<Overlay>() == 0
48
48
  assert t.count<Ring>() == 0
49
49
 
50
- # a tick is Steer with the keys held, then Tick, whose rules dispatch what happened before it is queued
50
+ # a tick is Steer with the keys held, then Tick, whose rules are followed by what happened
51
51
  fun aTickIsSteerWithTheKeysHeld() =
52
52
  t := PlayingScreenHelpers.orbOnShip(PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)).hold(Key.Right).hold(Key.KeyW).tick(0.016)
53
- assert PlayingScreenHelpers.names(t.effects<PlayAction>()) == "Steer(1.0, -1.0) Scored(10) Tick(0.016)"
53
+ assert PlayingScreenHelpers.names(t.actions<PlayAction>()) == "Steer(1.0, -1.0) Tick(0.016) Scored(10)"
54
54
 
55
- # collecting an orb dispatches Scored and respawns it elsewhere, and the HUD shows it
55
+ # collecting an orb is followed by Scored, which plays the pickup, and respawns it elsewhere, and the HUD shows it
56
56
  fun collectingAnOrbDispatchesScoredAndRespawnsIt() =
57
57
  t := PlayingScreenHelpers.orbOnShip(PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)).tick(0.016)
58
58
  out := PlayingScreenHelpers.ruledLast(t)
59
59
  assert PlayingScreenHelpers.names(out) == "Scored(10)"
60
+ assert Cmd.names(t.cmds) == "play(-1, 0.8)"
60
61
  assert t.screen.score == Orb.Points
61
62
  orb := t.screen.orbs.at(0)
62
63
  ship := t.screen.ship
@@ -65,10 +66,11 @@ primitive PlayingScreenTest[UnitTest] =
65
66
  assert t.count<Orb>() == PlayingScreen.OrbCount
66
67
  assert PlayingScreenHelpers.hud(t) == "Score 10, Best 10"
67
68
 
68
- # a mine dispatches Hit, a life icon goes, and the ship blinks while it is hurt
69
+ # a mine is followed by Hit, which plays the hit, a life icon goes, and the ship blinks while it is hurt
69
70
  fun aMineDispatchesHitALifeIconGoes() =
70
71
  t := PlayingScreenHelpers.mineOnShip(PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)).tick(0.016)
71
72
  assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "Hit"
73
+ assert Cmd.names(t.cmds) == "play(-1, 1.0)"
72
74
  assert t.screen.lives == PlayingScreen.StartLives - 1
73
75
  assert PlayingScreenHelpers.icons(t) == PlayingScreen.StartLives - 1
74
76
  assert t.screen.ship.hurt > 0.0
@@ -130,10 +132,11 @@ primitive PlayingScreenTest[UnitTest] =
130
132
  assert q.score == 20
131
133
  assert PlayingScreenHelpers.hud(PlayingScreenHelpers.poked(t, q)) == "Score 20, Best 20"
132
134
 
133
- # the game ends at zero lives, the ship leaves the view, and the keys do nothing
135
+ # the game ends at zero lives, the music stops for the game over sound, the ship leaves the view, and the keys do nothing
134
136
  fun theGameEndsAtZeroLivesTheShip() =
135
137
  t := PlayingScreenHelpers.mineOnShip(PlayingScreenHelpers.emptied(io, 40, 1)).tick(0.016)
136
138
  assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "Hit"
139
+ assert Cmd.names(t.cmds) == "stop(-1) play(-1, 1.0)"
137
140
  assert t.screen.over
138
141
  assert t.screen.lives == 0
139
142
  assert t.screen.best == 40
@@ -230,7 +233,7 @@ primitive PlayingScreenTest[UnitTest] =
230
233
  assert x.screen.best == 50
231
234
  assert x.screen.score == 0
232
235
 
233
- # losing the last life dispatches Hit and ends the run at once, on the same screen
236
+ # losing the last life is a Hit that ends the run at once, on the same screen
234
237
  fun losingTheLastLifeDispatchesHitAndEnds() =
235
238
  t := PlayingScreenHelpers.lastLife(io).tick()
236
239
  assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "Hit"
@@ -240,7 +243,7 @@ primitive PlayingScreenTest[UnitTest] =
240
243
  assert t.count<Overlay>() == 1
241
244
  assert t.showing() == "play"
242
245
 
243
- # while the game over panel shows, Enter or R plays again: the run starts over after the tick
246
+ # while the game over panel shows, Enter or R plays again: StartOver follows it at once and starts the music again
244
247
  fun whileTheGameOverPanelShowsEnterOr() =
245
248
  t := PlayingScreenHelpers.lastLife(io).press(Key.Enter).tick()
246
249
  assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "PlayAgain Hit"
@@ -249,7 +252,8 @@ primitive PlayingScreenTest[UnitTest] =
249
252
  assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(u)) == ""
250
253
  assert u.screen.over
251
254
  v := u.press(Key.Enter).tick()
252
- assert PlayingScreenHelpers.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({Ticker.Tick})"
255
+ assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "PlayAgain StartOver Steer(0.0, 0.0) Tick({Ticker.Tick})"
256
+ assert Cmd.names(v.cmds) == "stop(-1) loop(-1, 0.3)"
253
257
  assert !v.screen.over
254
258
  assert v.screen.score == 0
255
259
  assert v.screen.best == 30
@@ -391,7 +395,7 @@ primitive PlayingScreenHelpers =
391
395
 
392
396
  fun lastLife(io: Io) -> TestRig<PlayingScreen> = mineOnShip(emptied(io, 30, 1))
393
397
 
394
- fun ruledLast(t: TestRig<PlayingScreen>) -> List<PlayAction> = ruled(t.effects<PlayAction>())
398
+ fun ruledLast(t: TestRig<PlayingScreen>) -> List<PlayAction> = ruled(t.actions<PlayAction>())
395
399
 
396
400
  fun isOverlay(hit: Option<View>) -> Bool = match hit
397
401
  Some(a) => match a
tests/examples/games/two_screens.plum CHANGED
@@ -8,7 +8,6 @@ import std/game/Color
8
8
  import std/game/Input
9
9
  import std/game/View
10
10
  import std/game/Label
11
- import std/game/Control
12
11
  import std/game/Screen
13
12
  import std/game/ScreenSlice
14
13
  import std/game/Game
tests/port/game/screens.plum CHANGED
@@ -1,5 +1,5 @@
1
1
  # A game of screens drawn by their views (std/game/Game, ScreenSlice, headless): presses
2
- # hit-tested against the view, actions reduced and their effects run after the tick,
2
+ # hit-tested against the view, actions stepped and their commands done after the tick,
3
3
  # navigation, transitions, frames on demand, record and replay, undo and rewind, the
4
4
  # actors stepped by the game, a screen's hud and its camera.
5
5
  import std/Int
@@ -25,7 +25,7 @@ import std/game/Touch
25
25
  import std/game/Label
26
26
  import std/game/Overlay
27
27
  import std/game/Viewport
28
- import std/game/Control
28
+ import std/game/Cmd
29
29
  import std/game/Screen
30
30
  import std/game/ScreenSlice
31
31
  import std/game/Game
@@ -107,7 +107,6 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
107
107
  fun reduce(self, a: ProbeAct) -> ProbeScreen = match a
108
108
  Pressed(on) => ProbeScreen(..self, hits: self.hits.append([on]))
109
109
  Missed => ProbeScreen(..self, misses: self.misses + 1)
110
- Keyed => ProbeScreen(..self, keys: self.keys + 1, left: 3).dispatch(Echo)
111
110
  Echo => ProbeScreen(..self, echoes: self.echoes + 1)
112
111
  Ticked(_) => ProbeScreen(..self, ticks: self.ticks + 1, left: {self.left - 1}.max(0))
113
112
  Roll =>
@@ -115,10 +114,11 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
115
114
  ProbeScreen(..self, rng: r.rng, roll: r.value)
116
115
  _ => self
117
116
 
118
- fun effect(self, io: Io, a: ProbeAct, game: Control) = match a
117
+ fun act(self, a: ProbeAct) -> Next<ProbeScreen, ProbeAct> = match a
118
+ Keyed => Next(state: ProbeScreen(..self, keys: self.keys + 1, left: 3), then: [Echo])
119
- GoPlay => game.goTo("play")
119
+ GoPlay => Next(state: self, cmds: [GoTo(name: "play")])
120
- Quit => game.exit()
120
+ Quit => Next(state: self, cmds: [Exit])
121
- _ => Unit
121
+ _ => Next(state: self.reduce(a))
122
122
 
123
123
  primitive Screens =
124
124
  # The group turned a quarter.
@@ -169,14 +169,11 @@ struct PlayProbe[ScreenSlice<ProbeAct>](presses: Int, ticks: Int) =
169
169
 
170
170
  fun tick(self, dt: Float) -> Option<ProbeAct> = Some(Ticked(dt: dt))
171
171
 
172
- fun reduce(self, a: ProbeAct) -> PlayProbe = match a
172
+ fun act(self, a: ProbeAct) -> Next<PlayProbe, ProbeAct> = match a
173
- Ticked(_) => PlayProbe(..self, ticks: self.ticks + 1)
173
+ Ticked(_) => Next(state: PlayProbe(..self, ticks: self.ticks + 1))
174
- Missed => PlayProbe(..self, presses: self.presses + 1)
174
+ Missed => Next(state: PlayProbe(..self, presses: self.presses + 1))
175
- _ => self
176
-
177
- fun effect(self, io: Io, a: ProbeAct, game: Control) = match a
178
- Back => game.goTo("probe")
175
+ Back => Next(state: self, cmds: [GoTo(name: "probe")])
179
- _ => Unit
176
+ _ => Next(state: self)
180
177
 
181
178
  # A walker that moves right `speed` a second, stepped by the game.
182
179
  struct Walker[Actor](x: Float, speed: Float) =
@@ -186,7 +183,7 @@ struct Walker[Actor](x: Float, speed: Float) =
186
183
 
187
184
  fun step(self, dt: Float) -> Walker = Walker(..self, x: self.x + self.speed * dt)
188
185
 
189
- enum WalkAct = Saw(x: Float) | Walked(dt: Float) | Undo | Pause | Follow | HudPressed
186
+ enum WalkAct = Saw(x: Float) | Walked(dt: Float) | TakeBack | Pause | Follow | HudPressed
190
187
 
191
188
  # A screen of one walker: `held` notes where it is before the step and the tick action
192
189
  # after it; P pauses the stepping, F has the camera follow the walker, two times as
@@ -215,7 +212,7 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
215
212
  fun onPress(self, target: View, at: Vec2) -> Option<WalkAct> = Some(HudPressed)
216
213
 
217
214
  fun onKey(self, e: InputEvent) -> Option<WalkAct> = match e
218
- KeyDown(k) => if k == Key.KeyP then Some(Pause) else if k == Key.KeyF then Some(Follow) else if k == Key.KeyU then Some(Undo) else None
215
+ KeyDown(k) => if k == Key.KeyP then Some(Pause) else if k == Key.KeyF then Some(Follow) else if k == Key.KeyU then Some(TakeBack) else None
219
216
  _ => None
220
217
 
221
218
  fun reduce(self, a: WalkAct) -> WalkScreen = match a
@@ -224,11 +221,11 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
224
221
  Pause => WalkScreen(..self, paused: true)
225
222
  Follow => WalkScreen(..self, follow: true)
226
223
  HudPressed => WalkScreen(..self, hudPresses: self.hudPresses + 1)
227
- Undo => self
224
+ TakeBack => self
228
225
 
229
- fun effect(self, io: Io, a: WalkAct, game: Control) = match a
226
+ fun act(self, a: WalkAct) -> Next<WalkScreen, WalkAct> = match a
227
+ TakeBack => Next(state: self, cmds: [Undo])
230
- Undo => game.undo()
228
+ _ => Next(state: self.reduce(a))
231
- _ => Unit
232
229
 
233
230
  # A screen with no rules holding a walker: the game steps it all the same.
234
231
  struct StillScreen[Screen](walker: Walker) =
@@ -281,13 +278,22 @@ primitive ScreensTest[UnitTest] =
281
278
  u := t.press(Key.KeyA).tick()
282
279
  assert u.text(u.first<Label>()) == "keys 1"
283
280
 
284
- # a reducer's own dispatch is reduced at once and queued before the action reducing it
281
+ # the actions a step gives as `then` are stepped right after it, before the next action
285
- fun aReducersOwnDispatchIsReducedAtOnce() =
282
+ fun aStepsThenIsSteppedRightAfterIt() =
286
283
  t := Screens.probe(io).press(Key.KeyA).tick()
287
284
  assert t.screen.echoes == 1
288
- assert Screens.names(t.effects<ProbeAct>()) == "Echo Keyed Ticked"
285
+ assert Screens.names(t.actions<ProbeAct>()) == "Keyed Echo Ticked"
289
- s := ProbeScreen.create(Always).reduce(Keyed)
286
+ n := ProbeScreen.create(Always).act(Keyed)
287
+ assert n.state.keys == 1 && n.state.echoes == 0
288
+ assert Screens.names(n.then) == "Echo"
289
+ assert n.cmds.isEmpty()
290
+
291
+ # a step's commands are values, done after the tick and read back in order
292
+ fun aStepsCommandsAreReadBackInOrder() =
293
+ t := TestRig.play(io, Screens.twoScreens()).press(Key.KeyG).press(Key.KeyQ).tick()
294
+ assert Cmd.names(t.cmds) == "goTo(play) exit"
290
- assert s.echoes == 1
295
+ assert t.exited()
296
+ assert Cmd.names(ProbeScreen.create(Always).act(Quit).cmds) == "exit"
291
297
 
292
298
  # press gives one key down, hold steers every tick, ticks(n) is n ticks
293
299
  fun pressGivesOneKeyDownHoldSteersEvery() =
@@ -298,7 +304,7 @@ primitive ScreensTest[UnitTest] =
298
304
  assert u.held.isDown(Key.KeyA)
299
305
  assert !u.release(Key.KeyA).held.isDown(Key.KeyA)
300
306
 
301
- # effects go to another screen, which fades in, its presses dropped until it is in; the old one is kept and resumes
307
+ # a command goes to another screen, which fades in, its presses dropped until it is in; the old one is kept and resumes
302
308
  fun effectsGoToAnotherScreenWhichFadesIn() =
303
309
  t := TestRig.play(io, Screens.twoScreens()).press(Key.KeyG).tick()
304
310
  assert t.wentTo().unwrap() == "play"
@@ -402,11 +408,11 @@ primitive ScreensTest[UnitTest] =
402
408
  assert Math.near(u.toWorld(0.0, 300.0).x, 120.0 - 200.0, 0.000001)
403
409
  assert u.game.visible(0).min.x == u.toWorld(0.0, 0.0).x
404
410
 
405
- # the kit's dispatch does an undo its effect asks for at once
411
+ # the kit's dispatch does an undo its step asks for at once
406
412
  fun theKitsDispatchDoesAnUndoItsEffect() =
407
413
  t := TestRig.mountWith(io, WalkScreen.create()).press(Key.KeyP).ticks(3)
408
414
  assert t.screen.paused && t.game.tickNow() == 3
409
- u := t.dispatch(Undo)
415
+ u := t.dispatch(TakeBack)
410
416
  assert u.moved()
411
417
  assert !u.screen.paused
412
418
  assert u.game.tickNow() == 0
tests/std/game/Cmd.plum ADDED
@@ -0,0 +1,20 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Bool
5
+ import std/collections/List
6
+ import std/game/Audio
7
+ import std/game/Cmd
8
+ import std/Test
9
+
10
+ primitive CmdTest[UnitTest] =
11
+ fun commandsAreValuesThatNameThemselves() =
12
+ cmds: List<Cmd> := [GoTo(name: "play"), Exit, Undo, Redo, RewindTo(tick: 12), Play(sound: Sound.Silent, volume: 0.5), Loop(sound: Sound(id: 3), volume: 1.0), Stop(sound: Sound(id: 3))]
13
+ assert Cmd.names(cmds) == "goTo(play) exit undo redo rewindTo(12) play(-1, 0.5) loop(3, 1.0) stop(3)"
14
+ assert cmds.filter(|c| c.travels()).length() == 3
15
+
16
+ fun aSilentSoundsCommandsCallNoHost() =
17
+ Play(sound: Sound.Silent, volume: 1.0).sound(io)
18
+ Loop(sound: Sound.Silent, volume: 1.0).sound(io)
19
+ Stop(sound: Sound.Silent).sound(io)
20
+ Exit.sound(io)
tests/std/game/Control.plum DELETED
@@ -1,19 +0,0 @@
1
- import std/Int
2
- import std/Str
3
- import std/Bool
4
- import std/Slice
5
- import std/collections/List
6
- import std/game/Control
7
- import std/Test
8
-
9
- primitive ControlTest[UnitTest] =
10
- fun aControlKeepsWhatWasAskedInOrder() =
11
- c := Control.create()
12
- c.goTo("play")
13
- c.exit()
14
- c.undo()
15
- c.redo()
16
- c.rewindTo(12)
17
- asked := c.take()
18
- assert asked.map(|a| a.toStr()).fold("", |s, x| if s == "" then x else "{s} {x}") == "goTo(play) exit undo redo rewindTo(12)"
19
- assert asked.map(|a| if a.travels() then 1 else 0).fold(0, |n, x| n + x) == 3
tests/std/game/History.plum CHANGED
@@ -5,7 +5,6 @@ import std/Str
5
5
  import std/collections/List
6
6
  import std/math/Vec2
7
7
  import std/game/Input
8
- import std/game/Control
9
8
  import std/game/History
10
9
  import std/Test
11
10
 
@@ -69,4 +68,4 @@ primitive HistoryHelpers =
69
68
  TravelRedo => "redo"
70
69
 
71
70
  fun tick(user: Bool) -> HistoryTick =
72
- HistoryTick(input: Input.create(), pixels: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user, asks: Nil)
71
+ HistoryTick(input: Input.create(), pixels: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user)
tests/std/game/Screen.plum CHANGED
@@ -12,8 +12,6 @@ import std/game/Color
12
12
  import std/game/Input
13
13
  import std/game/View
14
14
  import std/game/Viewport
15
- import std/game/Control
16
- import std/game/Effects
17
15
  import std/game/ScreenSlice
18
16
  import std/game/Screen
19
17
  import std/Test
tests/traits/covariance.plum CHANGED
@@ -5,7 +5,7 @@ import std/Option
5
5
  import std/collections/List
6
6
 
7
7
  # Immutable containers are covariant over a trait (a `List<Sq>` is a `List<Shape>`, an
8
- # `Option<Sq>` an `Option<Shape>`), and the expected type flows into literals, branches
8
+ # `Option<Sq>` an `Option<Shape>`, a `Held<Sq, Int>` a `Held<Shape, Int>`), and the expected type flows into literals, branches
9
9
  # and calls, so none of these values is annotated.
10
10
 
11
11
  trait Shape =
@@ -30,6 +30,9 @@ struct Rect[Solid, Marked](w: Int, h: Int) =
30
30
  struct Dot[Shape](r: Int) =
31
31
  fun area(self) -> Int = self.r
32
32
 
33
+ # A struct with no `mut` field, covariant in `S`.
34
+ struct Held<S, A>(state: S, more: List<S> = Nil, tag: A)
35
+
33
36
  primitive Shapes =
34
37
  fun total(xs: List<Shape>) -> Int = xs.fold(0, |acc, x| acc + x.area())
35
38
 
@@ -49,6 +52,12 @@ primitive Shapes =
49
52
 
50
53
  fun many(n: Int, acc: List<Sq>) -> List<Sq> = if n == 0 then acc else Shapes.many(n - 1, Cons(Sq(k: 1), acc))
51
54
 
55
+ fun heldArea(h: Held<Shape, Int>) -> Int = h.state.area() + Shapes.total(h.more) + h.tag
56
+
57
+ fun heldSquare(k: Int) -> Held<Sq, Int> = Held(state: Sq(k: k), more: [Sq(k: 1)], tag: 100)
58
+
59
+ fun heldShape(k: Int) -> Held<Shape, Int> = Shapes.heldSquare(k)
60
+
52
61
  fun pick(c: Bool) -> Shape =
53
62
  s := if c then Sq(k: 2) else Dot(r: 3)
54
63
  s
@@ -103,3 +112,10 @@ primitive CovarianceTest[UnitTest] =
103
112
 
104
113
  fun aLongListIsUpcastInALoop() =
105
114
  assert Shapes.total(Shapes.many(100000, Nil)) == 100000
115
+
116
+ fun aStructIsUpcastFieldByField() =
117
+ assert Shapes.heldArea(Shapes.heldSquare(3)) == 110
118
+ assert Shapes.heldArea(Shapes.heldShape(2)) == 105
119
+ h := Held(state: Rect(w: 2, h: 3), tag: 0)
120
+ assert Shapes.heldArea(h) == 6
121
+ assert h.state.depth() == 2