plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
56bbbeb
— Peter John
2026-11-16T13:53:18+05:30
Elm-style screens (user: "the elm style looks good", "Yes" to the geometry and spawning): a slice screen has one entry point, `update(self, a: A) -> Next<Self, A>` (default `Next(state: self)`, so a screen with no actions compiles), and `subscriptions(self) -> List<Sub<A>>` (default empty) in place of `reduce`, `act`, `onKey`, `onPointer`, `held` and `tick`; `enum Sub<A>` (std/game/ScreenSlice) is `OnFrame(fn(Float) -> A)`, `OnKeyDown(key, act)`, `OnKeyUp(key, act)`, `OnHeld(fn(Held) -> A)`, `OnWheel(fn(Float, Vec2) -> A)` and `OnPointerDown`/`OnPointerUp`/`OnPointerMove(fn(Vec2) -> A)`, a list literal with `if` items (`if !self.over then OnHeld(..)`), read once a tick from the screen as the tick found it; each tick delivers the events (presses through `onPress` first, then the subscriptions answering, several in the order listed), then `OnHeld`, then `OnFrame` last; `wants` is "subscribes to `OnHeld`"; `Input.isKeyUpOf`; no stepping phase: the frame is an action and a screen steps its actors in it with its derived `stepped(dt)` (`Tick(dt) => self.stepped(dt)..rules()`), `Screen.steps()` is gone, a plain screen's tick is its `stepped`; every screen derives `stepped` without listing `Steps` (core/steps_derive.rs: `Steps` on a screen is an error, `Steps` stays opt-in for actors, `@stepsWhen` works on a screen or a `[Steps]` actor); the uniqueness analysis stamps a method call on a receiver of a bounded type parameter with the bound (in its own copy of the body) and resolves it among the bound's implementers (`s.update(a)` in `Delivery.actIn` had resolved to every `update`, `Game.update` and `Viewport.update` among them, and lost every update in place); geometry: `Vec2.near(other, dist)` (std/math/Vec2), replacing Orbit Runner's `overlaps`; Orb and Mine spawn themselves, `Orb.spawn(rng, near, phase, tex)` and `Mine.spawn(rng, near, tex)` returning `Rolled<..>` (positional: a fn call takes no named arguments), so `newOrb`/`newMine` are gone; Orbit Runner: `PlayAgain`, `reduce`, `act`, `followed`, `advance`, `onKey`, `held`, `tick` and `overlaps` gone, Enter and R subscribe straight to `StartOver` while the run is over, `deal` folds a `Rolled<List<Orb>>` and ends in `grown`, sounds read before the spread (`sounds := self.assets`), `rules` writes `rng` before `orbs`; PlayingScreen 19 functions to 12, 150 lines to 146; in place (`--explain-fusion`): Orbit Runner 29 spreads where there were 27 (`PlayingScreen.update` 5, `rules`, `deal`, `grown`, `at`, `stepped`), Balloon Pop 22 where there were 21 (`PlaygroundScreen.update` 1), the tick's std spreads kept; checksums: Orbit Runner 946756219 to 818414470 (subscriptions are read at the tick's start, so the tick Enter restarts on steers nothing; with `OnHeld` unconditional it is 946756219 again), scale 502378645 unchanged; benchmarks/screen_views (minimums of 5, before and after): orbit update 11.25 and 12.52 ms (11.1-11.6 and 12.0-12.3 in alternating reruns: the subscription closures called indirectly each tick and the list built each tick; not `Vec2.near`, not the `if` items, not the intermediate action lists, each measured), paint 128.7 and 130.9 ms, scale update view 22.2 and 22.5 ms, paint view 329.0 and 329.5 ms, spread 330.1 and 330.1 ms; ported: Balloon Pop, clicks (a `Tick` action steps the ball), two_screens, benchmarks/screen_views/scale.plum, the tests/std/game, tests/port/game and tests/examples mirrors, compiler/game fixtures and web-test fixtures, the inline games of host_test, game_entry_test and driver_tests (`Stress.update`), TestRig's docs (`dispatch` runs `update`; ticks reach the screen through its subscriptions); tests: tests/std/game/ScreenSlice.plum (the order in a tick, several subscriptions answering one event, an item there only while the state says so, the defaults, `OnHeld` waking an `OnDemand` screen), `Vec2.near`, `Orb.spawn` and `Mine.spawn`, checker diagnostics `stepsIsForAnActorStructHoldingActors` and `stepsWhenGoesOnAnActorFieldOfADerivedStepping`, game_in_place_test's new names; docs: game.md (the minimal game, Stepping, "The slice: update, subscriptions and view" replacing "The slice" and "Input and the tick as actions", undo, commands, testing, "Beside master"), std.md, language.md, backlog (the fold's copies, and a compiler bug met: a closure field bound by the same name in two match arms is "undefined function" in the second, worked around in `Sub.onEvent`), the review plan
- benchmarks/screen_views/scale.plum +11 -11
- compiler/checker/tests/checker/diagnostic_tests.rs +24 -11
- compiler/cli/tests/cli/game_entry_test.rs +4 -4
- compiler/cli/tests/cli/game_in_place_test.rs +15 -9
- compiler/core/src/steps_derive.rs +46 -30
- compiler/core/src/uniqueness.rs +84 -1
- compiler/core/tests/core/formatter_test.rs +2 -2
- compiler/driver/tests/driver_tests.rs +8 -8
- compiler/game/tests/fixtures/assets_fixture.plum +2 -2
- compiler/game/tests/fixtures/camera_fixture.plum +10 -16
- compiler/game/tests/fixtures/host_fixture.plum +2 -2
- compiler/game/tests/fixtures/main_game_fixture.plum +15 -14
- compiler/game/tests/fixtures/main_missing_fixture.plum +2 -2
- compiler/game/tests/fixtures/state_draw_keeps.plum +2 -2
- compiler/game/tests/fixtures/state_in_place.plum +3 -3
- compiler/game/tests/fixtures/state_main_alias.plum +2 -2
- compiler/game/tests/fixtures/state_reset.plum +3 -3
- compiler/game/tests/fixtures/target_fixture.plum +2 -2
- compiler/game/tests/host_test.rs +5 -5
- compiler/game/web-test/fixtures/interleave.plum +2 -2
- compiler/game/web-test/fixtures/main_game.plum +2 -2
- compiler/game/web-test/fixtures/rendertarget.plum +2 -2
- compiler/game/web-test/fixtures/stress.plum +2 -2
- compiler/game/web-test/fixtures/stress_state_view.plum +4 -4
- compiler/game/web-test/fixtures/text_sizes.plum +2 -2
- compiler/tooling/tree-sitter-plum/grammar.js +2 -1
- docs/backlog.md +4 -3
- docs/game.md +91 -76
- docs/language.md +2 -2
- docs/plans/2026-11-13-std-game-review.md +1 -0
- docs/std.md +9 -7
- examples/games/balloonpop/screens/PlaygroundScreen.plum +27 -30
- examples/games/clicks.plum +11 -15
- examples/games/orbitrunner/OrbitRunner.plum +2 -1
- examples/games/orbitrunner/actors/Mine.plum +6 -0
- examples/games/orbitrunner/actors/Orb.plum +6 -0
- examples/games/orbitrunner/screens/PlayingScreen.plum +53 -57
- examples/games/two_screens.plum +4 -9
- std/game/Cmd.plum +2 -3
- std/game/Game.plum +3 -2
- std/game/History.plum +2 -2
- std/game/Input.plum +5 -1
- std/game/Overlay.plum +2 -2
- std/game/Screen.plum +19 -23
- std/game/ScreenSlice.plum +138 -98
- std/game/TestRig.plum +5 -4
- std/game/View.plum +20 -20
- std/math/Vec2.plum +5 -0
- tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +3 -3
- tests/examples/games/orbitrunner/actors/Orb.plum +14 -0
- tests/examples/games/orbitrunner/screens/PlayingScreen.plum +14 -12
- tests/port/game/determinism.plum +10 -10
- tests/port/game/replay.plum +11 -12
- tests/port/game/screens.plum +44 -56
- tests/std/game/Button.plum +4 -4
- tests/std/game/ScreenSlice.plum +88 -8
- tests/std/game/View.plum +7 -7
- tests/std/math/Vec2.plum +8 -0
benchmarks/screen_views/scale.plum
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
# view (as master's benchmarks/screen_views/scale.plum): with `view`, actors whose view is
|
|
3
3
|
# one `Sprite`, made again at each draw; with `hand`, the same actors drawing the same
|
|
4
4
|
# sprite with a hand-written `paintSelf` (`Sprite.draw`). Each is an `Actor`,
|
|
5
|
-
# and the
|
|
5
|
+
# and the screen's frame action (`OnFrame`) steps every one each tick, through its
|
|
6
|
-
#
|
|
6
|
+
# derived `stepped` (`Views.stepIn` over its `List<View>`, or `Views.stepAll` over its
|
|
7
|
-
#
|
|
7
|
+
# `List<ViewDot>`), and does nothing else. One difference
|
|
8
8
|
# from master: master's stepping walk makes each actor's view to look under it, and this
|
|
9
9
|
# branch's does not (an actor found under another could not be put back into a value), so
|
|
10
10
|
# `update view` makes 10,000 fewer one-`Sprite` lists a tick here. With `spread`, the
|
|
@@ -119,21 +119,21 @@ struct HandDot[Actor](i: Int, at: Place, clock: Float) =
|
|
|
119
119
|
|
|
120
120
|
enum CrowdAct = CrowdTick(dt: Float)
|
|
121
121
|
|
|
122
|
-
struct CrowdScreen[ScreenSlice<CrowdAct>
|
|
122
|
+
struct CrowdScreen[ScreenSlice<CrowdAct>](hand: Bool, dots: List<View>) =
|
|
123
123
|
fun of(hand: Bool, n: Int) -> CrowdScreen = CrowdScreen(hand: hand, dots: ScaleBench.dotsFrom(hand, 0, n))
|
|
124
124
|
|
|
125
125
|
fun name(self) -> Str = "crowd"
|
|
126
126
|
|
|
127
127
|
fun view(self) -> List<View> = self.dots
|
|
128
128
|
|
|
129
|
-
fun
|
|
129
|
+
fun subscriptions(self) -> List<Sub<CrowdAct>> = [OnFrame(|dt| CrowdTick(dt: dt))]
|
|
130
130
|
|
|
131
|
-
fun
|
|
131
|
+
fun update(self, a: CrowdAct) -> Next<CrowdScreen, CrowdAct> = match a
|
|
132
|
-
CrowdTick(dt) => self
|
|
132
|
+
CrowdTick(dt) => Next(state: self.stepped(dt))
|
|
133
133
|
|
|
134
134
|
fun frameSum(self) -> Int = Timing.hash(self.dots.map(|d| ScaleBench.frameOf(d)))
|
|
135
135
|
|
|
136
|
-
struct SpreadScreen[ScreenSlice<CrowdAct>
|
|
136
|
+
struct SpreadScreen[ScreenSlice<CrowdAct>](dots: List<ViewDot>) =
|
|
137
137
|
fun of(n: Int) -> SpreadScreen = SpreadScreen(dots: Range.until(0, n).map(|i| ViewDot.of(i)))
|
|
138
138
|
|
|
139
139
|
fun name(self) -> Str = "spread"
|
|
@@ -143,9 +143,9 @@ struct SpreadScreen[ScreenSlice<CrowdAct>, Steps](dots: List<ViewDot>) =
|
|
|
143
143
|
Box(w: 800.0, h: 4.0, color: Color.White)
|
|
144
144
|
]
|
|
145
145
|
|
|
146
|
-
fun
|
|
146
|
+
fun subscriptions(self) -> List<Sub<CrowdAct>> = [OnFrame(|dt| CrowdTick(dt: dt))]
|
|
147
147
|
|
|
148
|
-
fun
|
|
148
|
+
fun update(self, a: CrowdAct) -> Next<SpreadScreen, CrowdAct> = match a
|
|
149
|
-
CrowdTick(dt) => self
|
|
149
|
+
CrowdTick(dt) => Next(state: self.stepped(dt))
|
|
150
150
|
|
|
151
151
|
fun frameSum(self) -> Int = Timing.hash(self.dots.map(|d| Int(d.clock * 8.0) % 4))
|
compiler/checker/tests/checker/diagnostic_tests.rs
CHANGED
|
@@ -395,18 +395,29 @@ fn stepsErrors(rest: &str) -> Vec<plum_core::diag::Diagnostic> {
|
|
|
395
395
|
frontErrors(&format!("{STEPS_TRAITS}{rest}\nprimitive Main[App] =\n fun main() -> Int = 1\n"))
|
|
396
396
|
}
|
|
397
397
|
|
|
398
|
+
/// Whether the front end takes `rest` after the stepping traits.
|
|
399
|
+
fn stepsOk(rest: &str) -> bool {
|
|
400
|
+
let mut source = plum_test_support::parseRawSource(&format!("{STEPS_TRAITS}{rest}\nprimitive Main[App] =\n fun main() -> Int = 1\n"));
|
|
401
|
+
source.stampFile("main.plum");
|
|
402
|
+
plum_core::lower::frontEndDiag(&mut source).is_ok()
|
|
403
|
+
}
|
|
404
|
+
|
|
398
|
-
/// `[Steps]` is for
|
|
405
|
+
/// `[Steps]` is for an actor struct holding actors; a screen's `stepped` is derived without it.
|
|
399
406
|
#[test]
|
|
400
|
-
fn
|
|
407
|
+
fn stepsIsForAnActorStructHoldingActors() {
|
|
401
408
|
let es = stepsErrors("enum E[Actor, Steps] = A | B\n");
|
|
402
409
|
assert!(es.iter().any(|e| e.message.contains("`E` lists `Steps`, which steps a struct's actor fields, but it is an enum")), "{es:?}");
|
|
403
410
|
let es = stepsErrors("struct P[Steps](w: W)\n");
|
|
404
411
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
405
|
-
assert!(es[0].message.contains("`P` lists `Steps` but is
|
|
412
|
+
assert!(es[0].message.contains("`P` lists `Steps` but is not an `Actor`"), "{es:?}");
|
|
406
413
|
assert_eq!((es[0].file.as_str(), es[0].line), ("main.plum", 12), "{es:?}");
|
|
407
|
-
let es = stepsErrors("struct P[Screen, Steps](
|
|
414
|
+
let es = stepsErrors("struct P[Screen, Steps](w: W) =\n fun name(self) -> Str = \"p\"\n");
|
|
415
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
416
|
+
assert!(es[0].message.contains("`P` is a screen and lists `Steps`: a screen's `stepped` is derived without it"), "{es:?}");
|
|
417
|
+
let es = stepsErrors("struct P[Actor, Steps](n: Int, ws: List<Int>) =\n fun step(self, dt: Float) -> P = self\n");
|
|
408
418
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
409
419
|
assert!(es[0].message.contains("`P` lists `Steps` but holds no actors"), "{es:?}");
|
|
420
|
+
assert!(stepsOk("struct P[Screen](n: Int, ws: List<Int>) =\n fun name(self) -> Str = \"p\"\n"), "a screen holding no actors keeps the default `stepped`");
|
|
410
421
|
}
|
|
411
422
|
|
|
412
423
|
/// `[Show]` derives `toStr` only when each field of a type of the program can be shown.
|
|
@@ -418,17 +429,19 @@ fn showNeedsEachFieldShown() {
|
|
|
418
429
|
assert_eq!(es[0].line, 6, "{es:?}");
|
|
419
430
|
}
|
|
420
431
|
|
|
421
|
-
/// `@stepsWhen` goes on a field holding actors of a `[Steps]`
|
|
432
|
+
/// `@stepsWhen` goes on a field holding actors of a screen, or of a `[Steps]` actor, whose
|
|
433
|
+
/// stepping is derived.
|
|
422
434
|
#[test]
|
|
423
|
-
fn
|
|
435
|
+
fn stepsWhenGoesOnAnActorFieldOfADerivedStepping() {
|
|
424
|
-
let es = stepsErrors("struct P[Screen
|
|
436
|
+
let es = stepsErrors("struct P[Screen](on: Bool, @stepsWhen(self.on) n: Int, w: W) =\n fun name(self) -> Str = \"p\"\n");
|
|
425
437
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
426
438
|
assert!(es[0].message.contains("`@stepsWhen` on `P.n`, a `Int`: only a field holding actors is stepped"), "{es:?}");
|
|
427
|
-
assert_eq!((es[0].line, es[0].column), (12,
|
|
439
|
+
assert_eq!((es[0].line, es[0].column), (12, 39), "{es:?}");
|
|
428
|
-
|
|
440
|
+
assert!(stepsOk("struct P[Screen](on: Bool, @stepsWhen(self.on) w: W) =\n fun name(self) -> Str = \"p\"\n"));
|
|
441
|
+
let es = stepsErrors("struct P(on: Bool, @stepsWhen(self.on) w: W)\n");
|
|
429
442
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
430
443
|
assert!(es[0].message.contains("`@stepsWhen` on `P.w`: `P` doesn't list `Steps`"), "{es:?}");
|
|
431
|
-
let es = stepsErrors("struct P[Screen
|
|
444
|
+
let es = stepsErrors("struct P[Screen](on: Bool, @stepsWhen(self.on) w: W) =\n fun name(self) -> Str = \"p\"\n\n fun stepped(self, dt: Float) -> P = self\n");
|
|
432
445
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
433
446
|
assert!(es[0].message.contains("`@stepsWhen` on `P.w` does nothing: `P` writes its own `stepped`"), "{es:?}");
|
|
434
447
|
}
|
|
@@ -436,6 +449,6 @@ fn stepsWhenGoesOnAnActorFieldOfAStepsType() {
|
|
|
436
449
|
/// `@stepsWhen` is the one field attribute.
|
|
437
450
|
#[test]
|
|
438
451
|
fn anUnknownFieldAttributeIsAnError() {
|
|
439
|
-
let es = errors(&format!("{STEPS_TRAITS}struct P[Screen
|
|
452
|
+
let es = errors(&format!("{STEPS_TRAITS}struct P[Screen](@later(1) w: W) =\n fun name(self) -> Str = \"p\"\n\nprimitive Main[App] =\n fun main() -> Int = 1\n"));
|
|
440
453
|
assert!(es.iter().any(|e| e.message.contains("`@later` is not a field attribute")), "{es:?}");
|
|
441
454
|
}
|
compiler/cli/tests/cli/game_entry_test.rs
CHANGED
|
@@ -64,8 +64,8 @@ const HEAD: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str
|
|
|
64
64
|
/// A whole game: one screen that counts its ticks.
|
|
65
65
|
const GAME: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/game/Input\nimport std/App\n\
|
|
66
66
|
import std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
|
|
67
|
-
struct CountScreen[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"count\"\n fun
|
|
67
|
+
struct CountScreen[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"count\"\n fun subscriptions(self) -> List<Sub<Int>> = [OnFrame(|dt| 1)]\n \
|
|
68
|
-
fun
|
|
68
|
+
fun update(self, a: Int) -> Next<CountScreen, Int> = Next(state: CountScreen(n: self.n + a))\n\nprimitive Main[App] =\n \
|
|
69
69
|
fun main(io: Io) -> Game =\n only: Screen := CountScreen(n: 0)\n Game(screens: [only])\n";
|
|
70
70
|
|
|
71
71
|
#[test]
|
|
@@ -130,8 +130,8 @@ fn screensGame(names: &[&str], to: &str) -> String {
|
|
|
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
132
|
import std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
|
|
133
|
-
struct Named[ScreenSlice<Int>](n: Str) =\n fun name(self) -> Str = self.n\n fun
|
|
133
|
+
struct Named[ScreenSlice<Int>](n: Str) =\n fun name(self) -> Str = self.n\n fun subscriptions(self) -> List<Sub<Int>> = [OnFrame(|dt| 1)]\n \
|
|
134
|
-
fun
|
|
134
|
+
fun update(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(), 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
|
@@ -3,11 +3,15 @@
|
|
|
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
5
|
//!
|
|
6
|
-
//! Orbit Runner's
|
|
6
|
+
//! Orbit Runner's updates are in place since std's fold copies the screen once as it enters
|
|
7
|
-
//!
|
|
7
|
+
//! (`@copy` in `Delivery.deliverTo`): every step of the tick is then unique, so
|
|
8
|
-
//! `PlayingScreen.
|
|
8
|
+
//! `PlayingScreen.update` (5: steer, the frame's spread after `stepped`, scored, hit and start
|
|
9
|
+
//! over, whose `best` is now read before the spread), `rules`, `deal`, `grown`, `at` and its
|
|
9
|
-
//!
|
|
10
|
+
//! derived `stepped` need no `$unique` version. Since the Elm-style screens (2026-11-16) a call
|
|
11
|
+
//! on a receiver of a bounded type parameter (`s.update(a)` with `S: ScreenSlice<A>`) resolves
|
|
12
|
+
//! among the bound's implementers alone, not to every `update` of the program (`Game.update`,
|
|
10
|
-
//!
|
|
13
|
+
//! `Viewport.update`). Balloon Pop's `update` has one in place (its `view` keeps `self`, as
|
|
14
|
+
//! before, so the others copy).
|
|
11
15
|
//!
|
|
12
16
|
//! `Mine.step` (1), `Mine.put` (1) and `Orb.put$unique` (1) went on 2026-11-16 (R3): an orb
|
|
13
17
|
//! and a mine hold their `Motion`, so a step is one spread of `self`, a copy as `self` is
|
|
@@ -65,17 +69,19 @@ const TICK: &[(&str, usize)] = &[
|
|
|
65
69
|
fn orbitRunnerKeepsItsInPlaceSpreads() {
|
|
66
70
|
let mut want = TICK.to_vec();
|
|
67
71
|
want.extend([
|
|
68
|
-
("PlayingScreen.
|
|
72
|
+
("PlayingScreen.update", 5),
|
|
73
|
+
("PlayingScreen.rules", 1),
|
|
69
74
|
("PlayingScreen.at", 1),
|
|
70
75
|
("PlayingScreen.stepped", 1),
|
|
71
76
|
("PlayingScreen.deal", 1),
|
|
72
|
-
("PlayingScreen.newOrb", 1),
|
|
73
|
-
("PlayingScreen.
|
|
77
|
+
("PlayingScreen.grown", 1),
|
|
74
78
|
]);
|
|
75
79
|
assertKept("examples/games/orbitrunner/OrbitRunner.plum", &want);
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
#[test]
|
|
79
83
|
fn balloonPopKeepsItsInPlaceSpreads() {
|
|
84
|
+
let mut want = TICK.to_vec();
|
|
85
|
+
want.push(("PlaygroundScreen.update", 1));
|
|
80
|
-
assertKept("examples/games/balloonpop/BalloonPop.plum",
|
|
86
|
+
assertKept("examples/games/balloonpop/BalloonPop.plum", &want);
|
|
81
87
|
}
|
compiler/core/src/steps_derive.rs
CHANGED
|
@@ -1,31 +1,34 @@
|
|
|
1
|
-
//!
|
|
1
|
+
//! The stepping of a struct's actor fields, derived: every `Screen`'s `stepped`, and the
|
|
2
|
+
//! field stepping of an `Actor` that lists `[Steps]` (std/game/View).
|
|
2
3
|
//!
|
|
3
|
-
//! A
|
|
4
|
+
//! A screen, and an actor that lists `Steps`, gets, as an ordinary method written out here
|
|
4
|
-
//! checker sees it, the stepping of each field that holds actors: a field whose
|
|
5
|
+
//! before the checker sees it, the stepping of each field that holds actors: a field whose
|
|
5
|
-
//! `Actor` (a type that implements it, or a trait type that is one), a `List` of
|
|
6
|
+
//! type is an `Actor` (a type that implements it, or a trait type that is one), a `List` of
|
|
6
|
-
//! `Option` of one, or a `List<View>` (each `Actor` in it, through
|
|
7
|
+
//! actors, an `Option` of one, or a `List<View>` (each `Actor` in it, through
|
|
7
|
-
//! test per item, as the list holds views of any kind). Other fields
|
|
8
|
+
//! `Views.stepIn`: a type test per item, as the list holds views of any kind). Other fields
|
|
9
|
+
//! are left as they are. What is made is what a screen would write by hand, one static
|
|
8
|
-
//!
|
|
10
|
+
//! construction:
|
|
9
11
|
//!
|
|
10
12
|
//! fun stepped(self, dt: Float) -> PlayingScreen =
|
|
11
13
|
//! PlayingScreen(..self, ship: self.ship.step(dt), mines: Views.stepAll(self.mines, dt))
|
|
12
14
|
//!
|
|
13
15
|
//! (`Views.stepSome` for an `Option`), so it costs what the hand-written one did.
|
|
14
16
|
//!
|
|
15
|
-
//! - On a `Screen` it is `stepped(dt)`,
|
|
17
|
+
//! - On a `Screen` it is `stepped(dt)`, which a slice calls in its frame action and a plain
|
|
18
|
+
//! screen's tick is. It needs no `Steps`. A screen that writes its own `stepped` keeps it,
|
|
16
|
-
//!
|
|
19
|
+
//! and one holding no actors keeps the default: nothing is derived.
|
|
17
|
-
//! - On an `Actor` it is part of `step`: the actor's own `step`, if it
|
|
20
|
+
//! - On an `Actor` that lists `Steps` it is part of `step`: the actor's own `step`, if it
|
|
18
|
-
//! (it is renamed `step$own`), and then its actor fields are stepped
|
|
21
|
+
//! writes one, runs first (it is renamed `step$own`), and then its actor fields are stepped
|
|
19
|
-
//! container writes only what is special about itself, and the
|
|
22
|
+
//! (`step$fields`), so a container writes only what is special about itself, and the
|
|
20
|
-
//! actor after its own step.
|
|
23
|
+
//! fields' conditions see the actor after its own step.
|
|
21
24
|
//! - `@stepsWhen(cond) name: T` steps that field only while `cond` (read on `self`) holds:
|
|
22
|
-
//! `if cond then <stepped> else self.name`.
|
|
25
|
+
//! `if cond then <stepped> else self.name`.
|
|
23
|
-
//! whole screen.
|
|
24
26
|
//!
|
|
25
|
-
//! Errors: `Steps` on
|
|
27
|
+
//! Errors: `Steps` on a screen (its `stepped` is derived without it), on an enum, on a
|
|
28
|
+
//! struct that is not an `Actor`, or on an actor with no field holding actors; `@stepsWhen`
|
|
26
|
-
//!
|
|
29
|
+
//! on a field that holds no actors, on an actor that doesn't list `Steps` or a type that is
|
|
27
|
-
//!
|
|
30
|
+
//! neither a screen nor an actor, or on a screen that writes its own `stepped` (the
|
|
28
|
-
//! would do nothing).
|
|
31
|
+
//! attribute would do nothing).
|
|
29
32
|
|
|
30
33
|
use std::collections::{HashMap, HashSet};
|
|
31
34
|
|
|
@@ -60,7 +63,8 @@ enum Holds {
|
|
|
60
63
|
pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
61
64
|
let anyAttr = source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.variants.iter().any(|v| !v.field_steps_when.is_empty())));
|
|
62
65
|
let anySteps = source.items.iter().any(|i| matches!(i, Item::Enum(e) if lists(e, STEPS_TRAIT)));
|
|
66
|
+
let anyScreen = source.items.iter().any(|i| matches!(i, Item::Trait(t) if t.name == SCREEN));
|
|
63
|
-
if !anyAttr && !anySteps {
|
|
67
|
+
if !anyAttr && !anySteps && !anyScreen {
|
|
64
68
|
return Vec::new();
|
|
65
69
|
}
|
|
66
70
|
let supers: HashMap<String, Vec<String>> = source
|
|
@@ -122,25 +126,35 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
122
126
|
.flat_map(|v| v.field_steps_when.iter().enumerate().filter_map(|(i, c)| c.as_ref().map(|c| (i, c))))
|
|
123
127
|
.collect();
|
|
124
128
|
let attrAt = |c: &Expr, msg: String| at(c.span.startLine.max(e.line), if c.span.startLine == 0 { e.column } else { c.span.startColumn }, msg);
|
|
129
|
+
let traits = &traitsOf[name];
|
|
130
|
+
let actor = traits.contains(ACTOR);
|
|
131
|
+
let screen = traits.contains(SCREEN);
|
|
125
|
-
|
|
132
|
+
let steps = lists(e, STEPS_TRAIT);
|
|
133
|
+
if steps && screen {
|
|
134
|
+
errors.push(here(format!(
|
|
135
|
+
"`{name}` is a screen and lists `Steps`: a screen's `stepped` is derived without it (leave `Steps` out; it is for actors)"
|
|
136
|
+
)));
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if !steps && !screen {
|
|
126
140
|
for (i, c) in &attrs {
|
|
127
141
|
let field = e.variants.iter().find_map(|v| v.field_names.get(*i)).cloned().unwrap_or_default();
|
|
128
142
|
errors.push(attrAt(
|
|
129
143
|
c,
|
|
130
|
-
format!("`@stepsWhen` on `{name}.{field}`: `{name}` doesn't list `Steps`, which steps
|
|
144
|
+
format!("`@stepsWhen` on `{name}.{field}`: `{name}` doesn't list `Steps`, which steps an actor's fields (`struct {name}[.., Steps](..)`)"),
|
|
131
145
|
));
|
|
132
146
|
}
|
|
133
147
|
continue;
|
|
134
148
|
}
|
|
135
149
|
if !e.isStruct() {
|
|
150
|
+
if steps {
|
|
136
|
-
|
|
151
|
+
errors.push(here(format!("`{name}` lists `Steps`, which steps a struct's actor fields, but it is an enum")));
|
|
152
|
+
}
|
|
137
153
|
continue;
|
|
138
154
|
}
|
|
139
|
-
let traits = &traitsOf[name];
|
|
140
|
-
let actor = traits.contains(ACTOR);
|
|
141
|
-
if
|
|
155
|
+
if steps && !actor {
|
|
142
156
|
errors.push(here(format!(
|
|
143
|
-
"`{name}` lists `Steps` but is
|
|
157
|
+
"`{name}` lists `Steps` but is not an `Actor`: `Steps` steps an actor's fields after its `step` (a screen's `stepped` is derived without it)"
|
|
144
158
|
)));
|
|
145
159
|
continue;
|
|
146
160
|
}
|
|
@@ -165,9 +179,11 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
165
179
|
}
|
|
166
180
|
}
|
|
167
181
|
if fields.is_empty() {
|
|
182
|
+
if steps {
|
|
168
|
-
|
|
183
|
+
errors.push(here(format!(
|
|
169
|
-
|
|
184
|
+
"`{name}` lists `Steps` but holds no actors: no field is an `Actor`, a `List` of actors, an `Option` of one or a `List<View>`"
|
|
170
|
-
|
|
185
|
+
)));
|
|
186
|
+
}
|
|
171
187
|
continue;
|
|
172
188
|
}
|
|
173
189
|
let ownStepped = !actor && hasMethod(&source.items, name, "stepped");
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -477,8 +477,11 @@ struct An {
|
|
|
477
477
|
/// Every method unit by name: a call `x.m()` is resolved to all of them (no types here).
|
|
478
478
|
methodIdx: HashMap<String, Vec<usize>>,
|
|
479
479
|
/// The program's traits: a call whose receiver is a trait object may run the method of any
|
|
480
|
-
/// implementer, so it resolves by name.
|
|
480
|
+
/// implementer, so it resolves by name among the trait's implementers.
|
|
481
481
|
traits: HashSet<String>,
|
|
482
|
+
/// The types implementing each trait (after `trait_defaults::expandSupertraits`, so a
|
|
483
|
+
/// subtrait's implementers are among its supertraits').
|
|
484
|
+
implementers: HashMap<String, HashSet<String>>,
|
|
482
485
|
enums: HashMap<String, Vec<String>>,
|
|
483
486
|
sites: Vec<Site>,
|
|
484
487
|
escaped: HashSet<usize>,
|
|
@@ -707,6 +710,13 @@ impl An {
|
|
|
707
710
|
let all = self.methodIdx.get(&c.name).map(|v| v.as_slice()).unwrap_or(&[]);
|
|
708
711
|
match &c.recv {
|
|
709
712
|
Some(t) if !self.traits.contains(t) => all.iter().copied().filter(|&g| self.units[g].ty.as_deref() == Some(t.as_str())).collect(),
|
|
713
|
+
Some(t) => {
|
|
714
|
+
let imps = self.implementers.get(t);
|
|
715
|
+
all.iter()
|
|
716
|
+
.copied()
|
|
717
|
+
.filter(|&g| self.units[g].ty.as_deref().is_none_or(|ty| ty == t || self.traits.contains(ty) || imps.is_some_and(|i| i.contains(ty))))
|
|
718
|
+
.collect()
|
|
719
|
+
}
|
|
710
720
|
_ => all.to_vec(),
|
|
711
721
|
}
|
|
712
722
|
}
|
|
@@ -2402,11 +2412,84 @@ fn build(src: &Source, distrust: &HashSet<String>) -> An {
|
|
|
2402
2412
|
}
|
|
2403
2413
|
}
|
|
2404
2414
|
let varTy: Vec<HashMap<String, Option<String>>> = units.iter().map(varTypes).collect();
|
|
2415
|
+
let paramBound: Vec<HashMap<String, String>> = units
|
|
2416
|
+
.iter()
|
|
2417
|
+
.map(|u| match (&u.kind, &src.items[u.itemIdx]) {
|
|
2418
|
+
(Kind::Fn, Item::Fn(f)) => {
|
|
2419
|
+
// Names bound again in the body (a local, a pattern binder) are left out.
|
|
2420
|
+
let mut rebound: HashSet<String> = HashSet::new();
|
|
2421
|
+
walkBlock(&u.block, &mut |n| {
|
|
2422
|
+
match n {
|
|
2423
|
+
Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
|
|
2424
|
+
for t in &a.targets {
|
|
2425
|
+
if let AssignTarget::Var(v) = t {
|
|
2426
|
+
rebound.insert(v.clone());
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
|
|
2431
|
+
let mut names = vec![];
|
|
2432
|
+
m.cases.iter().flat_map(|c| &c.patterns).for_each(|p| crate::visit::patternBinders(p, &mut names));
|
|
2433
|
+
rebound.extend(names);
|
|
2434
|
+
}
|
|
2435
|
+
Node::E(Expr { kind: ExprKind::Bind(b), .. }) => {
|
|
2436
|
+
let mut names = vec![];
|
|
2437
|
+
b.case.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
|
|
2438
|
+
rebound.extend(names);
|
|
2439
|
+
}
|
|
2440
|
+
_ => {}
|
|
2441
|
+
}
|
|
2442
|
+
true
|
|
2443
|
+
});
|
|
2444
|
+
f.params
|
|
2445
|
+
.iter()
|
|
2446
|
+
.filter_map(|p| {
|
|
2447
|
+
let ParamType::Type(t) = &p.ty else { return None };
|
|
2448
|
+
let b = f.bounds.iter().find(|(g, _)| *g == t.name).and_then(|(_, bs)| bs.first())?;
|
|
2449
|
+
(!rebound.contains(&p.name)).then(|| (p.name.clone(), b.name.clone()))
|
|
2450
|
+
})
|
|
2451
|
+
.collect()
|
|
2452
|
+
}
|
|
2453
|
+
_ => HashMap::new(),
|
|
2454
|
+
})
|
|
2455
|
+
.collect();
|
|
2456
|
+
// A method call on such a parameter is stamped with the bound (in the units' own copies of
|
|
2457
|
+
// the bodies), so `cands` resolves it among the bound's implementers alone, not to every
|
|
2458
|
+
// method of that name (`s.update(a)` is not `Game.update`).
|
|
2459
|
+
for (u, pb) in units.iter_mut().zip(¶mBound) {
|
|
2460
|
+
if pb.is_empty() {
|
|
2461
|
+
continue;
|
|
2462
|
+
}
|
|
2463
|
+
mutBlock(&mut u.block, &mut |e| {
|
|
2464
|
+
if let ExprKind::Attribute(a) = &mut e.kind {
|
|
2465
|
+
let n = match &a.object.kind {
|
|
2466
|
+
ExprKind::Var(n) => Some(n.clone()),
|
|
2467
|
+
_ => None,
|
|
2468
|
+
};
|
|
2469
|
+
if let (AttrKind::Method(c), Some(n)) = (&mut a.attr, n) {
|
|
2470
|
+
if c.recv.is_none() {
|
|
2471
|
+
c.recv = pb.get(&n).cloned();
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2405
2477
|
let mut an = An {
|
|
2406
2478
|
units,
|
|
2407
2479
|
freeIdx,
|
|
2408
2480
|
methodIdx,
|
|
2409
2481
|
traits: src.items.iter().filter_map(|i| if let Item::Trait(t) = i { Some(t.name.clone()) } else { None }).collect(),
|
|
2482
|
+
implementers: {
|
|
2483
|
+
let mut m: HashMap<String, HashSet<String>> = HashMap::new();
|
|
2484
|
+
for i in &src.items {
|
|
2485
|
+
if let Item::Enum(e) = i {
|
|
2486
|
+
for t in &e.implements {
|
|
2487
|
+
m.entry(t.name.clone()).or_default().insert(e.name.clone());
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
m
|
|
2492
|
+
},
|
|
2410
2493
|
enums,
|
|
2411
2494
|
sites: vec![],
|
|
2412
2495
|
escaped: HashSet::new(),
|
compiler/core/tests/core/formatter_test.rs
CHANGED
|
@@ -384,9 +384,9 @@ fn blocksAndListLinesFormat() {
|
|
|
384
384
|
/// A field's attribute stays before it, one space between.
|
|
385
385
|
#[test]
|
|
386
386
|
fn aFieldAttributeFormats() {
|
|
387
|
-
let input = "struct P[Screen
|
|
387
|
+
let input = "struct P[Screen](over: Bool, @stepsWhen( !self.over ) mines: List<Mine>, rings: List<Ring>) =\n fun name(self) -> Str = \"p\"\n";
|
|
388
388
|
let once = formatSource(input).expect("first pass");
|
|
389
|
-
let expected = "struct P[Screen
|
|
389
|
+
let expected = "struct P[Screen](over: Bool, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =\n fun name(self) -> Str = \"p\"\n";
|
|
390
390
|
assert_eq!(once, expected);
|
|
391
391
|
assertFormatsUnchanged(expected);
|
|
392
392
|
}
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -205,8 +205,8 @@ fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
|
|
|
205
205
|
|
|
206
206
|
// ---- a game: the host is the caller the proof cannot see ----
|
|
207
207
|
|
|
208
|
-
/// A game (std/game/Game) of one screen, `Stress`, a slice whose
|
|
208
|
+
/// A game (std/game/Game) of one screen, `Stress`, a slice whose frame action is `dt`; `step`,
|
|
209
|
-
/// `draw` and `main` are the
|
|
209
|
+
/// `draw` and `main` are the state of its update, its draw and the screen the game starts with.
|
|
210
210
|
fn gameSource(name: &str, main: &str, step: &str, draw: &str) -> Source {
|
|
211
211
|
let text = format!(
|
|
212
212
|
"module {name}\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Input\nimport std/App\n\
|
|
@@ -214,8 +214,8 @@ fn gameSource(name: &str, main: &str, step: &str, draw: &str) -> Source {
|
|
|
214
214
|
struct Stress[ScreenSlice<Float>](label: Str, t: Int, n: Int) =\n \
|
|
215
215
|
const Start = Stress(label: \"s\", t: 0, n: 0)\n \
|
|
216
216
|
fun name(self) -> Str = \"pane\"\n \
|
|
217
|
-
fun
|
|
217
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]\n \
|
|
218
|
-
fun
|
|
218
|
+
fun update(self, dt: Float) -> Next<Stress, Float> =\n Next(state: {step})\n \
|
|
219
219
|
fun later(self) -> Stress = Stress(..self, n: 99)\n \
|
|
220
220
|
fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =\n {draw}\nprimitive Main[App] =\n \
|
|
221
221
|
fun main(io: Io) -> Game =\n \
|
|
@@ -232,20 +232,20 @@ const SPREAD_T: &str = "Stress(..self, t: self.t + 1)";
|
|
|
232
232
|
const DRAW_N: &str = "io.printLn(\"{self.n}\")";
|
|
233
233
|
|
|
234
234
|
/// The game holds the constant itself: std's fold steps a copy of the screen (`@copy` in
|
|
235
|
-
/// `Delivery.deliverTo`), so the
|
|
235
|
+
/// `Delivery.deliverTo`), so the update is written in place into that copy and never into
|
|
236
236
|
/// `Stress.Start`.
|
|
237
237
|
#[test]
|
|
238
238
|
fn gameStartingFromAConstantActorCopies() {
|
|
239
239
|
let info = check(&gameSource("g_const", "Stress.Start", SPREAD_T, DRAW_N), &PassOptions::default()).expect("checks");
|
|
240
|
-
assert!(spreadInPlace(&info, "Stress", "
|
|
240
|
+
assert!(spreadInPlace(&info, "Stress", "update"));
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
-
///
|
|
243
|
+
/// An update may hand the game the constant on any tick, and the next tick would write into it.
|
|
244
244
|
#[test]
|
|
245
245
|
fn gameStepReturningAConstantCopies() {
|
|
246
246
|
let step = format!("if self.t > 5 then Stress.Start else {SPREAD_T}");
|
|
247
247
|
let info = check(&gameSource("g_reset", FRESH_ACTOR, &step, DRAW_N), &PassOptions::default()).expect("checks");
|
|
248
|
-
assert!(!spreadInPlace(&info, "Stress", "
|
|
248
|
+
assert!(!spreadInPlace(&info, "Stress", "update"));
|
|
249
249
|
}
|
|
250
250
|
|
|
251
251
|
/// The host reads the game again next frame, so the screen's `draw` must not write it, even
|
compiler/game/tests/fixtures/assets_fixture.plum
CHANGED
|
@@ -25,9 +25,9 @@ import std/App
|
|
|
25
25
|
struct State[ScreenSlice<Float>](frames: Int) =
|
|
26
26
|
fun name(self) -> Str = "page"
|
|
27
27
|
|
|
28
|
-
fun
|
|
28
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
29
29
|
|
|
30
|
-
fun
|
|
30
|
+
fun update(self, dt: Float) -> Next<State, Float> = Next(state: State(frames: self.frames + 1))
|
|
31
31
|
|
|
32
32
|
# Loads a texture and files from the asset root and reports what came back as text.
|
|
33
33
|
fun view(self) -> List<View> = [StateDrawing(s: self)]
|
compiler/game/tests/fixtures/camera_fixture.plum
CHANGED
|
@@ -35,23 +35,17 @@ struct CamScreen[ScreenSlice<CamAct>](scaling: Scaling) =
|
|
|
35
35
|
|
|
36
36
|
fun view(self) -> List<View> = [Box(x: 10.0, y: 100.0, w: 20.0, h: 20.0, color: Color.Red), Box(x: 420.0, y: 100.0, w: 20.0, h: 20.0, color: Color.Blue)]
|
|
37
37
|
|
|
38
|
-
fun
|
|
38
|
+
fun subscriptions(self) -> List<Sub<CamAct>> = [
|
|
39
|
-
KeyDown(k) =>
|
|
40
|
-
|
|
39
|
+
OnKeyDown(key: Key.KeyF, act: Use(scaling: Fit))
|
|
41
|
-
|
|
40
|
+
OnKeyDown(key: Key.KeyI, act: Use(scaling: Fill))
|
|
42
|
-
|
|
41
|
+
OnKeyDown(key: Key.KeyE, act: Use(scaling: Extend))
|
|
43
|
-
|
|
42
|
+
OnKeyDown(key: Key.KeyS, act: Use(scaling: Stretch))
|
|
44
|
-
|
|
43
|
+
OnKeyDown(key: Key.KeyG, act: Go)
|
|
45
|
-
|
|
44
|
+
]
|
|
46
|
-
|
|
45
|
+
|
|
47
|
-
|
|
48
|
-
fun reduce(self, a: CamAct) -> CamScreen = match a
|
|
49
|
-
Use(s) => CamScreen(scaling: s)
|
|
50
|
-
Go => self
|
|
51
|
-
|
|
52
|
-
fun
|
|
46
|
+
fun update(self, a: CamAct) -> Next<CamScreen, CamAct> = match a
|
|
47
|
+
Use(s) => Next(state: CamScreen(scaling: s))
|
|
53
48
|
Go => Next(state: self, cmds: [GoTo(name: "two")])
|
|
54
|
-
_ => Next(state: self.reduce(a))
|
|
55
49
|
|
|
56
50
|
# A culled 400 by 300 world, fitted: a green box at (10, 100) and a white one at (300, 100).
|
|
57
51
|
struct TwoScreen[Screen](n: Int) =
|
compiler/game/tests/fixtures/host_fixture.plum
CHANGED
|
@@ -26,9 +26,9 @@ import std/App
|
|
|
26
26
|
struct State[ScreenSlice<Float>](frames: Int) =
|
|
27
27
|
fun name(self) -> Str = "page"
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
30
30
|
|
|
31
|
-
fun
|
|
31
|
+
fun update(self, dt: Float) -> Next<State, Float> = Next(state: State(frames: self.frames + 1))
|
|
32
32
|
|
|
33
33
|
fun view(self) -> List<View> = [StateDrawing(s: self)]
|
|
34
34
|
|
compiler/game/tests/fixtures/main_game_fixture.plum
CHANGED
|
@@ -22,27 +22,28 @@ import std/game/Place
|
|
|
22
22
|
import std/App
|
|
23
23
|
|
|
24
24
|
# A game whose entry is `main`, declared to return a `Game`: one screen, `Orbs`, that
|
|
25
|
-
# counts the events of each tick (`Heard`
|
|
25
|
+
# counts the events of each tick (`Heard`: A going down, and each pointer event), keeps
|
|
26
|
-
# held at its last tick and moves while Right is held.
|
|
26
|
+
# what is held at its last tick and moves while Right is held.
|
|
27
27
|
enum Step = Heard | Saw(held: Held) | Moved(dt: Float)
|
|
28
28
|
|
|
29
29
|
struct Orbs[ScreenSlice<Step>](x: Float, ship: Texture, held: Held, heard: Int, events: Int, frame: Int) =
|
|
30
30
|
fun name(self) -> Str = "page"
|
|
31
31
|
|
|
32
|
-
fun onKey(self, e: InputEvent) -> Option<Step> = Some(Heard)
|
|
33
|
-
|
|
34
|
-
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<Step> = Some(Heard)
|
|
35
|
-
|
|
36
|
-
fun
|
|
32
|
+
fun subscriptions(self) -> List<Sub<Step>> = [
|
|
37
|
-
|
|
33
|
+
OnKeyDown(key: Key.KeyA, act: Heard)
|
|
34
|
+
OnPointerDown(|at| Heard)
|
|
35
|
+
OnPointerUp(|at| Heard)
|
|
36
|
+
OnPointerMove(|at| Heard)
|
|
37
|
+
OnHeld(|h| Saw(held: h))
|
|
38
|
-
|
|
38
|
+
OnFrame(|dt| Moved(dt: dt))
|
|
39
|
-
|
|
39
|
+
]
|
|
40
|
+
|
|
40
|
-
fun
|
|
41
|
+
fun update(self, a: Step) -> Next<Orbs, Step> = match a
|
|
41
|
-
Heard => Orbs(..self, heard: self.heard + 1)
|
|
42
|
+
Heard => Next(state: Orbs(..self, heard: self.heard + 1))
|
|
42
|
-
Saw(held) => Orbs(..self, held: held)
|
|
43
|
+
Saw(held) => Next(state: Orbs(..self, held: held))
|
|
43
44
|
Moved(dt) =>
|
|
44
45
|
x := if self.held.isKeyDown(Key.Right) then self.x + 100.0 * dt else self.x
|
|
45
|
-
Orbs(..self, x: x, events: self.heard, heard: 0, frame: self.frame + 1)
|
|
46
|
+
Next(state: Orbs(..self, x: x, events: self.heard, heard: 0, frame: self.frame + 1))
|
|
46
47
|
|
|
47
48
|
fun view(self) -> List<View> = [OrbsDrawing(s: self)]
|
|
48
49
|
|
compiler/game/tests/fixtures/main_missing_fixture.plum
CHANGED
|
@@ -22,9 +22,9 @@ import std/App
|
|
|
22
22
|
struct Broken[ScreenSlice<Float>](tex: Texture) =
|
|
23
23
|
fun name(self) -> Str = "page"
|
|
24
24
|
|
|
25
|
-
fun
|
|
25
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
26
26
|
|
|
27
|
-
fun
|
|
27
|
+
fun update(self, dt: Float) -> Next<Broken, Float> = Next(state: self)
|
|
28
28
|
|
|
29
29
|
fun view(self) -> List<View> = [BrokenDrawing(s: self)]
|
|
30
30
|
|
compiler/game/tests/fixtures/state_draw_keeps.plum
CHANGED
|
@@ -24,9 +24,9 @@ struct Log(mut last: Option<Run>)
|
|
|
24
24
|
struct Run[ScreenSlice<Float>](label: Str, log: Log, t: Int) =
|
|
25
25
|
fun name(self) -> Str = "page"
|
|
26
26
|
|
|
27
|
-
fun
|
|
27
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun update(self, dt: Float) -> Next<Run, Float> = Next(state: Run(..self, t: self.t + 1))
|
|
30
30
|
|
|
31
31
|
fun view(self) -> List<View> = [RunDrawing(s: self)]
|
|
32
32
|
|
compiler/game/tests/fixtures/state_in_place.plum
CHANGED
|
@@ -26,10 +26,10 @@ struct Part(label: Str, x: Int) =
|
|
|
26
26
|
struct Run[ScreenSlice<Float>](part: Part, t: Int) =
|
|
27
27
|
fun name(self) -> Str = "page"
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
30
30
|
|
|
31
|
-
fun
|
|
31
|
+
fun update(self, dt: Float) -> Next<Run, Float> =
|
|
32
|
-
Run(..self, part: self.part.step(), t: self.t + 1)
|
|
32
|
+
Next(state: Run(..self, part: self.part.step(), t: self.t + 1))
|
|
33
33
|
|
|
34
34
|
fun drawn(self) -> Run = Run(..self, t: 99)
|
|
35
35
|
|
compiler/game/tests/fixtures/state_main_alias.plum
CHANGED
|
@@ -25,9 +25,9 @@ struct Run[ScreenSlice<Float>](label: Str, t: Int) =
|
|
|
25
25
|
|
|
26
26
|
fun name(self) -> Str = "page"
|
|
27
27
|
|
|
28
|
-
fun
|
|
28
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
29
29
|
|
|
30
|
-
fun
|
|
30
|
+
fun update(self, dt: Float) -> Next<Run, Float> = Next(state: Run(..self, t: self.t + 1))
|
|
31
31
|
|
|
32
32
|
fun view(self) -> List<View> = [RunDrawing(s: self)]
|
|
33
33
|
|
compiler/game/tests/fixtures/state_reset.plum
CHANGED
|
@@ -24,10 +24,10 @@ struct Run[ScreenSlice<Float>](label: Str, t: Int) =
|
|
|
24
24
|
|
|
25
25
|
fun name(self) -> Str = "page"
|
|
26
26
|
|
|
27
|
-
fun
|
|
27
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun update(self, dt: Float) -> Next<Run, Float> =
|
|
30
|
-
if self.t >= 2 then Run.Start else Run(..self, t: self.t + 1)
|
|
30
|
+
Next(state: if self.t >= 2 then Run.Start else Run(..self, t: self.t + 1))
|
|
31
31
|
|
|
32
32
|
fun view(self) -> List<View> = [RunDrawing(s: self)]
|
|
33
33
|
|
compiler/game/tests/fixtures/target_fixture.plum
CHANGED
|
@@ -24,9 +24,9 @@ import std/App
|
|
|
24
24
|
struct State[ScreenSlice<Float>](target: Texture, bad: Int) =
|
|
25
25
|
fun name(self) -> Str = "page"
|
|
26
26
|
|
|
27
|
-
fun
|
|
27
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun update(self, dt: Float) -> Next<State, Float> = Next(state: self)
|
|
30
30
|
|
|
31
31
|
fun view(self) -> List<View> = [StateDrawing(s: self)]
|
|
32
32
|
|
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/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
|
|
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 update(self, a: Int) -> Next<State, Int> = Next(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/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
|
|
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 update(self, a: Int) -> Next<State, Int> = Next(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/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 = Seen(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
|
|
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 = Seen(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 subscriptions(self) -> List<Sub<Saw>> = [OnHeld(|h| Seen(keys: h.keys.length(), x: h.pointer.x)), OnFrame(|dt| Ticked)]\n fun update(self, a: Saw) -> Next<State, Saw> = match a\n Seen(k, x) => Next(state: State(..self, keys: self.keys + k, x: x))\n Ticked => Next(state: 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);
|
|
@@ -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/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
|
|
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 subscriptions(self) -> List<Sub<Int>> = [OnFrame(|dt| 1)]\n fun update(self, n: Int) -> Next<State, Int> = Next(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/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
|
|
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 subscriptions(self) -> List<Sub<Count>> = [OnKeyDown(key: Key.Space, act: Bump), OnFrame(|dt| Tock)]\n fun update(self, a: Count) -> Next<Counting, Count> = match a\n Bump => Next(state: Counting(..self, bumps: self.bumps + 1))\n Tock => Next(state: 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();
|
compiler/game/web-test/fixtures/interleave.plum
CHANGED
|
@@ -26,9 +26,9 @@ import std/App
|
|
|
26
26
|
struct Interleave[ScreenSlice<Float>](tex: Array<Texture>, t: Int) =
|
|
27
27
|
fun name(self) -> Str = "page"
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
30
30
|
|
|
31
|
-
fun
|
|
31
|
+
fun update(self, dt: Float) -> Next<Interleave, Float> = Next(state: Interleave(..self, t: self.t + 1))
|
|
32
32
|
|
|
33
33
|
fun view(self) -> List<View> = [InterleaveDrawing(s: self)]
|
|
34
34
|
|
compiler/game/web-test/fixtures/main_game.plum
CHANGED
|
@@ -24,9 +24,9 @@ import std/App
|
|
|
24
24
|
struct Mover[ScreenSlice<Float>](frame: Int) =
|
|
25
25
|
fun name(self) -> Str = "page"
|
|
26
26
|
|
|
27
|
-
fun
|
|
27
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun update(self, dt: Float) -> Next<Mover, Float> = Next(state: Mover(frame: self.frame + 1))
|
|
30
30
|
|
|
31
31
|
fun view(self) -> List<View> = [MoverDrawing(s: self)]
|
|
32
32
|
|
compiler/game/web-test/fixtures/rendertarget.plum
CHANGED
|
@@ -37,9 +37,9 @@ import std/App
|
|
|
37
37
|
struct Targets[ScreenSlice<Float>](big: Texture, small: Texture, glass: Texture, t: Int) =
|
|
38
38
|
fun name(self) -> Str = "page"
|
|
39
39
|
|
|
40
|
-
fun
|
|
40
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
41
41
|
|
|
42
|
-
fun
|
|
42
|
+
fun update(self, dt: Float) -> Next<Targets, Float> = Next(state: Targets(..self, t: self.t + 1))
|
|
43
43
|
|
|
44
44
|
fun view(self) -> List<View> = [TargetsDrawing(s: self)]
|
|
45
45
|
|
compiler/game/web-test/fixtures/stress.plum
CHANGED
|
@@ -26,9 +26,9 @@ import std/App
|
|
|
26
26
|
struct Stress[ScreenSlice<Float>](sheet: Texture, t: Int) =
|
|
27
27
|
fun name(self) -> Str = "page"
|
|
28
28
|
|
|
29
|
-
fun
|
|
29
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
30
30
|
|
|
31
|
-
fun
|
|
31
|
+
fun update(self, dt: Float) -> Next<Stress, Float> = Next(state: Stress(..self, t: self.t + 1))
|
|
32
32
|
|
|
33
33
|
fun view(self) -> List<View> = [StressDrawing(s: self)]
|
|
34
34
|
|
compiler/game/web-test/fixtures/stress_state_view.plum
CHANGED
|
@@ -108,11 +108,11 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
|
|
|
108
108
|
..Range.until(0, StressStateView.Buttons).map(|i| self.buttonLabel(i))
|
|
109
109
|
]
|
|
110
110
|
|
|
111
|
-
fun
|
|
111
|
+
fun subscriptions(self) -> List<Sub<StressAction>> = [OnFrame(|dt| Ticked(dt: dt))]
|
|
112
112
|
|
|
113
|
-
fun
|
|
113
|
+
fun update(self, a: StressAction) -> Next<ViewScreen, StressAction> = match a
|
|
114
|
-
Ticked(dt) => ViewScreen(..self, clock: self.clock + dt, frames: self.frames + 1)
|
|
114
|
+
Ticked(dt) => Next(state: ViewScreen(..self, clock: self.clock + dt, frames: self.frames + 1))
|
|
115
|
-
Clicked(_) => ViewScreen(..self, clicks: self.clicks + 1)
|
|
115
|
+
Clicked(_) => Next(state: ViewScreen(..self, clicks: self.clicks + 1))
|
|
116
116
|
|
|
117
117
|
fun spinner(self, gi: Int) -> View =
|
|
118
118
|
Spinner(x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.24 * self.clock) {
|
compiler/game/web-test/fixtures/text_sizes.plum
CHANGED
|
@@ -25,9 +25,9 @@ import std/App
|
|
|
25
25
|
struct Sizes[ScreenSlice<Float>](t: Int) =
|
|
26
26
|
fun name(self) -> Str = "page"
|
|
27
27
|
|
|
28
|
-
fun
|
|
28
|
+
fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
|
|
29
29
|
|
|
30
|
-
fun
|
|
30
|
+
fun update(self, dt: Float) -> Next<Sizes, Float> = Next(state: Sizes(t: self.t + 1))
|
|
31
31
|
|
|
32
32
|
fun view(self) -> List<View> = [SizesDrawing(s: self)]
|
|
33
33
|
|
compiler/tooling/tree-sitter-plum/grammar.js
CHANGED
|
@@ -263,7 +263,8 @@ module.exports = grammar({
|
|
|
263
263
|
|
|
264
264
|
// A struct field: `x: Float`, or with a default a construction may leave it out for:
|
|
265
265
|
// `size: Float = 20.0`. An attribute may come first: `@stepsWhen(!self.over) mines:
|
|
266
|
-
// List<Mine>` (a `[Steps]`
|
|
266
|
+
// List<Mine>` (a screen's or a `[Steps]` actor's field stepped only while the condition
|
|
267
|
+
// holds).
|
|
267
268
|
ctor_field: ($) =>
|
|
268
269
|
seq(
|
|
269
270
|
optional(field("attribute", $.field_attribute)),
|
docs/backlog.md
CHANGED
|
@@ -4,15 +4,16 @@ 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, commands as values for sounds and navigation (`std/game/Cmd`, returned by a slice's `
|
|
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 `update` beside its `then` actions, since 2026-11-16; one `update` and `subscriptions`, Elm style, since the same day), 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
|
+
- **A closure field bound by the same name in two arms of a `match` can't be called in the second.** `match self` / `One(f) => f(x)` / `Two(f) => f(x)` on `enum E = One(f: fn(Int) -> Int) | Two(f: fn(Int) -> Int)` is "undefined function 'f'" at the second arm's call; naming the binders apart (`Two(g) => g(x)`) works. std/game's `Sub.onEvent` names each arm's binder after its subscription (`turn`, `down`, `up`, `move`).
|
|
9
10
|
- **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
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).
|
|
11
|
-
- **What std's delivery fold still copies** (the screen is in place since 2026-11-16, `@copy` in `Delivery.deliverTo`
|
|
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.
|
|
12
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.
|
|
13
14
|
- **Master's other games** (`clockwork`, `menu`) are not ported.
|
|
14
15
|
- **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
|
|
15
|
-
- **Stepping without the screen naming its actors**: done at compile time on 2026-11-16:
|
|
16
|
+
- **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).
|
|
16
17
|
|
|
17
18
|
## Decided, not built
|
|
18
19
|
|
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,
|
|
23
|
+
its fields, its actions, its update, its subscriptions
|
|
24
|
-
|
|
24
|
+
and its 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/
|
|
@@ -31,12 +31,12 @@ examples/games/orbitrunner/
|
|
|
31
31
|
|
|
32
32
|
## A minimal game
|
|
33
33
|
|
|
34
|
-
A game is a `Game` (`std/game/Game`): a list of screens. A screen implements the `Screen` trait. Its state is plain fields, and its `view` says what the frame shows: a list of views, made again from those fields every time the frame is drawn. A screen with rules is a slice of the game ([The slice](#the-slice), below): an enum of its actions,
|
|
34
|
+
A game is a `Game` (`std/game/Game`): a list of screens. A screen implements the `Screen` trait. Its state is plain fields, and its `view` says what the frame shows: a list of views, made again from those fields every time the frame is drawn. A screen with rules is a slice of the game, in the Elm style ([The slice](#the-slice-update-subscriptions-and-view), below): an enum of its actions, one `update` that steps an action into the screen, and the `subscriptions` that say which input and which frames become actions. If `main` returns a `Game`, `plum run` runs it as a game. Any other `main` is a command line program.
|
|
35
35
|
|
|
36
|
-
This game counts the clicks on a button, rolls a ball while Right is held, and ends on Escape. The button says what a press on it means (`Button(.., on: Tapped)`, `std/game/Button`), so
|
|
36
|
+
This game counts the clicks on a button, rolls a ball while Right is held, and ends on Escape. The button says what a press on it means (`Button(.., on: Tapped)`, `std/game/Button`), so a press on it is `Tapped`. It draws its children (here a red box) in its own coordinates. The ball is an `Actor`: it has a `step(dt)`, and the screen steps it in its frame action through its `stepped`, which the compiler derives for every screen. `OnHeld` gets what is held after the tick's events (`Held`), and the ball rolls while Right is down. It is [`examples/games/clicks.plum`](../examples/games/clicks.plum):
|
|
37
37
|
|
|
38
38
|
```plum
|
|
39
|
-
enum TapAction = Tapped | Push(dx: Float) | Quit
|
|
39
|
+
enum TapAction = Tapped | Push(dx: Float) | Tick(dt: Float) | Quit
|
|
40
40
|
|
|
41
41
|
struct Ball[Actor](x: Float, y: Float, vx: Float) =
|
|
42
42
|
fun place(self) -> Place = Place.at(self.x, self.y)
|
|
@@ -47,7 +47,7 @@ struct Ball[Actor](x: Float, y: Float, vx: Float) =
|
|
|
47
47
|
|
|
48
48
|
fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
|
|
49
49
|
|
|
50
|
-
struct TapScreen[ScreenSlice<TapAction>
|
|
50
|
+
struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
51
51
|
fun start() -> TapScreen =
|
|
52
52
|
TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
|
|
53
53
|
|
|
@@ -61,20 +61,17 @@ struct TapScreen[ScreenSlice<TapAction>, Steps](taps: Int, ball: Ball) =
|
|
|
61
61
|
Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
|
|
62
62
|
]
|
|
63
63
|
|
|
64
|
-
fun
|
|
64
|
+
fun subscriptions(self) -> List<Sub<TapAction>> = [
|
|
65
|
-
|
|
65
|
+
OnKeyDown(key: Key.Escape, act: Quit)
|
|
66
|
-
_ => None
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
OnHeld(|h| Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
69
|
-
|
|
70
|
-
fun reduce(self, a: TapAction) -> TapScreen = match a
|
|
71
|
-
|
|
67
|
+
OnFrame(|dt| Tick(dt: dt))
|
|
72
|
-
Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
|
|
73
|
-
|
|
68
|
+
]
|
|
74
69
|
|
|
75
|
-
fun
|
|
70
|
+
fun update(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
|
|
71
|
+
Tapped => Next(state: TapScreen(..self, taps: self.taps + 1))
|
|
72
|
+
Push(dx) => Next(state: TapScreen(..self, ball: self.ball.push(dx)))
|
|
73
|
+
Tick(dt) => Next(state: self.stepped(dt))
|
|
76
74
|
Quit => Next(state: self, cmds: [Exit])
|
|
77
|
-
_ => Next(state: self.reduce(a))
|
|
78
75
|
|
|
79
76
|
primitive Clicks[App] =
|
|
80
77
|
fun main(io: Io) -> Game =
|
|
@@ -82,7 +79,7 @@ primitive Clicks[App] =
|
|
|
82
79
|
Game(screens: [only])
|
|
83
80
|
```
|
|
84
81
|
|
|
85
|
-
`main` runs once, after your assets have loaded. Then the game runs in ticks of 1/60 s: each tick is delivered to the shown screen as actions
|
|
82
|
+
`main` runs once, after your assets have loaded. Then the game runs in ticks of 1/60 s: each tick is delivered to the shown screen as actions (its events', what is held, and the frame), its `update` returns the next screen for each, and the game keeps the last; once per frame the game draws it, which only reads it: it clears the screen with the screen's `background()` (black by default) and draws the screen's view. Nothing is bound to anything and nothing is kept between frames: the label shows `self.taps` because the view reads it each time.
|
|
86
83
|
|
|
87
84
|
## A screen's view
|
|
88
85
|
|
|
@@ -109,9 +106,9 @@ fun view(self) -> List<View> = [
|
|
|
109
106
|
The view is one list literal, one item a line, its items in drawing order (later items draw over earlier ones). A parent's children are its block: `Overlay(w: .., h: ..) {` + one child a line + `}` is the overlay with those `children` (a construction's block is its last field; see [blocks](language.md#lists-slices-and-maps)), so the view reads as the tree it draws. What shows only sometimes is an `if` item (the ship until the run is over, the game over panel once it is), what repeats is a spread of a `map` over a range (forty stars, one icon a life), and a list the screen holds is spread as it is (`..self.mines`). Nothing is annotated: the literal is a `List<View>` because `view` returns one, and each spread `List<Mine>` widens to it (rebuilt as a `List<View>` there; see [Coercion](language.md#coercion) and [list literal items](language.md#lists-slices-and-maps)).
|
|
110
107
|
|
|
111
108
|
- **Drawn, not live.** The view is made again every time it is walked (to draw, to hit-test a press), and an item made inside it keeps nothing from one walk to the next. So each takes plain values read from the fields (a `Label`'s `text`, a `Sprite`'s `frame`). A `Group` or an `Overlay` in a view has the children it is made with (its block) as its own `view`, and an actor with a view of its own draws that, so views nest. Balloon Pop's clouds are groups: `Group(x: x, y: y) {` + three circles placed around the group's origin + `}`.
|
|
112
|
-
- **Two kinds of item.** An actor the screen holds in a field and names in its view (the ship, each mine of `self.mines`) is the very object in the field when the frame is drawn: a press on it reaches the screen as that object ([Clicks](#clicks)), and an actor that says what a press on it means (`Presses<A>`) gives that action. The
|
|
109
|
+
- **Two kinds of item.** An actor the screen holds in a field and names in its view (the ship, each mine of `self.mines`) is the very object in the field when the frame is drawn: a press on it reaches the screen as that object ([Clicks](#clicks)), and an actor that says what a press on it means (`Presses<A>`) gives that action. The screen steps it in its frame action, through its `stepped`, which returns the screen with the actor's next version. An item made inside `view` (the score label, the stars, the game over panel) is a new object every frame, made from the fields.
|
|
113
110
|
- **What is there, what shows.** An item that is not there is left out (the ship once the run is over). An actor that is there but hides itself for a moment says so with `visible()` (the ship blinking after a hit): it is not drawn or hit, but the screen still steps it.
|
|
114
|
-
- **The state rule.** `view` only reads; the state changes in the actors' `step`, the screen's `stepped` and
|
|
111
|
+
- **The state rule.** `view` only reads; the state changes in the actors' `step`, the screen's `stepped` and its `update`. A screen is a value, so this holds by construction: there is nothing for the draw to change.
|
|
115
112
|
|
|
116
113
|
What else a screen says about its frame, each with a default:
|
|
117
114
|
|
|
@@ -119,8 +116,7 @@ What else a screen says about its frame, each with a default:
|
|
|
119
116
|
|---|---|---|
|
|
120
117
|
| `view(self) -> List<View>` | empty | what the frame shows (above) |
|
|
121
118
|
| `hud(self, window: Vec2) -> List<View>` | empty | what is drawn over the view, one unit a pixel of the window (`window` pixels): Balloon Pop's score box. Hit before the view |
|
|
122
|
-
| `
|
|
123
|
-
| `stepped(self, dt) -> Self` | the screen as it is | the screen with each actor it holds stepped `dt` seconds on ([Views and actors](#views-and-actors)) |
|
|
119
|
+
| `stepped(self, dt) -> Self` | derived from the fields holding actors (none: the screen as it is) | the screen with each actor it holds stepped `dt` seconds on ([Views and actors](#views-and-actors)): what a slice's frame action calls, and a plain screen's tick |
|
|
124
120
|
| `camera(self, base: Viewport) -> Viewport` | `base` | the camera it is seen through, given the one its `size()` and `viewport()` make: `base.lookAt(x, y, zoom)` follows a point or zooms. Presses, `toWorld`, culling and the draw go through it |
|
|
125
121
|
| `size(self) -> Vec2` | 0 by 0 | the world the view is placed in, in its own units: Orbit Runner's arena, 800 by 600. 0 by 0 is the screen's own pixels |
|
|
126
122
|
| `viewport(self) -> Scaling` | `Fit` | how that world is put on the screen (`std/game/Viewport`): `Fit` letterboxes it, `Extend` grows it to fill the screen, `Fill`, `Stretch`, `Pixels` |
|
|
@@ -158,10 +154,10 @@ struct Mine[Actor](at: Motion, spin: Float = 0.0, clock: Float = 0.0, tex: Textu
|
|
|
158
154
|
fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt, at: self.at.drifted(Mine.Radius, dt), spin: self.spin + 2.0 * dt)
|
|
159
155
|
```
|
|
160
156
|
|
|
161
|
-
**Stepping.**
|
|
157
|
+
**Stepping.** There is no stepping phase: the frame reaches a slice screen as an action (`OnFrame(|dt| Tick(dt: dt))`), and its `update` steps its actors there with `stepped(dt)`, then runs its rules on what has moved. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen's own fields are stepped. Every screen has its `stepped` derived by the compiler (it lists nothing for it): each field that is an `Actor`, a `List` of actors (of one type, or of a trait type that is an `Actor`), an `Option` of one or a `List<View>` is stepped, and the other fields are as they are. `@stepsWhen(cond)` before a field steps it only while `cond`, read on `self`, holds. Orbit Runner's:
|
|
162
158
|
|
|
163
159
|
```plum
|
|
164
|
-
struct PlayingScreen[ScreenSlice<PlayAction>
|
|
160
|
+
struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
165
161
|
rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
|
|
166
162
|
@stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
|
|
167
163
|
fun name(self) -> Str = "play"
|
|
@@ -178,26 +174,31 @@ fun stepped(self, dt: Float) -> PlayingScreen =
|
|
|
178
174
|
rings: Views.stepAll(self.rings, dt))
|
|
179
175
|
```
|
|
180
176
|
|
|
181
|
-
and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`, `Views.stepIn` for a `List<View>`), not a walk at run time, so it costs what the hand-written one did
|
|
182
|
-
|
|
183
|
-
An actor that lists `Steps` has its actor fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds. An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field of a `Steps` type is stepped with `Views.stepIn`: it holds views of any kind, so each item is tested for being an `Actor` (or a `Group` or an `Overlay`) as it is stepped, the one place the stepping looks at an item's type at run time (`benchmarks/screen_views/scale.plum`'s `CrowdScreen`, 10,000 actors in a `List<View>`, lists `Steps`). An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not. So the tick action only runs the rules on what has moved:
|
|
177
|
+
and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`, `Views.stepIn` for a `List<View>`), not a walk at run time, so it costs what the hand-written one did. A screen that writes its own `stepped` keeps it; one holding no actors keeps the default, the screen as it is. Its frame action calls it:
|
|
184
178
|
|
|
185
179
|
```plum
|
|
186
|
-
fun
|
|
180
|
+
fun update(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
181
|
+
Tick(dt) =>
|
|
182
|
+
stepped := self.stepped(dt)
|
|
187
|
-
|
|
183
|
+
moved := PlayingScreen(..stepped, clock: stepped.clock + dt, rings: stepped.rings.filter(|r| !r.done()))
|
|
188
|
-
|
|
184
|
+
if moved.over then Next(state: moved) else moved.rules()
|
|
185
|
+
_ => Next(state: self)
|
|
189
186
|
```
|
|
190
187
|
|
|
188
|
+
so a screen that doesn't call it steps nothing, and one that pauses (a menu over the play) skips the call. A plain screen (no slice) has no actions: its tick is its `stepped`. 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.
|
|
189
|
+
|
|
190
|
+
An actor that lists `Steps` (`std/game/View`) has its actor fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds. An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field is stepped with `Views.stepIn`: it holds views of any kind, so each item is tested for being an `Actor` (or a `Group` or an `Overlay`) as it is stepped, the one place the stepping looks at an item's type at run time (`benchmarks/screen_views/scale.plum`'s `CrowdScreen`, 10,000 actors in a `List<View>`). An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not.
|
|
191
|
+
|
|
191
192
|
Once Orbit Runner's run is over its ship, orbs and mines 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; the rings, with no condition, step on, so the ripple of the last hit grows on under the panel.
|
|
192
193
|
|
|
193
|
-
`Steps` is an error on an enum, on a struct that is
|
|
194
|
+
`Steps` is an error on a screen (its `stepped` is derived without it), on an enum, on a struct that is not an `Actor`, and on an actor with no field holding actors; `@stepsWhen` is an error on a field that holds no actors, on a struct that is neither a screen nor a `[Steps]` actor, and on a screen that writes its own `stepped` (it would do nothing).
|
|
194
195
|
|
|
195
196
|
What else a view is, it says with a small trait:
|
|
196
197
|
|
|
197
198
|
| Trait | What it says |
|
|
198
199
|
|---|---|
|
|
199
200
|
| `Actor` (`std/game/View`) | `step(self, dt) -> Self`: its next version `dt` seconds on, which the screen's `stepped` keeps |
|
|
200
|
-
| `Steps` (`std/game/View`) | nothing to write: on
|
|
201
|
+
| `Steps` (`std/game/View`) | nothing to write: on an actor the compiler steps its actor fields after its `step` (above); `@stepsWhen(cond)` on a field. A screen needs none |
|
|
201
202
|
| `Sized` (`std/game/Sized`) | `bounds(self) -> Aabb`, the box it covers in its own coordinates. A view with bounds can be hit; one without cannot. `hit(self, p) -> Bool` is inside the bounds, edges included, unless the view says otherwise for an exact shape (`Circle` is hit inside its circle; a balloon on its body, its knot and its string). Culling goes by the bounds too |
|
|
202
203
|
| `Touch` (`std/game/Touch`) | `touch(self) -> Touchable`: whether it takes presses. `Enabled`: it is hit where it is (when it is `Sized`) and what is under it is; `Disabled`: neither it nor anything under it is hit; `ChildrenOnly`: what is under it is, it is not. A view that says nothing is `ChildrenOnly` |
|
|
203
204
|
|
|
@@ -218,13 +219,13 @@ Every kind is at the origin of what it is in unless given an `x` and a `y`: an a
|
|
|
218
219
|
|
|
219
220
|
The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
|
|
220
221
|
|
|
221
|
-
Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll`, `stepSome` and `stepIn` for a
|
|
222
|
+
Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll`, `stepSome` and `stepIn` for a derived stepping.
|
|
222
223
|
|
|
223
224
|
## Fixed timestep and determinism
|
|
224
225
|
|
|
225
226
|
The host adds up the time between frames and runs one tick (`Game.update`) for each whole tick, always with the same `dt` of 1/60 s. A slow frame runs several ticks (a 50 ms frame runs 3) and a fast one, on a 120 Hz screen say, may run none. A frame runs at most eight ticks: after a longer stall the rest is dropped, so the game slows down for a moment instead of falling ever further behind. The driver that does this is `Ticker` (`Ticker.Tick`, `Ticker.MaxTicks`) in [`std/game/Game.plum`](../std/game/Game.plum), held beside the game in `GameRun`, the state the host keeps between frames.
|
|
226
227
|
|
|
227
|
-
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
|
|
228
|
+
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 subscriptions (`OnKeyDown`, `OnHeld`, ..) and its presses; don't read input any other way.
|
|
228
229
|
|
|
229
230
|
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).
|
|
230
231
|
|
|
@@ -274,9 +275,9 @@ A move that can't be made (no history, a full one, a tick out of reach) leaves t
|
|
|
274
275
|
|
|
275
276
|
**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.
|
|
276
277
|
|
|
277
|
-
**A user action** is a tick in which the shown slice screen's
|
|
278
|
+
**A user action** is a tick in which the shown slice screen's subscriptions or a press gave an action for one of the tick's events (`OnKeyDown`, `OnPointerDown`, .., `onPress`), or `OnHeld` gave an action while what is held (the keys and the mouse buttons) differs from that screen's tick before. The frame action is not one, nor an unchanged `OnHeld`, nor an action an update'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.
|
|
278
279
|
|
|
279
|
-
**Offering undo in a game.** A slice's `
|
|
280
|
+
**Offering undo in a game.** A slice's `update` asks with a command: `Undo`, `Redo`, `RewindTo(tick: k)` (`std/game/Cmd`), done once the tick is recorded. Balloon Pop subscribes Z and Backspace to `TakeBack` (`OnKeyDown(key: Key.KeyZ, act: TakeBack)`), whose update is `Next(state: self, cmds: [Undo])`: the last press is taken back, and the balloon it popped is whole again.
|
|
280
281
|
|
|
281
282
|
**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.
|
|
282
283
|
|
|
@@ -308,7 +309,7 @@ Three files of `std/game` talk to the host. Each host call takes `io` first.
|
|
|
308
309
|
| Blending | `blendMode(io, m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` |
|
|
309
310
|
| Files | `loadFile(io, name)`, the file's text; `fileExists(io, name)` |
|
|
310
311
|
|
|
311
|
-
**`std/game/Input`:** keyboard, mouse and touch. The events are the input: a tick's input is an `Input(events, held, screen)`, a value, its `InputEvent`s in the order they came and what is held after them, a fold of them (`Held.after(e)`, `held.afterAll(events)`) over what was held before. A slice's
|
|
312
|
+
**`std/game/Input`:** keyboard, mouse and touch. The events are the input: a tick's input is an `Input(events, held, screen)`, a value, its `InputEvent`s in the order they came and what is held after them, a fold of them (`Held.after(e)`, `held.afterAll(events)`) over what was held before. A slice's subscriptions and `onPress` get the events one at a time, and its `OnHeld` gets the `Held`. No press or release is read from what is held: a key going down is its `KeyDown` (`e.isKeyDownOf(k)`), a click its `PointerDown`.
|
|
312
313
|
|
|
313
314
|
| | What it gives you |
|
|
314
315
|
|---|---|
|
|
@@ -327,11 +328,11 @@ A missing file stops the game and names the file, so typos show up straight away
|
|
|
327
328
|
|
|
328
329
|
## Screens
|
|
329
330
|
|
|
330
|
-
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
|
|
331
|
+
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 subscriptions, so Enter can play again while the game over shows.
|
|
331
332
|
|
|
332
333
|
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.
|
|
333
334
|
|
|
334
|
-
A screen left and shown again is as it was left: its state is its fields, which the game keeps. A screen has no
|
|
335
|
+
A screen left and shown again is as it was left: its state is its fields, which the game keeps. A screen has no hooks for going to it, leaving it or a resize: a slice screen gets its ticks as actions through its one `update`, a plain `Screen` (no rules) gets none and draws what it was made with, its actors stepped, and starting a run over is the update'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.
|
|
335
336
|
|
|
336
337
|
## Frames on demand
|
|
337
338
|
|
|
@@ -343,7 +344,7 @@ fun frames(self) -> Frames = OnDemand
|
|
|
343
344
|
|
|
344
345
|
`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:
|
|
345
346
|
|
|
346
|
-
- 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
|
|
347
|
+
- 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 the screen subscribes to `OnHeld` (what is held gives it an action);
|
|
347
348
|
- the tick before left the screen `busy()`, gave a command, or a transition is in progress;
|
|
348
349
|
- the screen was just entered, or the screen's size changed.
|
|
349
350
|
|
|
@@ -351,34 +352,48 @@ It then ticks as an `Always` screen until it goes quiet again. A tick it sleeps
|
|
|
351
352
|
|
|
352
353
|
**The host.** At the end of each frame's ticks the frame entry point (`GameRun.frame`) tells the host when the frame is idle (`Game.hostFrame`, the `frameIdle` host call); any other frame the host draws right after, so it counts as drawn. The browser then skips the draw, keeps the last frame on the canvas and asks for no next frame until input comes (a key, a press, a pointer move, the wheel, a resize or the page losing focus), one tick after the last; a replay keeps its frames coming. The native host's `PlumGame::idle()` says the same, and `plum-game` skips an idle frame's draw. A paused development run is idle the same way once its frame is drawn.
|
|
353
354
|
|
|
354
|
-
## The slice
|
|
355
|
+
## The slice: update, subscriptions and view
|
|
355
356
|
|
|
356
|
-
A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`),
|
|
357
|
+
A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), in the Elm style: its state is its fields, `A` (an enum) its actions, `update` steps one action into it, `subscriptions` says which input and which frames become actions, and `view` draws it. (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.
|
|
357
358
|
|
|
358
359
|
| A `ScreenSlice<A>`'s method | Default | What it does |
|
|
359
360
|
|---|---|---|
|
|
360
|
-
| `
|
|
361
|
-
| `
|
|
362
|
-
| `onKey(self, e) -> Option<A>` | None | the action for a key event |
|
|
363
|
-
| `onPointer(self, e, at: Vec2) -> Option<A>` | None | the action for a pointer event, `at` its point in the world |
|
|
361
|
+
| `update(self, a: A) -> Next<Self, A>` | `Next(state: self)` | steps `a` into the screen and says what follows: `Next(state, then, cmds)`, the next screen, the actions that follow (`then`) and the commands for the game (`cmds`, below). An exhaustive `match`, with no `Io` |
|
|
362
|
+
| `subscriptions(self) -> List<Sub<A>>` | empty | what the screen listens to (below), read once a tick |
|
|
364
363
|
| `onPress(self, target: View, at: Vec2) -> Option<A>` | what the item says a press on it means: `pressed()` of a `Presses<A>` (a `Button`), else None | the action for a press on an item that takes presses ([Clicks](#clicks)) |
|
|
365
|
-
| `held(self, h: Held) -> Option<A>` | None | the action for what is held after the tick's events, every tick |
|
|
366
|
-
| `tick(self, dt) -> Option<A>` | None | the tick action |
|
|
367
364
|
|
|
368
|
-
|
|
365
|
+
A screen with no actions writes neither: the defaults keep it as it is. Orbit Runner's play listens to the frame, to the steering keys while the run is on, and to Enter and R once it is over:
|
|
366
|
+
|
|
367
|
+
```plum
|
|
368
|
+
fun subscriptions(self) -> List<Sub<PlayAction>> = [
|
|
369
|
+
OnFrame(|dt| Tick(dt: dt))
|
|
370
|
+
if !self.over then OnHeld(|h| PlayingScreen.steering(h))
|
|
371
|
+
if self.over then OnKeyDown(key: Key.Enter, act: StartOver)
|
|
372
|
+
if self.over then OnKeyDown(key: Key.KeyR, act: StartOver)
|
|
373
|
+
]
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
| `Sub<A>` | The action |
|
|
377
|
+
|---|---|
|
|
378
|
+
| `OnFrame(act)` | `act(dt)` each tick, last: the frame, which steps the actors and runs the rules |
|
|
379
|
+
| `OnKeyDown(key, act)`, `OnKeyUp(key, act)` | `act` when that key goes down, or up |
|
|
380
|
+
| `OnHeld(act)` | `act(h)` each tick, with what is held after the tick's events (`Held`): the steering keys. It also wakes an `OnDemand` screen |
|
|
381
|
+
| `OnWheel(act)` | `act(dy, at)` for a turn of the wheel, `at` where the pointer is, in the world |
|
|
382
|
+
| `OnPointerDown(act)`, `OnPointerUp(act)`, `OnPointerMove(act)` | `act(at)` for a pointer event, `at` its point in the world; a pointer down that a press target took is not one |
|
|
383
|
+
|
|
384
|
+
The list is a list literal made again each tick, so an item is there only while the state says so (an `if` item). std reads it once a tick, from the screen as the tick found it: on the tick a run ends, its `OnHeld` still steers, and on the tick Enter starts it over, nothing steers until the next.
|
|
369
385
|
|
|
370
|
-
|
|
386
|
+
**Each tick**, std delivers to the shown screen, in this order:
|
|
371
387
|
|
|
372
|
-
Each tick,
|
|
388
|
+
1. **Each of the tick's events**, in the order they came: a key to each `OnKeyDown` or `OnKeyUp` of that key; a press (a `PointerDown`) on an item that takes presses through `onPress(target, at)`, and if that gives None, to `OnPointerDown` as any pointer down is; any other pointer event to its `OnPointer..`, with `at` the event's point in the world; a turn of the wheel to `OnWheel`, `at` where the pointer is. While a transition runs, the pointer events and the wheel are dropped.
|
|
389
|
+
2. **`OnHeld`**: an action for what is held after the events, every tick, events or none.
|
|
390
|
+
3. **`OnFrame`**: the frame action, last, which steps the actors (`stepped(dt)`) and runs the rules on what has moved.
|
|
373
391
|
|
|
374
|
-
|
|
375
|
-
2. **`held(h)`**: an action for what is held after the events (`Held`), every tick, events or none (the steering keys).
|
|
376
|
-
3. **The step**: the screen's `stepped(dt)`, unless `steps()` is false ([Views and actors](#views-and-actors)).
|
|
377
|
-
4. **`tick(dt)`**: the tick action, which sees the actors moved and runs the rules.
|
|
392
|
+
Several subscriptions may answer one event, each in the order listed. Then the transition in progress moves on, and the game does the commands.
|
|
378
393
|
|
|
379
|
-
A
|
|
394
|
+
**What follows from an action** is part of what `update` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`. Each action std delivers is stepped as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next action sees 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]`). 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`). The game keeps the screen it had (its screens, and the ones a rewind starts from), so the fold starts from a copy of it (`@copy`, one a tick delivered, [language.md](language.md#copies)): the copy is the fold's alone, and each `update` of the tick updates it in place, Orbit Runner's steering, frame, scoring, hits and start over among them (a sound read from the screen is read before the spread: `sounds := self.assets`). A test calls `update` itself: `s.update(Keyed).then`, `s.update(a).state`. An action enum that lists `Show` (std/Str) has its `toStr` derived, so a test can compare the actions sent as text (`"Steer(1.0, -1.0) Tick(0.016) Scored(10)"`). How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
|
|
380
395
|
|
|
381
|
-
Orbit Runner steers with `h.axis`: `Steer(ax: {h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`.
|
|
396
|
+
Orbit Runner steers with `h.axis`: `Steer(ax: {h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`. What the rules need of geometry is std's: `Vec2.near(other, dist)` (closer than `dist`), so two circles overlap when `a.near(b, ra + rb)`. An actor that appears somewhere new makes itself: `Orb.spawn(rng, near, phase, tex)` and `Mine.spawn(rng, near, tex)` return the actor and the next `Random` (a `Rolled<Orb>`), placed away from the ship.
|
|
382
397
|
|
|
383
398
|
## Clicks
|
|
384
399
|
|
|
@@ -390,15 +405,15 @@ The item hit becomes the slice's action through `onPress(target, at)`, which by
|
|
|
390
405
|
fun pressed(self) -> PopAction = Pop(id: self.id)
|
|
391
406
|
```
|
|
392
407
|
|
|
393
|
-
and `Pop(id)` bursts the balloon of `self.balloons` with that id; the screen writes no `onPress`. A balloon that has burst says `Disabled`, so a press goes through it to one behind. The match is on the trait at the slice's action type (`Presses<A> as p`), so an item that means an action of another type (a `Button<Int>` on a screen of `PopAction`s) gives None. A screen that decides itself writes `onPress`, matching the kind of item (`Overlay as o`): an item made inside `view` (a `Button`, Orbit Runner's game over panel) is a new object each walk, so its identity says nothing.
|
|
408
|
+
and `Pop(id)` bursts the balloon of `self.balloons` with that id; the screen writes no `onPress`. A press on no such item goes to the screen's `OnPointerDown`, if it has one. A balloon that has burst says `Disabled`, so a press goes through it to one behind. The match is on the trait at the slice's action type (`Presses<A> as p`), so an item that means an action of another type (a `Button<Int>` on a screen of `PopAction`s) gives None. A screen that decides itself writes `onPress`, matching the kind of item (`Overlay as o`): an item made inside `view` (a `Button`, Orbit Runner's game over panel) is a new object each walk, so its identity says nothing.
|
|
394
409
|
|
|
395
410
|
## What outlives a tick
|
|
396
411
|
|
|
397
|
-
A flash, a ripple, a slide: something that runs for a while after what started it is plain state too.
|
|
412
|
+
A flash, a ripple, a slide: something that runs for a while after what started it is plain state too. An update adds it, the frame action ages it and drops it once it is done; the view draws it at its age. Orbit Runner's ripple where the ship is hit is a `Ring`, an actor with its age: `Hit` appends one to `rings` where the ship is; each `Tick` ages them (the screen's `stepped`) and 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 in its frame action and reads in its view.
|
|
398
413
|
|
|
399
414
|
## Commands: sound and navigation
|
|
400
415
|
|
|
401
|
-
What a slice's `
|
|
416
|
+
What a slice's `update` 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:
|
|
402
417
|
|
|
403
418
|
| `Cmd` | What the game does |
|
|
404
419
|
|---|---|
|
|
@@ -407,7 +422,7 @@ What a slice's `act` asks of the game is data, an `enum Cmd` (`std/game/Cmd`) in
|
|
|
407
422
|
| `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 |
|
|
408
423
|
| `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) |
|
|
409
424
|
|
|
410
|
-
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 `
|
|
425
|
+
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 `update` says it beside the next screen: `Hit` plays the hit, or stops the music for the game over sound once the run is over (`cmds: if over then [Stop(sound: sounds.music), Play(sound: sounds.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.
|
|
411
426
|
|
|
412
427
|
## Assets
|
|
413
428
|
|
|
@@ -419,7 +434,7 @@ While `plum run` serves a game, it watches your code and assets, the game's own
|
|
|
419
434
|
|
|
420
435
|
## Testing a game
|
|
421
436
|
|
|
422
|
-
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)`);
|
|
437
|
+
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)`); an update the same way (`s.update(a).state`, `s.update(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).
|
|
423
438
|
|
|
424
439
|
### Testing a screen
|
|
425
440
|
|
|
@@ -441,8 +456,8 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
441
456
|
| | |
|
|
442
457
|
|---|---|
|
|
443
458
|
| 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)` |
|
|
444
|
-
| Time | `tick()` (the game's own tick:
|
|
445
|
-
| 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 |
|
|
459
|
+
| Time | `tick()` (the game's own tick: the subscriptions and presses, the frame action, 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 |
|
|
460
|
+
| An action | `dispatch(a)`: stepped into the rig's screen through its `update`, 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 |
|
|
446
461
|
| 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()`) |
|
|
447
462
|
| 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 |
|
|
448
463
|
| A whole run | `record(seed)`, `recorded()`, `replay(r)`, and `game` (its counters) |
|
|
@@ -453,34 +468,34 @@ Orbit Runner's game over test:
|
|
|
453
468
|
```plum
|
|
454
469
|
# tests/examples/games/orbitrunner/screens/PlayingScreen.plum
|
|
455
470
|
primitive PlayingScreenTest[UnitTest] =
|
|
456
|
-
# while the game over panel shows, Enter or R plays again: StartOver
|
|
471
|
+
# while the game over panel shows, Enter or R plays again: StartOver at once, which starts the music again; in play they do nothing
|
|
457
472
|
fun whileTheGameOverPanelShowsEnterOr() =
|
|
458
473
|
t := PlayingScreenHelpers.lastLife(io).press(Key.Enter).tick()
|
|
459
|
-
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "
|
|
474
|
+
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "Hit"
|
|
460
475
|
u := t.press(Key.Space).tick()
|
|
461
476
|
assert u.screen.over
|
|
462
477
|
v := u.press(Key.Enter).tick()
|
|
463
|
-
assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "
|
|
478
|
+
assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "StartOver Tick({Ticker.Tick})"
|
|
464
479
|
assert Cmd.names(v.cmds) == "stop(-1) loop(-1, 0.3)"
|
|
465
480
|
assert !v.screen.over
|
|
466
481
|
```
|
|
467
482
|
|
|
468
|
-
`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
|
|
483
|
+
`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 update's `then`, commands, navigation, transitions and the presses they drop, frames on demand, record and replay, undo and rewind, the stepping in the frame action and a pause, the hud, a camera that follows); [`tests/std/game/ScreenSlice.plum`](../tests/std/game/ScreenSlice.plum) checks the subscriptions (their order in a tick, several answering one event, an item there only while the state says so, `OnHeld` waking an `OnDemand` screen). `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.
|
|
469
484
|
|
|
470
485
|
## Beside master
|
|
471
486
|
|
|
472
|
-
The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its `hud`
|
|
487
|
+
The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its `hud` 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:
|
|
473
488
|
|
|
474
489
|
| Master | Here | Why |
|
|
475
490
|
|---|---|---|
|
|
476
491
|
| `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 |
|
|
477
|
-
| the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the
|
|
492
|
+
| 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 screen's frame action calls its `stepped(dt) -> Self`, which maps the fields that hold actors: derived by the compiler for every screen (an `Actor` field, a `List` or an `Option` of actors, a `List<View>`), a field paused by `@stepsWhen(cond)`, or written by hand (`Views.stepAll`, `Views.stepIn`); no `steps()`: a screen pauses by not calling it. An actor that lists `Steps` has its actor fields stepped after its own `step`. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
|
|
478
493
|
| `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 |
|
|
479
|
-
| `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` |
|
|
480
|
-
| `onKey(..) -> A?` and the
|
|
494
|
+
| `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` | one `fun update(self, a: A) -> Next<Self, A>` returning the next screen with the actions that follow (`then`) and the commands; no `dispatch` | the Elm style: one entry point returns the next screen, and what follows from an action is part of what it returns, not a call that queues it |
|
|
495
|
+
| `onKey(..) -> A?`, `onPointer`, `held(input)` and `tick(dt)`, and a stepping phase before the tick action | `subscriptions(self) -> List<Sub<A>>` (`OnFrame`, `OnKeyDown`, `OnKeyUp`, `OnHeld`, `OnWheel`, `OnPointerDown`, `OnPointerUp`, `OnPointerMove`), read once a tick; the frame is an action, and the screen steps its actors in it | one list says what a screen listens to, an item there only while the state says so; with the frame an action, nothing is stepped behind `update`'s back |
|
|
481
496
|
| `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 |
|
|
482
497
|
| `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 |
|
|
483
|
-
| `Input(held, events, pos, wheel)`, read through `isKeyDown`, `isKeyPressed`, `axis`, `isMouseDown`, `isMousePressed`, `isMouseReleased`; a slice's `held(self, input: Input)` | `Input(events, held, screen)`: the events, with the wheel among them (`Wheel(dy)`), and what is held after them (`Held(mouse, keys, buttons, pointer)`, `held.afterAll(events)`), read through `held.isKeyDown`, `axis`, `isButtonDown` and `pointer`; `
|
|
498
|
+
| `Input(held, events, pos, wheel)`, read through `isKeyDown`, `isKeyPressed`, `axis`, `isMouseDown`, `isMousePressed`, `isMouseReleased`; a slice's `held(self, input: Input)` | `Input(events, held, screen)`: the events, with the wheel among them (`Wheel(dy)`), and what is held after them (`Held(mouse, keys, buttons, pointer)`, `held.afterAll(events)`), read through `held.isKeyDown`, `axis`, `isButtonDown` and `pointer`; `OnHeld(|h| ..)`; no `isKeyPressed`, `isMousePressed`, `isMouseReleased`, `pos` or `wheel`; a replay's tick line has no wheel column, and there is one replay form, with no version number | the events are the one source of the input: what is held is their fold, and a press is its event, not a second reading of what is held |
|
|
484
499
|
| a press reaches `onPress(target, at)`, which tells the item by its identity or kind | the same, and by default `onPress` is what the item says a press on it means: `Presses<A>`'s `pressed()`, with `Button<A>(x, y, w, h, on: a) { .. }` ready-made; Balloon Pop's balloons are `Presses<PopAction>` (`Pop(id: self.id)`) | an item made in `view` is a new object each walk, so it says what it means rather than being compared with a field |
|
|
485
500
|
| `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 |
|
|
486
501
|
| 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) |
|
|
@@ -493,14 +508,14 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
493
508
|
| a replay's ticks and the ticker's in a growable array, read by index | `Replay.ticks: List<Input>`; the `Ticker` replaying holds the ticks not yet played (`played`), its head dropped each tick, with no cursor; the kit's recording is a value too (`t.recorded()`) | a replay is a value: the kit's rig, itself a value, no longer pushes into an array its copies share |
|
|
494
509
|
| an action enum writes its `toStr` for a test's names | `enum PlayAction[Show] = ..`: `[Show]` (std/Str) derives `toStr`, `Steer(1.0, -1.0)` ([language.md](language.md#structs), "Field attributes and derived methods") | the names a test compares are the variant and its fields; a derive writes them once |
|
|
495
510
|
| `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
|
|
496
|
-
| `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`) handed to an effect | `enum Cmd` (`GoTo`, `Exit`, `Undo`, `Redo`, `RewindTo`, `Play`, `Loop`, `Stop`) returned by `
|
|
511
|
+
| `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`) handed to an effect | `enum Cmd` (`GoTo`, `Exit`, `Undo`, `Redo`, `RewindTo`, `Play`, `Loop`, `Stop`) returned by `update` | commands are values: a test reads them (`t.cmds`), and a sound is one of them |
|
|
497
512
|
| `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
|
|
498
513
|
| the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
|
|
499
514
|
| a view literal's `if`, `for`, `..` elements | `if` and `..` items and children blocks (`Overlay(..) {` + an item a line + `}`); no `for` item: `..xs.map(..)` | a `for` item would be a second way to write a `map` |
|
|
500
515
|
| 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) |
|
|
501
516
|
| `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
|
|
502
517
|
|
|
503
|
-
The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `
|
|
518
|
+
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, and 818414470 since the Elm-style screens (the subscriptions are read once a tick, so the tick Enter restarts on steers nothing).
|
|
504
519
|
|
|
505
520
|
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.
|
|
506
521
|
|
docs/language.md
CHANGED
|
@@ -233,7 +233,7 @@ primitive Demo[App] =
|
|
|
233
233
|
b.x = 9.0 # a.x is still 1.0
|
|
234
234
|
```
|
|
235
235
|
|
|
236
|
-
**Field attributes and derived methods:** a field may start with an attribute, `@name(expr)`. The one there is is `@stepsWhen(cond)`, for std/game's
|
|
236
|
+
**Field attributes and derived methods:** a field may start with an attribute, `@name(expr)`. The one there is is `@stepsWhen(cond)`, for std/game's derived stepping: every struct that is a `Screen` gets a `stepped(self, dt)` written out by the compiler before checking, which steps each field holding actors (an `Actor`, a `List` of actors or an `Option` of one, a `List<View>`, the others as they are); an `Actor` that lists `Steps` has those fields stepped after its own `step`. `@stepsWhen(cond)` steps its field only while `cond`, an expression on `self`, holds. What is derived is an ordinary method, the same static construction one would write (`Screen(..self, ship: self.ship.step(dt), ..)`), so it costs nothing at run time; a screen that writes its own `stepped` keeps it. Any other attribute name is an error, and so is `@stepsWhen` on a field holding no actors or of a type that is neither a screen nor lists `Steps`, and `Steps` on a screen. See docs/game.md, "Stepping".
|
|
237
237
|
|
|
238
238
|
A type that lists `Show` (std/Str, `trait Show = fun toStr(self) -> Str`) and writes no `toStr` gets one derived the same way: its variant's name and its fields' values in order, each as it interpolates (`Steer(1.0, -1.0)`, `Hit`; a struct `Spot(1, 2)`, one with no fields its name), so it interpolates (`"{a}"`) and meets a `T: Show` bound. A type that writes its own `toStr` keeps it. A field whose type is one of the program's structs or enums with no `toStr` that doesn't list `Show` either is an error at the type, since it couldn't go in the string:
|
|
239
239
|
|
|
@@ -248,7 +248,7 @@ enum PlayAction[Show] =
|
|
|
248
248
|
```
|
|
249
249
|
|
|
250
250
|
```plum
|
|
251
|
-
struct PlayingScreen[ScreenSlice<PlayAction>
|
|
251
|
+
struct PlayingScreen[ScreenSlice<PlayAction>](over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>) =
|
|
252
252
|
fun name(self) -> Str = "play"
|
|
253
253
|
```
|
|
254
254
|
|
docs/plans/2026-11-13-std-game-review.md
CHANGED
|
@@ -36,4 +36,5 @@ Events stay the only source of truth; std keeps held state as a pure fold of the
|
|
|
36
36
|
- `subscriptions(self) -> List<Sub<A>>` replaces `onKey`, `onPointer`'s key-like uses, `held` and `tick`: `OnFrame(|dt| Tick(dt))`, `OnKeyDown(key, act)`, `OnKeyUp`, `OnHeld(|h| ..)`, `OnWheel`, list items allowed (`if !self.over then OnHeld(..)`); presses stay declared on views (`Presses<A>`, `Button`).
|
|
37
37
|
- No separate stepping phase: the game sends the frame as an action; the derived `stepped` stays as a callable helper (`Tick(dt) => self.stepped(dt).rules()`), `[Steps]` dropped on screens (derived for every screen), kept opt-in for actors; `@stepsWhen` stays.
|
|
38
38
|
- Also in the Elm task (user: "Yes"): geometry in std (`Vec2.near(other, dist)` or a Circle-to-Circle test) replaces Orbit Runner's `overlaps`; actors spawn themselves (`Orb.spawn(rng, near: ship)` returning the actor and the next Random) instead of the screen's `newOrb`/`newMine`; no `World` struct (removed on master by the user).
|
|
39
|
+
- Done on `sl/elm`: `trait ScreenSlice<A>` is `update(self, a) -> Next<Self, A>` (default `Next(state: self)`), `subscriptions(self) -> List<Sub<A>>` (default empty) and `onPress`; `enum Sub<A>` = `OnFrame(fn(Float) -> A)`, `OnKeyDown(key, act)`, `OnKeyUp(key, act)`, `OnHeld(fn(Held) -> A)`, `OnWheel(fn(Float, Vec2) -> A)`, `OnPointerDown`/`Up`/`Move(fn(Vec2) -> A)`, read once a tick from the screen as the tick found it; `wants` is "subscribes to `OnHeld`"; `reduce`, `act`, `onKey`, `onPointer`, `held`, `tick`, `steps()` and the stepping phase are gone (a plain screen's tick is its `stepped`); every screen derives `stepped` without `Steps` (`Steps` on a screen is an error); `Vec2.near`; `Orb.spawn(rng, near, phase, tex)` and `Mine.spawn(rng, near, tex)` return `Rolled<..>` (positional: a fn call takes no named arguments). The uniqueness analysis resolves a call on a receiver of a bounded type parameter among the bound's implementers (`s.update(a)` met `Game.update`). Orbit Runner's checksum 946756219 to 818414470 (the restart tick no longer steers: subscriptions are read at the tick's start, while the run is over); orbit update 11.3 to 12.1 ms (subscription closures called indirectly each tick), the 10,000-actor scale benchmark unchanged.
|
|
39
40
|
- After the Elm task (user: "After that benchmark and see if we have lost some perf please"): benchmark the tip against d8ce9bc7 (start of the no-globals queue, 2026-11-13) and a643bd8e (before the review batch) on a quiet machine: benchmarks/screen_views (Orbit Runner update/paint, 10,000 actors), benchmarks/run.py (compile time, wasm size, math/collections/map, game ticks), `plum test std` time; same toolchain, medians of 5; explain any loss and fix what is cheap.
|
docs/std.md
CHANGED
|
@@ -18,7 +18,7 @@ The [game engine](game.md) has its own page.
|
|
|
18
18
|
| [`Os`, `Http`](#files-and-network) | files and the network |
|
|
19
19
|
| [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `@sameRef`, `@copy`](#utilities) | utilities |
|
|
20
20
|
| [`Test`](#testing) | helpers for tests |
|
|
21
|
-
| [`game/Screen`, `game/ScreenSlice`](#game-screens-and-slices) | a game's screens, each with its own state, actions and
|
|
21
|
+
| [`game/Screen`, `game/ScreenSlice`](#game-screens-and-slices) | a game's screens, each with its own state, actions, update and subscriptions |
|
|
22
22
|
|
|
23
23
|
## Numbers
|
|
24
24
|
|
|
@@ -273,7 +273,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
|
|
|
273
273
|
|
|
274
274
|
## Game screens and slices
|
|
275
275
|
|
|
276
|
-
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
|
|
276
|
+
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 a screen steps through its `stepped(dt)`, derived for every screen from its fields holding actors, a `List<View>` among them), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), in the Elm style: its fields are its state, `A` its actions, `update(self, a) -> Next<Self, A>` its one entry point (pure, with no `Io`, so the same actions from the same state give the same state), returning the next screen 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. Its `subscriptions(self) -> List<Sub<A>>` say which of each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) and which frames become its actions: `OnFrame(|dt| ..)`, `OnKeyDown(key:, act:)`, `OnKeyUp`, `OnHeld(|h| ..)`, `OnWheel`, `OnPointerDown`, `OnPointerUp`, `OnPointerMove`, read once a tick; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default. The frame is an action: the screen steps its actors in it. std keeps the screen each `update` returns. `Vec2.near(other, dist)` (`std/math/Vec2`) is the overlap test of two circles (`a.near(b, ra + rb)`). A run records as a `Replay` (`std/game/Replay`: the seed and a `List<Input>`, one a tick). All of it is in [the game engine](game.md).
|
|
277
277
|
|
|
278
278
|
```plum
|
|
279
279
|
import std/Int
|
|
@@ -289,9 +289,11 @@ enum Act = Collected(points: Int) | Hurt
|
|
|
289
289
|
struct Run[ScreenSlice<Act>](score: Int, lives: Int) =
|
|
290
290
|
fun name(self) -> Str = "run"
|
|
291
291
|
|
|
292
|
+
fun subscriptions(self) -> List<Sub<Act>> = [OnKeyDown(key: Key.KeyH, act: Hurt)]
|
|
293
|
+
|
|
292
|
-
fun
|
|
294
|
+
fun update(self, a: Act) -> Next<Run, Act> = match a
|
|
293
|
-
Collected(p) => Run(..self, score: self.score + p)
|
|
295
|
+
Collected(p) => Next(state: Run(..self, score: self.score + p))
|
|
294
|
-
Hurt => Run(..self, lives: self.lives - 1)
|
|
296
|
+
Hurt => Next(state: Run(..self, lives: self.lives - 1))
|
|
295
297
|
```
|
|
296
298
|
|
|
297
299
|
```plum
|
|
@@ -300,7 +302,7 @@ import std/Test
|
|
|
300
302
|
import run
|
|
301
303
|
|
|
302
304
|
primitive RunTest[UnitTest] =
|
|
303
|
-
fun
|
|
305
|
+
fun updateAlonePlaysTheSlice() =
|
|
304
|
-
r := Run(score: 0, lives: 3).
|
|
306
|
+
r := Run(score: 0, lives: 3).update(Collected(points: 5)).state.update(Hurt).state
|
|
305
307
|
assert r.score == 5 && r.lives == 2
|
|
306
308
|
```
|
examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -5,7 +5,6 @@ import std/Float
|
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/Str
|
|
7
7
|
import std/Io
|
|
8
|
-
import std/Option
|
|
9
8
|
import std/Slice
|
|
10
9
|
import std/collections/List
|
|
11
10
|
import std/math/Random
|
|
@@ -32,7 +31,7 @@ enum PopAction[Show] =
|
|
|
32
31
|
| TakeBack
|
|
33
32
|
| Tick(dt: Float)
|
|
34
33
|
|
|
35
|
-
struct PlaygroundScreen[ScreenSlice<PopAction>
|
|
34
|
+
struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
36
35
|
rng: Random, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
|
|
37
36
|
const Count = 6
|
|
38
37
|
const PartyEvery = 10
|
|
@@ -68,38 +67,36 @@ struct PlaygroundScreen[ScreenSlice<PopAction>, Steps](
|
|
|
68
67
|
Label(x: 80.0, y: 20.0, text: "{self.pops}", size: 44.0, color: Color.rgb(0.15, 0.15, 0.3))
|
|
69
68
|
]
|
|
70
69
|
|
|
71
|
-
fun
|
|
70
|
+
fun subscriptions(self) -> List<Sub<PopAction>> = [
|
|
71
|
+
OnFrame(|dt| Tick(dt: dt))
|
|
72
|
+
OnKeyDown(key: Key.KeyZ, act: TakeBack)
|
|
72
|
-
|
|
73
|
+
OnKeyDown(key: Key.Backspace, act: TakeBack)
|
|
73
|
-
|
|
74
|
+
]
|
|
74
|
-
|
|
75
|
-
fun tick(self, dt: Float) -> Option<PopAction> = Some(Tick(dt: dt))
|
|
76
|
-
|
|
77
|
-
fun reduce(self, a: PopAction) -> PlaygroundScreen = match a
|
|
78
|
-
Pop(id) => PlaygroundScreen(..self, balloons: self.balloons.map(|x| if x.id == id then x.pop() else x))
|
|
79
|
-
Popped(at) => self.popped(at)
|
|
80
|
-
TakeBack => self
|
|
81
|
-
Tick(dt) => self.advance(dt)
|
|
82
75
|
|
|
83
|
-
fun
|
|
76
|
+
fun update(self, a: PopAction) -> Next<PlaygroundScreen, PopAction> = match a
|
|
77
|
+
Pop(id) =>
|
|
78
|
+
at := self.clock
|
|
84
|
-
|
|
79
|
+
Next(state: PlaygroundScreen(..self, balloons: self.balloons.map(|x| if x.id == id then x.pop() else x)), then: [Popped(at: at)])
|
|
85
|
-
Popped(
|
|
80
|
+
Popped(at) =>
|
|
81
|
+
sounds := self.assets
|
|
86
|
-
p := self.
|
|
82
|
+
p := self.popped(at)
|
|
87
83
|
Next(state: p, cmds: [
|
|
88
|
-
Play(sound:
|
|
84
|
+
Play(sound: sounds.pop, volume: 0.9)
|
|
89
|
-
if p.pops % PlaygroundScreen.PartyEvery == 0 then Play(sound:
|
|
85
|
+
if p.pops % PlaygroundScreen.PartyEvery == 0 then Play(sound: sounds.party, volume: 0.6)
|
|
90
86
|
])
|
|
91
87
|
TakeBack => Next(state: self, cmds: [Undo])
|
|
88
|
+
Tick(dt) =>
|
|
92
|
-
|
|
89
|
+
moved := self.stepped(dt)
|
|
93
|
-
|
|
94
|
-
fun advance(self, dt: Float) -> PlaygroundScreen =
|
|
95
|
-
|
|
90
|
+
clock := moved.clock + dt
|
|
91
|
+
balloons := moved.balloons
|
|
96
|
-
|
|
92
|
+
risen := PlaygroundScreen(..moved, clock: clock, balloons: Nil)
|
|
97
|
-
|
|
93
|
+
next := balloons.fold(risen, |s, b|
|
|
98
|
-
|
|
94
|
+
if b.done()
|
|
99
|
-
|
|
95
|
+
sp := Balloon.spawn(b.id, s.rng, 0.0, clock)
|
|
100
|
-
|
|
96
|
+
PlaygroundScreen(..s, rng: sp.rng, balloons: s.balloons.append([sp.balloon]))
|
|
101
|
-
|
|
97
|
+
else
|
|
102
|
-
|
|
98
|
+
PlaygroundScreen(..s, balloons: s.balloons.append([b])))
|
|
99
|
+
Next(state: next)
|
|
103
100
|
|
|
104
101
|
fun popped(self, at: Float) -> PlaygroundScreen =
|
|
105
102
|
pops := self.pops + 1
|
examples/games/clicks.plum
CHANGED
|
@@ -3,7 +3,6 @@ module clicks
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
-
import std/Option
|
|
7
6
|
import std/Io
|
|
8
7
|
import std/collections/List
|
|
9
8
|
import std/math/Vec2
|
|
@@ -22,7 +21,7 @@ import std/game/Game
|
|
|
22
21
|
import std/game/TestRig
|
|
23
22
|
import std/App
|
|
24
23
|
|
|
25
|
-
enum TapAction = Tapped | Push(dx: Float) | Quit
|
|
24
|
+
enum TapAction = Tapped | Push(dx: Float) | Tick(dt: Float) | Quit
|
|
26
25
|
|
|
27
26
|
struct Ball[Actor](x: Float, y: Float, vx: Float) =
|
|
28
27
|
fun place(self) -> Place = Place.at(self.x, self.y)
|
|
@@ -33,7 +32,7 @@ struct Ball[Actor](x: Float, y: Float, vx: Float) =
|
|
|
33
32
|
|
|
34
33
|
fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
|
|
35
34
|
|
|
36
|
-
struct TapScreen[ScreenSlice<TapAction>
|
|
35
|
+
struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
37
36
|
fun start() -> TapScreen =
|
|
38
37
|
TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
|
|
39
38
|
|
|
@@ -47,20 +46,17 @@ struct TapScreen[ScreenSlice<TapAction>, Steps](taps: Int, ball: Ball) =
|
|
|
47
46
|
Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
|
|
48
47
|
]
|
|
49
48
|
|
|
50
|
-
fun
|
|
49
|
+
fun subscriptions(self) -> List<Sub<TapAction>> = [
|
|
51
|
-
|
|
50
|
+
OnKeyDown(key: Key.Escape, act: Quit)
|
|
52
|
-
_ => None
|
|
53
|
-
|
|
54
|
-
|
|
51
|
+
OnHeld(|h| Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
55
|
-
|
|
56
|
-
fun reduce(self, a: TapAction) -> TapScreen = match a
|
|
57
|
-
|
|
52
|
+
OnFrame(|dt| Tick(dt: dt))
|
|
58
|
-
Push(dx) => TapScreen(..self, ball: self.ball.push(dx))
|
|
59
|
-
|
|
53
|
+
]
|
|
60
54
|
|
|
61
|
-
fun
|
|
55
|
+
fun update(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
|
|
56
|
+
Tapped => Next(state: TapScreen(..self, taps: self.taps + 1))
|
|
57
|
+
Push(dx) => Next(state: TapScreen(..self, ball: self.ball.push(dx)))
|
|
58
|
+
Tick(dt) => Next(state: self.stepped(dt))
|
|
62
59
|
Quit => Next(state: self, cmds: [Exit])
|
|
63
|
-
_ => Next(state: self.reduce(a))
|
|
64
60
|
|
|
65
61
|
primitive Clicks[App] =
|
|
66
62
|
fun main(io: Io) -> Game =
|
examples/games/orbitrunner/OrbitRunner.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/Str
|
|
|
8
8
|
import std/collections/List
|
|
9
9
|
import std/math/Random
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/math/Vec2
|
|
11
12
|
import std/game/Gfx
|
|
12
13
|
import std/game/Audio
|
|
13
14
|
import std/game/Screen
|
|
@@ -38,7 +39,7 @@ struct Motion(x: Float, y: Float, vx: Float, vy: Float) =
|
|
|
38
39
|
dy := dx.rng.nextFloat()
|
|
39
40
|
x := margin + dx.value * {Arena.W - 2.0 * margin}
|
|
40
41
|
y := margin + dy.value * {Arena.H - 2.0 * margin}
|
|
41
|
-
if tries <= 1 ||
|
|
42
|
+
if tries <= 1 || !Vec2(x: x, y: y).near(Vec2(x: ax, y: ay), gap)
|
|
42
43
|
Spawned(at: Motion(x: x, y: y, vx: 0.0, vy: 0.0), rng: dy.rng)
|
|
43
44
|
else
|
|
44
45
|
Motion.spot(dy.rng, ax, ay, gap, tries - 1)
|
examples/games/orbitrunner/actors/Mine.plum
CHANGED
|
@@ -4,14 +4,20 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/collections/List
|
|
6
6
|
import std/math/Math
|
|
7
|
+
import std/math/Random
|
|
7
8
|
import std/game/Place
|
|
8
9
|
import std/game/View
|
|
9
10
|
import std/game/Sprite
|
|
10
11
|
import OrbitRunner
|
|
12
|
+
import actors/Ship
|
|
11
13
|
|
|
12
14
|
struct Mine[Actor](at: Motion, spin: Float = 0.0, clock: Float = 0.0, tex: Texture) =
|
|
13
15
|
const Radius = 11.0
|
|
14
16
|
|
|
17
|
+
fun spawn(rng: Random, near: Ship, tex: Texture) -> Rolled<Mine> =
|
|
18
|
+
sp := Motion.spawn(rng, near.at.x, near.at.y, 220.0, 90.0)
|
|
19
|
+
Rolled(value: Mine(at: sp.at, tex: tex), rng: sp.rng)
|
|
20
|
+
|
|
15
21
|
fun countFor(score: Int) -> Int = {3 + score / 50}.min(8)
|
|
16
22
|
|
|
17
23
|
fun place(self) -> Place = Place.pivoted(self.at.x, self.at.y, Sheet.Size / 2.0, Sheet.Size / 2.0).rotateTo(self.spin)
|
examples/games/orbitrunner/actors/Orb.plum
CHANGED
|
@@ -7,17 +7,23 @@ import std/Io
|
|
|
7
7
|
import std/collections/List
|
|
8
8
|
import std/math/Vec2
|
|
9
9
|
import std/math/Affine
|
|
10
|
+
import std/math/Random
|
|
10
11
|
import std/game/Color
|
|
11
12
|
import std/game/Gfx
|
|
12
13
|
import std/game/Place
|
|
13
14
|
import std/game/View
|
|
14
15
|
import std/game/Sprite
|
|
15
16
|
import OrbitRunner
|
|
17
|
+
import actors/Ship
|
|
16
18
|
|
|
17
19
|
struct Orb[Actor](at: Motion, phase: Float = 0.0, clock: Float = 0.0, tex: Texture) =
|
|
18
20
|
const Radius = 10.0
|
|
19
21
|
const Points = 10
|
|
20
22
|
|
|
23
|
+
fun spawn(rng: Random, near: Ship, phase: Float, tex: Texture) -> Rolled<Orb> =
|
|
24
|
+
sp := Motion.spawn(rng, near.at.x, near.at.y, 120.0, 40.0)
|
|
25
|
+
Rolled(value: Orb(at: sp.at, phase: phase, tex: tex), rng: sp.rng)
|
|
26
|
+
|
|
21
27
|
fun place(self) -> Place = Place.pivoted(self.at.x, self.at.y, Sheet.Size / 2.0, Sheet.Size / 2.0)
|
|
22
28
|
|
|
23
29
|
fun view(self) -> List<View> =
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -5,7 +5,6 @@ import std/Float
|
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/Str
|
|
7
7
|
import std/Io
|
|
8
|
-
import std/Option
|
|
9
8
|
import std/Slice
|
|
10
9
|
import std/collections/List
|
|
11
10
|
import std/math/Vec2
|
|
@@ -33,12 +32,11 @@ import OrbitRunner
|
|
|
33
32
|
enum PlayAction[Show] =
|
|
34
33
|
| Steer(ax: Float, ay: Float)
|
|
35
34
|
| Tick(dt: Float)
|
|
36
|
-
| PlayAgain
|
|
37
35
|
| Scored(points: Int)
|
|
38
36
|
| Hit
|
|
39
37
|
| StartOver
|
|
40
38
|
|
|
41
|
-
struct PlayingScreen[ScreenSlice<PlayAction>
|
|
39
|
+
struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
42
40
|
rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
|
|
43
41
|
@stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
|
|
44
42
|
const OrbCount = 3
|
|
@@ -74,77 +72,75 @@ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
|
|
|
74
72
|
}
|
|
75
73
|
]
|
|
76
74
|
|
|
77
|
-
fun deal(self) -> PlayingScreen =
|
|
78
|
-
fresh := PlayingScreen(..self, clock: 0.0, ship: Ship.create(self.assets.sheet), orbs: Nil, mines: Nil, rings: Nil)
|
|
79
|
-
withOrbs := Range.until(0, PlayingScreen.OrbCount).fold(fresh, |s, i| s.newOrb(i))
|
|
80
|
-
Range.until(0, Mine.countFor(0)).fold(withOrbs, |s, i| s.newMine())
|
|
81
|
-
|
|
82
|
-
fun newOrb(self, i: Int) -> PlayingScreen =
|
|
83
|
-
sp := Motion.spawn(self.rng, self.ship.at.x, self.ship.at.y, 120.0, 40.0)
|
|
84
|
-
PlayingScreen(..self, rng: sp.rng, orbs: self.orbs.append([Orb(at: sp.at, phase: Float(i) * 0.1, tex: self.assets.sheet)]))
|
|
85
|
-
|
|
86
|
-
fun newMine(self) -> PlayingScreen =
|
|
87
|
-
sp := Motion.spawn(self.rng, self.ship.at.x, self.ship.at.y, 220.0, 90.0)
|
|
88
|
-
PlayingScreen(..self, rng: sp.rng, mines: self.mines.append([Mine(at: sp.at, tex: self.assets.sheet)]))
|
|
89
|
-
|
|
90
|
-
fun
|
|
75
|
+
fun subscriptions(self) -> List<Sub<PlayAction>> = [
|
|
76
|
+
OnFrame(|dt| Tick(dt: dt))
|
|
77
|
+
if !self.over then OnHeld(|h| PlayingScreen.steering(h))
|
|
78
|
+
if self.over then OnKeyDown(key: Key.Enter, act: StartOver)
|
|
91
|
-
|
|
79
|
+
if self.over then OnKeyDown(key: Key.KeyR, act: StartOver)
|
|
92
|
-
|
|
80
|
+
]
|
|
93
81
|
|
|
94
|
-
fun
|
|
82
|
+
fun steering(h: Held) -> PlayAction =
|
|
95
83
|
ax := h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)
|
|
96
84
|
ay := h.axis(Key.Up, Key.Down) + h.axis(Key.KeyW, Key.KeyS)
|
|
97
|
-
|
|
85
|
+
Steer(ax: ax.max(-1.0).min(1.0), ay: ay.max(-1.0).min(1.0))
|
|
98
|
-
|
|
99
|
-
|
|
86
|
+
|
|
100
|
-
|
|
101
|
-
fun
|
|
87
|
+
fun update(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
102
|
-
Steer(ax, ay) => PlayingScreen(..self, ship: self.ship.steer(ax, ay))
|
|
88
|
+
Steer(ax, ay) => Next(state: PlayingScreen(..self, ship: self.ship.steer(ax, ay)))
|
|
89
|
+
Tick(dt) =>
|
|
103
|
-
|
|
90
|
+
stepped := self.stepped(dt)
|
|
91
|
+
moved := PlayingScreen(..stepped, clock: stepped.clock + dt, rings: stepped.rings.filter(|r| !r.done()))
|
|
92
|
+
if moved.over then Next(state: moved) else moved.rules()
|
|
104
|
-
|
|
93
|
+
Scored(points) =>
|
|
94
|
+
sounds := self.assets
|
|
105
|
-
|
|
95
|
+
Next(state: PlayingScreen(..self, score: self.score + points).grown(), cmds: [Play(sound: sounds.pickup, volume: 0.8)])
|
|
106
96
|
Hit =>
|
|
97
|
+
sounds := self.assets
|
|
107
98
|
lives := self.lives - 1
|
|
108
99
|
ring := Ring.at(self.ship.at.x + Sheet.Size / 2.0, self.ship.at.y + Sheet.Size / 2.0)
|
|
109
|
-
|
|
100
|
+
over := self.over || lives <= 0
|
|
101
|
+
Next(
|
|
110
|
-
|
|
102
|
+
state: PlayingScreen(
|
|
111
|
-
|
|
103
|
+
..self, best: if over then self.best.max(self.score) else self.best, lives: lives, over: over,
|
|
112
|
-
|
|
104
|
+
ship: self.ship.hurtFor(Ship.HurtTime), rings: self.rings.append([ring])),
|
|
105
|
+
cmds: if over then [Stop(sound: sounds.music), Play(sound: sounds.over, volume: 1.0)] else [Play(sound: sounds.hit, volume: 1.0)])
|
|
113
106
|
StartOver =>
|
|
107
|
+
sounds := self.assets
|
|
108
|
+
best := self.best.max(self.score)
|
|
109
|
+
Next(
|
|
114
|
-
|
|
110
|
+
state: PlayingScreen(..self, score: 0, best: best, lives: PlayingScreen.StartLives, over: false).deal(),
|
|
115
|
-
|
|
116
|
-
fun act(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
117
|
-
Tick(dt) => self.advance(dt)
|
|
118
|
-
_ => self.reduce(a).followed(a)
|
|
119
|
-
|
|
120
|
-
fun followed(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
121
|
-
PlayAgain => Next(state: self, then: [if self.over then StartOver])
|
|
122
|
-
Scored(_) => Next(state: self, cmds: [Play(sound: self.assets.pickup, volume: 0.8)])
|
|
123
|
-
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)])
|
|
124
|
-
|
|
111
|
+
cmds: [Stop(sound: sounds.music), Loop(sound: sounds.music, volume: Assets.MusicVolume)])
|
|
125
|
-
_ => Next(state: self)
|
|
126
|
-
|
|
127
|
-
fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
|
|
128
|
-
moved := PlayingScreen(..self, clock: self.clock + dt, rings: self.rings.filter(|r| !r.done()))
|
|
129
|
-
if self.over then Next(state: moved) else moved.rules()
|
|
130
112
|
|
|
131
113
|
fun rules(self) -> Next<PlayingScreen, PlayAction> =
|
|
132
114
|
sh := self.ship
|
|
115
|
+
p := Vec2(x: sh.at.x, y: sh.at.y)
|
|
133
116
|
caught := self.orbs.fold(Caught(orbs: Nil, rng: self.rng, points: 0), |c, orb|
|
|
134
|
-
if
|
|
117
|
+
if p.near(Vec2(x: orb.at.x, y: orb.at.y), Ship.Radius + Orb.Radius)
|
|
135
|
-
|
|
118
|
+
o := Orb.spawn(c.rng, sh, orb.phase, orb.tex)
|
|
136
|
-
Caught(orbs: Cons(
|
|
119
|
+
Caught(orbs: Cons(o.value, c.orbs), rng: o.rng, points: c.points + Orb.Points)
|
|
137
120
|
else
|
|
138
121
|
Caught(..c, orbs: Cons(orb, c.orbs))
|
|
139
122
|
)
|
|
140
|
-
hit := sh.hurt <= 0.0 && self.mines.any(|m|
|
|
123
|
+
hit := sh.hurt <= 0.0 && self.mines.any(|m| p.near(Vec2(x: m.at.x, y: m.at.y), Ship.Radius + Mine.Radius))
|
|
141
|
-
Next(state: PlayingScreen(..self,
|
|
124
|
+
Next(state: PlayingScreen(..self, rng: caught.rng, orbs: caught.orbs.reverse()), then: [
|
|
142
125
|
if caught.points > 0 then Scored(points: caught.points)
|
|
143
126
|
if hit then Hit
|
|
144
127
|
])
|
|
145
128
|
|
|
129
|
+
fun deal(self) -> PlayingScreen =
|
|
130
|
+
ship := Ship.create(self.assets.sheet)
|
|
131
|
+
tex := self.assets.sheet
|
|
132
|
+
none: List<Orb> := Nil
|
|
133
|
+
dealt := Range.until(0, PlayingScreen.OrbCount).fold(Rolled(value: none, rng: self.rng), |r, i|
|
|
134
|
+
o := Orb.spawn(r.rng, ship, Float(i) * 0.1, tex)
|
|
135
|
+
Rolled(value: r.value.append([o.value]), rng: o.rng)
|
|
136
|
+
)
|
|
137
|
+
PlayingScreen(..self, rng: dealt.rng, clock: 0.0, ship: ship, orbs: dealt.value, mines: Nil, rings: Nil).grown()
|
|
138
|
+
|
|
139
|
+
fun grown(self) -> PlayingScreen =
|
|
146
|
-
|
|
140
|
+
if self.mines.length() < Mine.countFor(self.score)
|
|
147
|
-
|
|
141
|
+
m := Mine.spawn(self.rng, self.ship, self.assets.sheet)
|
|
148
|
-
|
|
142
|
+
PlayingScreen(..self, rng: m.rng, mines: self.mines.append([m.value])).grown()
|
|
143
|
+
else
|
|
144
|
+
self
|
|
149
145
|
|
|
150
146
|
struct Caught(orbs: List<Orb>, rng: Random, points: Int)
|
examples/games/two_screens.plum
CHANGED
|
@@ -3,7 +3,6 @@ module two_screens
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
-
import std/Option
|
|
7
6
|
import std/Io
|
|
8
7
|
import std/collections/List
|
|
9
8
|
import std/game/Color
|
|
@@ -28,11 +27,9 @@ struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
|
|
|
28
27
|
|
|
29
28
|
fun frames(self) -> Frames = OnDemand
|
|
30
29
|
|
|
31
|
-
fun
|
|
30
|
+
fun subscriptions(self) -> List<Sub<TitleAction>> = [OnKeyDown(key: Key.Enter, act: Start)]
|
|
32
|
-
KeyDown(k) => if k == Key.Enter then Some(Start) else None
|
|
33
|
-
_ => None
|
|
34
31
|
|
|
35
|
-
fun
|
|
32
|
+
fun update(self, a: TitleAction) -> Next<TitleScreen, TitleAction> = Next(state: TitleScreen(starts: self.starts + 1), cmds: [GoTo(name: "play")])
|
|
36
33
|
|
|
37
34
|
struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
|
|
38
35
|
fun name(self) -> Str = "play"
|
|
@@ -41,11 +38,9 @@ struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
|
|
|
41
38
|
|
|
42
39
|
fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
|
|
43
40
|
|
|
44
|
-
fun
|
|
41
|
+
fun subscriptions(self) -> List<Sub<PlayAction>> = [OnKeyDown(key: Key.Escape, act: Back)]
|
|
45
|
-
KeyDown(k) => if k == Key.Escape then Some(Back) else None
|
|
46
|
-
_ => None
|
|
47
42
|
|
|
48
|
-
fun
|
|
43
|
+
fun update(self, a: PlayAction) -> Next<PlayScreen, PlayAction> = Next(state: PlayScreen(runs: self.runs + 1), cmds: [GoTo(name: "title")])
|
|
49
44
|
|
|
50
45
|
primitive TwoScreens[App] =
|
|
51
46
|
fun game() -> Game =
|
std/game/Cmd.plum
CHANGED
|
@@ -8,14 +8,13 @@ import std/Io
|
|
|
8
8
|
import std/collections/List
|
|
9
9
|
import std/game/Audio
|
|
10
10
|
|
|
11
|
-
# What
|
|
11
|
+
# What an update asks of the game, as a value: a slice's `update(a)` returns its commands
|
|
12
12
|
# with its next state (std/game/ScreenSlice's `Next`), and the game does them once the tick
|
|
13
13
|
# is over, in the order given, with the `Io` the tick has (std/game/Game):
|
|
14
14
|
#
|
|
15
|
-
# fun
|
|
15
|
+
# fun update(self, a: MenuAction) -> Next<MenuScreen, MenuAction> = match a
|
|
16
16
|
# Start => Next(state: self, cmds: [GoTo(name: "play"), Play(sound: self.assets.click, volume: 1.0)])
|
|
17
17
|
# Quit => Next(state: self, cmds: [Exit])
|
|
18
|
-
# _ => Next(state: self.reduce(a))
|
|
19
18
|
#
|
|
20
19
|
# GoTo shows the screen of that name from the next tick on, as it was left, coming
|
|
21
20
|
# in by its `transition(from)`. A name no screen has stops the program and
|
std/game/Game.plum
CHANGED
|
@@ -54,8 +54,9 @@ import std/game/Replay
|
|
|
54
54
|
#
|
|
55
55
|
# One tick (`update`, or `step` with the window's size given, as a test runs it): the
|
|
56
56
|
# current screen gets the tick (`deliver`, with a `Delivery`: the tick's input, its
|
|
57
|
-
# camera, what was held at its tick before, and no `Io`), as actions for a slice screen
|
|
57
|
+
# camera, what was held at its tick before, and no `Io`), as actions for a slice screen
|
|
58
|
-
#
|
|
58
|
+
# (its subscriptions' and its presses', the frame last: the screen steps its `Actor`s in
|
|
59
|
+
# its frame action), or as its actors stepped for a plain screen;
|
|
59
60
|
# then the transition in progress moves on; then the game does the commands the tick's
|
|
60
61
|
# actions gave (std/game/Cmd), in order, with `io`: a sound, a `GoTo`, an `Exit`; an undo,
|
|
61
62
|
# a redo or a rewind once the tick is recorded. A tick takes nothing from `io` but its
|
std/game/History.plum
CHANGED
|
@@ -26,8 +26,8 @@ import std/game/Input
|
|
|
26
26
|
# `resume`. Ticks played since an undo that are no user action (time passing) leave the
|
|
27
27
|
# future where it is: they lie after `fork`, and a redo or an undo drops them.
|
|
28
28
|
#
|
|
29
|
-
# A user action tick is one in which the shown slice screen's
|
|
29
|
+
# A user action tick is one in which the shown slice screen's subscriptions (or a press)
|
|
30
|
-
# action for one of the tick's events, or `
|
|
30
|
+
# gave an action for one of the tick's events, or `OnHeld` gave an action while what is held
|
|
31
31
|
# differs from the tick before (std/game/Game, `run`). A tick whose commands asked for an
|
|
32
32
|
# undo, a redo or a rewind is the command, not something to undo.
|
|
33
33
|
#
|
std/game/Input.plum
CHANGED
|
@@ -184,6 +184,10 @@ enum InputEvent =
|
|
|
184
184
|
KeyDown(k) => k == key
|
|
185
185
|
_ => false
|
|
186
186
|
|
|
187
|
+
fun isKeyUpOf(self, key: Int) -> Bool = match self
|
|
188
|
+
KeyUp(k) => k == key
|
|
189
|
+
_ => false
|
|
190
|
+
|
|
187
191
|
fun isPointerDown(self) -> Bool = match self
|
|
188
192
|
PointerDown(_, _) => true
|
|
189
193
|
_ => false
|
|
@@ -206,7 +210,7 @@ enum InputEvent =
|
|
|
206
210
|
# What is held, a fold of the events (`after`): the left mouse button (or a touch), the
|
|
207
211
|
# keys that are down, the other mouse buttons that are down (`Mouse.Right`,
|
|
208
212
|
# `Mouse.Middle`), and where the pointer is, in screen pixels; nothing unless given
|
|
209
|
-
# (`Held()`, `Held(keys: keys)`). A slice's `
|
|
213
|
+
# (`Held()`, `Held(keys: keys)`). A slice's `OnHeld` (std/game/ScreenSlice) maps it.
|
|
210
214
|
struct Held(mouse: Bool = false, keys: List<Int> = Nil, buttons: List<Int> = Nil, pointer: Vec2 = Vec2(x: 0.0, y: 0.0)) =
|
|
211
215
|
# Whether `o` holds the same: the mouse buttons, and the same keys in any order (where
|
|
212
216
|
# the pointer is aside).
|
std/game/Overlay.plum
CHANGED
|
@@ -32,8 +32,8 @@ import std/game/Label
|
|
|
32
32
|
# 0.6 alpha unless given) over what is under it, then its children (its `view`) at their
|
|
33
33
|
# own opacity. Its size is required. It takes presses (`touch: Enabled` unless given,
|
|
34
34
|
# std/game/Touch) inside its box, so no item under it there is pressed; its children are
|
|
35
|
-
# hit first. Keys still go to the screen's
|
|
35
|
+
# hit first. Keys still go to the screen's subscriptions (`OnKeyDown`, std/game/ScreenSlice),
|
|
36
|
-
#
|
|
36
|
+
# which say what they do while it shows (Enter plays again).
|
|
37
37
|
struct Overlay[View, Sized, Touch](x: Float = 0.0, y: Float = 0.0, w: Float, h: Float, color: Color = Overlay.Shade, touch: Touchable = Enabled, children: List<View>) =
|
|
38
38
|
const Shade = Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6)
|
|
39
39
|
|
std/game/Screen.plum
CHANGED
|
@@ -22,21 +22,20 @@ import std/game/ScreenSlice
|
|
|
22
22
|
# another by name, when a slice's step asks it to (`GoTo(name)`, std/game/Cmd).
|
|
23
23
|
#
|
|
24
24
|
# A screen with rules is a `ScreenSlice<A>` (std/game/ScreenSlice), which extends
|
|
25
|
-
# `Screen`: its fields are its state, `A` its actions,
|
|
25
|
+
# `Screen`: its fields are its state, `A` its actions, `update` its one entry point, and
|
|
26
|
-
#
|
|
26
|
+
# its `subscriptions` say which input and frames become actions. A screen with no rules
|
|
27
|
-
# actions, and draws what its fields were made with, its
|
|
27
|
+
# is a plain `Screen`: it gets no actions, and draws what its fields were made with, its
|
|
28
|
+
# actors stepped each tick.
|
|
28
29
|
#
|
|
29
30
|
# A screen is a value: each tick the game keeps the next version the tick returned.
|
|
30
31
|
#
|
|
31
|
-
# Each tick the screen gets, before its tick action is reduced, the game has it step its
|
|
32
|
-
# `Actor`s (std/game/View), unless it says `steps()` is false: it calls the screen's
|
|
33
|
-
# `stepped(dt)`
|
|
32
|
+
# Every screen has `stepped(dt)`: the screen with each actor it holds stepped `dt`
|
|
34
|
-
# step an actor where it finds it in the view, since the
|
|
33
|
+
# seconds on. The game can't step an actor where it finds it in the view, since the
|
|
35
|
-
#
|
|
34
|
+
# screen holding it is a value, so the screen's own fields are stepped. The compiler
|
|
36
|
-
#
|
|
35
|
+
# derives it from the fields holding actors (an `Actor`, a `List` or `Option` of them, a
|
|
37
|
-
# field steps it only while `cond` holds
|
|
36
|
+
# `List<View>`); `@stepsWhen(cond)` before a field steps it only while `cond` holds:
|
|
38
37
|
#
|
|
39
|
-
# struct PlayingScreen[ScreenSlice<PlayAction>
|
|
38
|
+
# struct PlayingScreen[ScreenSlice<PlayAction>](over: Bool, @stepsWhen(!self.over) ship: Ship, mines: List<Mine>)
|
|
40
39
|
#
|
|
41
40
|
# is stepped as if it wrote
|
|
42
41
|
#
|
|
@@ -44,7 +43,8 @@ import std/game/ScreenSlice
|
|
|
44
43
|
# PlayingScreen(..self, ship: if !self.over then self.ship.step(dt) else self.ship, mines: Views.stepAll(self.mines, dt))
|
|
45
44
|
#
|
|
46
45
|
# which a screen may write itself (it wins over the derive). A screen holding no actors
|
|
47
|
-
#
|
|
46
|
+
# has the default, the screen as it is. A slice calls it in its frame action
|
|
47
|
+
# (`Tick(dt) => self.stepped(dt).rules()`); a plain screen's tick is its `stepped`.
|
|
48
48
|
#
|
|
49
49
|
# What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of
|
|
50
50
|
# the screen it sits on, an `Overlay` (std/game/Overlay) in its view, there while the
|
|
@@ -59,10 +59,8 @@ import std/game/ScreenSlice
|
|
|
59
59
|
# hud what is drawn over the view, one unit a pixel of the window, which is
|
|
60
60
|
# `window` pixels: a score in a corner. Hit before the view. Empty by
|
|
61
61
|
# default.
|
|
62
|
-
# steps false to step none of its actors this tick (a game paused, a run over).
|
|
63
|
-
# True by default.
|
|
64
|
-
# stepped the screen with its actors stepped `dt` seconds on (above)
|
|
62
|
+
# stepped the screen with its actors stepped `dt` seconds on (above). The screen as
|
|
65
|
-
#
|
|
63
|
+
# it is by default.
|
|
66
64
|
# camera the camera it is seen through, given the one its `size()` and `viewport()`
|
|
67
65
|
# make (`base`): `base` by default, `base.lookAt(x, y, zoom)` to follow
|
|
68
66
|
# something or zoom (std/game/Viewport). Presses, `toWorld`, culling and the
|
|
@@ -84,10 +82,10 @@ import std/game/ScreenSlice
|
|
|
84
82
|
# in docs/game.md).
|
|
85
83
|
# deliver std's, not the screen's: how the game runs one tick of the screen. A
|
|
86
84
|
# plain screen's steps its actors; a slice's delivers the tick as actions
|
|
87
|
-
#
|
|
85
|
+
# (its frame among them).
|
|
88
86
|
# wants std's too: whether what is held after the tick's input gives an
|
|
89
87
|
# `OnDemand` screen something to do. A plain screen's is never; a slice's
|
|
90
|
-
# is
|
|
88
|
+
# is whether it subscribes to `OnHeld`.
|
|
91
89
|
#
|
|
92
90
|
# The game keeps a screen as it is when it goes to another, so coming back shows it as it
|
|
93
91
|
# was left.
|
|
@@ -103,8 +101,6 @@ trait Screen =
|
|
|
103
101
|
|
|
104
102
|
fun hud(self, window: Vec2) -> List<View> = Nil
|
|
105
103
|
|
|
106
|
-
fun steps(self) -> Bool = true
|
|
107
|
-
|
|
108
104
|
fun stepped(self, dt: Float) -> Self = self
|
|
109
105
|
|
|
110
106
|
fun camera(self, base: Viewport) -> Viewport = base
|
|
@@ -123,14 +119,14 @@ trait Screen =
|
|
|
123
119
|
|
|
124
120
|
fun frames(self) -> Frames = Always
|
|
125
121
|
|
|
126
|
-
fun deliver(self, d: Delivery) -> Delivered = Delivered(screen:
|
|
122
|
+
fun deliver(self, d: Delivery) -> Delivered = Delivered(screen: self.stepped(d.dt))
|
|
127
123
|
|
|
128
124
|
fun wants(self, h: Held) -> Bool = false
|
|
129
125
|
|
|
130
126
|
# One tick of a screen, delivered: the screen after it, the commands its actions gave for
|
|
131
127
|
# the game (std/game/Cmd), in order, the actions stepped, and whether the tick was a user
|
|
132
|
-
# action (std/game/History):
|
|
128
|
+
# action (std/game/History): a subscription or a press gave an action for one of its
|
|
133
|
-
# gave one while what is held differs from the screen's tick before.
|
|
129
|
+
# events, or `OnHeld` gave one while what is held differs from the screen's tick before.
|
|
134
130
|
struct Delivered(screen: Screen, cmds: List<Cmd> = Nil, sent: List<Dispatched> = Nil, acted: Bool = false)
|
|
135
131
|
|
|
136
132
|
# How often a screen gets its ticks and is drawn: every frame (`Always`), or only when
|
std/game/ScreenSlice.plum
CHANGED
|
@@ -15,93 +15,140 @@ import std/game/Viewport
|
|
|
15
15
|
import std/game/Cmd
|
|
16
16
|
import std/game/Screen
|
|
17
17
|
|
|
18
|
-
# A screen with a slice of the game,
|
|
18
|
+
# A screen with a slice of the game, in the Elm style (master's `Slice<A>`; here the name
|
|
19
|
-
#
|
|
19
|
+
# `Slice` is std's growable array): the screen's own fields are its state, `A` (an enum,
|
|
20
|
+
# usually) its actions, `update` steps one action into it, `subscriptions` says which
|
|
20
|
-
#
|
|
21
|
+
# input and which frames become its actions, and `view` (std/game/Screen) draws it:
|
|
21
|
-
# tick's input becomes its actions and what its tick action is; std delivers them, so a
|
|
22
|
-
# slice screen has no `update` of its own:
|
|
23
22
|
#
|
|
24
23
|
# enum Act = Bump | Tick(dt: Float)
|
|
25
24
|
#
|
|
26
|
-
# struct CountScreen[ScreenSlice<Act>](count: Int) =
|
|
25
|
+
# struct CountScreen[ScreenSlice<Act>](count: Int, ball: Ball) =
|
|
27
26
|
# fun name(self) -> Str = "count"
|
|
28
27
|
#
|
|
29
|
-
# fun
|
|
28
|
+
# fun subscriptions(self) -> List<Sub<Act>> = [
|
|
29
|
+
# OnFrame(|dt| Tick(dt: dt))
|
|
30
|
-
#
|
|
30
|
+
# OnKeyDown(key: Key.Space, act: Bump)
|
|
31
|
-
#
|
|
31
|
+
# ]
|
|
32
32
|
#
|
|
33
|
-
# fun
|
|
33
|
+
# fun update(self, a: Act) -> Next<CountScreen, Act> = match a
|
|
34
|
-
# Bump => CountScreen(count: self.count + 1)
|
|
34
|
+
# Bump => Next(state: CountScreen(..self, count: self.count + 1), cmds: [Play(sound: self.click, volume: 1.0)])
|
|
35
|
-
# Tick(dt) => self
|
|
35
|
+
# Tick(dt) => Next(state: self.stepped(dt))
|
|
36
36
|
#
|
|
37
|
-
# The slice is a value: `
|
|
37
|
+
# The slice is a value: `update` returns a `Next`, its next version with the actions that
|
|
38
|
+
# follow from this one (`then`) and what it asks of the game (`cmds`, std/game/Cmd: a
|
|
39
|
+
# sound, another screen, an undo); std keeps that version. By default `update` keeps the
|
|
40
|
+
# slice as it is and `subscriptions` is empty, so a screen with no actions compiles.
|
|
38
41
|
#
|
|
39
|
-
#
|
|
42
|
+
# The frame is an action like any other: a screen that moves subscribes to `OnFrame` and
|
|
40
|
-
# it returns a `Next`, the next state with the actions that follow from this one (`then`)
|
|
41
|
-
#
|
|
43
|
+
# steps its actors in its frame action, with `stepped(dt)` (std/game/Screen: derived for
|
|
44
|
+
# every screen from its fields holding actors), then runs its rules. Nothing is stepped
|
|
45
|
+
# that `update` doesn't step.
|
|
42
46
|
#
|
|
43
|
-
# fun act(self, a: Act) -> Next<CountScreen, Act> = match a
|
|
44
|
-
# Bump => Next(state: CountScreen(count: self.count + 1), cmds: [Play(sound: self.click, volume: 1.0)])
|
|
45
|
-
# _ => Next(state: self.reduce(a))
|
|
46
|
-
#
|
|
47
|
-
#
|
|
47
|
+
# Each tick of the screen, std reads its `subscriptions()` once (from the screen as the
|
|
48
|
-
# a screen writes the one it needs.
|
|
49
|
-
#
|
|
50
|
-
#
|
|
48
|
+
# tick found it) and delivers, in this order:
|
|
51
49
|
#
|
|
52
50
|
# 1. each of the tick's events, in the order they came:
|
|
53
|
-
# a key `
|
|
51
|
+
# a key `OnKeyDown(key, act)` and `OnKeyUp(key, act)`: `act` for that key
|
|
54
52
|
# a press `onPress(target, at)`, with the top-most item of the screen's
|
|
55
53
|
# `hud`, or else of its view, under the press that takes presses
|
|
56
54
|
# (`Sized` and `Enabled`, std/game/View's `Views.hitIn`) and the press
|
|
57
55
|
# in the world's coordinates; if it gives None, or the press is on
|
|
58
|
-
# no such item,
|
|
56
|
+
# no such item, the press goes to `OnPointerDown` as any pointer
|
|
59
|
-
# default it is what the item says a press on it
|
|
57
|
+
# down does. By default it is what the item says a press on it
|
|
60
|
-
# `pressed()` of an item that `Presses<A>`
|
|
58
|
+
# means: the `pressed()` of an item that `Presses<A>`
|
|
61
|
-
# `Button(.., on: Tapped)`, or an actor of your
|
|
59
|
+
# (std/game/Button: a `Button(.., on: Tapped)`, or an actor of your
|
|
62
|
-
# any other
|
|
60
|
+
# own), None for any other
|
|
63
|
-
# a pointer event `
|
|
61
|
+
# a pointer event `OnPointerDown(at)`, `OnPointerUp(at)`, `OnPointerMove(at)`, with
|
|
64
|
-
# (through the screen's camera)
|
|
62
|
+
# the event's point in the world (through the screen's camera)
|
|
65
|
-
# a wheel turn `
|
|
63
|
+
# a wheel turn `OnWheel(dy, at)`, at where the pointer is after the tick's events
|
|
66
|
-
# events
|
|
67
64
|
# While a transition runs, the pointer events and the wheel are dropped: only keys
|
|
68
65
|
# come.
|
|
69
|
-
# 2. `
|
|
66
|
+
# 2. `OnHeld(h)`: an action for what is held after the events (`Held`, std/game/Input:
|
|
70
67
|
# the steering keys), every tick.
|
|
71
|
-
# 3. The game has the screen step its `Actor`s (`stepped(dt)`, std/game/Screen), unless
|
|
72
|
-
# its `steps()` is false.
|
|
73
|
-
#
|
|
68
|
+
# 3. `OnFrame(dt)`: the frame action, which steps the actors and runs the rules.
|
|
74
69
|
#
|
|
70
|
+
# Several subscriptions may answer one event (each in the order listed). Each action is
|
|
75
|
-
#
|
|
71
|
+
# stepped as it is made, and then each action of its `then`, in order, each with its own
|
|
76
|
-
# each action of its `then`, in order, each with its own `then` first: so the next
|
|
77
|
-
#
|
|
72
|
+
# `then` first: so the next action sees what they did. The delivery is a fold
|
|
78
|
-
# screen after the tick, the actions stepped, in order, and
|
|
73
|
+
# (`Delivery.deliverTo`): the screen after the tick, the actions stepped, in order, and
|
|
79
|
-
# does after the tick (and the transition's step).
|
|
74
|
+
# their commands, which the game does after the tick (and the transition's step).
|
|
80
75
|
trait ScreenSlice<A>[Screen] =
|
|
81
|
-
fun reduce(self, a: A) -> Self = self
|
|
82
|
-
|
|
83
|
-
fun
|
|
76
|
+
fun update(self, a: A) -> Next<Self, A> = Next(state: self)
|
|
84
77
|
|
|
85
|
-
fun
|
|
78
|
+
fun subscriptions(self) -> List<Sub<A>> = Nil
|
|
86
|
-
|
|
87
|
-
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<A> = None
|
|
88
79
|
|
|
89
80
|
fun onPress(self, target: View, at: Vec2) -> Option<A> = match target
|
|
90
81
|
Presses<A> as p => Some(p.pressed())
|
|
91
82
|
_ => None
|
|
92
83
|
|
|
93
|
-
fun held(self, h: Held) -> Option<A> = None
|
|
94
|
-
|
|
95
|
-
fun tick(self, dt: Float) -> Option<A> = None
|
|
96
|
-
|
|
97
|
-
# std's: whether what is held gives an `OnDemand` screen something to do:
|
|
84
|
+
# std's: whether what is held gives an `OnDemand` screen something to do: it subscribes
|
|
98
|
-
#
|
|
85
|
+
# to `OnHeld`.
|
|
99
|
-
fun wants(self, h: Held) -> Bool = self.
|
|
86
|
+
fun wants(self, h: Held) -> Bool = self.subscriptions().any(|s| s.isHeld())
|
|
100
87
|
|
|
101
88
|
# std's: one tick of the screen, delivered as actions (see the top of this file).
|
|
102
89
|
fun deliver(self, d: Delivery) -> Delivered = Delivery.deliverTo<A, Self>(self, d)
|
|
103
90
|
|
|
91
|
+
# What a slice listens to (its `subscriptions`), each giving it an action of type `A`:
|
|
92
|
+
#
|
|
93
|
+
# OnFrame(act) `act(dt)` each tick, last: the frame
|
|
94
|
+
# OnKeyDown(key, act) `act` when `key` goes down (a `Key`, std/game/Input)
|
|
95
|
+
# OnKeyUp(key, act) `act` when `key` goes up
|
|
96
|
+
# OnHeld(act) `act(h)` each tick, with what is held after the tick's events
|
|
97
|
+
# OnWheel(act) `act(dy, at)` for a wheel turn, `at` the pointer in the world
|
|
98
|
+
# OnPointerDown(act) `act(at)` for a pointer down that no press target took
|
|
99
|
+
# OnPointerUp(act) `act(at)` for a pointer up
|
|
100
|
+
# OnPointerMove(act) `act(at)` for a pointer move (a drag, with `OnHeld`'s `h.mouse`)
|
|
101
|
+
#
|
|
102
|
+
# A list of them is made again each tick, so one can be there only while the state says
|
|
103
|
+
# so: `if !self.over then OnHeld(|h| Steer(..))`.
|
|
104
|
+
enum Sub<A> =
|
|
105
|
+
| OnFrame(act: fn(Float) -> A)
|
|
106
|
+
| OnKeyDown(key: Int, act: A)
|
|
107
|
+
| OnKeyUp(key: Int, act: A)
|
|
108
|
+
| OnHeld(act: fn(Held) -> A)
|
|
109
|
+
| OnWheel(act: fn(Float, Vec2) -> A)
|
|
110
|
+
| OnPointerDown(act: fn(Vec2) -> A)
|
|
111
|
+
| OnPointerUp(act: fn(Vec2) -> A)
|
|
112
|
+
| OnPointerMove(act: fn(Vec2) -> A)
|
|
113
|
+
|
|
114
|
+
fun isHeld(self) -> Bool = match self
|
|
115
|
+
OnHeld(_) => true
|
|
116
|
+
_ => false
|
|
117
|
+
|
|
118
|
+
# Its action for the event `e`, at the world point `at` (a pointer's or the wheel's), or
|
|
119
|
+
# None.
|
|
120
|
+
fun onEvent(self, e: InputEvent, at: Vec2) -> Option<A> = match self
|
|
121
|
+
OnKeyDown(k, a) => if e.isKeyDownOf(k) then Some(a) else None
|
|
122
|
+
OnKeyUp(k, a) => if e.isKeyUpOf(k) then Some(a) else None
|
|
123
|
+
OnWheel(turn) => match e
|
|
124
|
+
Wheel(dy) => Some(turn(dy, at))
|
|
125
|
+
_ => None
|
|
126
|
+
OnPointerDown(down) => if e.isPointerDown() then Some(down(at)) else None
|
|
127
|
+
OnPointerUp(up) => if e.isPointerUp() then Some(up(at)) else None
|
|
128
|
+
OnPointerMove(move) => if e.isPointerMove() then Some(move(at)) else None
|
|
129
|
+
_ => None
|
|
130
|
+
|
|
131
|
+
# Its action for what is held, or None.
|
|
132
|
+
fun onHeld(self, h: Held) -> Option<A> = match self
|
|
133
|
+
OnHeld(held) => Some(held(h))
|
|
134
|
+
_ => None
|
|
135
|
+
|
|
136
|
+
# Its action for a frame of `dt` seconds, or None.
|
|
137
|
+
fun onFrame(self, dt: Float) -> Option<A> = match self
|
|
138
|
+
OnFrame(frame) => Some(frame(dt))
|
|
139
|
+
_ => None
|
|
140
|
+
|
|
141
|
+
primitive Subs =
|
|
142
|
+
# What `f` gives for each of `subs` that answers, in order.
|
|
143
|
+
fun picked<A>(subs: List<Sub<A>>, f: fn(Sub<A>) -> Option<A>) -> List<A> = match subs
|
|
144
|
+
Nil => Nil
|
|
145
|
+
Cons(sub, rest) =>
|
|
146
|
+
got := f(sub)
|
|
147
|
+
match got
|
|
148
|
+
Some(a) => Cons(a, Subs.picked<A>(rest, f))
|
|
149
|
+
None => Subs.picked<A>(rest, f)
|
|
150
|
+
|
|
104
|
-
# What a slice's `
|
|
151
|
+
# What a slice's `update` gives: its next state, the actions that follow from the one stepped
|
|
105
152
|
# (stepped next, in order, before anything else), and the commands for the game.
|
|
106
153
|
struct Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)
|
|
107
154
|
|
|
@@ -139,69 +186,62 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
139
186
|
h := Views.hitIn(hud, p)
|
|
140
187
|
if h.isSome() then h else Views.hitIn(view, at)
|
|
141
188
|
|
|
142
|
-
# `s` with its actors stepped (`stepped(dt)`), unless it says it `steps()` none this
|
|
143
|
-
# tick.
|
|
144
|
-
fun stepScreen<S: Screen>(self, s: S) -> S = if s.steps() then s.stepped(self.dt) else s
|
|
145
|
-
|
|
146
|
-
# One tick of the slice `s`, as `deliver` describes: a fold of its events,
|
|
189
|
+
# One tick of the slice `s`, as `deliver` describes: a fold of its events, what is held
|
|
147
|
-
# and
|
|
190
|
+
# and the frame over the slice, through its `subscriptions()`, read once from `s`. The
|
|
191
|
+
# game keeps `s` (its screens, and the ones a rewind starts from), so the fold steps a
|
|
148
|
-
#
|
|
192
|
+
# copy of it (`@copy`, one per tick delivered): the copy is the fold's alone, and each
|
|
149
|
-
#
|
|
193
|
+
# step may update it in place.
|
|
150
194
|
fun deliverTo<A, S: ScreenSlice<A>>(s: S, d: Delivery) -> Delivered =
|
|
195
|
+
subs := s.subscriptions()
|
|
151
196
|
none: Trail<A> := Trail()
|
|
152
|
-
afterEvents := d.eventsInto<A, S>(@copy(s), none, d.input.events)
|
|
197
|
+
afterEvents := d.eventsInto<A, S>(@copy(s), subs, none, d.input.events)
|
|
153
198
|
match afterEvents
|
|
154
|
-
Folded(cur, trail) => d.heldInto<A, S>(cur, trail)
|
|
199
|
+
Folded(cur, trail) => d.heldInto<A, S>(cur, subs, trail)
|
|
155
|
-
|
|
156
|
-
# The slice `s` after its `held`, its actors' step and its `tick`, delivered.
|
|
157
|
-
fun heldInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>) -> Delivered =
|
|
158
|
-
h := s.held(self.input.held)
|
|
159
|
-
afterHeld := match h
|
|
160
|
-
Some(a) => Delivery.actIn<A, S>(s, trail.user(!self.before.same(self.input.held)), a)
|
|
161
|
-
None => Folded(state: s, trail: trail)
|
|
162
|
-
match afterHeld
|
|
163
|
-
Folded(held, heldTrail) => self.tickInto<A, S>(self.stepScreen(held), heldTrail)
|
|
164
200
|
|
|
165
|
-
# The slice `s`
|
|
201
|
+
# The slice `s` after what is held and the frame, delivered.
|
|
166
|
-
fun
|
|
202
|
+
fun heldInto<A, S: ScreenSlice<A>>(self, s: S, subs: List<Sub<A>>, trail: Trail<A>) -> Delivered =
|
|
203
|
+
h := self.input.held
|
|
204
|
+
held := Subs.picked<A>(subs, |sub| sub.onHeld(h))
|
|
205
|
+
afterHeld := if held.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(!self.before.same(h)), held)
|
|
167
|
-
|
|
206
|
+
dt := self.dt
|
|
168
|
-
match
|
|
207
|
+
match afterHeld
|
|
169
|
-
|
|
208
|
+
Folded(cur, heldTrail) => Delivery.done<A, S>(Delivery.actAll<A, S>(cur, heldTrail, Subs.picked<A>(subs, |sub| sub.onFrame(dt))))
|
|
170
|
-
None => Delivery.done<A, S>(Folded(state: s, trail: trail))
|
|
171
209
|
|
|
172
210
|
# The slice `s` after the tick's events `es`.
|
|
173
|
-
fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, es: List<InputEvent>) -> Folded<S, A> = match es
|
|
211
|
+
fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, subs: List<Sub<A>>, trail: Trail<A>, es: List<InputEvent>) -> Folded<S, A> = match es
|
|
174
212
|
Nil => Folded(state: s, trail: trail)
|
|
175
213
|
Cons(e, rest) =>
|
|
176
|
-
f := self.eventInto<A, S>(s, trail, e)
|
|
214
|
+
f := self.eventInto<A, S>(s, subs, trail, e)
|
|
177
215
|
match f
|
|
178
|
-
Folded(next, after) => self.eventsInto<A, S>(next, after, rest)
|
|
216
|
+
Folded(next, after) => self.eventsInto<A, S>(next, subs, after, rest)
|
|
179
217
|
|
|
180
|
-
# The slice `s` after the event `e`
|
|
218
|
+
# The slice `s` after the event `e`: a press on an item that takes it, else what the
|
|
181
|
-
# turn while a transition runs is
|
|
219
|
+
# subscriptions give for it; a pointer event or a wheel turn while a transition runs is
|
|
220
|
+
# dropped.
|
|
182
|
-
fun eventInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, e: InputEvent) -> Folded<S, A> =
|
|
221
|
+
fun eventInto<A, S: ScreenSlice<A>>(self, s: S, subs: List<Sub<A>>, trail: Trail<A>, e: InputEvent) -> Folded<S, A> =
|
|
183
|
-
|
|
222
|
+
acts := match e.position()
|
|
184
223
|
Some(p) =>
|
|
185
224
|
if self.shifting
|
|
186
|
-
|
|
225
|
+
Nil
|
|
187
226
|
else
|
|
188
227
|
at := self.camera.toWorld(p.x, p.y)
|
|
189
228
|
target := if e.isPointerDown() then Delivery.pressed(s.hud(self.pixels), s.view(), p, at) else None
|
|
190
229
|
pressed := match target
|
|
191
230
|
Some(t) => s.onPress(t, at)
|
|
192
231
|
None => None
|
|
232
|
+
match pressed
|
|
233
|
+
Some(a) => [a]
|
|
193
|
-
|
|
234
|
+
None => Subs.picked<A>(subs, |sub| sub.onEvent(e, at))
|
|
194
235
|
None =>
|
|
195
236
|
if !e.isWheel()
|
|
196
|
-
|
|
237
|
+
Subs.picked<A>(subs, |sub| sub.onEvent(e, Vec2.Zero))
|
|
197
238
|
else if self.shifting
|
|
198
|
-
|
|
239
|
+
Nil
|
|
199
240
|
else
|
|
200
241
|
p := self.input.held.pointer
|
|
201
|
-
|
|
242
|
+
at := self.camera.toWorld(p.x, p.y)
|
|
202
|
-
|
|
243
|
+
Subs.picked<A>(subs, |sub| sub.onEvent(e, at))
|
|
203
|
-
|
|
244
|
+
if acts.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(true), acts)
|
|
204
|
-
None => Folded(state: s, trail: trail)
|
|
205
245
|
|
|
206
246
|
# `a` stepped into the slice `s`, with its `then`, as a delivery steps an action: what
|
|
207
247
|
# std/game/TestRig's `dispatch` runs.
|
|
@@ -211,7 +251,7 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
211
251
|
|
|
212
252
|
# The slice `s` with `a` stepped into it, and then each action of its `then`.
|
|
213
253
|
fun actIn<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, a: A) -> Folded<S, A> =
|
|
214
|
-
n := s.
|
|
254
|
+
n := s.update(a)
|
|
215
255
|
match n
|
|
216
256
|
Next(next, then, cmds) =>
|
|
217
257
|
after := Trail(..trail, actions: Cons(a, trail.actions), cmds: cmds.fold(trail.cmds, |acc, c| Cons(c, acc)))
|
std/game/TestRig.plum
CHANGED
|
@@ -56,11 +56,12 @@ import std/game/Game
|
|
|
56
56
|
# send(e) any `InputEvent`, raw; what is held follows it
|
|
57
57
|
# next(held, evs) the next tick's input is exactly that
|
|
58
58
|
#
|
|
59
|
-
# `dispatch(a)` steps an action into the shown screen (the rig's screen)
|
|
59
|
+
# `dispatch(a)` steps an action into the shown screen (the rig's screen) through its
|
|
60
|
-
# would (with its `then`), then does what ends a tick: its commands, an undo, a redo or a rewind included.
|
|
60
|
+
# `update`, as a delivery would (with its `then`), then does what ends a tick: its commands, an undo, a redo or a rewind included.
|
|
61
61
|
#
|
|
62
|
-
# Time: `tick()` runs one tick of the game's own path (`Game.step`: the screen's
|
|
62
|
+
# Time: `tick()` runs one tick of the game's own path (`Game.step`: the screen's
|
|
63
|
-
# its
|
|
63
|
+
# subscriptions and presses, its frame action, the transition and the commands they
|
|
64
|
+
# gave), with the input
|
|
64
65
|
# waiting and what is held; `ticks(n)` runs `n`, the input waiting going to the first.
|
|
65
66
|
# `tick(dt)` runs one of `dt` seconds instead. `frame(input, frameDt)` is the host's
|
|
66
67
|
# frame, the `Ticker` turning wall time into ticks, for scripted runs.
|
std/game/View.plum
CHANGED
|
@@ -40,11 +40,11 @@ import std/game/Overlay
|
|
|
40
40
|
# additive glow, a line), with `Gfx` through `m`. Nothing by default
|
|
41
41
|
#
|
|
42
42
|
# A view whose state advances each tick (its place, its clock) is an `Actor`, which
|
|
43
|
-
# extends `View` with `step(self, dt) -> Self`, its next version `dt` seconds on.
|
|
43
|
+
# extends `View` with `step(self, dt) -> Self`, its next version `dt` seconds on. A screen
|
|
44
|
+
# steps its actors in its frame action (std/game/Screen's `stepped`, std/game/ScreenSlice's
|
|
45
|
+
# `OnFrame`): a screen is a value, so nothing can step an actor where it finds it in the
|
|
44
|
-
#
|
|
46
|
+
# view, and the screen's `stepped`, derived for every screen, puts each actor it holds
|
|
45
|
-
# (std/game/Screen's `steps` and `stepped`): a screen is a value, so the game cannot step
|
|
46
|
-
# an actor where it finds it in the view, and the screen's `stepped`, derived when it lists
|
|
47
|
-
# `
|
|
47
|
+
# through `step` and each list of them through `Views.stepAll` (`ship:
|
|
48
48
|
# self.ship.step(dt)`, `mines: Views.stepAll(self.mines, dt)`).
|
|
49
49
|
#
|
|
50
50
|
# struct Walker[Actor](at: Place, speed: Float) =
|
|
@@ -84,8 +84,8 @@ import std/game/Overlay
|
|
|
84
84
|
#
|
|
85
85
|
# and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind),
|
|
86
86
|
# `stepSome` (an `Option` of one) and `stepIn` (each `Actor` of a list of views, what a
|
|
87
|
-
# `Group` or an `Overlay` holds, and the others as they are: a `[Steps]`
|
|
87
|
+
# `Group` or an `Overlay` holds, and the others as they are: a screen's or a `[Steps]`
|
|
88
|
-
# `List<View>` field).
|
|
88
|
+
# actor's `List<View>` field).
|
|
89
89
|
trait View =
|
|
90
90
|
fun place(self) -> Place
|
|
91
91
|
|
|
@@ -95,23 +95,23 @@ trait View =
|
|
|
95
95
|
|
|
96
96
|
fun paintSelf(self, io: Io, m: Affine, alpha: Float) = Unit
|
|
97
97
|
|
|
98
|
-
# A view with state that advances each tick: its next version `dt` seconds on. The
|
|
98
|
+
# A view with state that advances each tick: its next version `dt` seconds on. The screen
|
|
99
|
-
#
|
|
99
|
+
# holding it steps it in its frame action (std/game/Screen's `stepped`).
|
|
100
|
-
# tick action is reduced.
|
|
101
100
|
trait Actor[View] =
|
|
102
101
|
fun step(self, dt: Float) -> Self
|
|
103
102
|
|
|
104
|
-
#
|
|
103
|
+
# An actor whose fields holding actors the compiler steps after its own `step`: each
|
|
105
|
-
# an `Actor`, a `List` of actors, an `Option` of one or a `List<View>`
|
|
104
|
+
# field that is an `Actor`, a `List` of actors, an `Option` of one or a `List<View>`
|
|
105
|
+
# (`Views.stepIn`, each item's type tested as it is stepped), the others as they are, at
|
|
106
|
-
#
|
|
106
|
+
# compile time (the same static construction a hand-written step is), so its own `step`
|
|
107
|
-
#
|
|
107
|
+
# holds only what is special about it. A screen needs no `Steps`: its `stepped` is derived
|
|
108
|
-
#
|
|
108
|
+
# from the same fields (std/game/Screen). `@stepsWhen(cond)` before a field, on a screen or
|
|
109
|
-
# `
|
|
109
|
+
# a `[Steps]` actor, steps it only while `cond` holds, read on `self`:
|
|
110
110
|
#
|
|
111
|
-
# struct PlayingScreen[ScreenSlice<PlayAction>
|
|
111
|
+
# struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
112
112
|
# over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>)
|
|
113
113
|
#
|
|
114
|
-
# steps the rings each
|
|
114
|
+
# steps the rings each frame and the ship only while the run is on (docs/game.md, "Stepping").
|
|
115
115
|
trait Steps
|
|
116
116
|
|
|
117
117
|
# One entry of a draw list: an item drawn, its transform (its own coordinates to the
|
|
@@ -124,8 +124,8 @@ primitive Views =
|
|
|
124
124
|
# actors it holds.
|
|
125
125
|
fun stepAll<T: Actor>(xs: List<T>, dt: Float) -> List<T> = xs.map(|x| x.step(dt))
|
|
126
126
|
|
|
127
|
-
# The actor `x` holds stepped by `dt`, or None: what a
|
|
127
|
+
# The actor `x` holds stepped by `dt`, or None: what a derived stepping does with
|
|
128
|
-
# `Option` of an actor.
|
|
128
|
+
# an `Option` of an actor.
|
|
129
129
|
fun stepSome<T: Actor>(x: Option<T>, dt: Float) -> Option<T> = match x
|
|
130
130
|
Some(a) => Some(a.step(dt))
|
|
131
131
|
None => None
|
std/math/Vec2.plum
CHANGED
|
@@ -30,3 +30,8 @@ struct Vec2(x: Float, y: Float) =
|
|
|
30
30
|
|
|
31
31
|
fun distance(self, o: Vec2) -> Float =
|
|
32
32
|
self.sub(o).length()
|
|
33
|
+
|
|
34
|
+
# Whether `o` is closer than `dist`: two circles overlap when their centres are nearer
|
|
35
|
+
# than the sum of their radii (`a.near(b, ra + rb)`).
|
|
36
|
+
fun near(self, o: Vec2, dist: Float) -> Bool =
|
|
37
|
+
Math.hypot(self.x - o.x, self.y - o.y) < dist
|
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -123,9 +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
|
-
assert Cmd.names(s.
|
|
126
|
+
assert Cmd.names(s.update(Popped(at: 12.0)).cmds) == "play(-1, 0.9) play(-1, 0.6)"
|
|
127
|
-
assert Cmd.names(t.
|
|
127
|
+
assert Cmd.names(t.update(Popped(at: 13.0)).cmds) == "play(-1, 0.9)"
|
|
128
|
-
assert Cmd.names(t.
|
|
128
|
+
assert Cmd.names(t.update(TakeBack).cmds) == "undo"
|
|
129
129
|
|
|
130
130
|
fun aRecordedRunReplaysToTheSameBalloons() =
|
|
131
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))
|
tests/examples/games/orbitrunner/actors/Orb.plum
CHANGED
|
@@ -5,6 +5,8 @@ import std/Io
|
|
|
5
5
|
import std/collections/List
|
|
6
6
|
import std/math/Vec2
|
|
7
7
|
import std/math/Affine
|
|
8
|
+
import std/math/Random
|
|
9
|
+
import std/math/Math
|
|
8
10
|
import std/game/Color
|
|
9
11
|
import std/game/Gfx
|
|
10
12
|
import std/game/Place
|
|
@@ -12,6 +14,8 @@ import std/game/View
|
|
|
12
14
|
import std/game/Sprite
|
|
13
15
|
import examples/games/orbitrunner/OrbitRunner
|
|
14
16
|
import examples/games/orbitrunner/actors/Orb
|
|
17
|
+
import examples/games/orbitrunner/actors/Ship
|
|
18
|
+
import examples/games/orbitrunner/actors/Mine
|
|
15
19
|
import std/Test
|
|
16
20
|
|
|
17
21
|
primitive OrbTest[UnitTest] =
|
|
@@ -20,3 +24,13 @@ primitive OrbTest[UnitTest] =
|
|
|
20
24
|
assert orb.at.vx == -100.0
|
|
21
25
|
assert orb.at.x == Arena.W - 10.0
|
|
22
26
|
assert orb.clock == 0.1
|
|
27
|
+
|
|
28
|
+
# an orb and a mine spawn themselves away from the ship, handing on the random stream
|
|
29
|
+
fun orbsAndMinesSpawnAwayFromTheShip() =
|
|
30
|
+
ship := Ship.create(Texture.none())
|
|
31
|
+
o := Orb.spawn(Random.seeded(7), ship, 0.2, Texture.none())
|
|
32
|
+
assert Math.hypot(o.value.at.x - ship.at.x, o.value.at.y - ship.at.y) >= 120.0
|
|
33
|
+
assert o.value.phase == 0.2 && o.value.clock == 0.0 && o.rng.seed != Random.seeded(7).seed
|
|
34
|
+
m := Mine.spawn(o.rng, ship, Texture.none())
|
|
35
|
+
assert Math.hypot(m.value.at.x - ship.at.x, m.value.at.y - ship.at.y) >= 220.0
|
|
36
|
+
assert Orb.spawn(Random.seeded(7), ship, 0.2, Texture.none()).value.at.x == o.value.at.x
|
tests/examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -87,7 +87,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
87
87
|
# a mine the rules push is in the view at once, and moves from the next tick
|
|
88
88
|
fun aMineTheRulesPushIsInThe() =
|
|
89
89
|
t := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)
|
|
90
|
-
p := t.screen.
|
|
90
|
+
p := t.screen.update(Scored(points: 50)).state
|
|
91
91
|
assert p.mines.length() == 4
|
|
92
92
|
late := p.mines.at(3)
|
|
93
93
|
u := PlayingScreenHelpers.poked(t, p)
|
|
@@ -121,14 +121,16 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
121
121
|
u := t.release(Key.KeyW).hold(Key.Left).tick(0.1)
|
|
122
122
|
assert u.screen.ship.ax == 0.0
|
|
123
123
|
|
|
124
|
-
#
|
|
124
|
+
# update alone plays the slice: Steer sets the thrust and Tick steps the ship; the view draws what it left
|
|
125
|
-
fun
|
|
125
|
+
fun updateAlonePlaysTheSliceSteerSets() =
|
|
126
126
|
t := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)
|
|
127
|
-
|
|
127
|
+
steered := t.screen.update(Steer(ax: 1.0, ay: 0.0)).state
|
|
128
|
-
assert
|
|
128
|
+
assert steered.ship.ax == 1.0
|
|
129
|
+
assert steered.ship.at.x == Arena.W / 2.0
|
|
130
|
+
p := steered.update(Tick(dt: 0.1)).state
|
|
129
|
-
assert p.ship.at.x
|
|
131
|
+
assert p.ship.at.x > Arena.W / 2.0
|
|
130
|
-
assert t.hold(Key.Right).tick(0.1).screen.ship.at.x
|
|
132
|
+
assert p.ship.at.x == t.hold(Key.Right).tick(0.1).screen.ship.at.x
|
|
131
|
-
q := p.
|
|
133
|
+
q := p.update(Scored(points: 20)).state
|
|
132
134
|
assert q.score == 20
|
|
133
135
|
assert PlayingScreenHelpers.hud(PlayingScreenHelpers.poked(t, q)) == "Score 20, Best 20"
|
|
134
136
|
|
|
@@ -199,7 +201,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
199
201
|
# the arrows and WASD steer alike, and the axes cancel when both ways are held
|
|
200
202
|
fun theArrowsAndWASDSteerAlikeAndThe() =
|
|
201
203
|
p := PlayingScreenHelpers.mounted(io, 7, 0, 3).screen
|
|
202
|
-
steer := |keys: List<Int>|
|
|
204
|
+
steer := |keys: List<Int>| PlayingScreen.steering(Held(keys: keys)).toStr()
|
|
203
205
|
assert steer([Key.Left, Key.KeyW]) == "Steer(-1.0, -1.0)"
|
|
204
206
|
assert steer([Key.KeyD, Key.Down]) == "Steer(1.0, 1.0)"
|
|
205
207
|
assert steer([Key.Right, Key.KeyD]) == "Steer(1.0, 0.0)"
|
|
@@ -243,16 +245,16 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
243
245
|
assert t.count<Overlay>() == 1
|
|
244
246
|
assert t.showing() == "play"
|
|
245
247
|
|
|
246
|
-
# while the game over panel shows, Enter or R plays again: StartOver
|
|
248
|
+
# while the game over panel shows, Enter or R plays again: StartOver at once, which starts the music again; in play they do nothing
|
|
247
249
|
fun whileTheGameOverPanelShowsEnterOr() =
|
|
248
250
|
t := PlayingScreenHelpers.lastLife(io).press(Key.Enter).tick()
|
|
249
|
-
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "
|
|
251
|
+
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(t)) == "Hit"
|
|
250
252
|
assert t.screen.over
|
|
251
253
|
u := t.press(Key.Space).tick()
|
|
252
254
|
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(u)) == ""
|
|
253
255
|
assert u.screen.over
|
|
254
256
|
v := u.press(Key.Enter).tick()
|
|
255
|
-
assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "
|
|
257
|
+
assert PlayingScreenHelpers.names(v.actions<PlayAction>()) == "StartOver Tick({Ticker.Tick})"
|
|
256
258
|
assert Cmd.names(v.cmds) == "stop(-1) loop(-1, 0.3)"
|
|
257
259
|
assert !v.screen.over
|
|
258
260
|
assert v.screen.score == 0
|
tests/port/game/determinism.plum
CHANGED
|
@@ -18,7 +18,7 @@ import std/Test
|
|
|
18
18
|
# most 8 a frame, and hands each tick its input as a value; randomness is a `Random`
|
|
19
19
|
# held by the screen. So one seed and one list of inputs give the same game.
|
|
20
20
|
|
|
21
|
-
# A press of Space, what a tick saw held (from `
|
|
21
|
+
# A press of Space, what a tick saw held (from `OnHeld`), and the tick itself.
|
|
22
22
|
enum Saw =
|
|
23
23
|
| Pressed
|
|
24
24
|
| Seen(spaceHeld: Bool)
|
|
@@ -32,18 +32,18 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, time: Float, minDt: Floa
|
|
|
32
32
|
|
|
33
33
|
fun name(self) -> Str = "probe"
|
|
34
34
|
|
|
35
|
-
fun
|
|
35
|
+
fun subscriptions(self) -> List<Sub<Saw>> = [
|
|
36
|
+
OnKeyDown(key: Key.Space, act: Pressed)
|
|
37
|
+
OnHeld(|h| Seen(spaceHeld: h.isKeyDown(Key.Space)))
|
|
38
|
+
OnFrame(|dt| Ticked(dt: dt))
|
|
39
|
+
]
|
|
36
40
|
|
|
37
|
-
fun held(self, h: Held) -> Option<Saw> = Some(Seen(spaceHeld: h.isKeyDown(Key.Space)))
|
|
38
|
-
|
|
39
|
-
fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked(dt: dt))
|
|
40
|
-
|
|
41
|
-
fun
|
|
41
|
+
fun update(self, saw: Saw) -> Next<Probe, Saw> = match saw
|
|
42
42
|
Pressed =>
|
|
43
43
|
r := self.rng.nextInt()
|
|
44
|
-
Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value)
|
|
44
|
+
Next(state: Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value))
|
|
45
|
-
Seen(spaceHeld) => Probe(..self, held: if spaceHeld then self.held + 1 else self.held)
|
|
45
|
+
Seen(spaceHeld) => Next(state: Probe(..self, held: if spaceHeld then self.held + 1 else self.held))
|
|
46
|
-
Ticked(dt) => Probe(..self, ticks: self.ticks + 1, time: self.time + dt, minDt: self.minDt.min(dt), maxDt: self.maxDt.max(dt))
|
|
46
|
+
Ticked(dt) => Next(state: Probe(..self, ticks: self.ticks + 1, time: self.time + dt, minDt: self.minDt.min(dt), maxDt: self.maxDt.max(dt)))
|
|
47
47
|
|
|
48
48
|
fun same(self, o: Probe) -> Bool =
|
|
49
49
|
self.rng.seed == o.rng.seed && self.ticks == o.ticks && self.time == o.time && self.presses == o.presses && self.held == o.held && self.roll == o.roll
|
tests/port/game/replay.plum
CHANGED
|
@@ -20,7 +20,7 @@ import std/Test
|
|
|
20
20
|
# Record and replay (std/game/Replay): a run is its seed and one `Input` per tick, as text
|
|
21
21
|
# with exact floats. A game's `Ticker` records the ticks of each frame and replays them.
|
|
22
22
|
|
|
23
|
-
# A press of Space or a click, what a tick saw held (from `
|
|
23
|
+
# A press of Space or a click, what a tick saw held (from `OnHeld`), and the tick itself.
|
|
24
24
|
enum Saw =
|
|
25
25
|
| Pressed
|
|
26
26
|
| Seen(spaceHeld: Bool, x: Float, y: Float)
|
|
@@ -37,20 +37,19 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, presses: Int, held: Int,
|
|
|
37
37
|
|
|
38
38
|
fun name(self) -> Str = "probe"
|
|
39
39
|
|
|
40
|
+
fun subscriptions(self) -> List<Sub<Saw>> = [
|
|
41
|
+
OnKeyDown(key: Key.Space, act: Pressed)
|
|
42
|
+
OnPointerDown(|at| Pressed)
|
|
40
|
-
|
|
43
|
+
OnHeld(|h| Seen(spaceHeld: h.isKeyDown(Key.Space), x: h.pointer.x, y: h.pointer.y))
|
|
44
|
+
OnFrame(|dt| Ticked(dt: dt))
|
|
45
|
+
]
|
|
41
46
|
|
|
42
|
-
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<Saw> = if e.isPointerDown() then Some(Pressed) else None
|
|
43
|
-
|
|
44
|
-
fun held(self, h: Held) -> Option<Saw> = Some(Seen(spaceHeld: h.isKeyDown(Key.Space), x: h.pointer.x, y: h.pointer.y))
|
|
45
|
-
|
|
46
|
-
fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked(dt: dt))
|
|
47
|
-
|
|
48
|
-
fun
|
|
47
|
+
fun update(self, saw: Saw) -> Next<Probe, Saw> = match saw
|
|
49
48
|
Pressed =>
|
|
50
49
|
r := self.rng.nextInt()
|
|
51
|
-
Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value)
|
|
50
|
+
Next(state: Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value))
|
|
52
|
-
Seen(spaceHeld, x, y) => Probe(..self, held: if spaceHeld then self.held + 1 else self.held, px: x, py: y)
|
|
51
|
+
Seen(spaceHeld, x, y) => Next(state: Probe(..self, held: if spaceHeld then self.held + 1 else self.held, px: x, py: y))
|
|
53
|
-
Ticked(dt) => Probe(..self, ticks: self.ticks + 1, x: self.x + self.px * dt, y: self.y + self.py * dt)
|
|
52
|
+
Ticked(dt) => Next(state: Probe(..self, ticks: self.ticks + 1, x: self.x + self.px * dt, y: self.y + self.py * dt))
|
|
54
53
|
|
|
55
54
|
fun same(self, o: Probe) -> Bool =
|
|
56
55
|
self.rng.seed == o.rng.seed && self.ticks == o.ticks && self.presses == o.presses && self.held == o.held && self.roll == o.roll && self.x == o.x && self.y == o.y
|
tests/port/game/screens.plum
CHANGED
|
@@ -93,33 +93,27 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
|
|
|
93
93
|
|
|
94
94
|
fun onPress(self, target: View, at: Vec2) -> Option<ProbeAct> = Some(Pressed(on: target))
|
|
95
95
|
|
|
96
|
-
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<ProbeAct> = if e.isPointerDown() then Some(Missed) else None
|
|
97
|
-
|
|
98
|
-
fun
|
|
96
|
+
fun subscriptions(self) -> List<Sub<ProbeAct>> = [
|
|
99
|
-
|
|
97
|
+
OnPointerDown(|at| Missed)
|
|
100
|
-
|
|
98
|
+
OnKeyDown(key: Key.KeyG, act: GoPlay)
|
|
101
|
-
|
|
99
|
+
OnKeyDown(key: Key.KeyQ, act: Quit)
|
|
102
|
-
|
|
100
|
+
OnKeyDown(key: Key.Space, act: Roll)
|
|
103
|
-
|
|
101
|
+
OnKeyDown(key: Key.KeyA, act: Keyed)
|
|
104
|
-
_ => None
|
|
105
|
-
|
|
106
|
-
|
|
102
|
+
OnFrame(|dt| Ticked(dt: dt))
|
|
107
|
-
|
|
103
|
+
]
|
|
104
|
+
|
|
108
|
-
fun
|
|
105
|
+
fun update(self, a: ProbeAct) -> Next<ProbeScreen, ProbeAct> = match a
|
|
109
|
-
Pressed(on) => ProbeScreen(..self, hits: self.hits.append([on]))
|
|
106
|
+
Pressed(on) => Next(state: ProbeScreen(..self, hits: self.hits.append([on])))
|
|
110
|
-
Missed => ProbeScreen(..self, misses: self.misses + 1)
|
|
107
|
+
Missed => Next(state: ProbeScreen(..self, misses: self.misses + 1))
|
|
111
|
-
Echo => ProbeScreen(..self, echoes: self.echoes + 1)
|
|
108
|
+
Echo => Next(state: ProbeScreen(..self, echoes: self.echoes + 1))
|
|
112
|
-
Ticked(_) => ProbeScreen(..self, ticks: self.ticks + 1, left: {self.left - 1}.max(0))
|
|
109
|
+
Ticked(_) => Next(state: ProbeScreen(..self, ticks: self.ticks + 1, left: {self.left - 1}.max(0)))
|
|
113
110
|
Roll =>
|
|
114
111
|
r := self.rng.nextInt()
|
|
115
|
-
ProbeScreen(..self, rng: r.rng, roll: r.value)
|
|
112
|
+
Next(state: ProbeScreen(..self, rng: r.rng, roll: r.value))
|
|
116
|
-
_ => self
|
|
117
|
-
|
|
118
|
-
fun act(self, a: ProbeAct) -> Next<ProbeScreen, ProbeAct> = match a
|
|
119
113
|
Keyed => Next(state: ProbeScreen(..self, keys: self.keys + 1, left: 3), then: [Echo])
|
|
120
114
|
GoPlay => Next(state: self, cmds: [GoTo(name: "play")])
|
|
121
115
|
Quit => Next(state: self, cmds: [Exit])
|
|
122
|
-
_ => Next(state: self
|
|
116
|
+
_ => Next(state: self)
|
|
123
117
|
|
|
124
118
|
primitive Screens =
|
|
125
119
|
# The group turned a quarter.
|
|
@@ -160,17 +154,15 @@ struct Turned[View, Touch](group: Group) =
|
|
|
160
154
|
struct PlayProbe[ScreenSlice<ProbeAct>](presses: Int, ticks: Int) =
|
|
161
155
|
fun name(self) -> Str = "play"
|
|
162
156
|
|
|
163
|
-
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<ProbeAct> = if e.isPointerDown() then Some(Missed) else None
|
|
164
|
-
|
|
165
157
|
fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
|
|
166
158
|
|
|
167
|
-
fun
|
|
159
|
+
fun subscriptions(self) -> List<Sub<ProbeAct>> = [
|
|
160
|
+
OnPointerDown(|at| Missed)
|
|
168
|
-
|
|
161
|
+
OnKeyDown(key: Key.Escape, act: Back)
|
|
169
|
-
_ => None
|
|
170
|
-
|
|
171
|
-
|
|
162
|
+
OnFrame(|dt| Ticked(dt: dt))
|
|
163
|
+
]
|
|
172
164
|
|
|
173
|
-
fun
|
|
165
|
+
fun update(self, a: ProbeAct) -> Next<PlayProbe, ProbeAct> = match a
|
|
174
166
|
Ticked(_) => Next(state: PlayProbe(..self, ticks: self.ticks + 1))
|
|
175
167
|
Missed => Next(state: PlayProbe(..self, presses: self.presses + 1))
|
|
176
168
|
Back => Next(state: self, cmds: [GoTo(name: "probe")])
|
|
@@ -186,7 +178,7 @@ struct Walker[Actor](x: Float, speed: Float) =
|
|
|
186
178
|
|
|
187
179
|
enum WalkAct = Saw(x: Float) | Walked(dt: Float) | TakeBack | Pause | Follow | HudPressed
|
|
188
180
|
|
|
189
|
-
# A screen of one walker: `
|
|
181
|
+
# A screen of one walker: `OnHeld` notes where it is before the step and the frame action
|
|
190
182
|
# after it; P pauses the stepping, F has the camera follow the walker, two times as
|
|
191
183
|
# close; its hud is a button at the window's bottom-right corner; U asks for an undo.
|
|
192
184
|
struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, paused: Bool, follow: Bool, hudPresses: Int) =
|
|
@@ -204,35 +196,31 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
|
|
|
204
196
|
}
|
|
205
197
|
]
|
|
206
198
|
|
|
207
|
-
fun steps(self) -> Bool = !self.paused
|
|
208
|
-
|
|
209
199
|
fun stepped(self, dt: Float) -> WalkScreen = WalkScreen(..self, walker: self.walker.step(dt))
|
|
210
200
|
|
|
211
201
|
fun camera(self, base: Viewport) -> Viewport = if self.follow then base.lookAt(self.walker.x, 0.0, 2.0) else base
|
|
212
202
|
|
|
213
|
-
fun held(self, h: Held) -> Option<WalkAct> = Some(Saw(x: self.walker.x))
|
|
214
|
-
|
|
215
|
-
fun tick(self, dt: Float) -> Option<WalkAct> = Some(Walked(dt: dt))
|
|
216
|
-
|
|
217
|
-
fun
|
|
203
|
+
fun subscriptions(self) -> List<Sub<WalkAct>> = [
|
|
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(TakeBack) else None
|
|
219
|
-
_ => None
|
|
220
|
-
|
|
221
|
-
fun reduce(self, a: WalkAct) -> WalkScreen = match a
|
|
222
|
-
|
|
204
|
+
OnHeld(|h| Saw(x: self.walker.x))
|
|
223
|
-
|
|
205
|
+
OnFrame(|dt| Walked(dt: dt))
|
|
224
|
-
|
|
206
|
+
OnKeyDown(key: Key.KeyP, act: Pause)
|
|
225
|
-
|
|
207
|
+
OnKeyDown(key: Key.KeyF, act: Follow)
|
|
226
|
-
|
|
208
|
+
OnKeyDown(key: Key.KeyU, act: TakeBack)
|
|
227
|
-
|
|
209
|
+
]
|
|
228
210
|
|
|
229
|
-
fun
|
|
211
|
+
fun update(self, a: WalkAct) -> Next<WalkScreen, WalkAct> = match a
|
|
212
|
+
Saw(x) => Next(state: WalkScreen(..self, seen: self.seen.append([x])))
|
|
213
|
+
Walked(dt) =>
|
|
214
|
+
moved := if self.paused then self else self.stepped(dt)
|
|
215
|
+
Next(state: WalkScreen(..moved, seen: moved.seen.append([moved.walker.x])))
|
|
216
|
+
Pause => Next(state: WalkScreen(..self, paused: true))
|
|
217
|
+
Follow => Next(state: WalkScreen(..self, follow: true))
|
|
218
|
+
HudPressed => Next(state: WalkScreen(..self, hudPresses: self.hudPresses + 1))
|
|
230
219
|
TakeBack => Next(state: self, cmds: [Undo])
|
|
231
|
-
_ => Next(state: self.reduce(a))
|
|
232
220
|
|
|
233
221
|
# A screen with no rules holding a walker: the game steps it all the same, through the
|
|
234
|
-
# `stepped`
|
|
222
|
+
# `stepped` derived for every screen.
|
|
235
|
-
struct StillScreen[Screen
|
|
223
|
+
struct StillScreen[Screen](walker: Walker) =
|
|
236
224
|
fun name(self) -> Str = "still"
|
|
237
225
|
|
|
238
226
|
fun view(self) -> List<View> = [self.walker]
|
|
@@ -285,7 +273,7 @@ primitive ScreensTest[UnitTest] =
|
|
|
285
273
|
t := Screens.probe(io).press(Key.KeyA).tick()
|
|
286
274
|
assert t.screen.echoes == 1
|
|
287
275
|
assert Screens.names(t.actions<ProbeAct>()) == "Keyed Echo Ticked"
|
|
288
|
-
n := ProbeScreen.create(Always).
|
|
276
|
+
n := ProbeScreen.create(Always).update(Keyed)
|
|
289
277
|
assert n.state.keys == 1 && n.state.echoes == 0
|
|
290
278
|
assert Screens.names(n.then) == "Echo"
|
|
291
279
|
assert n.cmds.isEmpty()
|
|
@@ -295,7 +283,7 @@ primitive ScreensTest[UnitTest] =
|
|
|
295
283
|
t := TestRig.play(io, Screens.twoScreens()).press(Key.KeyG).press(Key.KeyQ).tick()
|
|
296
284
|
assert Cmd.names(t.cmds) == "goTo(play) exit"
|
|
297
285
|
assert t.exited()
|
|
298
|
-
assert Cmd.names(ProbeScreen.create(Always).
|
|
286
|
+
assert Cmd.names(ProbeScreen.create(Always).update(Quit).cmds) == "exit"
|
|
299
287
|
|
|
300
288
|
# press gives one key down, hold steers every tick, ticks(n) is n ticks
|
|
301
289
|
fun pressGivesOneKeyDownHoldSteersEvery() =
|
|
@@ -376,8 +364,8 @@ primitive ScreensTest[UnitTest] =
|
|
|
376
364
|
assert p.game.tickNow() == 4
|
|
377
365
|
assert p.resume().tick().game.tickNow() == 5
|
|
378
366
|
|
|
379
|
-
# the
|
|
367
|
+
# the frame action steps the screen's actors, after OnHeld; a paused screen doesn't step them
|
|
380
|
-
fun
|
|
368
|
+
fun theFrameActionStepsTheScreensActorsAfterHeld() =
|
|
381
369
|
t := TestRig.mount(io, WalkScreen.create()).tick(0.5)
|
|
382
370
|
assert t.screen.seen.length() == 2 && t.screen.seen.at(0) == 0.0 && t.screen.seen.at(1) == 30.0
|
|
383
371
|
u := t.press(Key.KeyP).tick(0.5)
|
tests/std/game/Button.plum
CHANGED
|
@@ -52,9 +52,9 @@ struct PickScreen[ScreenSlice<Pick>](picks: List<Int>, others: Int) =
|
|
|
52
52
|
Button(x: 400.0, y: 400.0, w: 10.0, h: 10.0, on: 7)
|
|
53
53
|
]
|
|
54
54
|
|
|
55
|
-
fun
|
|
55
|
+
fun update(self, a: Pick) -> Next<PickScreen, Pick> = match a
|
|
56
|
-
Picked(n) => PickScreen(..self, picks: self.picks.append([n]))
|
|
56
|
+
Picked(n) => Next(state: PickScreen(..self, picks: self.picks.append([n])))
|
|
57
|
-
Other => PickScreen(..self, others: self.others + 1)
|
|
57
|
+
Other => Next(state: PickScreen(..self, others: self.others + 1))
|
|
58
58
|
|
|
59
59
|
primitive ButtonTest[UnitTest] =
|
|
60
60
|
# a button is a box that takes presses, with its children placed in it
|
|
@@ -64,7 +64,7 @@ primitive ButtonTest[UnitTest] =
|
|
|
64
64
|
assert b.place().x == 5.0 && b.view().length() == 1 && b.pressed() == "go"
|
|
65
65
|
assert Button(w: 1.0, h: 1.0, on: 3).view().isEmpty() && Button(w: 1.0, h: 1.0, on: 3).x == 0.0
|
|
66
66
|
|
|
67
|
-
# a slice's onPress is what the item pressed says it means, by default
|
|
67
|
+
# a slice's onPress is what the item pressed says it means, by default, stepped through update
|
|
68
68
|
fun aPressIsWhatTheItemSaysItMeans() =
|
|
69
69
|
t := TestRig.mount(io, PickScreen(picks: Nil, others: 0))
|
|
70
70
|
u := t.clickAt(20.0, 15.0).tick().clickAt(110.0, 110.0).tick().clickAt(205.0, 305.0).tick()
|
tests/std/game/ScreenSlice.plum
CHANGED
|
@@ -7,31 +7,79 @@ import std/Option
|
|
|
7
7
|
import std/collections/List
|
|
8
8
|
import std/math/Vec2
|
|
9
9
|
import std/game/Input
|
|
10
|
+
import std/game/Cmd
|
|
10
11
|
import std/game/Screen
|
|
11
12
|
import std/game/ScreenSlice
|
|
13
|
+
import std/game/Game
|
|
12
14
|
import std/game/TestRig
|
|
13
15
|
import std/Test
|
|
14
16
|
|
|
15
17
|
enum Turn = Rolled(dy: Float, x: Float) | Steered(ax: Float, x: Float)
|
|
16
18
|
|
|
17
|
-
# A screen that keeps each wheel turn with where it happened, and what `
|
|
19
|
+
# A screen that keeps each wheel turn with where it happened, and what `OnHeld` saw.
|
|
18
20
|
struct WheelScreen[ScreenSlice<Turn>](turns: List<Turn>) =
|
|
19
21
|
fun name(self) -> Str = "wheel"
|
|
20
22
|
|
|
21
|
-
fun
|
|
23
|
+
fun subscriptions(self) -> List<Sub<Turn>> = [
|
|
22
|
-
|
|
24
|
+
OnWheel(|dy, at| Rolled(dy: dy, x: at.x))
|
|
23
|
-
|
|
25
|
+
OnHeld(|h| Steered(ax: h.axis(Key.Left, Key.Right), x: h.pointer.x))
|
|
26
|
+
]
|
|
24
27
|
|
|
25
|
-
fun held(self, h: Held) -> Option<Turn> = Some(Steered(ax: h.axis(Key.Left, Key.Right), x: h.pointer.x))
|
|
26
|
-
|
|
27
|
-
fun
|
|
28
|
+
fun update(self, a: Turn) -> Next<WheelScreen, Turn> = Next(state: WheelScreen(turns: self.turns.append([a])))
|
|
28
29
|
|
|
29
30
|
fun said(t: Turn) -> Str = match t
|
|
30
31
|
Rolled(dy, x) => "rolled {dy} at {x}"
|
|
31
32
|
Steered(ax, x) => "steered {ax} at {x}"
|
|
32
33
|
|
|
34
|
+
enum Heard = Down(key: Int) | Up(key: Int) | Pressed(x: Float) | Moved(x: Float) | Released(x: Float) | Holding(n: Int) | Frame(dt: Float) | Stop
|
|
35
|
+
|
|
36
|
+
# A screen that logs what each subscription gave, in the order the actions came. It hears
|
|
37
|
+
# Space only while it is not stopped, and `Stop` (Escape) stops it.
|
|
38
|
+
struct LogScreen[ScreenSlice<Heard>](log: List<Str>, stopped: Bool) =
|
|
39
|
+
fun name(self) -> Str = "log"
|
|
40
|
+
|
|
41
|
+
fun subscriptions(self) -> List<Sub<Heard>> = [
|
|
42
|
+
OnFrame(|dt| Frame(dt: dt))
|
|
43
|
+
OnHeld(|h| Holding(n: h.keys.length()))
|
|
44
|
+
if !self.stopped then OnKeyDown(key: Key.Space, act: Down(key: Key.Space))
|
|
45
|
+
OnKeyUp(key: Key.Space, act: Up(key: Key.Space))
|
|
46
|
+
OnKeyDown(key: Key.Escape, act: Stop)
|
|
47
|
+
OnKeyDown(key: Key.Escape, act: Down(key: Key.Escape))
|
|
48
|
+
OnPointerDown(|at| Pressed(x: at.x))
|
|
49
|
+
OnPointerMove(|at| Moved(x: at.x))
|
|
50
|
+
OnPointerUp(|at| Released(x: at.x))
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
fun update(self, a: Heard) -> Next<LogScreen, Heard> = match a
|
|
54
|
+
Stop => Next(state: LogScreen(..self, log: self.log.append(["stop"]), stopped: true))
|
|
55
|
+
_ => Next(state: LogScreen(..self, log: self.log.append([LogScreen.said(a)])))
|
|
56
|
+
|
|
57
|
+
fun said(a: Heard) -> Str = match a
|
|
58
|
+
Down(k) => "down {k}"
|
|
59
|
+
Up(k) => "up {k}"
|
|
60
|
+
Pressed(x) => "pressed {x}"
|
|
61
|
+
Moved(x) => "moved {x}"
|
|
62
|
+
Released(x) => "released {x}"
|
|
63
|
+
Holding(n) => "holding {n}"
|
|
64
|
+
Frame(dt) => "frame"
|
|
65
|
+
Stop => "stop"
|
|
66
|
+
|
|
67
|
+
# A screen with no actions: the default `update` and `subscriptions`.
|
|
68
|
+
struct StillScreen[ScreenSlice<Int>](n: Int) =
|
|
69
|
+
fun name(self) -> Str = "still"
|
|
70
|
+
|
|
71
|
+
# An `OnDemand` screen that steers only while it says so: what is held wakes it then.
|
|
72
|
+
struct SleepyScreen[ScreenSlice<Int>](steering: Bool, seen: Int) =
|
|
73
|
+
fun name(self) -> Str = "sleepy"
|
|
74
|
+
|
|
75
|
+
fun frames(self) -> Frames = OnDemand
|
|
76
|
+
|
|
77
|
+
fun subscriptions(self) -> List<Sub<Int>> = [if self.steering then OnHeld(|h| h.keys.length())]
|
|
78
|
+
|
|
79
|
+
fun update(self, n: Int) -> Next<SleepyScreen, Int> = Next(state: SleepyScreen(..self, seen: self.seen + 1))
|
|
80
|
+
|
|
33
81
|
primitive ScreenSliceTest[UnitTest] =
|
|
34
|
-
# a wheel turn reaches `
|
|
82
|
+
# a wheel turn reaches `OnWheel` where the pointer is, and `OnHeld` sees what is held
|
|
35
83
|
# after the tick's events, the pointer with it
|
|
36
84
|
fun aWheelTurnIsAPointerEventAtThePointer() =
|
|
37
85
|
t := TestRig.mount(io, WheelScreen(turns: Nil))
|
|
@@ -40,3 +88,35 @@ primitive ScreenSliceTest[UnitTest] =
|
|
|
40
88
|
assert u.held.pointer == Vec2(x: 40.0, y: 30.0) && u.held.isKeyDown(Key.Right)
|
|
41
89
|
v := u.release(Key.Right).tick()
|
|
42
90
|
assert WheelScreen.said(v.screen.turns.at(2)) == "steered 0.0 at 40.0"
|
|
91
|
+
|
|
92
|
+
# a tick delivers the events (keys and pointer, in the order they came), then what is
|
|
93
|
+
# held, then the frame, last
|
|
94
|
+
fun eventsThenHeldThenTheFrame() =
|
|
95
|
+
t := TestRig.mount(io, LogScreen(log: Nil, stopped: false))
|
|
96
|
+
u := t.send(KeyDown(key: Key.Space)).send(PointerDown(x: 5.0, y: 6.0)).send(PointerMove(x: 7.0, y: 6.0)).send(PointerUp(x: 9.0, y: 6.0)).tick()
|
|
97
|
+
assert u.screen.log.join(", ") == "down {Key.Space}, pressed 5.0, moved 7.0, released 9.0, holding 1, frame"
|
|
98
|
+
v := u.release(Key.Space).tick()
|
|
99
|
+
assert v.actions<Heard>().map(|a| LogScreen.said(a)).join(", ") == "up {Key.Space}, holding 0, frame"
|
|
100
|
+
|
|
101
|
+
# every subscription that answers an event gives its action, in the order listed, and a
|
|
102
|
+
# list item is there only while the state says so (read once, as the tick starts)
|
|
103
|
+
fun subscriptionsAreReadFromTheState() =
|
|
104
|
+
t := TestRig.mount(io, LogScreen(log: Nil, stopped: false))
|
|
105
|
+
u := t.press(Key.Escape).press(Key.Space).tick()
|
|
106
|
+
assert u.screen.log.join(", ") == "stop, down {Key.Escape}, down {Key.Space}, up {Key.Space}, holding 0, frame"
|
|
107
|
+
v := u.press(Key.Space).tick()
|
|
108
|
+
assert v.screen.stopped && v.actions<Heard>().map(|a| LogScreen.said(a)).join(", ") == "up {Key.Space}, holding 0, frame"
|
|
109
|
+
|
|
110
|
+
# a screen with no actions has the default `update` and no subscriptions
|
|
111
|
+
fun aScreenWithNoActionsGetsNone() =
|
|
112
|
+
t := TestRig.mount(io, StillScreen(n: 4)).press(Key.Space).clickAt(1.0, 1.0).tick()
|
|
113
|
+
assert t.screen.n == 4 && t.actions<Int>().isEmpty()
|
|
114
|
+
assert t.dispatch(9).screen.n == 4
|
|
115
|
+
|
|
116
|
+
# an `OnDemand` screen subscribed to `OnHeld` wakes for what is held; one that is not
|
|
117
|
+
# sleeps through it
|
|
118
|
+
fun onHeldWakesAnOnDemandScreen() =
|
|
119
|
+
t := TestRig.mount(io, SleepyScreen(steering: true, seen: 0)).hold(Key.Left).ticks(3)
|
|
120
|
+
assert t.screen.seen == 3
|
|
121
|
+
u := TestRig.mount(io, SleepyScreen(steering: false, seen: 0)).tick().hold(Key.Left).tick().ticks(3)
|
|
122
|
+
assert u.screen.seen == 0 && u.game.skipped >= 3
|
tests/std/game/View.plum
CHANGED
|
@@ -130,9 +130,9 @@ primitive ViewTest[UnitTest] =
|
|
|
130
130
|
|
|
131
131
|
# A view that logs where it is painted (the x of its origin) and at what alpha.
|
|
132
132
|
|
|
133
|
-
# a
|
|
133
|
+
# a screen's derived `stepped` (it lists no `Steps`) steps each field holding actors (the
|
|
134
|
-
# `List<View>`, a group's among them), and leaves the others
|
|
134
|
+
# actors of a `List<View>`, a group's among them), and leaves the others
|
|
135
|
-
fun
|
|
135
|
+
fun aScreenStepsItsActorFields() =
|
|
136
136
|
s := Stage(n: 7, one: Stepper(time: 0.0), many: [Stepper(time: 1.0), Stepper(time: 2.0)], maybe: Some(Stepper(time: 3.0)), nothing: None, anyOne: Stepper(time: 4.0), anyMany: [Stepper(time: 5.0)], loose: Stepper(time: 6.0), scene: [Stepper(time: 7.0), Group() { Stepper(time: 8.0) }]).stepped(0.5)
|
|
137
137
|
assert s.n == 7 && s.one.time == 0.5 && ViewHelpers.timeOf(s.loose) == 6.0
|
|
138
138
|
assert s.many.map(|x| x.time) == [1.5, 2.5]
|
|
@@ -230,15 +230,15 @@ primitive ViewHelpers =
|
|
|
230
230
|
fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
|
|
231
231
|
|
|
232
232
|
# A screen whose actors are stepped for it, of each kind a field can hold them in.
|
|
233
|
-
struct Stage[Screen
|
|
233
|
+
struct Stage[Screen](n: Int, one: Stepper, many: List<Stepper>, maybe: Option<Stepper>, nothing: Option<Stepper>, anyOne: Actor, anyMany: List<Actor>, loose: View, scene: List<View>) =
|
|
234
234
|
fun name(self) -> Str = "stage"
|
|
235
235
|
|
|
236
236
|
# A walker paused with the screen, clocks that run on.
|
|
237
|
-
struct Paused[Screen
|
|
237
|
+
struct Paused[Screen](paused: Bool, @stepsWhen(!self.paused) walker: Stepper, clocks: List<Stepper>) =
|
|
238
238
|
fun name(self) -> Str = "paused"
|
|
239
239
|
|
|
240
|
-
# A screen that
|
|
240
|
+
# A screen that steps its actor twice as fast itself.
|
|
241
|
-
struct Owned[Screen
|
|
241
|
+
struct Owned[Screen](one: Stepper) =
|
|
242
242
|
fun name(self) -> Str = "owned"
|
|
243
243
|
|
|
244
244
|
fun stepped(self, dt: Float) -> Owned = Owned(one: self.one.step(dt * 2.0))
|
tests/std/math/Vec2.plum
CHANGED
|
@@ -16,3 +16,11 @@ primitive Vec2Test[UnitTest] =
|
|
|
16
16
|
assert Vec2(x: 3.0, y: 4.0).length() == 5.0
|
|
17
17
|
assert Vec2(x: 1.0, y: 1.0).distance(Vec2(x: 4.0, y: 5.0)) == 5.0
|
|
18
18
|
assert Vec2.Zero == Vec2(x: 0.0, y: 0.0)
|
|
19
|
+
|
|
20
|
+
# near is closer than a distance: two circles overlap when their centres are nearer than
|
|
21
|
+
# the sum of their radii
|
|
22
|
+
fun vec2NearIsCloserThanADistance() =
|
|
23
|
+
a := Vec2(x: 0.0, y: 0.0)
|
|
24
|
+
assert a.near(Vec2(x: 3.0, y: 4.0), 5.5)
|
|
25
|
+
assert !a.near(Vec2(x: 3.0, y: 4.0), 5.0)
|
|
26
|
+
assert Vec2(x: 10.0, y: 0.0).near(Vec2(x: 25.0, y: 0.0), 10.0 + 6.0)
|