plum

#treesitter#compiler#wasm

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

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


c151e44 — Peter John 2026-11-16T16:45:31+05:30
master's games ported: examples/games/clockwork (Clockwork.plum, screens/OrreryScreen, actors/Orbit, Spinner, Walker; master's sprites.png) and examples/games/menu (Menu.plum, screens/MenuScreen, TurnScreen, actors/Turner), in this branch's style, the same rules and look: an orbit (`Orbit[Actor, Steps](hub: Body, reach, planet: Spinner, moons: List<Orbit>)`, no `step` of its own), a planet or moon (`Spinner`, its clock) and a walker (a `Body` with a `Wrap` edge) move by `Body`s stepped through the derive; presses say what they mean (`Presses<SkyAction>`: `Pick(body)` by id, `Front(walker)` then `Pick(-1)`), Space pauses by `@stepsWhen(!self.paused)` on the stepped fields (the pausing tick steps nothing, as on master), the minimap's spots worked out from the orbits when the hud is made (`Orbit.spots`); the menu's items are `Button`s, choosing a `GoTo(play)` or `Exit` command, its square turned by a `Body`; `[Show]` on the actions. Compiler fix: `[Show]` on an enum whose variant the loader renamed in a clash (both menu screens declare `Tick`, so one is `Tick@..`) wrote the renamed name into the text it parses and panicked; the arms now show the source name and the patterns get the renamed one (tests/modules/shown_variant.plum, beat.plum). Tests: tests/examples/games/clockwork (actors and screen: 22, a recorded 400-frame run replays, its checksum 294124446 pinned, a rewind to its middle), tests/examples/games/menu (10: sleeping, sliding, choosing, clicking, Play and Escape through the whole game, an idle recording, a rewind); compiler/cli replay check records all four games; web-test: Clockwork renders and animates, the menu sleeps until a key (`on_demand_and_travel`). Docs: game.md (Try it, Beside master), backlog (item gone), web-test README
compiler/cli/src/replay.rs CHANGED
@@ -112,7 +112,7 @@ mod tests {
112
112
  /// seed is the clock's: a failure keeps the recording (`keepRecording`) and says where.
113
113
  #[test]
114
114
  fn eachExampleGameReplaysARecordedRun() {
115
- for name in ["orbitrunner/OrbitRunner.plum", "balloonpop/BalloonPop.plum"] {
115
+ for name in ["orbitrunner/OrbitRunner.plum", "balloonpop/BalloonPop.plum", "clockwork/Clockwork.plum", "menu/Menu.plum"] {
116
116
  let (wasm, assets) = exampleWasm(name);
117
117
  let (text, recorded) = record(&wasm, &assets, 600);
118
118
  let (ticks, replayed) = match runReplay(&wasm, assets.clone(), &text) {
compiler/core/src/show_derive.rs CHANGED
@@ -12,7 +12,8 @@
12
12
  //! Hit => "Hit"
13
13
  //!
14
14
  //! A struct's is `"Name({self.a}, {self.b})"`, and one with no fields is its name. A type
15
- //! that writes its own `toStr` keeps it.
15
+ //! that writes its own `toStr` keeps it. A variant the loader renamed in a clash (`Tick@menu`,
16
+ //! as two files declare `Tick`) is shown by the name it was written with (`Tick(..)`).
16
17
  //!
17
18
  //! Error, at the type: a field whose type is a struct or an enum of the program that has no
18
19
  //! `toStr` and doesn't list `Show` (it couldn't be put in the string).
@@ -20,6 +21,8 @@
20
21
  use crate::ast::*;
21
22
  use crate::diag::{DiagKind, Diagnostic};
22
23
  use crate::main_result::parseItems;
24
+ use crate::modules::sourceFnName;
25
+ use std::collections::HashMap;
23
26
 
24
27
  /// The trait a type lists to have its `toStr` derived.
25
28
  pub const SHOW_TRAIT: &str = "Show";
@@ -87,21 +90,31 @@ pub fn deriveShow(source: &mut Source) -> Vec<Diagnostic> {
87
90
  .variants
88
91
  .iter()
89
92
  .map(|v| {
93
+ let shown = sourceFnName(&v.name);
90
94
  if v.fields.is_empty() {
91
- format!(" {} => \"{}\"", v.name, v.name)
95
+ format!(" {shown} => \"{shown}\"")
92
96
  } else {
93
97
  let binds: Vec<String> = (0..v.fields.len()).map(|i| format!("v{i}")).collect();
94
98
  let parts: Vec<String> = binds.iter().map(|b| format!("{{{b}}}")).collect();
95
- format!(" {}({}) => \"{}({})\"", v.name, binds.join(", "), v.name, parts.join(", "))
99
+ format!(" {shown}({}) => \"{shown}({})\"", binds.join(", "), parts.join(", "))
96
100
  }
97
101
  })
98
102
  .collect();
99
103
  format!("match self\n{}", arms.join("\n"))
100
104
  };
101
105
  let text = format!("struct {name}{gens} =\n fun toStr(self) -> Str = {body}\n");
106
+ let renamed: HashMap<String, String> =
107
+ e.variants.iter().filter(|v| sourceFnName(&v.name) != v.name).map(|v| (sourceFnName(&v.name).to_string(), v.name.clone())).collect();
102
108
  for it in parseItems(&text, &e.file) {
103
- if let Item::Fn(f) = it {
109
+ if let Item::Fn(mut f) = it {
104
110
  if f.type_param.as_deref() == Some(name.as_str()) {
111
+ if !renamed.is_empty() {
112
+ match &mut f.body {
113
+ FnBody::Block(b) => renamePatterns(b, &renamed),
114
+ FnBody::Expr(x) => crate::visit::innerBlocks(x, &mut |b| renamePatterns(b, &renamed)),
115
+ FnBody::Extern => {}
116
+ }
117
+ }
105
118
  made.push(Item::Fn(f));
106
119
  }
107
120
  }
@@ -110,3 +123,24 @@ pub fn deriveShow(source: &mut Source) -> Vec<Diagnostic> {
110
123
  source.items.extend(made);
111
124
  errors
112
125
  }
126
+
127
+ /// Gives each pattern of the derived `match` that names a renamed variant by its source name
128
+ /// the variant's renamed one (`Tick` to `Tick@menu`): the text the derive parses can't spell it.
129
+ fn renamePatterns(b: &mut Block, renamed: &HashMap<String, String>) {
130
+ for s in &mut b.stmts {
131
+ if let StmtKind::Match(m) = &mut s.kind {
132
+ for case in &mut m.cases {
133
+ for p in &mut case.patterns {
134
+ if let CasePattern::Class { name, .. } | CasePattern::Name(name) = p {
135
+ if let Some(global) = renamed.get(name.as_str()) {
136
+ *name = global.clone();
137
+ }
138
+ }
139
+ }
140
+ }
141
+ }
142
+ for e in crate::visit::stmtExprs(s) {
143
+ crate::visit::innerBlocks(e, &mut |inner| renamePatterns(inner, renamed));
144
+ }
145
+ }
146
+ }
compiler/game/web-test/README.md CHANGED
@@ -25,4 +25,4 @@ Options: `--browser chromium|webkit` (default chromium; WebKit is Playwright's S
25
25
  Exit code is non-zero with a message on failure.
26
26
 
27
27
  `cargo test --manifest-path compiler/game/web-test/Cargo.toml` runs the same check on
28
- `examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs, Orbit Runner with `--stall-adapter`, and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there), and `examples/games/two_screens.plum`'s `OnDemand` title (the page counts its frames through `__plumDrawLog`: once idle it runs no frame for a second, a key wakes it for a drawn frame and it sleeps again; then, as `plum run --dev` serves it, its history line is drawn and `\` pauses it and `[` steps it back a tick); each skips with a note if its browser is not installed. The checks take turns, one browser at a time: several software-WebGPU browsers at once starve each other of frames.
28
+ `examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum`, `examples/games/clockwork/Clockwork.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs, Orbit Runner with `--stall-adapter`, and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there), and the `OnDemand` first screens of `examples/games/two_screens.plum` and `examples/games/menu` (each page counts its frames through `__plumDrawLog`: once idle it runs no frame for a second, a key wakes it for a drawn frame and it sleeps again; then, as `plum run --dev` serves it, its history line is drawn and `\` pauses it and `[` steps it back a tick); each skips with a note if its browser is not installed. The checks take turns, one browser at a time: several software-WebGPU browsers at once starve each other of frames.
compiler/game/web-test/tests/web_check.rs CHANGED
@@ -17,6 +17,11 @@ fn balloon_pop_renders_and_animates() {
17
17
  orb_run("examples/games/balloonpop/BalloonPop.plum");
18
18
  }
19
19
 
20
+ #[test]
21
+ fn clockwork_renders_and_animates() {
22
+ orb_run("examples/games/clockwork/Clockwork.plum");
23
+ }
24
+
20
25
  #[test]
21
26
  fn state_view_renders_and_animates() {
22
27
  orb_run("compiler/game/web-test/fixtures/stress_state_view.plum");
@@ -211,3 +216,16 @@ fn an_idle_page_sleeps_and_a_dev_run_travels() {
211
216
  let report = rt.block_on(plum_web_test::on_demand_and_travel(&repo_root().join("examples/games/two_screens.plum"))).unwrap_or_else(|e| panic!("{e}"));
212
217
  println!("{report}");
213
218
  }
219
+
220
+ /// The menu example's `OnDemand` menu, the same way: drawn, asleep, woken by a key, asleep again.
221
+ #[test]
222
+ fn the_menu_sleeps_until_a_key() {
223
+ if !chromium_installed() {
224
+ eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
225
+ return;
226
+ }
227
+ let _one = one_browser();
228
+ let rt = tokio::runtime::Runtime::new().unwrap();
229
+ let report = rt.block_on(plum_web_test::on_demand_and_travel(&repo_root().join("examples/games/menu/Menu.plum"))).unwrap_or_else(|e| panic!("{e}"));
230
+ println!("{report}");
231
+ }
docs/backlog.md CHANGED
@@ -11,7 +11,6 @@ The retained scene tree was replaced by master's screen view in functional form:
11
11
  - **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).
12
12
  - **What std's delivery fold still copies** (the screen is in place since 2026-11-16, `@copy` in `Delivery.deliverTo`; since the Elm-style screens, Orbit Runner's `PlayingScreen.update` 5 (steer, the frame's spread after `stepped`, scored, hit and start over, whose `best` is read before the spread now), `rules`, `deal`, `grown`, `at` and the derived `stepped`: 29 spreads in place, 27 before; a call on a receiver of a bounded type parameter, `s.update(a)` with `S: ScreenSlice<A>`, is stamped with the bound in the analysis' copy of the body and resolves among its implementers, where it resolved to every `update` of the program, `Game.update` and `Viewport.update` among them): an update that reads `self` again after a spread of it copies (Orbit Runner reads its sounds first, `sounds := self.assets`); a screen fold whose result `passes` can't follow (`Range.fold` over the screen; Orbit Runner's `deal` folds a `Rolled<List<Orb>>` instead); Balloon Pop's `update`, one spread in place, the others copies, as its `view` keeps `self` (`s.view()` in `eventInto` then shares the copy) and its frame action spreads inside a fold's closure; an orb's and a mine's `step` (R3: one spread of `self`, the head of the list it is stepped in, `List.head`, which std's read-only walks `List.all`, `filter` and `next` hand to closures and results, and `Ticker.input` binds out of a field read; the screen's `mines` and `orbs` are also handed to the view's upcasts). The proof the fold needed: read-only parameters through calls (`readOnlyParams`: a screen's `view` hands `self` to the fused copies of its closures), a field taken out of a fresh value (rechecked by `analyse` when the field turns out shared), a value stored beside reads of itself (`Next(state: self, then: [if self.over ..])`), a local used once standing for its value in `passes`. The cost: the in-place pass takes about 2.5 times as long (debug, Orbit Runner 183 to 480 ms): 9 version rounds where there were 5, each about 30% dearer.
13
13
  - **A program with no `Sized` or `Touch` view drops the dead code pass**: std's `Views.touchOf`, `sizedHit` and `missesArea` match `Touch as t` and `Sized as s` on a `View`, and once the pass has dropped every type that is one, the re-check calls each match impossible ("no type is both a View and a Touch"). Every game has such a view, so only a minimal test program meets it. A trait default's copy is told apart since 2026-11-16 (`defaultPositions` reads the trait's declarations), but these are statics.
14
- - **Master's other games** (`clockwork`, `menu`) are not ported.
15
14
  - **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
16
15
  - **Stepping without the screen naming its actors**: done at compile time on 2026-11-16: every screen, and an actor that lists `Steps` (std/game/View), has its fields holding actors stepped by a derived `stepped` (or after its own `step`); since the Elm-style screens a screen calls it in its frame action (no stepping phase, no `steps()`), one field paused by `@stepsWhen(cond)` (`docs/game.md`, "Stepping"). A `List<View>` field is stepped by `Views.stepIn` since R3 (each item's type tested as it is stepped).
17
16
 
docs/game.md CHANGED
@@ -10,7 +10,7 @@ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It
10
10
  plum run examples/games/orbitrunner/OrbitRunner.plum
11
11
  ```
12
12
 
13
- This builds the game, starts a local server and opens your browser. `plum run examples/games/orbitrunner` does the same: given a folder, `plum run`, `plum build` and `plum compile` take the one `.plum` file in it with the program's `[App]` primitive, which holds its `main` (none, or more than one, is an error that says so). Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back.
13
+ This builds the game, starts a local server and opens your browser. `plum run examples/games/orbitrunner` does the same: given a folder, `plum run`, `plum build` and `plum compile` take the one `.plum` file in it with the program's `[App]` primitive, which holds its `main` (none, or more than one, is an error that says so). Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back. In `examples/games/clockwork` planets and moons turn about a sun: click one to light it and name it, Space stops and starts the sky, and a click on a walker brings it to the front. `examples/games/menu` is a menu that sleeps until you press a key (Up, Down, Enter, or a click), and its Play fades into a turning square that Escape leaves.
14
14
 
15
15
  ## A game's files
16
16
 
@@ -535,7 +535,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
535
535
 
536
536
  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)`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), no `restart`, pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, frames on demand in the hosts (`frameIdle`, the browser waiting for input, `PlumGame::idle`), `plum run --dev` (its keys, its line, the page's Cmd key fixes), and `plum compile <folder>`. Orbit Runner's state checksum was master's (925878360) until its rules returned what happened as `then` actions (the mines are checked before more are added for the tick's points, and a restart starts at once), 946756219 then, 818414470 since the Elm-style screens (the subscriptions are read once a tick, so the tick Enter restarts on steers nothing), and 181767343 since the rules (counter-based draws, so every spawn lands elsewhere; each orb caught is its own action).
537
537
 
538
- 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.
538
+ Master's `clockwork` and `menu` games are ported, in this branch's style rather than line for line, the same rules and look. Clockwork (`examples/games/clockwork`): an orbit, a planet or moon and a walker each move by a `Body` that `[Steps]` steps (an orbit's moons are its `List<Orbit>`, stepped through the derive, where master's `Orbit` stepped its children with `stepIn`); a press on a body or a walker says what it means (`Presses<SkyAction>`), so the screen tells them apart by an id, not by reference (`@sameRef`); Space pauses with `@stepsWhen(!self.paused)` on the stepped fields; the minimap's spots are worked out from the orbits when the hud is made (`Orbit.spots`), where master kept them in a field each tick; a walker wraps round by its body's `Wrap` edge, keeping the distance it went past. The menu (`examples/games/menu`): `Button`s say what a press means, choosing is a `GoTo` or `Exit` command, and the square of the second screen turns by a `Body`. Both have their tests in the `tests/` mirror, a recorded run each and Clockwork's state checksum among them. This branch keeps `examples/games/clicks.plum` and `two_screens.plum`, which master doesn't have.
539
539
 
540
540
  ## Publishing
541
541
 
examples/games/clockwork/Clockwork.plum ADDED
@@ -0,0 +1,34 @@
1
+ module clockwork
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Io
6
+ import std/Str
7
+ import std/collections/List
8
+ import std/game/Gfx
9
+ import std/game/Screen
10
+ import std/game/Game
11
+ import std/App
12
+ import screens/OrreryScreen
13
+
14
+ primitive Arena =
15
+ const W = 800.0
16
+ const H = 600.0
17
+ const CentreX = 400.0
18
+ const CentreY = 300.0
19
+
20
+ primitive Sheet =
21
+ const Cell = 16.0
22
+ const MapW = 160.0
23
+ const MapH = 120.0
24
+ const MapScale = 0.2
25
+
26
+ struct Assets(sheet: Texture) =
27
+ fun load(io: Io) -> Assets = Assets(sheet: Texture.load(io, "sprites.png"))
28
+
29
+ fun none() -> Assets = Assets(sheet: Texture.none())
30
+
31
+ primitive Clockwork[App] =
32
+ fun main(io: Io) -> Game =
33
+ sky: Screen := OrreryScreen.start(Assets.load(io))
34
+ Game(screens: [sky])
examples/games/clockwork/actors/Orbit.plum ADDED
@@ -0,0 +1,40 @@
1
+ module clockwork_orbit
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/collections/List
7
+ import std/math/Vec2
8
+ import std/math/Affine
9
+ import std/game/Place
10
+ import std/game/Body
11
+ import std/game/View
12
+ import std/game/Group
13
+ import Clockwork
14
+ import actors/Spinner
15
+
16
+ struct Orbit[Actor, Steps](hub: Body, reach: Float, planet: Spinner, moons: List<Orbit> = Nil) =
17
+ fun chart(i: Int, id: Int, name: Str, moons: Int, tex: Texture) -> Orbit =
18
+ Orbit(
19
+ hub: Body(pos: Vec2(x: Arena.CentreX, y: Arena.CentreY), turn: 0.9 / Float(1 + i)), reach: 90.0 + Float(i) * 60.0,
20
+ planet: Spinner.make(id, name, 2, i, 40.0, 1.5, tex),
21
+ moons: Range.until(0, moons).map(|m| Orbit(
22
+ hub: Body(pos: Vec2.Zero, turn: 2.0 + Float(m)), reach: 36.0 + Float(m) * 16.0,
23
+ planet: Spinner.make(id + 1 + m, "{name} moon {m + 1}", 1, m, 18.0, 3.0, tex))))
24
+
25
+ fun place(self) -> Place = self.hub.place(Vec2.Zero)
26
+
27
+ fun view(self) -> List<View> = [
28
+ Group(x: self.reach) {
29
+ self.planet
30
+ ..self.moons
31
+ }
32
+ ]
33
+
34
+ fun lit(self, id: Int) -> Orbit = Orbit(..self, planet: self.planet.light(id), moons: self.moons.map(|m| m.lit(id)))
35
+
36
+ fun spots(self, m: Affine) -> List<Spot> =
37
+ arm := Place.at(self.reach, 0.0).under(self.place().under(m))
38
+ self.moons.fold([Spot(spinner: self.planet, at: arm.apply(Vec2.Zero))], |all, o| all.append(o.spots(arm)))
39
+
40
+ struct Spot(spinner: Spinner, at: Vec2)
examples/games/clockwork/actors/Spinner.plum ADDED
@@ -0,0 +1,52 @@
1
+ module clockwork_spinner
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/collections/List
8
+ import std/math/Aabb
9
+ import std/math/Vec2
10
+ import std/math/Math
11
+ import std/game/Color
12
+ import std/game/Place
13
+ import std/game/Body
14
+ import std/game/View
15
+ import std/game/Circle
16
+ import std/game/Sprite
17
+ import std/game/Sized
18
+ import std/game/Touch
19
+ import std/game/Button
20
+ import Clockwork
21
+ import screens/OrreryScreen
22
+
23
+ struct Spinner[Actor, Sized, Touch, Presses<SkyAction>, Steps](
24
+ id: Int, name: Str, size: Float, body: Body, tex: Texture, srcX: Float = 0.0, srcY: Float = 0.0, fps: Float = 0.0, frames: Int = 1,
25
+ clock: Float = 0.0, lit: Bool = false) =
26
+ fun make(id: Int, name: Str, row: Int, frame: Int, size: Float, spin: Float, tex: Texture) -> Spinner =
27
+ Spinner(id: id, name: name, size: size, body: Body(pos: Vec2.Zero, turn: spin), tex: tex, srcX: Float(frame) * Sheet.Cell, srcY: Float(row) * Sheet.Cell)
28
+
29
+ fun place(self) -> Place = self.body.place(Vec2(x: self.size / 2.0, y: self.size / 2.0))
30
+
31
+ fun halo(self) -> Float = self.size * 0.8
32
+
33
+ fun view(self) -> List<View> =
34
+ c := self.size / 2.0
35
+ [
36
+ if self.lit then Circle(x: c, y: c, r: self.halo(), color: Color(r: 1.0, g: 0.9, b: 0.5, a: 0.35))
37
+ Sprite(tex: self.tex, w: self.size, h: self.size, srcX: self.srcX, srcY: self.srcY, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, self.fps, self.frames))
38
+ ]
39
+
40
+ fun light(self, id: Int) -> Spinner = Spinner(..self, lit: self.id == id)
41
+
42
+ fun step(self, dt: Float) -> Spinner = Spinner(..self, clock: self.clock + dt)
43
+
44
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.size, self.size)
45
+
46
+ fun hit(self, p: Vec2) -> Bool =
47
+ c := self.size / 2.0
48
+ self.bounds().containsPoint(p) || {self.lit && Math.hypot(p.x - c, p.y - c) <= self.halo()}
49
+
50
+ fun touch(self) -> Touchable = Enabled
51
+
52
+ fun pressed(self) -> SkyAction = Pick(body: self.id)
examples/games/clockwork/actors/Walker.plum ADDED
@@ -0,0 +1,44 @@
1
+ module clockwork_walker
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/collections/List
7
+ import std/math/Aabb
8
+ import std/math/Vec2
9
+ import std/math/Math
10
+ import std/game/Place
11
+ import std/game/Body
12
+ import std/game/View
13
+ import std/game/Sprite
14
+ import std/game/Sized
15
+ import std/game/Touch
16
+ import std/game/Button
17
+ import Clockwork
18
+ import screens/OrreryScreen
19
+
20
+ struct Walker[Actor, Sized, Touch, Presses<SkyAction>, Steps](id: Int, body: Body, phase: Float, tex: Texture) =
21
+ const Min = 500.0
22
+ const Max = 1300.0
23
+ const Size = 24.0
24
+ const Ground = 510.0
25
+
26
+ fun spawn(i: Int, tex: Texture) -> Walker =
27
+ pace := 20.0 + Float(i % 7) * 9.0
28
+ Walker(
29
+ id: i,
30
+ body: Body(
31
+ pos: Vec2(x: Walker.Max - 1800.0 + Float(i * 61 % 1800), y: Walker.Ground), vel: Vec2(x: if i % 2 == 0 then 0.0 - pace else pace, y: 0.0),
32
+ edge: Wrap(box: Aabb(min: Vec2(x: 0.0 - Walker.Min, y: 0.0), max: Vec2(x: Walker.Max, y: Arena.H)))),
33
+ phase: Float(i), tex: tex)
34
+
35
+ fun place(self) -> Place = Place.at(self.body.pos.x, self.body.pos.y + 50.0 * Math.sin(self.body.pos.x / 90.0 + self.phase))
36
+
37
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, Walker.Size, Walker.Size)
38
+
39
+ fun touch(self) -> Touchable = Enabled
40
+
41
+ fun pressed(self) -> SkyAction = Front(walker: self.id)
42
+
43
+ fun view(self) -> List<View> =
44
+ [Sprite(tex: self.tex, w: Walker.Size, h: Walker.Size, srcX: Float(self.id % 3) * Sheet.Cell, srcY: Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell)]
examples/games/clockwork/assets/sprites.png ADDED
Binary file
examples/games/clockwork/screens/OrreryScreen.plum ADDED
@@ -0,0 +1,108 @@
1
+ module clockwork_orrery
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/Option
8
+ import std/Slice
9
+ import std/collections/List
10
+ import std/math/Vec2
11
+ import std/math/Affine
12
+ import std/game/Color
13
+ import std/game/Input
14
+ import std/game/Body
15
+ import std/game/View
16
+ import std/game/Box
17
+ import std/game/Circle
18
+ import std/game/Group
19
+ import std/game/Label
20
+ import std/game/Viewport
21
+ import std/game/Screen
22
+ import std/game/ScreenSlice
23
+ import std/game/Game
24
+ import actors/Orbit
25
+ import actors/Spinner
26
+ import actors/Walker
27
+ import Clockwork
28
+
29
+ enum SkyAction[Show] =
30
+ | TogglePause
31
+ | Pick(body: Int)
32
+ | Front(walker: Int)
33
+ | Tick(dt: Float)
34
+
35
+ struct OrreryScreen[ScreenSlice<SkyAction>](
36
+ @stepsWhen(!self.paused) sun: Spinner, @stepsWhen(!self.paused) orbits: List<Orbit>, @stepsWhen(!self.paused) walkers: List<Walker>,
37
+ paused: Bool = false, selected: Int = -1, front: Int = -1) =
38
+ const Names = ["Ember", "Cinder", "Ashen", "Glacier"]
39
+ const Moons = [0, 1, 2, 1]
40
+ const Walkers = 60
41
+
42
+ fun start(assets: Assets) -> OrreryScreen =
43
+ tex := assets.sheet
44
+ OrreryScreen(
45
+ sun: Spinner(id: -1, name: "Sun", size: 96.0, body: Body(pos: Vec2(x: Arena.CentreX, y: Arena.CentreY), turn: 0.3), tex: tex, srcY: Sheet.Cell, fps: 6.0, frames: 4),
46
+ orbits: Range.until(0, OrreryScreen.Names.length()).map(|i|
47
+ Orbit.chart(i, Range.until(0, i).fold(i, |id, k| id + OrreryScreen.Moons.at(k)), OrreryScreen.Names.at(i), OrreryScreen.Moons.at(i), tex)),
48
+ walkers: OrreryScreen.crowd(Range.until(0, OrreryScreen.Walkers).map(|i| Walker.spawn(i, tex)), -1))
49
+
50
+ fun name(self) -> Str = "orrery"
51
+
52
+ fun size(self) -> Vec2 = Vec2(x: Arena.W, y: Arena.H)
53
+
54
+ fun viewport(self) -> Scaling = Extend
55
+
56
+ fun culls(self) -> Bool = true
57
+
58
+ fun view(self) -> List<View> = [
59
+ Box(w: Arena.W, h: Arena.H, color: Color.rgb(0.04, 0.05, 0.1))
60
+ ..Range.until(0, 40).map(|i| Circle(x: Float({i * 7919} % 800), y: Float({i * 104729} % 600), r: 1.0 + Float(i % 3) * 0.5, color: Color(r: 0.7, g: 0.8, b: 1.0, a: 0.4)))
61
+ ..self.orbits.map(|o| Circle(x: Arena.CentreX, y: Arena.CentreY, r: o.reach, color: Color.White.withAlpha(0.04)))
62
+ ..self.orbits
63
+ self.sun
64
+ ..self.walkers
65
+ Label(x: 16.0, y: 12.0, text: self.title())
66
+ ]
67
+
68
+ fun hud(self, window: Vec2) -> List<View> =
69
+ k := Sheet.MapScale
70
+ w := Sheet.MapW
71
+ h := Sheet.MapH
72
+ [
73
+ Group(x: window.x - w - 8.0, y: window.y - h - 8.0) {
74
+ Box(w: w, h: h, color: Color(r: 0.05, g: 0.1, b: 0.2, a: 0.85))
75
+ Box(w: w, h: 1.0, color: Color.White)
76
+ Box(y: h - 1.0, w: w, h: 1.0, color: Color.White)
77
+ Box(w: 1.0, h: h, color: Color.White)
78
+ Box(x: w - 1.0, w: 1.0, h: h, color: Color.White)
79
+ Circle(x: Arena.CentreX * k, y: Arena.CentreY * k, r: 5.0, color: Color.Yellow)
80
+ ..self.spots().map(|s| Circle(x: s.at.x * k, y: s.at.y * k, r: 2.0, color: if s.spinner.lit then Color.Yellow else Color(r: 0.6, g: 0.8, b: 1.0, a: 1.0)))
81
+ }
82
+ ]
83
+
84
+ fun subscriptions(self) -> List<Sub<SkyAction>> = [
85
+ OnKeyDown(key: Key.Space, act: TogglePause)
86
+ OnPointerDown(|at| Pick(body: -1))
87
+ OnFrame(|dt| Tick(dt: dt))
88
+ ]
89
+
90
+ fun update(self, a: SkyAction) -> Next<OrreryScreen, SkyAction> = match a
91
+ TogglePause => Next(state: OrreryScreen(..self, paused: !self.paused))
92
+ Pick(body) =>
93
+ chosen := if body == self.selected then -1 else body
94
+ Next(state: OrreryScreen(..self, selected: chosen, orbits: self.orbits.map(|o| o.lit(chosen))))
95
+ Front(walker) => Next(state: OrreryScreen(..self, front: walker, walkers: OrreryScreen.crowd(self.walkers, walker)), then: [Pick(body: -1)])
96
+ Tick(dt) =>
97
+ moved := self.stepped(dt)
98
+ Next(state: OrreryScreen(..moved, walkers: OrreryScreen.crowd(moved.walkers, moved.front)))
99
+
100
+ fun spots(self) -> List<Spot> = self.orbits.fold(Nil, |all, o| all.append(o.spots(Affine.Identity)))
101
+
102
+ fun title(self) -> Str = match self.spots().find(|s| s.spinner.lit)
103
+ Some(s) => s.spinner.name
104
+ None => "Click a planet"
105
+
106
+ fun crowd(walkers: List<Walker>, front: Int) -> List<Walker> =
107
+ sorted := List.fromSlice(walkers.toSlice().sort(|a, b| a.place().y < b.place().y))
108
+ [..sorted.filter(|w| w.id != front), ..sorted.filter(|w| w.id == front)]
examples/games/menu/Menu.plum ADDED
@@ -0,0 +1,24 @@
1
+ module menu_example
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Io
6
+ import std/Str
7
+ import std/collections/List
8
+ import std/game/Screen
9
+ import std/game/Game
10
+ import std/App
11
+ import screens/MenuScreen
12
+ import screens/TurnScreen
13
+
14
+ primitive Arena =
15
+ const W = 800.0
16
+ const H = 600.0
17
+
18
+ primitive Menu[App] =
19
+ fun game() -> Game =
20
+ menu: Screen := MenuScreen.start()
21
+ play: Screen := TurnScreen.start()
22
+ Game(screens: [menu, play])
23
+
24
+ fun main(io: Io) -> Game = Menu.game()
examples/games/menu/actors/Turner.plum ADDED
@@ -0,0 +1,15 @@
1
+ module menu_turner
2
+
3
+ import std/Float
4
+ import std/collections/List
5
+ import std/math/Vec2
6
+ import std/game/Color
7
+ import std/game/Place
8
+ import std/game/Body
9
+ import std/game/View
10
+ import std/game/Box
11
+
12
+ struct Turner[Actor, Steps](body: Body) =
13
+ fun place(self) -> Place = self.body.place(Vec2.Zero)
14
+
15
+ fun view(self) -> List<View> = [Box(x: -40.0, y: -40.0, w: 80.0, h: 80.0, color: Color.Red)]
examples/games/menu/screens/MenuScreen.plum ADDED
@@ -0,0 +1,81 @@
1
+ module menu_screen
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/collections/List
8
+ import std/math/Vec2
9
+ import std/game/Color
10
+ import std/game/Input
11
+ import std/game/View
12
+ import std/game/Box
13
+ import std/game/Label
14
+ import std/game/Button
15
+ import std/game/Tween
16
+ import std/game/Cmd
17
+ import std/game/Screen
18
+ import std/game/ScreenSlice
19
+ import std/game/Game
20
+ import Menu
21
+
22
+ enum MenuAction[Show] =
23
+ | MoveBy(step: Int)
24
+ | Choose
25
+ | Clicked(index: Int)
26
+ | Tick(dt: Float)
27
+
28
+ struct MenuScreen[ScreenSlice<MenuAction>](selected: Int, highlight: Tween) =
29
+ const Items = ["Play", "Quit"]
30
+ const SlideTime = 0.15
31
+
32
+ fun start() -> MenuScreen = MenuScreen(selected: 0, highlight: Tween(from: MenuScreen.highlightAt(0), to: MenuScreen.highlightAt(0), secs: 0.0))
33
+
34
+ fun buttonY(i: Int) -> Float = 240.0 + Float(i) * 100.0
35
+
36
+ fun highlightAt(i: Int) -> Float = MenuScreen.buttonY(i) - 6.0
37
+
38
+ fun name(self) -> Str = "menu"
39
+
40
+ fun frames(self) -> Frames = OnDemand
41
+
42
+ fun size(self) -> Vec2 = Vec2(x: Arena.W, y: Arena.H)
43
+
44
+ fun background(self) -> Color = Color.rgb(0.1, 0.1, 0.18)
45
+
46
+ fun busy(self) -> Bool = !self.highlight.done()
47
+
48
+ fun view(self) -> List<View> = [
49
+ Label(x: 400.0, y: 120.0, text: "Menu", size: 48.0, align: Centre)
50
+ Box(x: 276.0, y: self.highlight.value(), w: 248.0, h: 68.0, color: Color.Yellow)
51
+ ..Range.until(0, MenuScreen.Items.length()).map(|i| button(i))
52
+ Label(x: 400.0, y: 520.0, text: "Selected: {MenuScreen.Items.at(self.selected)}", align: Centre)
53
+ ]
54
+
55
+ fun button(i: Int) -> Button<MenuAction> =
56
+ Button(x: 280.0, y: MenuScreen.buttonY(i), w: 240.0, h: 56.0, on: Clicked(index: i)) {
57
+ Box(w: 240.0, h: 56.0, color: Color.rgb(0.2, 0.3, 0.6))
58
+ Label(x: 120.0, y: 16.0, text: MenuScreen.Items.at(i), align: Centre)
59
+ }
60
+
61
+ fun subscriptions(self) -> List<Sub<MenuAction>> = [
62
+ OnKeyDown(key: Key.Up, act: MoveBy(step: -1))
63
+ OnKeyDown(key: Key.Down, act: MoveBy(step: 1))
64
+ OnKeyDown(key: Key.Enter, act: Choose)
65
+ OnKeyDown(key: Key.Space, act: Choose)
66
+ OnFrame(|dt| Tick(dt: dt))
67
+ ]
68
+
69
+ fun update(self, a: MenuAction) -> Next<MenuScreen, MenuAction> = match a
70
+ MoveBy(step) =>
71
+ n := MenuScreen.Items.length()
72
+ Next(state: self.select({self.selected + step + n} % n))
73
+ Choose => Next(state: self, cmds: [if self.selected == 0 then GoTo(name: "play") else Exit])
74
+ Clicked(index) => Next(state: self.select(index), then: [Choose])
75
+ Tick(dt) => Next(state: MenuScreen(..self, highlight: self.highlight.advance(dt)))
76
+
77
+ fun select(self, i: Int) -> MenuScreen =
78
+ if i == self.selected
79
+ self
80
+ else
81
+ MenuScreen(..self, selected: i, highlight: Tween(from: self.highlight.value(), to: MenuScreen.highlightAt(i), secs: MenuScreen.SlideTime, ease: QuadOut))
examples/games/menu/screens/TurnScreen.plum ADDED
@@ -0,0 +1,42 @@
1
+ module menu_turn
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/collections/List
7
+ import std/math/Vec2
8
+ import std/game/Input
9
+ import std/game/Body
10
+ import std/game/View
11
+ import std/game/Label
12
+ import std/game/Cmd
13
+ import std/game/Screen
14
+ import std/game/ScreenSlice
15
+ import std/game/Game
16
+ import actors/Turner
17
+ import Menu
18
+
19
+ enum TurnAction[Show] = Back | Tick(dt: Float)
20
+
21
+ struct TurnScreen[ScreenSlice<TurnAction>](turner: Turner) =
22
+ fun start() -> TurnScreen = TurnScreen(turner: Turner(body: Body(pos: Vec2(x: Arena.W / 2.0, y: Arena.H / 2.0), turn: 2.0)))
23
+
24
+ fun name(self) -> Str = "play"
25
+
26
+ fun transition(self, from: Str) -> Transition = Fade(secs: 0.3)
27
+
28
+ fun size(self) -> Vec2 = Vec2(x: Arena.W, y: Arena.H)
29
+
30
+ fun view(self) -> List<View> = [
31
+ self.turner
32
+ Label(x: 400.0, y: 520.0, text: "Escape: back to the menu", align: Centre)
33
+ ]
34
+
35
+ fun subscriptions(self) -> List<Sub<TurnAction>> = [
36
+ OnKeyDown(key: Key.Escape, act: Back)
37
+ OnFrame(|dt| Tick(dt: dt))
38
+ ]
39
+
40
+ fun update(self, a: TurnAction) -> Next<TurnScreen, TurnAction> = match a
41
+ Back => Next(state: self, cmds: [GoTo(name: "menu")])
42
+ Tick(dt) => Next(state: self.stepped(dt))
tests/examples/games/clockwork/actors/Orbit.plum ADDED
@@ -0,0 +1,47 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/math/Vec2
8
+ import std/math/Affine
9
+ import std/math/Math
10
+ import std/game/Body
11
+ import std/game/View
12
+ import examples/games/clockwork/Clockwork
13
+ import examples/games/clockwork/actors/Orbit
14
+ import examples/games/clockwork/actors/Spinner
15
+ import std/Test
16
+
17
+ primitive OrbitTest[UnitTest] =
18
+ # an orbit turns what it carries with it, and steps the orbits it carries, which add their own turns
19
+ fun anOrbitTurnsItsChildrenWithIt() =
20
+ dot := Spinner(id: 1, name: "dot", size: 2.0, body: Body(pos: Vec2.Zero), tex: Texture.none())
21
+ inner := Orbit(hub: Body(pos: Vec2.Zero, turn: 2.0), reach: 10.0, planet: dot)
22
+ outer := Orbit(hub: Body(pos: Vec2(x: 100.0, y: 100.0), turn: 1.0), reach: 50.0, planet: Spinner(..dot, id: 0), moons: [inner])
23
+ p := OrbitTest.centreOf(outer, 1)
24
+ assert Math.near(p.x, 160.0, 0.01) && Math.near(p.y, 100.0, 0.01)
25
+ later := outer.step(Float.HalfPi / 2.0)
26
+ q := OrbitTest.centreOf(later, 1)
27
+ assert Math.near(q.x, 128.284, 0.01) && Math.near(q.y, 142.426, 0.01)
28
+ assert later.moons.at(0).planet.clock == Float.HalfPi / 2.0
29
+
30
+ # its spots are where each body it carries is, the same place the view draws it
31
+ fun itsSpotsAreWhereTheViewDrawsEachBody() =
32
+ o := Orbit.chart(2, 3, "Ashen", 2, Texture.none()).step(1.3)
33
+ spots := o.spots(Affine.Identity)
34
+ assert spots.map(|s| s.spinner.name).join(", ") == "Ashen, Ashen moon 1, Ashen moon 2"
35
+ assert spots.map(|s| s.spinner.id).join(", ") == "3, 4, 5"
36
+ assert spots.all(|s|
37
+ drawn := Views.worldIn([o], s.spinner, Affine.Identity).unwrap().apply(Vec2(x: s.spinner.size / 2.0, y: s.spinner.size / 2.0))
38
+ drawn.distance(s.at) < 0.000001)
39
+
40
+ # lighting a body lights that one alone, a moon among them
41
+ fun lightingABodyLightsThatOneAlone() =
42
+ o := Orbit.chart(1, 1, "Cinder", 1, Texture.none()).lit(2)
43
+ assert !o.planet.lit
44
+ assert o.moons.at(0).planet.lit
45
+ assert !o.lit(-1).moons.at(0).planet.lit
46
+
47
+ fun centreOf(o: Orbit, id: Int) -> Vec2 = o.spots(Affine.Identity).find(|s| s.spinner.id == id).unwrap().at
tests/examples/games/clockwork/actors/Spinner.plum ADDED
@@ -0,0 +1,38 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/collections/List
6
+ import std/math/Vec2
7
+ import std/math/Math
8
+ import std/game/Body
9
+ import std/game/View
10
+ import std/game/Sprite
11
+ import examples/games/clockwork/Clockwork
12
+ import examples/games/clockwork/actors/Spinner
13
+ import examples/games/clockwork/screens/OrreryScreen
14
+ import std/Test
15
+
16
+ primitive SpinnerTest[UnitTest] =
17
+ # a spinner is hit in its box, and on its halo only while lit
18
+ fun aSpinnerIsHitOnItsHaloOnlyWhileLit() =
19
+ s := Spinner(id: 4, name: "s", size: 40.0, body: Body(pos: Vec2.Zero, turn: 1.0), tex: Texture.none())
20
+ assert s.hit(Vec2(x: 20.0, y: 20.0))
21
+ assert !s.hit(Vec2(x: -8.0, y: 20.0))
22
+ assert s.view().length() == 1
23
+ lit := s.light(4)
24
+ assert lit.hit(Vec2(x: -8.0, y: 20.0))
25
+ assert lit.view().length() == 2
26
+ assert !lit.light(5).lit
27
+ assert s.pressed().toStr() == "Pick(4)"
28
+
29
+ # it plays its strip as its clock runs, and turns about its centre
30
+ fun itPlaysItsStripAndTurnsAboutItsCentre() =
31
+ s := Spinner(id: 0, name: "s", size: 40.0, body: Body(pos: Vec2(x: 100.0, y: 50.0), turn: 1.0), tex: Texture.none(), fps: 6.0, frames: 4).step(0.5)
32
+ frame := match s.view().at(0)
33
+ Sprite as f => f.frame
34
+ _ => -1
35
+ assert frame == 3
36
+ assert s.clock == 0.5
37
+ assert s.place().rotation == 0.5
38
+ assert s.place().pivot() == Vec2(x: 100.0, y: 50.0)
tests/examples/games/clockwork/actors/Walker.plum ADDED
@@ -0,0 +1,30 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/collections/List
6
+ import std/math/Vec2
7
+ import std/math/Math
8
+ import std/game/Body
9
+ import std/game/View
10
+ import examples/games/clockwork/Clockwork
11
+ import examples/games/clockwork/actors/Walker
12
+ import examples/games/clockwork/screens/OrreryScreen
13
+ import std/Test
14
+
15
+ primitive WalkerTest[UnitTest] =
16
+ # a walker walks, bobs as it goes and comes round at the other side
17
+ fun aWalkerWalksBobsAndWrapsRound() =
18
+ w := Walker.spawn(1, Texture.none())
19
+ pace := w.body.vel.x
20
+ assert pace == 29.0
21
+ near := Walker(..w, body: Body(..w.body, pos: Vec2(x: Walker.Max - 1.0, y: Walker.Ground)))
22
+ on := near.step(0.02)
23
+ assert on.body.pos.x == Walker.Max - 1.0 + pace * 0.02
24
+ assert on.place().y == Walker.Ground + 50.0 * Math.sin(on.body.pos.x / 90.0 + 1.0)
25
+ round := on.step(0.1)
26
+ assert round.body.pos.x < 0.0 - Walker.Min + 5.0
27
+ assert Walker.spawn(2, Texture.none()).body.vel.x < 0.0
28
+
29
+ fun aPressOnAWalkerBringsItToTheFront() =
30
+ assert Walker.spawn(7, Texture.none()).pressed().toStr() == "Front(7)"
tests/examples/games/clockwork/screens/OrreryScreen.plum ADDED
@@ -0,0 +1,239 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Io
6
+ import std/Option
7
+ import std/Slice
8
+ import std/collections/List
9
+ import std/math/Vec2
10
+ import std/math/Affine
11
+ import std/math/Math
12
+ import std/game/Color
13
+ import std/game/Input
14
+ import std/game/Body
15
+ import std/game/Replay
16
+ import std/game/View
17
+ import std/game/Label
18
+ import std/game/Screen
19
+ import std/game/ScreenSlice
20
+ import std/game/Game
21
+ import std/game/TestRig
22
+ import examples/games/clockwork/Clockwork
23
+ import examples/games/clockwork/actors/Orbit
24
+ import examples/games/clockwork/actors/Spinner
25
+ import examples/games/clockwork/actors/Walker
26
+ import examples/games/clockwork/screens/OrreryScreen
27
+ import std/Test
28
+
29
+ primitive OrreryScreenTest[UnitTest] =
30
+ # the sky has a sun, four planets and their moons
31
+ fun theSkyHasASunFourPlanetsAndTheirMoons() =
32
+ t := OrreryScreenHelpers.sky(io)
33
+ spots := t.screen.spots()
34
+ assert spots.length() == 8
35
+ assert spots.map(|s| s.spinner.id).join(",") == "0,1,2,3,4,5,6,7"
36
+ assert spots.at(0).spinner.name == "Ember"
37
+ assert spots.at(2).spinner.name == "Cinder moon 1"
38
+ assert spots.at(6).spinner.name == "Glacier"
39
+ assert t.count<Spinner>() == 9
40
+ assert t.count<Walker>() == OrreryScreen.Walkers
41
+ assert t.drawn().length() > 60
42
+ assert t.text(t.first<Label>()) == "Click a planet"
43
+
44
+ # planets start on the right of the sun and orbit clockwise
45
+ fun planetsStartOnTheRightAndOrbitClockwise() =
46
+ t := OrreryScreenHelpers.sky(io)
47
+ c := OrreryScreenHelpers.centre(t, 0)
48
+ assert Math.near(c.x, 490.0, 0.01) && Math.near(c.y, 300.0, 0.01)
49
+ u := t.tick(Float.HalfPi / 0.9)
50
+ d := OrreryScreenHelpers.centre(u, 0)
51
+ assert Math.near(d.x, 400.0, 0.01) && Math.near(d.y, 390.0, 0.01)
52
+ assert Math.near(u.worldOf(u.screen.spots().at(0).spinner).unwrap().apply(Vec2(x: 20.0, y: 20.0)).y, 390.0, 0.01)
53
+
54
+ # a moon stays its orbit's reach from its planet while both move
55
+ fun aMoonStaysItsReachFromItsPlanet() =
56
+ sun := Vec2(x: Arena.CentreX, y: Arena.CentreY)
57
+ end := Range.until(0, 50).fold(OrreryScreenHelpers.sky(io), |t, i|
58
+ u := t.tick(0.1)
59
+ p := OrreryScreenHelpers.centre(u, 3)
60
+ assert Math.near(p.distance(OrreryScreenHelpers.centre(u, 4)), 36.0, 0.01)
61
+ assert Math.near(sun.distance(p), 210.0, 0.01)
62
+ u)
63
+ assert end.screen.spots().at(3).spinner.clock > 4.9
64
+
65
+ # each orbit steps the bodies and moons it carries once a tick, and a pause steps nothing
66
+ fun eachOrbitStepsWhatItCarriesOnceATick() =
67
+ t := OrreryScreenHelpers.sky(io).tick(0.5).tick(0.25)
68
+ assert t.screen.spots().all(|s| s.spinner.clock == 0.75)
69
+ assert t.screen.sun.clock == 0.75
70
+ u := t.press(Key.Space).tick(1.0)
71
+ assert u.screen.paused
72
+ assert u.screen.spots().at(4).spinner.clock == 0.75
73
+ assert OrreryScreenHelpers.centre(u, 4) == OrreryScreenHelpers.centre(t, 4)
74
+ assert OrreryScreenHelpers.names(u) == "TogglePause Tick(1.0)"
75
+
76
+ # a click selects a body even after it has moved, and lights it; a second click lets it go
77
+ fun clickingSelectsABodyAndAgainLetsItGo() =
78
+ t := OrreryScreenHelpers.sky(io).tick(3.0)
79
+ c := OrreryScreenHelpers.centre(t, 1)
80
+ u := t.clickAt(c.x, c.y).tick(0.0)
81
+ assert u.screen.selected == 1
82
+ assert u.text(u.first<Label>()) == "Cinder"
83
+ assert u.screen.spots().at(1).spinner.lit
84
+ assert !u.screen.spots().at(0).spinner.lit
85
+ v := u.clickAt(c.x, c.y).tick(0.0)
86
+ assert v.screen.selected == -1
87
+ assert !v.screen.spots().at(1).spinner.lit
88
+ assert v.text(v.first<Label>()) == "Click a planet"
89
+
90
+ # two presses in one tick are picked at once, in the order pressed
91
+ fun twoPressesInOneTickArePickedInOrder() =
92
+ t := OrreryScreenHelpers.sky(io)
93
+ c := OrreryScreenHelpers.centre(t, 1)
94
+ u := t.clickAt(c.x, c.y).clickAt(c.x, c.y).tick()
95
+ assert OrreryScreenHelpers.names(u) == "Pick(1) Pick(1) Tick({Ticker.Tick})"
96
+ assert u.screen.selected == -1
97
+
98
+ # a click on a moon selects it; one on empty space, or on the sun, selects nothing
99
+ fun clickingAMoonEmptySpaceOrTheSun() =
100
+ t := OrreryScreenHelpers.sky(io)
101
+ m := OrreryScreenHelpers.centre(t, 2)
102
+ u := t.clickAt(m.x, m.y).tick(0.0)
103
+ assert u.text(u.first<Label>()) == "Cinder moon 1"
104
+ assert u.hit(2.0, 2.0).isNone()
105
+ v := u.clickAt(2.0, 2.0).tick(0.0)
106
+ assert OrreryScreenHelpers.names(v) == "Pick(-1) Tick(0.0)"
107
+ assert v.screen.selected == -1
108
+ w := u.clickAt(400.0, 300.0).tick(0.0)
109
+ assert OrreryScreenHelpers.names(w) == "Pick(-1) Tick(0.0)"
110
+ assert w.screen.selected == -1
111
+
112
+ # while paused nothing turns, but a click still selects
113
+ fun pausingFreezesTheSky() =
114
+ t := OrreryScreenHelpers.sky(io).press(Key.Space).tick(1.0)
115
+ c := OrreryScreenHelpers.centre(t, 0)
116
+ assert Math.near(c.x, 490.0, 0.01)
117
+ assert t.screen.sun.clock == 0.0
118
+ u := t.clickAt(c.x, c.y).tick()
119
+ assert u.screen.selected == 0
120
+ assert OrreryScreenHelpers.centre(u, 0) == c
121
+ v := u.press(Key.Space).tick()
122
+ assert !v.screen.paused
123
+ assert v.screen.sun.clock > 0.0
124
+
125
+ # a halo is drawn and hit only while its body is selected
126
+ fun aHaloIsDrawnAndHitOnlyWhileSelected() =
127
+ t := OrreryScreenHelpers.sky(io)
128
+ body := t.screen.spots().at(1).spinner
129
+ edge := t.worldOf(body).unwrap().apply(Vec2(x: 20.0 - body.halo() + 2.0, y: 20.0))
130
+ assert OrreryScreenHelpers.hitId(t, edge) != 1
131
+ drawn := t.drawn().length()
132
+ u := t.dispatch(Pick(body: 1))
133
+ assert OrreryScreenHelpers.hitId(u, edge) == 1
134
+ assert u.drawn().length() == drawn + 1
135
+
136
+ # the sky is fitted to the window and grown to fill it, and screen points map back
137
+ fun theSkyIsGrownToFillTheWindow() =
138
+ t := OrreryScreenHelpers.sky(io).resize(1600.0, 600.0)
139
+ p := t.toWorld(800.0, 300.0)
140
+ assert Math.near(p.x, 400.0, 0.01) && Math.near(p.y, 300.0, 0.01)
141
+ assert Math.near(t.toWorld(0.0, 0.0).x, -400.0, 0.01)
142
+
143
+ # the crowd is sorted by height every tick and culled to the window
144
+ fun theCrowdIsSortedEveryTickAndCulled() =
145
+ t := OrreryScreenHelpers.sky(io).tick(0.5).tick(0.5)
146
+ w := t.screen.walkers
147
+ assert w.length() == OrreryScreen.Walkers
148
+ assert Range.until(0, w.length() - 1).all(|i| w.at(i).place().y <= w.at(i + 1).place().y)
149
+ assert w.all(|x| x.body.pos.x >= 0.0 - Walker.Min && x.body.pos.x <= Walker.Max)
150
+ shown := t.drawn().length()
151
+ assert t.resize(100000.0, 600.0).drawn().length() > shown
152
+
153
+ # a click on a walker brings it to the front, after every later sort too, and selects nothing
154
+ fun clickingAWalkerBringsItToTheFront() =
155
+ t := OrreryScreenHelpers.sky(io).resize(1800.0, 600.0).dispatch(Pick(body: 3))
156
+ w := t.screen.walkers.at(0)
157
+ u := t.click(w).tick(0.0)
158
+ assert OrreryScreenHelpers.names(u) == "Front({w.id}) Pick(-1) Tick(0.0)"
159
+ assert u.screen.selected == -1
160
+ assert u.screen.walkers.at(OrreryScreen.Walkers - 1).id == w.id
161
+ v := u.tick(0.1)
162
+ assert v.screen.walkers.at(OrreryScreen.Walkers - 1).id == w.id
163
+ assert v.find<Walker>().at(OrreryScreen.Walkers - 1).id == w.id
164
+
165
+ # the minimap sits at the window's bottom-right corner and marks each body where it is
166
+ fun theMinimapMarksEachBodyWhereItIs() =
167
+ t := OrreryScreenHelpers.sky(io).resize(1600.0, 600.0).tick(1.0)
168
+ s := t.screen
169
+ assert s.spots().at(3).at == t.worldOf(s.spots().at(3).spinner).unwrap().apply(Vec2(x: 20.0, y: 20.0))
170
+ map := s.hud(Vec2(x: 1600.0, y: 600.0)).at(0)
171
+ assert map.place().x == 1600.0 - Sheet.MapW - 8.0
172
+ assert map.place().y == 600.0 - Sheet.MapH - 8.0
173
+ assert map.view().length() == 6 + 8
174
+
175
+ # a recorded run replays to the same sky, whose checksum is pinned
176
+ fun aRecordedRunReplaysToTheSameSky() =
177
+ start := OrreryScreenHelpers.sky(io).screen.spots().map(|s| s.at)
178
+ a := Range.until(0, 400).fold(OrreryScreenHelpers.sky(io).record(0), |r, f| r.frame(OrreryScreenHelpers.runInput(f, start), 0.0166 + Float(f % 3) * 0.004 - 0.004))
179
+ r := a.recorded()
180
+ assert r.length() == a.game.ticks
181
+ assert a.game.ticks > 350
182
+ assert OrreryScreenHelpers.checksum(a.screen) == 294124446
183
+ back := Replay.decode(r.encode()).unwrap()
184
+ b := OrreryScreenHelpers.sky(io).replay(back)
185
+ assert b.game.ticks == a.game.ticks
186
+ assert OrreryScreenHelpers.checksum(b.screen) == OrreryScreenHelpers.checksum(a.screen)
187
+ assert OrreryScreenHelpers.checksum(OrreryScreenHelpers.sky(io).screen) != OrreryScreenHelpers.checksum(a.screen)
188
+
189
+ # a run rewound to its middle and played on again reaches the same sky
190
+ fun aRunRewoundToItsMiddleReachesTheSameSky() =
191
+ start := OrreryScreenHelpers.sky(io).screen.spots().map(|s| s.at)
192
+ a := OrreryScreenHelpers.framesFrom(TestRig.mountWith(io, OrreryScreen.start(Assets.none())), start, 0, 400)
193
+ b := OrreryScreenHelpers.framesFrom(OrreryScreenHelpers.sky(io), start, 0, 400)
194
+ assert OrreryScreenHelpers.checksum(a.screen) == OrreryScreenHelpers.checksum(b.screen)
195
+ mid := OrreryScreenHelpers.framesFrom(OrreryScreenHelpers.sky(io), start, 0, 200)
196
+ back := a.rewindTo(200)
197
+ assert back.moved()
198
+ assert back.game.rewound == 200
199
+ assert OrreryScreenHelpers.checksum(back.screen) == OrreryScreenHelpers.checksum(mid.screen)
200
+ again := OrreryScreenHelpers.framesFrom(back, start, 200, 200)
201
+ assert OrreryScreenHelpers.checksum(again.screen) == OrreryScreenHelpers.checksum(b.screen)
202
+ assert again.screen.selected == b.screen.selected
203
+
204
+ primitive OrreryScreenHelpers =
205
+ fun sky(io: Io) -> TestRig<OrreryScreen> = TestRig.mount(io, OrreryScreen.start(Assets.none()))
206
+
207
+ fun centre(t: TestRig<OrreryScreen>, i: Int) -> Vec2 = t.screen.spots().at(i).at
208
+
209
+ fun names(t: TestRig<OrreryScreen>) -> Str = t.actions<SkyAction>().map(|a| a.toStr()).join(" ")
210
+
211
+ fun hitId(t: TestRig<OrreryScreen>, p: Vec2) -> Int = match t.hit(p.x, p.y)
212
+ Some(v) => match v
213
+ Spinner as s => s.id
214
+ _ => -100
215
+ None => -100
216
+
217
+ fun runInput(i: Int, start: List<Vec2>) -> Input =
218
+ p := if i % 120 == 119 then Vec2(x: 400.0, y: 515.0) else start.at({i / 40} % start.length())
219
+ Input(events: [
220
+ if i % 97 == 96 then KeyDown(key: Key.Space)
221
+ if i % 40 == 39 then PointerDown(x: p.x, y: p.y)
222
+ ])
223
+
224
+ fun framesFrom(t: TestRig<OrreryScreen>, start: List<Vec2>, from: Int, n: Int) -> TestRig<OrreryScreen> =
225
+ Range.until(0, n).fold(t, |r, f| r.frame(runInput(from + f, start), Ticker.Tick))
226
+
227
+ fun checksum(s: OrreryScreen) -> Int =
228
+ parts := [
229
+ s.selected
230
+ s.front
231
+ if s.paused then 1 else 0
232
+ Int(s.sun.clock * 1000000.0)
233
+ ..s.spots().map(|p| Int(p.at.x * 1000000.0) + 7 * Int(p.at.y * 1000000.0))
234
+ ..s.walkers.map(|w| w.id + 61 * Int(w.body.pos.x * 1000000.0))
235
+ ]
236
+ parts.fold(17, |h, x|
237
+ v0 := x % 1000000007
238
+ v := if v0 < 0 then v0 + 1000000007 else v0
239
+ {h * 31 + v} % 1000000007)
tests/examples/games/menu/Menu.plum ADDED
@@ -0,0 +1,83 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Io
6
+ import std/Option
7
+ import std/collections/List
8
+ import std/math/Vec2
9
+ import std/math/Math
10
+ import std/game/Input
11
+ import std/game/Replay
12
+ import std/game/View
13
+ import std/game/Button
14
+ import std/game/Screen
15
+ import std/game/ScreenSlice
16
+ import std/game/Game
17
+ import std/game/TestRig
18
+ import examples/games/menu/Menu
19
+ import examples/games/menu/screens/MenuScreen
20
+ import examples/games/menu/screens/TurnScreen
21
+ import std/Test
22
+
23
+ primitive MenuTest[UnitTest] =
24
+ # clicking Play fades in the play, which ticks every frame and turns its square; Escape comes back to the menu as it was left
25
+ fun clickingPlayGoesToThePlayAndEscapeComesBack() =
26
+ t := TestRig.play(io, Menu.game())
27
+ u := t.clickAt(400.0, MenuScreen.buttonY(0) + 28.0).tick()
28
+ assert u.wentTo().unwrap() == "play"
29
+ assert u.showing() == "play"
30
+ assert u.game.shifting()
31
+ v := u.ticks(30)
32
+ assert v.game.skipped == 0
33
+ turner := MenuHelpers.play(v).turner
34
+ assert turner.place().rotation > 0.9
35
+ square := v.worldOf(turner).unwrap()
36
+ assert Math.near(square.rotation(), turner.place().rotation, 0.000001)
37
+ w := v.press(Key.Escape).tick()
38
+ assert w.showing() == "menu"
39
+ assert MenuHelpers.menu(w).selected == 0
40
+
41
+ # a recorded session with long idle stretches replays to the same menu, sleeping through the same ticks
42
+ fun aRecordedIdleSessionReplaysToTheSameMenu() =
43
+ a := MenuHelpers.framesFrom(TestRig.play(io, Menu.game()).record(1), 0, 600)
44
+ assert a.game.skipped > 550
45
+ back := Replay.decode(a.recorded().encode()).unwrap()
46
+ b := TestRig.play(io, Menu.game()).replay(back)
47
+ assert MenuHelpers.sameMenu(b, a)
48
+ assert MenuHelpers.menu(a).selected == 0
49
+ assert MenuHelpers.menu(a).highlight.value() == MenuScreen.highlightAt(0)
50
+
51
+ # a sleeping menu rewound and played on sleeps through the same ticks, and a rewind draws again
52
+ fun aSleepingMenuRewoundSleepsThroughTheSameTicks() =
53
+ a := MenuHelpers.framesFrom(TestRig.playWith(io, Menu.game()), 0, 600)
54
+ b := MenuHelpers.framesFrom(TestRig.play(io, Menu.game()), 0, 600)
55
+ assert a.game.frameDrawn().idle()
56
+ back := TestRig(..a, game: a.game.frameDrawn()).rewindTo(300)
57
+ assert back.moved()
58
+ assert !back.game.idle()
59
+ again := MenuHelpers.framesFrom(back, 300, 300)
60
+ assert MenuHelpers.sameMenu(again, b)
61
+
62
+ primitive MenuHelpers =
63
+ fun menu(t: TestRig<Screen>) -> MenuScreen = match t.game.screens.at(0)
64
+ MenuScreen as m => m
65
+ _ => MenuScreen.start()
66
+
67
+ fun play(t: TestRig<Screen>) -> TurnScreen = match t.game.screens.at(1)
68
+ TurnScreen as p => p
69
+ _ => TurnScreen.start()
70
+
71
+ fun idleInput(i: Int) -> Input =
72
+ Input(events: [
73
+ if i == 100 || i == 400 then KeyDown(key: Key.Down)
74
+ if i == 100 || i == 400 then KeyUp(key: Key.Down)
75
+ if i == 250 then PointerMove(x: 50.0, y: 50.0)
76
+ ], held: Held(pointer: Vec2(x: 50.0, y: 50.0)))
77
+
78
+ fun framesFrom(t: TestRig<Screen>, from: Int, n: Int) -> TestRig<Screen> =
79
+ Range.until(0, n).fold(t, |r, f| r.frame(idleInput(from + f), Ticker.Tick))
80
+
81
+ fun sameMenu(a: TestRig<Screen>, b: TestRig<Screen>) -> Bool =
82
+ menu(a).selected == menu(b).selected && menu(a).highlight.value() == menu(b).highlight.value()
83
+ && a.game.skipped == b.game.skipped && a.game.delivered == b.game.delivered
tests/examples/games/menu/actors/Turner.plum ADDED
@@ -0,0 +1,21 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Option
5
+ import std/collections/List
6
+ import std/math/Vec2
7
+ import std/math/Affine
8
+ import std/math/Math
9
+ import std/game/Body
10
+ import std/game/View
11
+ import examples/games/menu/actors/Turner
12
+ import std/Test
13
+
14
+ primitive TurnerTest[UnitTest] =
15
+ # it turns about its centre, which stays where it is
16
+ fun itTurnsAboutItsCentre() =
17
+ t := Turner(body: Body(pos: Vec2(x: 400.0, y: 300.0), turn: 2.0)).step(0.25)
18
+ assert t.place().rotation == 0.5
19
+ assert t.place().pivot() == Vec2(x: 400.0, y: 300.0)
20
+ corner := t.place().local().apply(Vec2(x: -40.0, y: -40.0))
21
+ assert Math.near(corner.distance(Vec2(x: 400.0, y: 300.0)), 40.0 * Math.sqrt(2.0), 0.000001)
tests/examples/games/menu/screens/MenuScreen.plum ADDED
@@ -0,0 +1,76 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Io
6
+ import std/Option
7
+ import std/collections/List
8
+ import std/math/Vec2
9
+ import std/game/Input
10
+ import std/game/View
11
+ import std/game/Label
12
+ import std/game/Button
13
+ import std/game/Cmd
14
+ import std/game/Screen
15
+ import std/game/ScreenSlice
16
+ import std/game/Game
17
+ import std/game/TestRig
18
+ import examples/games/menu/Menu
19
+ import examples/games/menu/screens/MenuScreen
20
+ import std/Test
21
+
22
+ primitive MenuScreenTest[UnitTest] =
23
+ # the menu sleeps while nobody touches it: one tick to come in, then none
24
+ fun theMenuSleepsWhileNobodyTouchesIt() =
25
+ t := MenuScreenHelpers.menu(io).ticks(100)
26
+ assert t.game.delivered == 1
27
+ assert t.game.skipped == 99
28
+ assert !t.game.idle()
29
+ assert t.game.frameDrawn().idle()
30
+
31
+ # Down slides the highlight there, and the menu ticks only while it moves
32
+ fun downSlidesTheHighlightThere() =
33
+ t := MenuScreenHelpers.menu(io).ticks(10).press(Key.Down).tick()
34
+ assert t.screen.selected == 1
35
+ assert t.text(t.find<Label>().at(MenuScreen.Items.length() + 1)) == "Selected: Quit"
36
+ u := t.ticks(60)
37
+ assert u.screen.highlight.value() == MenuScreen.highlightAt(1)
38
+ assert u.game.delivered == 1 + 9
39
+ v := u.press(Key.Down).ticks(60)
40
+ assert v.screen.selected == 0
41
+ assert v.screen.highlight.value() == MenuScreen.highlightAt(0)
42
+ assert MenuScreenHelpers.names(u.press(Key.Up).tick()) == "MoveBy(-1) Tick({Ticker.Tick})"
43
+
44
+ # any key or a pointer that moves wakes the menu for a tick; a pointer that stays put doesn't
45
+ fun aPointerThatDoesNotMoveWakesNothing() =
46
+ t := MenuScreenHelpers.menu(io).tick().press(Key.KeyA).tick()
47
+ assert t.game.delivered == 2
48
+ u := t.ticks(10).pointerMove(10.0, 10.0).tick()
49
+ assert u.game.delivered == 3
50
+ v := u.pointerMove(10.0, 10.0).ticks(10)
51
+ assert v.game.delivered == 3
52
+
53
+ # Enter or Space chooses: Play goes to the play, Quit ends the game
54
+ fun choosingPlaysOrQuits() =
55
+ t := TestRig.play(io, Menu.game()).press(Key.Enter).tick()
56
+ assert t.actions<MenuAction>().map(|a| a.toStr()).join(" ") == "Choose Tick({Ticker.Tick})"
57
+ assert t.showing() == "play"
58
+ assert Cmd.names(MenuScreen.start().update(Choose).cmds) == "goTo(play)"
59
+ assert Cmd.names(MenuScreen.start().update(MoveBy(step: 1)).state.update(Choose).cmds) == "exit"
60
+ u := MenuScreenHelpers.menu(io).press(Key.Down).press(Key.Space).tick()
61
+ assert u.exited()
62
+
63
+ # a click on a button selects it and chooses it; a click beside the buttons does nothing
64
+ fun aClickOnAButtonSelectsAndChoosesIt() =
65
+ t := MenuScreenHelpers.menu(io)
66
+ assert t.count<Button<MenuAction>>() == 2
67
+ u := t.clickAt(400.0, MenuScreen.buttonY(1) + 28.0).tick()
68
+ assert MenuScreenHelpers.names(u) == "Clicked(1) Choose Tick({Ticker.Tick})"
69
+ assert u.screen.selected == 1
70
+ assert u.exited()
71
+ assert MenuScreenHelpers.menu(io).clickAt(400.0, 40.0).tick().cmds.isEmpty()
72
+
73
+ primitive MenuScreenHelpers =
74
+ fun menu(io: Io) -> TestRig<MenuScreen> = TestRig.mount(io, MenuScreen.start())
75
+
76
+ fun names(t: TestRig<MenuScreen>) -> Str = t.actions<MenuAction>().map(|a| a.toStr()).join(" ")
tests/examples/games/menu/screens/TurnScreen.plum ADDED
@@ -0,0 +1,23 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Io
6
+ import std/collections/List
7
+ import std/game/Input
8
+ import std/game/Cmd
9
+ import std/game/Screen
10
+ import std/game/ScreenSlice
11
+ import std/game/Game
12
+ import std/game/TestRig
13
+ import examples/games/menu/Menu
14
+ import examples/games/menu/screens/TurnScreen
15
+ import std/Test
16
+
17
+ primitive TurnScreenTest[UnitTest] =
18
+ # the square turns every tick, and Escape goes back to the menu
19
+ fun theSquareTurnsAndEscapeGoesBack() =
20
+ t := TestRig.mount(io, TurnScreen.start()).ticks(30)
21
+ assert t.screen.turner.place().rotation > 0.9
22
+ assert t.tick().actions<TurnAction>().map(|a| a.toStr()).join(" ") == "Tick({Ticker.Tick})"
23
+ assert Cmd.names(t.screen.update(Back).cmds) == "goTo(menu)"
tests/modules/beat.plum ADDED
@@ -0,0 +1,9 @@
1
+ # A fixture for shown_variant.plum: `Tick` is also a variant there.
2
+ import std/Float
3
+ import std/Str
4
+
5
+ enum Beat[Show] =
6
+ | Tick(dt: Float)
7
+ | Rest
8
+
9
+ fun tick(dt: Float) -> Beat = Tick(dt: dt)
tests/modules/shown_variant.plum ADDED
@@ -0,0 +1,21 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import tests/modules/beat
5
+ import std/Test
6
+
7
+ # `[Show]` on enums of two files that both declare `Tick`: the loader renames one of them,
8
+ # and each still shows the name it was written with.
9
+
10
+ enum Clock[Show] =
11
+ | Tick(n: Int)
12
+ | Stop
13
+
14
+ primitive ShownVariantTest[UnitTest] =
15
+ # each file's `Tick` is shown as `Tick`, with its own fields
16
+ fun aRenamedVariantIsShownByItsName() =
17
+ assert Tick(n: 3).toStr() == "Tick(3)"
18
+ assert Stop.toStr() == "Stop"
19
+ assert ShownVariantTest.beat(0.5) == "Tick(0.5)"
20
+
21
+ fun beat(dt: Float) -> Str = Beat.tick(dt).toStr()