plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
254f0c7
— Peter John
2026-11-16T11:54:55+05:30
views declare presses, input is events and their fold (std/game review item 3 and the input addendum): `trait Presses<A>` with `pressed(self) -> A` and a ready-made `Button<A>(x = 0.0, y = 0.0, w, h, on: A, children: List<View> = Nil)` (std/game/Button: a box that takes presses, `Enabled`, hit inside its bounds, drawn by its children, its block), and a slice's default `onPress` is `match target / Presses<A> as p => Some(p.pressed())`, so a screen whose pressable items say what they mean writes no `onPress`; the generic trait match works at runtime as it is (an item that is a `Presses<Int>` gives None on a screen of `Pick`s; tests/traits/generic_trait_match.plum); Balloon Pop's balloons are `Presses<PopAction>` (`Pop(id: self.id)` in place of `Pop(balloon: b)`, the screen's `onPress` gone), clicks has a `Button(.., on: Tapped) { Box(..) }` in its view in place of a `box` field compared by `@sameRef`, the web-test stress fixture's 20 buttons are `Button`s with `Clicked(i: i)` (its `buttons` field and `@sameRef` search gone, the labels still drawn after the boxes); input: the events are the one source and what is held is their fold: `Input(events: List<InputEvent> = Nil, held: Held = Held(), screen)`, `Held(mouse, keys: List<Int>, buttons: List<Int>, pointer: Vec2)` with `isKeyDown`, `axis`, `isButtonDown`, `same` (the pointer aside), `after(e)` (each pointer event moves `pointer`) and `afterAll(events)`, `InputEvent` gains `Wheel(dy)`, delivered to `onPointer` at the pointer (dropped during a transition like the pointer events), a slice's `held(self, h: Held)` and `wants(h: Held)`; the host poll is still the one imperative boundary: `InputEvent.poll(io, prev, skip) -> List<InputEvent>` built as a list literal (`pointerPolled`, `buttonPolled`, `keysPolled`, a `Wheel` if the wheel turned) and `Input.poll` folds it into what is held, with no `out: Slice` parameters; removed: `Input.create` (`Input()`), `Input.isKeyDown`/`axis`/`isKeyPressed`/`isMouseDown`/`isMousePressed`/`isMouseReleased`, `pos`, `wheel`, `Held.isDown` (`isKeyDown`), `Held.withOrWithout`, `Polled`; `Slice` is `List` in `Held` and `Input` (`keyCodes()` a `List`); replays: the tick line keeps what is held (keys, buttons, pointer) beside the events, so a replay does not depend on the fold, and the wheel is an event (`W<dy>`): `plum-replay 2`, whose tick line has no wheel column; a `plum-replay 1` file is still read (its wheel column a `Wheel` after the tick's events, written back as a 2), the native host and the bridge write 2 and read 1 or 2, the old test strings stay as tests of version 1 and new ones cover 2; `Game.obeyAll` does a tick's commands by recursion instead of a fold with a closure (with the new folds in std, `List.fold`'s eight specialised copies ran out in Balloon Pop and `Game.obey`'s two in-place spreads were lost); compiler: a trait default's copy is told from a method the type wrote in the passes' re-check too: `defaultPositions` also reads each trait declaration's methods with a default, which `dropTraitBodies` leaves (the dead code pass dropped std's `Button` from Orbit Runner and the re-check then called the copied `Presses<PlayAction> as p` impossible, dropping the pass); not done: a unique version of std's generic delivery fold (Orbit Runner's `reduce$unique`/`newMine$unique`): `Delivery.actIn`'s slice is never a mixed parameter, as its only unique caller is `actAll` with the `state` of the `Next` that `s.act(a)` returned, and a version would also need `act$unique` for every implementer through a generic receiver; large, in the backlog with a pre-existing re-check failure of a program with no `Sized` or `Touch` view; tests: tests/std/game/Button.plum (a button's box and children, the default `onPress` through a group, an actor of its own, a box that says nothing and a button of another action type), tests/std/game/ScreenSlice.plum (a wheel turn at the pointer, `held` with the pointer), tests/std/game/Input.plum (the fold, the pointer, the wheel, `same`), tests/port/game/replay.plum (version 2 round trip with wheel events, version 1 read and written as 2, bad lines of both), the probes of replay and determinism map presses with `onKey`/`onPointer`, tests/port/game/screens.plum's hud is a `Button` (the default `onPress`), the host fixture counts a tick's events through `onKey`/`onPointer`, driver test `aDefaultMatchingATraitNoTypeIsKeepsEveryPass` (fails without the fix); the games are 22 lines added, 17 removed; Orbit Runner's checksum 946756219, unchanged; benchmarks/screen_views (minimums, a loaded machine): orbit update 14.1 ms before, 14.2 after, paint 135-136 ms both, scale update view 25.8 and 25.0 ms, paint view 398 and 399 ms, spread 17.1 and 17.0 ms; docs: game.md (the minimal game with a `Button`, presses, the input table, `held(h)`, the wheel, replay version 2, two "Beside master" rows), std.md, backlog, the review plan
- benchmarks/screen_views/scale.plum +2 -2
- benchmarks/screen_views/timing.plum +7 -13
- compiler/checker/tests/checker/modules_tests.rs +1 -1
- compiler/cli/src/replay.rs +1 -1
- compiler/cli/tests/cli/game_entry_test.rs +1 -1
- compiler/core/src/trait_defaults.rs +12 -1
- compiler/driver/tests/driver_tests.rs +20 -0
- compiler/game/src/host.rs +4 -3
- compiler/game/tests/fixtures/main_game_fixture.plum +16 -12
- compiler/game/tests/host_test.rs +2 -2
- compiler/game/web-test/fixtures/stress_state_view.plum +11 -10
- compiler/game/web-test/src/lib.rs +1 -1
- compiler/game/web/plum_bridge.js +2 -2
- docs/backlog.md +2 -0
- docs/game.md +34 -27
- docs/plans/2026-11-13-std-game-review.md +1 -1
- docs/std.md +1 -1
- examples/games/balloonpop/actors/Balloon.plum +5 -1
- examples/games/balloonpop/screens/PlaygroundScreen.plum +3 -7
- examples/games/clicks.plum +11 -6
- examples/games/orbitrunner/screens/PlayingScreen.plum +3 -3
- std/game/Button.plum +41 -0
- std/game/Game.plum +14 -20
- std/game/Input.plum +105 -140
- std/game/Replay.plum +59 -62
- std/game/Screen.plum +4 -4
- std/game/ScreenSlice.plum +35 -18
- std/game/TestRig.plum +10 -10
- tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +2 -5
- tests/examples/games/clicks.plum +10 -3
- tests/examples/games/orbitrunner/screens/PlayingScreen.plum +8 -15
- tests/port/game/determinism.plum +14 -24
- tests/port/game/replay.plum +62 -48
- tests/port/game/screens.plum +20 -8
- tests/std/game/Button.plum +75 -0
- tests/std/game/Game.plum +6 -6
- tests/std/game/History.plum +1 -1
- tests/std/game/Input.plum +39 -47
- tests/std/game/ScreenSlice.plum +42 -0
- tests/traits/generic_trait_match.plum +49 -0
benchmarks/screen_views/scale.plum
CHANGED
|
@@ -73,7 +73,7 @@ primitive ScaleBench[App] =
|
|
|
73
73
|
_ => ScaleBench.crowdOf(g).frameSum()
|
|
74
74
|
|
|
75
75
|
fun tickOnce(io: Io, g: Game, paint: Bool) -> Game =
|
|
76
|
-
next := g.update(io, Input
|
|
76
|
+
next := g.update(io, Input(), Ticker.Tick)
|
|
77
77
|
if paint
|
|
78
78
|
next.draw(io)
|
|
79
79
|
next
|
|
@@ -81,7 +81,7 @@ primitive ScaleBench[App] =
|
|
|
81
81
|
# `ticks` ticks of `s` on an 800 by 600 screen, with no host (a test's).
|
|
82
82
|
fun run(io: Io, s: CrowdScreen, ticks: Int) -> CrowdScreen =
|
|
83
83
|
only: Screen := s
|
|
84
|
-
crowdOf(Range.until(0, ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input
|
|
84
|
+
crowdOf(Range.until(0, ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input(), Ticker.Tick, Vec2(x: 800.0, y: 600.0))))
|
|
85
85
|
|
|
86
86
|
fun main(io: Io) =
|
|
87
87
|
args := io.args()
|
benchmarks/screen_views/timing.plum
CHANGED
|
@@ -18,19 +18,13 @@ primitive Timing =
|
|
|
18
18
|
x0 := {seed * 1103515245 + {tick / 20} * 12345 + 12345} % 2147483648
|
|
19
19
|
x := {x0 * 1103515245 + 12345} % 2147483648
|
|
20
20
|
way := {x / 65536} % 9
|
|
21
|
-
keys :=
|
|
21
|
+
keys := [
|
|
22
|
-
|
|
22
|
+
if way % 3 == 0 then Key.Left
|
|
23
|
-
keys.push(Key.Left)
|
|
24
|
-
|
|
23
|
+
if way % 3 == 2 then Key.KeyD
|
|
25
|
-
keys.push(Key.KeyD)
|
|
26
|
-
|
|
24
|
+
if way / 3 == 0 then Key.KeyW
|
|
27
|
-
keys.push(Key.KeyW)
|
|
28
|
-
|
|
25
|
+
if way / 3 == 2 then Key.Down
|
|
29
|
-
|
|
26
|
+
]
|
|
30
|
-
events := Slice<InputEvent>()
|
|
31
|
-
if tick % 150 == 149
|
|
32
|
-
events.push(KeyDown(key: Key.Enter))
|
|
33
|
-
Input(
|
|
27
|
+
Input(events: [if tick % 150 == 149 then KeyDown(key: Key.Enter)], held: Held(keys: keys))
|
|
34
28
|
|
|
35
29
|
fun hash(xs: List<Int>) -> Int =
|
|
36
30
|
xs.fold(17, |h, x|
|
compiler/checker/tests/checker/modules_tests.rs
CHANGED
|
@@ -286,7 +286,7 @@ fn the_old_module_forms_are_errors() {
|
|
|
286
286
|
fn a_game_calls_the_host_through_statics() {
|
|
287
287
|
run(
|
|
288
288
|
"gamemods",
|
|
289
|
-
"import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\n\nprimitive Main =\n fun f(io: Io) -> Float =\n Gfx.clear(io, Color.Black)\n _ := Held(keys: InputEvent.keyCodes()).
|
|
289
|
+
"import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\n\nprimitive Main =\n fun f(io: Io) -> Float =\n Gfx.clear(io, Color.Black)\n _ := Held(keys: InputEvent.keyCodes()).isKeyDown(Key.Left)\n Input().poll(io).held.axis(Key.Left, Key.Right)\n",
|
|
290
290
|
)
|
|
291
291
|
.unwrap();
|
|
292
292
|
}
|
compiler/cli/src/replay.rs
CHANGED
|
@@ -127,7 +127,7 @@ mod tests {
|
|
|
127
127
|
|
|
128
128
|
// The input mattered: the same seed with no input ends elsewhere.
|
|
129
129
|
let header = text.lines().next().unwrap();
|
|
130
|
-
let idle = format!("{header}\n{}", "- 0 0 0
|
|
130
|
+
let idle = format!("{header}\n{}", "- 0 0 0\n".repeat(ticks));
|
|
131
131
|
let still = match runReplay(&wasm, assets, &idle) {
|
|
132
132
|
Ok((_, still)) => still,
|
|
133
133
|
Err(e) => panic!("{name}: the idle replay failed: {e:#}; {}", keepRecording(name, &text)),
|
compiler/cli/tests/cli/game_entry_test.rs
CHANGED
|
@@ -132,7 +132,7 @@ fn screensGame(names: &[&str], to: &str) -> String {
|
|
|
132
132
|
import std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
|
|
133
133
|
struct Named[ScreenSlice<Int>](n: Str) =\n fun name(self) -> Str = self.n\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n \
|
|
134
134
|
fun act(self, a: Int) -> Next<Named, Int> = Next(state: self, cmds: [GoTo(name: \"{to}\")])\n\nprimitive Main[App] =\n \
|
|
135
|
-
fun main(io: Io) =\n{} g := Game(screens: [{}])\n g1 := g.step(io, Input
|
|
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(", ")
|
|
138
138
|
)
|
compiler/core/src/trait_defaults.rs
CHANGED
|
@@ -279,7 +279,9 @@ pub fn isDefaultCopy(f: &Fn, defaultsAt: &HashSet<(String, usize, usize, String)
|
|
|
279
279
|
}
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
-
/// `(file, line, column, name)` of each default body of a trait in `src`
|
|
282
|
+
/// `(file, line, column, name)` of each default body of a trait in `src`: of the trait's own
|
|
283
|
+
/// bodies, and of each method its declaration says has one, so that a copy is still told from
|
|
284
|
+
/// a method the type wrote once `dropTraitBodies` took the bodies out (the passes' re-check).
|
|
283
285
|
pub fn defaultPositions(src: &Source) -> (HashSet<(String, usize, usize, String)>, HashSet<String>) {
|
|
284
286
|
let names: HashSet<String> = src
|
|
285
287
|
.items
|
|
@@ -298,6 +300,15 @@ pub fn defaultPositions(src: &Source) -> (HashSet<(String, usize, usize, String)
|
|
|
298
300
|
}
|
|
299
301
|
_ => None,
|
|
300
302
|
})
|
|
303
|
+
.chain(src.items.iter().flat_map(|i| match i {
|
|
304
|
+
Item::Trait(t) => t
|
|
305
|
+
.methods
|
|
306
|
+
.iter()
|
|
307
|
+
.filter(|m| m.hasDefault)
|
|
308
|
+
.map(|m| (if m.sig.file.is_empty() { t.file.clone() } else { m.sig.file.clone() }, m.sig.line, m.sig.column, m.sig.name.clone()))
|
|
309
|
+
.collect::<Vec<_>>(),
|
|
310
|
+
_ => Vec::new(),
|
|
311
|
+
}))
|
|
301
312
|
.collect();
|
|
302
313
|
(at, names)
|
|
303
314
|
}
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -298,6 +298,26 @@ fn unreachableImportedFnsArePruned() {
|
|
|
298
298
|
assert!(loweredNames(&src, &none).iter().any(|n| n == "replaceAll"));
|
|
299
299
|
}
|
|
300
300
|
|
|
301
|
+
const DEFAULT_MATCH: &str = "import std/Int\nimport std/Float\nimport std/Str\nimport std/Option\nimport std/collections/List\n\
|
|
302
|
+
import std/game/Color\nimport std/game/View\nimport std/game/Box\n\
|
|
303
|
+
import std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/App\n\n\
|
|
304
|
+
enum Act = Go\n\nstruct One[ScreenSlice<Act>](n: Int) =\n fun name(self) -> Str = \"one\"\n\n fun view(self) -> List<View> = [Box(w: 1.0, h: 1.0, color: Color.White)]\n\n\
|
|
305
|
+
primitive Main[App] =\n fun main() -> Int =\n s: Screen := One(n: 1)\n Game(screens: [s]).screens.length()\n";
|
|
306
|
+
|
|
307
|
+
/// A trait default that matches a generic trait (`ScreenSlice`'s `onPress`, `Presses<A> as p`)
|
|
308
|
+
/// keeps every pass when the program has no type that is one: the dead code pass drops std's
|
|
309
|
+
/// `Button`, and the re-check, which runs once the trait's own bodies are gone, still tells
|
|
310
|
+
/// the implementer's copy of the default from a method it wrote (its errors are the default's).
|
|
311
|
+
#[test]
|
|
312
|
+
fn aDefaultMatchingATraitNoTypeIsKeepsEveryPass() {
|
|
313
|
+
let src = load("drv_default_match", DEFAULT_MATCH);
|
|
314
|
+
let (r, dropped) = plum_driver::checkReport(&src, &PassOptions::default(), &PASSES);
|
|
315
|
+
let info = r.expect("checks");
|
|
316
|
+
assert!(dropped.is_empty(), "{dropped:?}");
|
|
317
|
+
let lowered = info.lowered.as_ref().unwrap();
|
|
318
|
+
assert!(!lowered.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == "Button")), "Button is pruned");
|
|
319
|
+
}
|
|
320
|
+
|
|
301
321
|
/// `tests/core/passes_upcasts.plum`, with a `main` that reaches each of its fns.
|
|
302
322
|
fn upcastsSource() -> String {
|
|
303
323
|
let body = std::fs::read_to_string(plum_test_support::repoRoot().join("tests/core/passes_upcasts.plum")).expect("reads");
|
compiler/game/src/host.rs
CHANGED
|
@@ -41,12 +41,13 @@ const REPLAYING: i32 = 2;
|
|
|
41
41
|
const DEV: i32 = 3;
|
|
42
42
|
|
|
43
43
|
/// The seed halves and screen size from a replay's first line,
|
|
44
|
-
/// `plum-replay
|
|
44
|
+
/// `plum-replay 2 <hi> <lo> <width> <height>` (or a `plum-replay 1`, whose tick lines
|
|
45
|
+
/// std/game/Replay reads too).
|
|
45
46
|
pub fn replay_header(text: &str) -> Result<([i32; 2], (i64, i64))> {
|
|
46
47
|
let first = text.lines().next().unwrap_or("");
|
|
47
48
|
let f: Vec<&str> = first.split_whitespace().collect();
|
|
48
49
|
let bad = || wasmtime::Error::msg(format!("not a plum replay: the first line is `{first}`"));
|
|
49
|
-
if f.len() != 6 || f[0] != "plum-replay" || f[1] != "1" {
|
|
50
|
+
if f.len() != 6 || f[0] != "plum-replay" || (f[1] != "1" && f[1] != "2") {
|
|
50
51
|
return Err(bad());
|
|
51
52
|
}
|
|
52
53
|
let n = |i: usize| f[i].parse::<i64>().map_err(|_| bad());
|
|
@@ -331,7 +332,7 @@ impl<B: Backend> PlumGame<B> {
|
|
|
331
332
|
let rp = &self.store.data().replay;
|
|
332
333
|
let half = |i: usize| rp.halves.get(i).copied().unwrap_or(0);
|
|
333
334
|
// The low half as the unsigned value, as std/game/Replay's `header` writes it.
|
|
334
|
-
format!("plum-replay
|
|
335
|
+
format!("plum-replay 2 {} {} {} {}\n{}", half(0), half(1) as u32, rp.screen.0, rp.screen.1, rp.text)
|
|
335
336
|
}
|
|
336
337
|
|
|
337
338
|
/// Replays `text` (a recording) from `main` on: call before `init`. `main` gets the
|
compiler/game/tests/fixtures/main_game_fixture.plum
CHANGED
|
@@ -21,29 +21,33 @@ import std/game/View
|
|
|
21
21
|
import std/game/Place
|
|
22
22
|
import std/App
|
|
23
23
|
|
|
24
|
-
# A game whose entry is `main`, declared to return a `Game`: one screen, `Orbs`, that
|
|
24
|
+
# A game whose entry is `main`, declared to return a `Game`: one screen, `Orbs`, that
|
|
25
|
+
# counts the events of each tick (`Heard`, from `onKey` and `onPointer`), keeps what is
|
|
25
|
-
#
|
|
26
|
+
# held at its last tick and moves while Right is held.
|
|
26
|
-
enum Step = Saw(
|
|
27
|
+
enum Step = Heard | Saw(held: Held) | Moved(dt: Float)
|
|
27
28
|
|
|
28
|
-
struct Orbs[ScreenSlice<Step>](x: Float, ship: Texture,
|
|
29
|
+
struct Orbs[ScreenSlice<Step>](x: Float, ship: Texture, held: Held, heard: Int, events: Int, frame: Int) =
|
|
29
30
|
fun name(self) -> Str = "page"
|
|
30
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
|
+
|
|
31
|
-
fun held(self,
|
|
36
|
+
fun held(self, h: Held) -> Option<Step> = Some(Saw(held: h))
|
|
32
37
|
|
|
33
38
|
fun tick(self, dt: Float) -> Option<Step> = Some(Moved(dt: dt))
|
|
34
39
|
|
|
35
40
|
fun reduce(self, a: Step) -> Orbs = match a
|
|
41
|
+
Heard => Orbs(..self, heard: self.heard + 1)
|
|
36
|
-
Saw(
|
|
42
|
+
Saw(held) => Orbs(..self, held: held)
|
|
37
43
|
Moved(dt) =>
|
|
38
|
-
x := if self.
|
|
44
|
+
x := if self.held.isKeyDown(Key.Right) then self.x + 100.0 * dt else self.x
|
|
39
|
-
Orbs(..self, x: x, frame: self.frame + 1)
|
|
45
|
+
Orbs(..self, x: x, events: self.heard, heard: 0, frame: self.frame + 1)
|
|
40
46
|
|
|
41
47
|
fun view(self) -> List<View> = [OrbsDrawing(s: self)]
|
|
42
48
|
|
|
43
49
|
fun draw(self, io: Io, m: Affine, alpha: Float, area: Aabb) =
|
|
44
|
-
first := self.input.events.length()
|
|
45
|
-
second := self.input.events.length()
|
|
46
|
-
Gfx.drawText(io, "frame {self.frame} ev {
|
|
50
|
+
Gfx.drawText(io, "frame {self.frame} ev {self.events} {self.events} x {self.x} tex {self.ship.id} w {Gfx.screenWidth(io)}", 0.0, 0.0, 8.0, Color.White)
|
|
47
51
|
|
|
48
52
|
# What the screen draws each frame, with `Gfx` by hand.
|
|
49
53
|
struct OrbsDrawing[View](s: Orbs) =
|
|
@@ -53,5 +57,5 @@ struct OrbsDrawing[View](s: Orbs) =
|
|
|
53
57
|
|
|
54
58
|
primitive MainGameFixture[App] =
|
|
55
59
|
fun main(io: Io) -> Game =
|
|
56
|
-
s: Screen := Orbs(x: 0.0, ship: Texture.load(io, "sprites.png"),
|
|
60
|
+
s: Screen := Orbs(x: 0.0, ship: Texture.load(io, "sprites.png"), held: Held(), heard: 0, events: 0, frame: 0)
|
|
57
61
|
Game(screens: [s])
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -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 =
|
|
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 held(self, h: Held) -> Option<Saw> = Some(Seen(keys: h.keys.length(), x: h.pointer.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Seen(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `Gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
|
|
392
392
|
)
|
|
393
393
|
.unwrap();
|
|
394
394
|
let wasm = compile(&path);
|
|
@@ -418,7 +418,7 @@ fn aRecordedRunReplaysWithItsSeedAndInput() {
|
|
|
418
418
|
g.draw().unwrap();
|
|
419
419
|
let recorded = lastText(&g);
|
|
420
420
|
let text = g.recording();
|
|
421
|
-
assert!(text.starts_with("plum-replay
|
|
421
|
+
assert!(text.starts_with("plum-replay 2 ") && text.contains(" 1024 700\n"), "{text}");
|
|
422
422
|
assert_eq!(plum_game::host::replay_ticks(&text), 30);
|
|
423
423
|
assert!(recorded.contains("ticks 30 keys 20 "), "{recorded}");
|
|
424
424
|
|
compiler/game/web-test/fixtures/stress_state_view.plum
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
# Entity counts: 5000 sprites (50 groups x 100), 500 rects, 200 circles, 50 texts,
|
|
7
7
|
# plus 200 animated sprites (pulsers, pose = anim.at(clock - start)) and 20 buttons
|
|
8
8
|
# (screen space, outside the scaled world) that take presses: a press on one is the
|
|
9
|
-
#
|
|
9
|
+
# `Clicked` it says it means (a `Button`), which the screen counts.
|
|
10
10
|
module stress_state_view
|
|
11
11
|
import std/Str
|
|
12
12
|
import std/Int
|
|
@@ -24,6 +24,7 @@ import std/game/Input
|
|
|
24
24
|
import std/game/Place
|
|
25
25
|
import std/game/View
|
|
26
26
|
import std/game/Box
|
|
27
|
+
import std/game/Button
|
|
27
28
|
import std/game/Sprite
|
|
28
29
|
import std/game/Label
|
|
29
30
|
import std/game/Screen
|
|
@@ -86,12 +87,10 @@ struct Scaled[View](scale: Float, children: List<View>) =
|
|
|
86
87
|
|
|
87
88
|
enum StressAction = Ticked(dt: Float) | Clicked(i: Int)
|
|
88
89
|
|
|
89
|
-
# The one screen: its clock, its frame count
|
|
90
|
+
# The one screen: its clock, its frame count and the clicks so far.
|
|
90
|
-
# compares a press with.
|
|
91
|
-
struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks: Int, sheet: Texture, white: Texture,
|
|
91
|
+
struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks: Int, sheet: Texture, white: Texture, anim: Anim) =
|
|
92
92
|
fun create(sheet: Texture, white: Texture) -> ViewScreen =
|
|
93
|
-
buttons := Range.until(0, StressStateView.Buttons).map(|i| Box(x: Float(i % 10 * 70 + 10), y: Float(i / 10 * 30 + 10), w: 64.0, h: 24.0, color: Color.rgb(0.2, 0.2, 0.3), touch: Enabled))
|
|
94
|
-
ViewScreen(clock: 0.0, frames: 0, clicks: 0, sheet: sheet, white: white,
|
|
93
|
+
ViewScreen(clock: 0.0, frames: 0, clicks: 0, sheet: sheet, white: white, anim: StressStateView.pulseAnim())
|
|
95
94
|
|
|
96
95
|
fun name(self) -> Str = "view"
|
|
97
96
|
|
|
@@ -105,13 +104,10 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
|
|
|
105
104
|
..Range.until(0, StressStateView.Circles).map(|i| self.circle(i))
|
|
106
105
|
..Range.until(0, StressStateView.Texts).map(|i| self.counter(i))
|
|
107
106
|
}
|
|
108
|
-
..self.
|
|
107
|
+
..Range.until(0, StressStateView.Buttons).map(|i| self.button(i))
|
|
109
108
|
..Range.until(0, StressStateView.Buttons).map(|i| self.buttonLabel(i))
|
|
110
109
|
]
|
|
111
110
|
|
|
112
|
-
fun onPress(self, target: View, at: Vec2) -> Option<StressAction> =
|
|
113
|
-
Range.until(0, StressStateView.Buttons).find(|i| @sameRef(target, self.buttons.at(i))).map(|i| Clicked(i: i))
|
|
114
|
-
|
|
115
111
|
fun tick(self, dt: Float) -> Option<StressAction> = Some(Ticked(dt: dt))
|
|
116
112
|
|
|
117
113
|
fun reduce(self, a: StressAction) -> ViewScreen = match a
|
|
@@ -145,4 +141,9 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
|
|
|
145
141
|
|
|
146
142
|
fun counter(self, i: Int) -> View = Label(x: Float(i * 30 % StressStateView.WorldW), y: Float(i * 17 % StressStateView.WorldH), text: "n {i + self.frames}", size: 14.0)
|
|
147
143
|
|
|
144
|
+
fun button(self, i: Int) -> View =
|
|
145
|
+
Button(x: Float(i % 10 * 70 + 10), y: Float(i / 10 * 30 + 10), w: 64.0, h: 24.0, on: Clicked(i: i)) {
|
|
146
|
+
Box(w: 64.0, h: 24.0, color: Color.rgb(0.2, 0.2, 0.3))
|
|
147
|
+
}
|
|
148
|
+
|
|
148
149
|
fun buttonLabel(self, i: Int) -> View = Label(x: Float(i % 10 * 70 + 16), y: Float(i / 10 * 30 + 14), text: "b{i}", size: 14.0)
|
compiler/game/web-test/src/lib.rs
CHANGED
|
@@ -987,7 +987,7 @@ async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u1
|
|
|
987
987
|
if !errs.is_empty() {
|
|
988
988
|
return Err(format!("recording page: {errs:?}"));
|
|
989
989
|
}
|
|
990
|
-
if !text.starts_with("plum-replay
|
|
990
|
+
if !text.starts_with("plum-replay 2 ") {
|
|
991
991
|
return Err(format!("plumReplay() gave no recording: {:?}", text.chars().take(80).collect::<String>()));
|
|
992
992
|
}
|
|
993
993
|
let ticks = text.lines().skip(1).filter(|l| !l.trim().is_empty()).count();
|
compiler/game/web/plum_bridge.js
CHANGED
|
@@ -1154,7 +1154,7 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1154
1154
|
// The first line of a replay: its seed halves and screen size, or an error.
|
|
1155
1155
|
function replayHeader(text) {
|
|
1156
1156
|
const f = (text.split("\n", 1)[0] || "").trim().split(/\s+/);
|
|
1157
|
-
if (f.length !== 6 || f[0] !== "plum-replay" || f[1] !== "1") throw new Error("not a plum replay");
|
|
1157
|
+
if (f.length !== 6 || f[0] !== "plum-replay" || (f[1] !== "1" && f[1] !== "2")) throw new Error("not a plum replay");
|
|
1158
1158
|
return { halves: [Number(f[2]) | 0, Number(f[3]) | 0], size: [Number(f[4]) || 0, Number(f[5]) || 0] };
|
|
1159
1159
|
}
|
|
1160
1160
|
|
|
@@ -1195,7 +1195,7 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1195
1195
|
const lines = [];
|
|
1196
1196
|
const size = [Math.round(view.w), Math.round(view.h)];
|
|
1197
1197
|
// The low half as the unsigned value, as std/game/Replay's `header` writes it.
|
|
1198
|
-
const recording = () => "plum-replay
|
|
1198
|
+
const recording = () => "plum-replay 2 " + (halves[0] | 0) + " " + ((halves[1] | 0) >>> 0) + " " + size[0] + " " + size[1] + "\n" + lines.join("");
|
|
1199
1199
|
globalThis.plumReplay = recording;
|
|
1200
1200
|
const save = Object.assign(document.createElement("button"), {
|
|
1201
1201
|
textContent: "Save replay",
|
docs/backlog.md
CHANGED
|
@@ -8,6 +8,8 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
8
8
|
|
|
9
9
|
- **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
|
|
10
10
|
- **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
|
|
11
|
+
- **No unique version of std's generic delivery fold**: Orbit Runner's `reduce$unique` and `newMine$unique` went when its rules became `then` actions (2026-11-16). The uniqueness pass never plans `Delivery.actIn$unique`: its slice parameter `s` is unique only through `actAll`, whose `s` is the `state` binder of the `Next` that `s.act(a)` returned, and the proof doesn't see a method's result's field of a generic struct as fresh; and a version of `actIn` would still call `s.act(a)` on a generic receiver, which `versionCallers` only retargets with the receiver's type known. Restoring it needs the three: freshness through a returned `Next`'s field, versioning `actIn`/`actAll` as a recursive pair, and an `act$unique` for every implementer reached by name. Large; not started.
|
|
12
|
+
- **A program with no `Sized` or `Touch` view drops the dead code pass**: std's `Views.touchOf`, `sizedHit` and `missesArea` match `Touch as t` and `Sized as s` on a `View`, and once the pass has dropped every type that is one, the re-check calls each match impossible ("no type is both a View and a Touch"). Every game has such a view, so only a minimal test program meets it. A trait default's copy is told apart since 2026-11-16 (`defaultPositions` reads the trait's declarations), but these are statics.
|
|
11
13
|
- **Master's other games** (`clockwork`, `menu`) are not ported.
|
|
12
14
|
- **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
|
|
13
15
|
- **Stepping without the screen naming its actors**: the game cannot step an actor found in a view, as the screen holding it is a value; each screen maps its own fields in `stepped`. A lens per field, or a view walk that rebuilds the screen, would let std do it; not designed.
|
docs/game.md
CHANGED
|
@@ -33,7 +33,7 @@ examples/games/orbitrunner/
|
|
|
33
33
|
|
|
34
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, the input mapped to them, and a reducer that returns the next screen. If `main` returns a `Game`, `plum run` runs it as a game. Any other `main` is a command line program.
|
|
35
35
|
|
|
36
|
-
This game counts the clicks on a
|
|
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 the screen writes no `onPress`: 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 game steps it each tick through the screen's `stepped`. `held` 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
39
|
enum TapAction = Tapped | Push(dx: Float) | Quit
|
|
@@ -47,23 +47,27 @@ 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>](taps: Int,
|
|
50
|
+
struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
51
51
|
fun start() -> TapScreen =
|
|
52
|
-
TapScreen(taps: 0,
|
|
52
|
+
TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
|
|
53
53
|
|
|
54
54
|
fun name(self) -> Str = "tap"
|
|
55
55
|
|
|
56
|
+
fun view(self) -> List<View> = [
|
|
57
|
+
Button(x: 350.0, y: 250.0, w: 100.0, h: 100.0, on: Tapped) {
|
|
58
|
+
Box(w: 100.0, h: 100.0, color: Color.Red)
|
|
59
|
+
}
|
|
60
|
+
self.ball
|
|
56
|
-
|
|
61
|
+
Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
|
|
62
|
+
]
|
|
57
63
|
|
|
58
64
|
fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
|
|
59
65
|
|
|
60
|
-
fun onPress(self, target: View, at: Vec2) -> Option<TapAction> = if @sameRef(target, self.box) then Some(Tapped) else None
|
|
61
|
-
|
|
62
66
|
fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
|
|
63
67
|
KeyDown(k) => if k == Key.Escape then Some(Quit) else None
|
|
64
68
|
_ => None
|
|
65
69
|
|
|
66
|
-
fun held(self,
|
|
70
|
+
fun held(self, h: Held) -> Option<TapAction> = Some(Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
67
71
|
|
|
68
72
|
fun reduce(self, a: TapAction) -> TapScreen = match a
|
|
69
73
|
Tapped => TapScreen(..self, taps: self.taps + 1)
|
|
@@ -107,7 +111,7 @@ fun view(self) -> List<View> = [
|
|
|
107
111
|
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)).
|
|
108
112
|
|
|
109
113
|
- **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 + `}`.
|
|
110
|
-
- **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
|
|
114
|
+
- **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 game steps it through the screen's `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.
|
|
111
115
|
- **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.
|
|
112
116
|
- **The state rule.** `view` only reads; the state changes in the actors' `step`, the screen's `stepped` and the reducer. A screen is a value, so this holds by construction: there is nothing for the draw to change.
|
|
113
117
|
|
|
@@ -226,7 +230,7 @@ A run of a game is its seed and one `Input` per tick, so a recording is that and
|
|
|
226
230
|
|
|
227
231
|
While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `Ticker` hands it the inputs of each frame's ticks. While replaying, `io.randomSeed()` returns the recorded seed and the screen size is the recorded one: each replayed tick's `Input.screen` is the header's. Only the first `io.randomSeed()` call is recorded; while recording or replaying, any later call returns a seed derived from that one, the same in the browser and natively, so it replays too. The screen size is the one at the start of the recording: resizing the window while recording isn't recorded.
|
|
228
232
|
|
|
229
|
-
The text is one line for the seed and screen size, then one line per tick
|
|
233
|
+
The text is one line for the seed and screen size (`plum-replay 2 ..`), then one line per tick: what is held after the tick (the keys, the mouse buttons and the pointer) and the tick's events, a turn of the wheel among them (`W<dy>`). What is held is a fold of the events (`Held.after`), and each line keeps it all the same, so a replay doesn't depend on the fold. Floats are written exactly. A `plum-replay 1` file, written before the wheel was an event, is read too: its wheel column becomes a `Wheel` event after the tick's others, and it is written back as a `plum-replay 2`. The details are at the top of `std/game/Replay.plum`.
|
|
230
234
|
|
|
231
235
|
## Undo and time travel
|
|
232
236
|
|
|
@@ -255,7 +259,7 @@ primitive BalloonPop[App] =
|
|
|
255
259
|
|
|
256
260
|
A move that can't be made (no history, a full one, a tick out of reach) leaves the game as it was with `moved` false. After a move the game plays on from there: the ticks undone stay as the future, for `redo`, until a user action cuts them.
|
|
257
261
|
|
|
258
|
-
**What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length and whether it was a user action. Not actions:
|
|
262
|
+
**What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length and whether it was a user action. Not actions: the recorded input is mapped again into fresh actions against the state made again, so an action needs no text form of its own.
|
|
259
263
|
|
|
260
264
|
**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.
|
|
261
265
|
|
|
@@ -293,15 +297,18 @@ Three files of `std/game` talk to the host. Each host call takes `io` first.
|
|
|
293
297
|
| Blending | `blendMode(io, m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` |
|
|
294
298
|
| Files | `loadFile(io, name)`, the file's text; `fileExists(io, name)` |
|
|
295
299
|
|
|
296
|
-
**`std/game/Input`:** keyboard, mouse and touch.
|
|
300
|
+
**`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 `onKey`, `onPointer` and `onPress` get the events one at a time, and its `held(h)` 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`.
|
|
297
301
|
|
|
298
|
-
|
|
|
302
|
+
| | What it gives you |
|
|
299
303
|
|---|---|
|
|
300
|
-
| `
|
|
301
|
-
| `
|
|
302
|
-
| `
|
|
303
|
-
| `
|
|
304
|
-
| `
|
|
304
|
+
| `InputEvent` | `PointerDown(x, y)`, `PointerUp`, `PointerMove` (the left button or a finger, in window pixels), `ButtonDown(button, x, y)`, `ButtonUp(..)` (the right and middle buttons), `KeyDown(key)`, `KeyUp(key)`, `Wheel(dy)` (a turn of the wheel) |
|
|
305
|
+
| `held.isKeyDown(k)` | whether a key is down, with `Key.Space`, `Key.KeyA`, `Key.Up`, `Key.Enter`, `Key.BracketLeft`, `Key.RightShift`, `Key.LeftAlt`, `Key.LeftSuper` (Cmd, or the Windows key), ... |
|
|
306
|
+
| `held.axis(low, high)` | -1, 0 or 1: the key `high` held against the key `low`, 0 when both or neither are (`h.axis(Key.Left, Key.Right)`) |
|
|
307
|
+
| `held.isButtonDown(b)`, `held.mouse` | a mouse button held: `Mouse.Left` (also a finger), `Mouse.Right`, `Mouse.Middle` |
|
|
308
|
+
| `held.pointer` | where the pointer is, in window pixels |
|
|
309
|
+
| `input.screen` | the window's size in pixels |
|
|
310
|
+
|
|
311
|
+
The host is read once a frame, in one place (`InputEvent.poll`, which gives the frame's events as a `List`, and `Input.poll`, which folds them into what is held); nothing in a tick reads the host.
|
|
305
312
|
|
|
306
313
|
**`std/game/Audio`:** `Sound.load(io, name)` gives a `Sound` with `play(io, volume)`, `loop(io, volume)`, `stop(io)` and `setVolume(io, volume)`.
|
|
307
314
|
|
|
@@ -343,8 +350,8 @@ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux
|
|
|
343
350
|
| `act(self, a: A) -> Next<Self, A>` | `Next(state: self.reduce(a))` | applies `a` and says what follows from it: `Next(state, then, cmds)`, the next screen, the actions that follow (`then`) and the commands for the game (`cmds`, below) |
|
|
344
351
|
| `onKey(self, e) -> Option<A>` | None | the action for a key event |
|
|
345
352
|
| `onPointer(self, e, at: Vec2) -> Option<A>` | None | the action for a pointer event, `at` its point in the world |
|
|
346
|
-
| `onPress(self, target: View, at: Vec2) -> Option<A>` | None | the action for a press on an item that takes presses ([Clicks](#clicks)) |
|
|
347
|
-
| `held(self,
|
|
353
|
+
| `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)) |
|
|
354
|
+
| `held(self, h: Held) -> Option<A>` | None | the action for what is held after the tick's events, every tick |
|
|
348
355
|
| `tick(self, dt) -> Option<A>` | None | the tick action |
|
|
349
356
|
|
|
350
357
|
**What follows from an action** is a value `act` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`: a screen with nothing more to say writes `reduce` alone, and one that has writes `act` (and keeps `reduce` for the plain state changes, or not). Each action std delivers is acted on as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next mapping and the next action see what they did. Orbit Runner's rules return what happened as actions (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), and `PlayAgain` on the game over panel is followed by `StartOver` at once (`then: [if self.over then StartOver]`). The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). A test calls `reduce` or `act` itself: `s.act(Keyed).then`. How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
|
|
@@ -353,28 +360,26 @@ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux
|
|
|
353
360
|
|
|
354
361
|
Each tick, std delivers to the shown screen's slice, in this order:
|
|
355
362
|
|
|
356
|
-
1. **Each of the tick's events**, in the order they came: a key through `onKey(e)`; a press (a `PointerDown`) on an item that takes presses through `onPress(target, at)`, and if that gives None, through `onPointer` as any pointer event is; any other pointer event through `onPointer(e, at)`, with `at` the event's point in the world. While a transition runs, the pointer events are dropped.
|
|
357
|
-
2. **`held(
|
|
363
|
+
1. **Each of the tick's events**, in the order they came: a key through `onKey(e)`; a press (a `PointerDown`) on an item that takes presses through `onPress(target, at)`, and if that gives None, through `onPointer` as any pointer event is; any other pointer event through `onPointer(e, at)`, with `at` the event's point in the world; a turn of the wheel (`Wheel(dy)`) through `onPointer` too, `at` where the pointer is. While a transition runs, the pointer events and the wheel are dropped.
|
|
364
|
+
2. **`held(h)`**: an action for what is held after the events (`Held`), every tick, events or none (the steering keys).
|
|
358
365
|
3. **The step**: the screen's `stepped(dt)`, unless `steps()` is false ([Views and actors](#views-and-actors)).
|
|
359
366
|
4. **`tick(dt)`**: the tick action, which sees the actors moved and runs the rules.
|
|
360
367
|
|
|
361
368
|
A mapping that gives None sends nothing. Then the transition in progress moves on, and the game does the commands.
|
|
362
369
|
|
|
363
|
-
Orbit Runner steers with `
|
|
370
|
+
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), ..)`.
|
|
364
371
|
|
|
365
372
|
## Clicks
|
|
366
373
|
|
|
367
374
|
A press is hit-tested by std against what the shown screen's `hud` draws, then its view: the press is on the top-most visible item under it that is `Sized` with `touch` `Enabled` and whose `hit(p)` says the point (in its own coordinates) is on it: what is drawn later before what is drawn earlier, what is under an item (its `view`: the children of a `Group` or an `Overlay`) before the item, through every turn and scale on the way. A `Disabled` item takes everything under it out of the walk. The view is made again for the press, from the screen as the tick has left it so far. [`tests/port/game/routing.plum`](../tests/port/game/routing.plum) checks the walk against a brute-force reference on 300 random nested views.
|
|
368
375
|
|
|
369
|
-
The item hit becomes the slice's action through `onPress(target, at)`. Balloon Pop's balloons
|
|
376
|
+
The item hit becomes the slice's action through `onPress(target, at)`, which by default is what the item says a press on it means: an item that is a `Presses<A>` (`std/game/Button`) gives its `pressed()`, and any other gives None. A `Button(x, y, w, h, on: action) { .. }` is one ready-made: a box that takes presses, drawn by its children. An actor of your own says it the same way; Balloon Pop's balloons, each `Sized` with its exact shape and `Enabled` while whole, are `Presses<PopAction>`:
|
|
370
377
|
|
|
371
378
|
```plum
|
|
372
|
-
fun
|
|
379
|
+
fun pressed(self) -> PopAction = Pop(id: self.id)
|
|
373
|
-
Balloon as b => Some(Pop(balloon: b))
|
|
374
|
-
_ => None
|
|
375
380
|
```
|
|
376
381
|
|
|
377
|
-
and `Pop(
|
|
382
|
+
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.
|
|
378
383
|
|
|
379
384
|
## What outlives a tick
|
|
380
385
|
|
|
@@ -464,6 +469,8 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
464
469
|
| `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
|
|
465
470
|
| `deliver(&self, d: Delivery)`, the delivery noting `acted` | `deliver(self, d: Delivery) -> Delivered` (the next screen, the tick's commands, the actions stepped, whether it was a user action), a fold with no queue | the delivery returns what it made |
|
|
466
471
|
| `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 |
|
|
472
|
+
| `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`; `held(self, h: Held)`; no `isKeyPressed`, `isMousePressed`, `isMouseReleased`, `pos` or `wheel`; a replay is a `plum-replay 2` (a `plum-replay 1` is read too) | 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 |
|
|
473
|
+
| 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 |
|
|
467
474
|
| `Viewport` updated in place (`v.update(w, h)`), `lookAt(x, y, zoom = 1.0)` | `Viewport.of(..).update(w, h) -> Viewport`, the same `lookAt` and `moved` | a value |
|
|
468
475
|
| the frame sets the host's camera (`setCamera`) for a camera with one scale, and puts a `Stretch` camera into the transform | every camera goes into the transform the view is drawn through, in window pixels, and culling maps its area through it | this branch's draw has always gone through the transform; the host sees no `setCamera`/`resetCamera` in a frame, so the recorder's calls differ (`compiler/game/tests/host_test.rs` checks the pixels) |
|
|
469
476
|
| the window's size on each tick's input (`input.screen`, `Input.sized`) | the same; `Game.step(io, input, dt, pixels)` takes it from a test, and an input of 0 by 0 leaves the window as it was | |
|
docs/plans/2026-11-13-std-game-review.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# std/game review (simpler-language @ 257d46e6), 2026-11-13
|
|
2
2
|
|
|
3
|
-
User: "one general review on the std/game and how it can be improved, made more declarative and functional please". Read-only review by a fresh agent; items in priority order. Not yet chosen for building. Items 1 and 2 built on 2026-11-16 (branch `sl/next-cmd`: `Next`, `act` (not `step`, which an `Actor` has), the delivery as a fold, `enum Cmd`; no escape hatch, as nothing needed one).
|
|
3
|
+
User: "one general review on the std/game and how it can be improved, made more declarative and functional please". Read-only review by a fresh agent; items in priority order. Not yet chosen for building. Items 1 and 2 built on 2026-11-16 (branch `sl/next-cmd`: `Next`, `act` (not `step`, which an `Actor` has), the delivery as a fold, `enum Cmd`; no escape hatch, as nothing needed one). Item 3 and the input addendum built on 2026-11-16 (branch `sl/press-input`: `trait Presses<A>` and `Button<A>` in std/game/Button, the default `onPress`; `Input(events, held, screen)`, `Held` a fold with `pointer`, `Wheel(dy)`, `held(h: Held)`, `Polled` gone, `plum-replay 2` with `plum-replay 1` still read). Not restored: a unique version of std's generic delivery fold (see the backlog).
|
|
4
4
|
|
|
5
5
|
1. Reducers return their follow-ups: `Next<S, A>(state, then: List<A>, cmds: List<Cmd>)`, `step(a) -> Next` defaulting to `reduce`; `deliverTo` a pure fold; removes the global `Effects.Running` slot (Effects.plum:43) and the mutable `q`/`acted` Slices (ScreenSlice.plum:114-160); TestRig.dispatch reuses the fold. M, std.
|
|
6
6
|
2. Effects as data, `Control` removed: `enum Cmd = GoTo | Exit | Undo | Redo | RewindTo | Play | Loop | Stop` (+ `Run(fn(Io))` escape hatch); the game interprets them; rewinds skip sounds by construction; Balloon Pop loses its six "heard" fields (~25 lines); `Effects.sent`/`Queued`/`Sink`/`ActionSink` go. M, std.
|
docs/std.md
CHANGED
|
@@ -270,7 +270,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
|
|
|
270
270
|
|
|
271
271
|
## Game screens and slices
|
|
272
272
|
|
|
273
|
-
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`): its fields are its state, `A` its actions, `reduce(self, a) -> Self` its reducer (pure, with no `Io`, so the same actions from the same state give the same state) and `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
|
|
273
|
+
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`): its fields are its state, `A` its actions, `reduce(self, a) -> Self` its reducer (pure, with no `Io`, so the same actions from the same state give the same state) and `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
|
|
274
274
|
|
|
275
275
|
```plum
|
|
276
276
|
import std/Int
|
examples/games/balloonpop/actors/Balloon.plum
CHANGED
|
@@ -19,9 +19,11 @@ import std/game/Circle
|
|
|
19
19
|
import std/game/Label
|
|
20
20
|
import std/game/Sized
|
|
21
21
|
import std/game/Touch
|
|
22
|
+
import std/game/Button
|
|
22
23
|
import BalloonPop
|
|
24
|
+
import screens/PlaygroundScreen
|
|
23
25
|
|
|
24
|
-
struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, clock: Float, poppedAt: Float) =
|
|
26
|
+
struct Balloon[Actor, Sized, Touch, Presses<PopAction>](id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, clock: Float, poppedAt: Float) =
|
|
25
27
|
const Radius = 40.0
|
|
26
28
|
const MinSpeed = 35.0
|
|
27
29
|
const MaxSpeed = 70.0
|
|
@@ -58,6 +60,8 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
|
|
|
58
60
|
|
|
59
61
|
fun touch(self) -> Touchable = if self.popped() then Disabled else Enabled
|
|
60
62
|
|
|
63
|
+
fun pressed(self) -> PopAction = Pop(id: self.id)
|
|
64
|
+
|
|
61
65
|
fun bounds(self) -> Aabb =
|
|
62
66
|
r := Balloon.Radius
|
|
63
67
|
Aabb.of(0.0 - r, 0.0 - r, 2.0 * r, r * 3.6 + 1.0)
|
examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -27,13 +27,13 @@ import actors/Balloon
|
|
|
27
27
|
import BalloonPop
|
|
28
28
|
|
|
29
29
|
enum PopAction =
|
|
30
|
-
| Pop(
|
|
30
|
+
| Pop(id: Int)
|
|
31
31
|
| Popped(at: Float)
|
|
32
32
|
| TakeBack
|
|
33
33
|
| Tick(dt: Float)
|
|
34
34
|
|
|
35
35
|
fun toStr(self) -> Str = match self
|
|
36
|
-
Pop(
|
|
36
|
+
Pop(id) => "Pop({id})"
|
|
37
37
|
Popped(at) => "Popped({at})"
|
|
38
38
|
TakeBack => "TakeBack"
|
|
39
39
|
Tick(dt) => "Tick({dt})"
|
|
@@ -76,10 +76,6 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
76
76
|
|
|
77
77
|
fun stepped(self, dt: Float) -> PlaygroundScreen = PlaygroundScreen(..self, balloons: Views.stepAll(self.balloons, dt))
|
|
78
78
|
|
|
79
|
-
fun onPress(self, target: View, at: Vec2) -> Option<PopAction> = match target
|
|
80
|
-
Balloon as b => Some(Pop(balloon: b))
|
|
81
|
-
_ => None
|
|
82
|
-
|
|
83
79
|
fun onKey(self, e: InputEvent) -> Option<PopAction> = match e
|
|
84
80
|
KeyDown(k) => if k == Key.KeyZ || k == Key.Backspace then Some(TakeBack) else None
|
|
85
81
|
_ => None
|
|
@@ -87,7 +83,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
87
83
|
fun tick(self, dt: Float) -> Option<PopAction> = Some(Tick(dt: dt))
|
|
88
84
|
|
|
89
85
|
fun reduce(self, a: PopAction) -> PlaygroundScreen = match a
|
|
90
|
-
Pop(
|
|
86
|
+
Pop(id) => PlaygroundScreen(..self, balloons: self.balloons.map(|x| if x.id == id then x.pop() else x))
|
|
91
87
|
Popped(at) => self.popped(at)
|
|
92
88
|
TakeBack => self
|
|
93
89
|
Tick(dt) => self.advance(dt)
|
examples/games/clicks.plum
CHANGED
|
@@ -12,6 +12,7 @@ import std/game/Input
|
|
|
12
12
|
import std/game/Place
|
|
13
13
|
import std/game/View
|
|
14
14
|
import std/game/Box
|
|
15
|
+
import std/game/Button
|
|
15
16
|
import std/game/Circle
|
|
16
17
|
import std/game/Label
|
|
17
18
|
import std/game/Cmd
|
|
@@ -32,23 +33,27 @@ struct Ball[Actor](x: Float, y: Float, vx: Float) =
|
|
|
32
33
|
|
|
33
34
|
fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
|
|
34
35
|
|
|
35
|
-
struct TapScreen[ScreenSlice<TapAction>](taps: Int,
|
|
36
|
+
struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
36
37
|
fun start() -> TapScreen =
|
|
37
|
-
TapScreen(taps: 0,
|
|
38
|
+
TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
|
|
38
39
|
|
|
39
40
|
fun name(self) -> Str = "tap"
|
|
40
41
|
|
|
42
|
+
fun view(self) -> List<View> = [
|
|
43
|
+
Button(x: 350.0, y: 250.0, w: 100.0, h: 100.0, on: Tapped) {
|
|
44
|
+
Box(w: 100.0, h: 100.0, color: Color.Red)
|
|
45
|
+
}
|
|
46
|
+
self.ball
|
|
41
|
-
|
|
47
|
+
Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
|
|
48
|
+
]
|
|
42
49
|
|
|
43
50
|
fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
|
|
44
51
|
|
|
45
|
-
fun onPress(self, target: View, at: Vec2) -> Option<TapAction> = if @sameRef(target, self.box) then Some(Tapped) else None
|
|
46
|
-
|
|
47
52
|
fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
|
|
48
53
|
KeyDown(k) => if k == Key.Escape then Some(Quit) else None
|
|
49
54
|
_ => None
|
|
50
55
|
|
|
51
|
-
fun held(self,
|
|
56
|
+
fun held(self, h: Held) -> Option<TapAction> = Some(Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
52
57
|
|
|
53
58
|
fun reduce(self, a: TapAction) -> TapScreen = match a
|
|
54
59
|
Tapped => TapScreen(..self, taps: self.taps + 1)
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -104,9 +104,9 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
104
104
|
KeyDown(k) => if k == Key.Enter || k == Key.KeyR then Some(PlayAgain) else None
|
|
105
105
|
_ => None
|
|
106
106
|
|
|
107
|
-
fun held(self,
|
|
107
|
+
fun held(self, h: Held) -> Option<PlayAction> =
|
|
108
|
-
ax :=
|
|
108
|
+
ax := h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)
|
|
109
|
-
ay :=
|
|
109
|
+
ay := h.axis(Key.Up, Key.Down) + h.axis(Key.KeyW, Key.KeyS)
|
|
110
110
|
Some(Steer(ax: ax.max(-1.0).min(1.0), ay: ay.max(-1.0).min(1.0)))
|
|
111
111
|
|
|
112
112
|
fun tick(self, dt: Float) -> Option<PlayAction> = Some(Tick(dt: dt))
|
std/game/Button.plum
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Float
|
|
4
|
+
import std/Bool
|
|
5
|
+
import std/collections/List
|
|
6
|
+
import std/math/Vec2
|
|
7
|
+
import std/math/Aabb
|
|
8
|
+
import std/game/Place
|
|
9
|
+
import std/game/View
|
|
10
|
+
import std/game/Sized
|
|
11
|
+
import std/game/Touch
|
|
12
|
+
|
|
13
|
+
# A view that says what a press on it means: the action `pressed()` gives. A slice's
|
|
14
|
+
# `onPress` (std/game/ScreenSlice) is that action by default, so a screen whose pressable
|
|
15
|
+
# items all say what they mean writes no `onPress`. A press still lands only on an item
|
|
16
|
+
# that is `Sized` and takes presses (std/game/Touch): a `Button`, or an actor of your own
|
|
17
|
+
# (a balloon: `fun pressed(self) -> PopAction = Pop(id: self.id)`).
|
|
18
|
+
trait Presses<A> =
|
|
19
|
+
fun pressed(self) -> A
|
|
20
|
+
|
|
21
|
+
# A `w` by `h` area at (x, y) (the origin unless given) that a press lands on, meaning
|
|
22
|
+
# `on`, with the children it is drawn with placed in its coordinates, its block (its last
|
|
23
|
+
# field, `children`); it paints nothing itself:
|
|
24
|
+
#
|
|
25
|
+
# Button(x: 350.0, y: 250.0, w: 100.0, h: 100.0, on: Tapped) {
|
|
26
|
+
# Box(w: 100.0, h: 100.0, color: Color.Red)
|
|
27
|
+
# Label(x: 20.0, y: 40.0, text: "Tap", size: 24.0)
|
|
28
|
+
# }
|
|
29
|
+
#
|
|
30
|
+
# It is hit inside its box, edges included, unless a child under the press takes it
|
|
31
|
+
# (a child is decoration unless it takes presses itself).
|
|
32
|
+
struct Button<A>[View, Sized, Touch, Presses<A>](x: Float = 0.0, y: Float = 0.0, w: Float, h: Float, on: A, children: List<View> = Nil) =
|
|
33
|
+
fun place(self) -> Place = Place.at(self.x, self.y)
|
|
34
|
+
|
|
35
|
+
fun view(self) -> List<View> = self.children
|
|
36
|
+
|
|
37
|
+
fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
|
|
38
|
+
|
|
39
|
+
fun touch(self) -> Touchable = Enabled
|
|
40
|
+
|
|
41
|
+
fun pressed(self) -> A = self.on
|
std/game/Game.plum
CHANGED
|
@@ -191,7 +191,7 @@ struct Game(screens: List<Screen>) =
|
|
|
191
191
|
news := Game.heardIn(input, sized.pointer)
|
|
192
192
|
s := sized.screen()
|
|
193
193
|
base := Game(..sized, pointer: Game.lastPointer(input, sized.pointer), ticks: sized.ticks + 1, sent: Nil, cmds: Nil, acted: false)
|
|
194
|
-
if Game.onDemand(s) && !sized.wake && sized.shift.isNone() && !news && !s.wants(input)
|
|
194
|
+
if Game.onDemand(s) && !sized.wake && sized.shift.isNone() && !news && !s.wants(input.held)
|
|
195
195
|
Game(..base, skipped: base.skipped + 1)
|
|
196
196
|
else
|
|
197
197
|
d := s.deliver(Delivery(input: input, dt: dt, before: base.helds.at(base.current), camera: base.camera(base.current), pixels: base.pixels, shifting: base.shift.isSome()))
|
|
@@ -201,12 +201,17 @@ struct Game(screens: List<Screen>) =
|
|
|
201
201
|
ticked := Game(
|
|
202
202
|
..base, screens: Game.setAt(base.screens, base.current, d.screen), helds: Game.setAt(base.helds, base.current, input.held), shift: shift,
|
|
203
203
|
delivered: base.delivered + 1, dirty: true, acted: d.acted, sent: d.sent, cmds: d.cmds)
|
|
204
|
-
after := if replayed then ticked.redone(d.cmds) else
|
|
204
|
+
after := if replayed then ticked.redone(d.cmds) else ticked.obeyAll(io, d.cmds)
|
|
205
205
|
Game(..after, wake: !d.cmds.isEmpty() || after.shift.isSome() || after.screen().busy())
|
|
206
206
|
|
|
207
207
|
# The window is `pixels` from now on.
|
|
208
208
|
fun resized(self, pixels: Vec2) -> Game = Game(..self, pixels: pixels, wake: true, dirty: true)
|
|
209
209
|
|
|
210
|
+
# Does each of the tick's commands, in order (`obey`).
|
|
211
|
+
fun obeyAll(self, io: Io, cmds: List<Cmd>) -> Game = match cmds
|
|
212
|
+
Nil => self
|
|
213
|
+
Cons(c, rest) => self.obey(io, c).obeyAll(io, rest)
|
|
214
|
+
|
|
210
215
|
# Does a command of the tick (std/game/Cmd); an undo, a redo or a rewind waits for the
|
|
211
216
|
# end of the tick (`step`).
|
|
212
217
|
fun obey(self, io: Io, c: Cmd) -> Game = match c
|
|
@@ -466,20 +471,14 @@ struct Game(screens: List<Screen>) =
|
|
|
466
471
|
# Whether the tick's input has an event, a pointer move to where the pointer already was
|
|
467
472
|
# aside.
|
|
468
473
|
fun heardIn(input: Input, pointer: Vec2) -> Bool =
|
|
469
|
-
evs := input.events
|
|
470
|
-
|
|
474
|
+
input.events.fold(Pair(first: false, second: pointer), |acc, e| match e
|
|
471
|
-
e := evs.at(i)
|
|
472
|
-
match e
|
|
473
|
-
|
|
475
|
+
PointerMove(x, y) => Pair(first: acc.first || x != acc.second.x || y != acc.second.y, second: Vec2(x: x, y: y))
|
|
474
|
-
_ => match e.position()
|
|
475
|
-
Some(p) => Pair(first: true, second: p)
|
|
476
|
-
|
|
476
|
+
_ => Pair(first: true, second: e.position().unwrapOr(acc.second))
|
|
477
477
|
).first
|
|
478
478
|
|
|
479
479
|
# Where the pointer is after the tick's events.
|
|
480
480
|
fun lastPointer(input: Input, pointer: Vec2) -> Vec2 =
|
|
481
|
-
evs := input.events
|
|
482
|
-
|
|
481
|
+
input.events.fold(pointer, |p, e| e.position().unwrapOr(p))
|
|
483
482
|
|
|
484
483
|
# A game's ticker: its clock and input between frames: the input not yet given to a tick
|
|
485
484
|
# (`pending`), the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in
|
|
@@ -499,7 +498,7 @@ struct Game(screens: List<Screen>) =
|
|
|
499
498
|
# keys first (`keys`, std/game/History's `TravelKeys`), keeps them from the game's input
|
|
500
499
|
# and leaves their commands in `travel` for the game (`Game.devFrame`).
|
|
501
500
|
struct Ticker(
|
|
502
|
-
pending: Input = Input
|
|
501
|
+
pending: Input = Input(), acc: Float = 0.0, n: Int = 0, ticks: Int = 0, mode: Int = ReplayMode.Off, played: Slice<Input> = Slice<Input>(), cursor: Int = 0,
|
|
503
502
|
keys: TravelKeys = TravelKeys(), travel: List<TravelCmd> = Nil) =
|
|
504
503
|
# The tick length in seconds (1/60), the most ticks one frame runs (a longer stall drops
|
|
505
504
|
# the rest, so the game slows down instead of falling further behind), and how much
|
|
@@ -548,12 +547,7 @@ struct Ticker(
|
|
|
548
547
|
|
|
549
548
|
# Adds a frame's input and time. No host calls: what `frame` does after polling.
|
|
550
549
|
fun accept(self, frame: Input, dt: Float) -> Ticker =
|
|
551
|
-
events := Slice<InputEvent>()
|
|
552
|
-
for i := range self.pending.events.length()
|
|
553
|
-
events.push(self.pending.events.at(i))
|
|
554
|
-
for i := range frame.events.length()
|
|
555
|
-
events.push(frame.events.at(i))
|
|
556
|
-
pending := Input(..frame, events:
|
|
550
|
+
pending := Input(..frame, events: self.pending.events.append(frame.events))
|
|
557
551
|
Ticker(..self, pending: pending, acc: self.acc + dt.max(0.0), n: 0, travel: Nil)
|
|
558
552
|
|
|
559
553
|
fun replaying(self) -> Bool =
|
|
@@ -570,7 +564,7 @@ struct Ticker(
|
|
|
570
564
|
# After a tick: its time is spent and its events are used up.
|
|
571
565
|
fun ticked(self) -> Ticker =
|
|
572
566
|
p := self.pending
|
|
573
|
-
pending := if self.replaying() then p else Input(..p, events:
|
|
567
|
+
pending := if self.replaying() then p else Input(..p, events: Nil)
|
|
574
568
|
Ticker(..self, pending: pending, acc: self.acc - Ticker.Tick, n: self.n + 1, ticks: self.ticks + 1, cursor: if self.replaying() then self.cursor + 1 else self.cursor)
|
|
575
569
|
|
|
576
570
|
# After the frame's last tick: a stall's leftover time is dropped.
|
std/game/Input.plum
CHANGED
|
@@ -2,7 +2,6 @@ module std
|
|
|
2
2
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
|
-
import std/Slice
|
|
6
5
|
import std/math/Vec2
|
|
7
6
|
import std/Io
|
|
8
7
|
import std/Option
|
|
@@ -10,12 +9,13 @@ import std/collections/List
|
|
|
10
9
|
import std/Str
|
|
11
10
|
import std/game/Gfx
|
|
12
11
|
|
|
13
|
-
# Player input. `InputEvent.poll` is the only code that reads
|
|
12
|
+
# Player input. `InputEvent.poll` is the only code that reads input from the host, and
|
|
14
|
-
# input from the host: a game that feeds every polled `InputEvent` into its state reads
|
|
15
|
-
#
|
|
13
|
+
# the events it gives are the input: what is held is a fold of them (`Held.after`), so a
|
|
14
|
+
# game that maps every event and what is held reads nothing else, and a recorded list of
|
|
16
|
-
# std/game/Replay and docs/game.md, "Record and
|
|
15
|
+
# inputs replays the game exactly (see std/game/Replay and docs/game.md, "Record and
|
|
16
|
+
# replay").
|
|
17
17
|
|
|
18
|
-
# Key codes (GLFW numbering)
|
|
18
|
+
# Key codes (GLFW numbering), as `KeyDown` and `KeyUp` carry them and `Held.isKeyDown` takes.
|
|
19
19
|
# Letter keys are `KeyA`..`KeyZ` (a constant name needs two characters). Super is Cmd on a
|
|
20
20
|
# Mac, the Windows key elsewhere.
|
|
21
21
|
primitive Key =
|
|
@@ -76,7 +76,7 @@ primitive Key =
|
|
|
76
76
|
const RightAlt = 346
|
|
77
77
|
const RightSuper = 347
|
|
78
78
|
|
|
79
|
-
# Mouse button numbers for `
|
|
79
|
+
# Mouse button numbers for `Held.isButtonDown`. The left button (or a touch)
|
|
80
80
|
# is the pointer: `PointerDown` and `PointerUp`; the others come as `ButtonDown` and
|
|
81
81
|
# `ButtonUp`.
|
|
82
82
|
primitive Mouse =
|
|
@@ -86,7 +86,7 @@ primitive Mouse =
|
|
|
86
86
|
|
|
87
87
|
# One input: a pointer event in screen pixels (the left button or a touch, or a move), the
|
|
88
88
|
# right or middle mouse button going down or up where the pointer is (`button` a `Mouse`
|
|
89
|
-
# number),
|
|
89
|
+
# number), a key going down or up, or the wheel turned by `dy`.
|
|
90
90
|
enum InputEvent =
|
|
91
91
|
| PointerDown(x: Float, y: Float)
|
|
92
92
|
| PointerUp(x: Float, y: Float)
|
|
@@ -95,6 +95,7 @@ enum InputEvent =
|
|
|
95
95
|
| ButtonUp(button: Int, x: Float, y: Float)
|
|
96
96
|
| KeyDown(key: Int)
|
|
97
97
|
| KeyUp(key: Int)
|
|
98
|
+
| Wheel(dy: Float)
|
|
98
99
|
|
|
99
100
|
# The host's input, read only by `poll` and `Input.poll`.
|
|
100
101
|
extern fun isKeyDown(io: Io, k: Int) -> Bool
|
|
@@ -104,77 +105,73 @@ enum InputEvent =
|
|
|
104
105
|
extern fun isMousePressed(io: Io, b: Int) -> Bool
|
|
105
106
|
extern fun mouseWheel(io: Io) -> Float
|
|
106
107
|
|
|
107
|
-
# This frame's
|
|
108
|
+
# This frame's events: the host's mouse buttons and keys compared with `prev`, what was
|
|
108
109
|
# held after the last poll; the keys in `skip` read as up (a development run's time
|
|
109
|
-
# travel keys, std/game/History's `TravelKeys`). One pointer
|
|
110
|
+
# travel keys, std/game/History's `TravelKeys`). One pointer event (down, up or move)
|
|
110
111
|
# comes first, then a ButtonDown or ButtonUp for the right and the middle button if it
|
|
111
|
-
# changed, then a KeyDown or KeyUp for each key that changed, in key-code order
|
|
112
|
+
# changed, then a KeyDown or KeyUp for each key that changed, in key-code order, then a
|
|
112
|
-
# that began and ended between two polls gives a
|
|
113
|
+
# `Wheel` if the wheel turned. A click that began and ended between two polls gives a
|
|
114
|
+
# down and an up.
|
|
113
|
-
fun poll(io: Io, prev: Held, skip: List<Int> = Nil) ->
|
|
115
|
+
fun poll(io: Io, prev: Held, skip: List<Int> = Nil) -> List<InputEvent> =
|
|
114
|
-
out := Slice<InputEvent>()
|
|
115
116
|
m := mousePos(io)
|
|
116
117
|
down := isMouseDown(io, Mouse.Left)
|
|
118
|
+
dy := mouseWheel(io)
|
|
119
|
+
[
|
|
120
|
+
..InputEvent.pointerPolled(down, prev.mouse, !down && isMousePressed(io, Mouse.Left), m)
|
|
121
|
+
..InputEvent.buttonPolled(io, Mouse.Right, prev, m)
|
|
122
|
+
..InputEvent.buttonPolled(io, Mouse.Middle, prev, m)
|
|
123
|
+
..InputEvent.keysPolled(io, prev, skip)
|
|
124
|
+
if dy != 0.0 then Wheel(dy: dy)
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# The left button, `down` now and `was` down before, at `m`; `clicked` if it went down
|
|
128
|
+
# and up between two polls.
|
|
129
|
+
fun pointerPolled(down: Bool, was: Bool, clicked: Bool, m: Vec2) -> List<InputEvent> =
|
|
117
|
-
if down && !
|
|
130
|
+
if down && !was
|
|
118
|
-
|
|
131
|
+
[PointerDown(x: m.x, y: m.y)]
|
|
119
|
-
else if !down &&
|
|
132
|
+
else if !down && was
|
|
120
|
-
|
|
133
|
+
[PointerUp(x: m.x, y: m.y)]
|
|
121
|
-
else if
|
|
134
|
+
else if clicked
|
|
122
|
-
# pressed and released between two polls: a click must not be lost
|
|
123
|
-
out.push(PointerDown(x: m.x, y: m.y))
|
|
124
|
-
|
|
135
|
+
[PointerDown(x: m.x, y: m.y), PointerUp(x: m.x, y: m.y)]
|
|
125
136
|
else
|
|
126
|
-
|
|
137
|
+
[PointerMove(x: m.x, y: m.y)]
|
|
127
|
-
buttons := Slice<Int>()
|
|
128
|
-
InputEvent.pollButton(io, Mouse.Right, prev, m, out, buttons)
|
|
129
|
-
InputEvent.pollButton(io, Mouse.Middle, prev, m, out, buttons)
|
|
130
|
-
keys := Slice<Int>()
|
|
131
|
-
codes := InputEvent.keyCodes()
|
|
132
|
-
for i := range codes.length()
|
|
133
|
-
k := codes.at(i)
|
|
134
|
-
now := isKeyDown(io, k) && !skip.any(|s| s == k)
|
|
135
|
-
was := prev.isDown(k)
|
|
136
|
-
if now
|
|
137
|
-
keys.push(k)
|
|
138
|
-
if now && !was
|
|
139
|
-
out.push(KeyDown(key: k))
|
|
140
|
-
if !now && was
|
|
141
|
-
out.push(KeyUp(key: k))
|
|
142
|
-
Polled(inputs: out, held: Held(mouse: down, keys: keys, buttons: buttons))
|
|
143
138
|
|
|
144
|
-
# The mouse button `b` polled, at `m`: its ButtonDown or ButtonUp
|
|
139
|
+
# The mouse button `b` polled, at `m`: its ButtonDown or ButtonUp if it changed since
|
|
145
|
-
#
|
|
140
|
+
# `prev` (both if it went down and up between two polls).
|
|
146
|
-
# `buttons` if it is down.
|
|
147
|
-
fun
|
|
141
|
+
fun buttonPolled(io: Io, b: Int, prev: Held, m: Vec2) -> List<InputEvent> =
|
|
148
142
|
now := isMouseDown(io, b)
|
|
149
143
|
was := prev.isButtonDown(b)
|
|
150
|
-
if now
|
|
151
|
-
buttons.push(b)
|
|
152
144
|
if now && !was
|
|
153
|
-
|
|
145
|
+
[ButtonDown(button: b, x: m.x, y: m.y)]
|
|
154
146
|
else if !now && was
|
|
155
|
-
|
|
147
|
+
[ButtonUp(button: b, x: m.x, y: m.y)]
|
|
156
148
|
else if !now && isMousePressed(io, b)
|
|
157
|
-
out.push(ButtonDown(button: b, x: m.x, y: m.y))
|
|
158
|
-
|
|
149
|
+
[ButtonDown(button: b, x: m.x, y: m.y), ButtonUp(button: b, x: m.x, y: m.y)]
|
|
150
|
+
else
|
|
151
|
+
Nil
|
|
152
|
+
|
|
153
|
+
# A KeyDown or KeyUp for each key that changed since `prev`, in key-code order; the keys
|
|
154
|
+
# in `skip` read as up.
|
|
155
|
+
fun keysPolled(io: Io, prev: Held, skip: List<Int>) -> List<InputEvent> =
|
|
156
|
+
none: List<InputEvent> := Nil
|
|
157
|
+
InputEvent.keyCodes().fold(none, |acc, k|
|
|
158
|
+
now := isKeyDown(io, k) && !skip.any(|s| s == k)
|
|
159
|
+
was := prev.isKeyDown(k)
|
|
160
|
+
if now && !was then Cons(KeyDown(key: k), acc) else if !now && was then Cons(KeyUp(key: k), acc) else acc
|
|
161
|
+
).reverse()
|
|
159
162
|
|
|
160
163
|
# Every `Key` code in std/game/Input, in increasing order.
|
|
161
|
-
fun keyCodes() ->
|
|
164
|
+
fun keyCodes() -> List<Int> = [
|
|
162
|
-
|
|
165
|
+
Key.Space
|
|
163
|
-
for i := range 10
|
|
164
|
-
|
|
166
|
+
..Range.until(0, 10).map(|i| Key.Num0 + i)
|
|
165
|
-
for i := range 26
|
|
166
|
-
|
|
167
|
+
..Range.until(0, 26).map(|i| Key.KeyA + i)
|
|
167
|
-
for i := range 3
|
|
168
|
-
|
|
168
|
+
..Range.until(0, 3).map(|i| Key.BracketLeft + i)
|
|
169
|
-
for i := range 4
|
|
170
|
-
|
|
169
|
+
..Range.until(0, 4).map(|i| Key.Escape + i)
|
|
171
|
-
for i := range 4
|
|
172
|
-
|
|
170
|
+
..Range.until(0, 4).map(|i| Key.Right + i)
|
|
173
|
-
for i := range 8
|
|
174
|
-
|
|
171
|
+
..Range.until(0, 8).map(|i| Key.LeftShift + i)
|
|
175
|
-
|
|
172
|
+
]
|
|
176
173
|
|
|
177
|
-
# The pointer position, or None for a key.
|
|
174
|
+
# The pointer position, or None for a key or the wheel.
|
|
178
175
|
fun position(self) -> Option<Vec2> = match self
|
|
179
176
|
PointerDown(x, y) => Some(Vec2(x: x, y: y))
|
|
180
177
|
PointerUp(x, y) => Some(Vec2(x: x, y: y))
|
|
@@ -202,93 +199,61 @@ enum InputEvent =
|
|
|
202
199
|
fun isPointer(self) -> Bool =
|
|
203
200
|
self.position().isSome()
|
|
204
201
|
|
|
202
|
+
fun isWheel(self) -> Bool = match self
|
|
203
|
+
Wheel(_) => true
|
|
204
|
+
_ => false
|
|
205
|
+
|
|
205
|
-
# What is held: the left mouse button (or a touch), the
|
|
206
|
+
# What is held, a fold of the events (`after`): the left mouse button (or a touch), the
|
|
207
|
+
# keys that are down, the other mouse buttons that are down (`Mouse.Right`,
|
|
206
|
-
#
|
|
208
|
+
# `Mouse.Middle`), and where the pointer is, in screen pixels; nothing unless given
|
|
207
|
-
# (`Held()`, `Held(keys: keys)`)
|
|
209
|
+
# (`Held()`, `Held(keys: keys)`). A slice's `held(h)` (std/game/ScreenSlice) maps it.
|
|
208
|
-
struct Held(mouse: Bool = false, keys:
|
|
210
|
+
struct Held(mouse: Bool = false, keys: List<Int> = Nil, buttons: List<Int> = Nil, pointer: Vec2 = Vec2(x: 0.0, y: 0.0)) =
|
|
209
|
-
# Whether `o` holds the same: the mouse buttons, and the same keys in any order
|
|
211
|
+
# Whether `o` holds the same: the mouse buttons, and the same keys in any order (where
|
|
212
|
+
# the pointer is aside).
|
|
210
213
|
fun same(self, o: Held) -> Bool =
|
|
211
|
-
self.mouse == o.mouse && self.keys.length() == o.keys.length() && self.keys.all(|k| o.
|
|
214
|
+
self.mouse == o.mouse && self.keys.length() == o.keys.length() && self.keys.all(|k| o.isKeyDown(k))
|
|
212
|
-
&& self.buttons.length() == o.buttons.length() && self.buttons.all(|b| o.
|
|
215
|
+
&& self.buttons.length() == o.buttons.length() && self.buttons.all(|b| o.isButtonDown(b))
|
|
216
|
+
|
|
217
|
+
# Whether the key `key` (a `Key` code) is down.
|
|
218
|
+
fun isKeyDown(self, key: Int) -> Bool = self.keys.any(|k| k == key)
|
|
213
219
|
|
|
220
|
+
# -1, 0 or 1: the key `high` held against the key `low`, 0 when both or neither are.
|
|
221
|
+
# `held.axis(Key.Left, Key.Right)` is the horizontal steering of a ship.
|
|
214
|
-
fun
|
|
222
|
+
fun axis(self, low: Int, high: Int) -> Float =
|
|
215
|
-
self.
|
|
223
|
+
{if self.isKeyDown(high) then 1.0 else 0.0} - {if self.isKeyDown(low) then 1.0 else 0.0}
|
|
216
224
|
|
|
217
|
-
# Whether the mouse button `b` (a `Mouse` number) is down.
|
|
225
|
+
# Whether the mouse button `b` (a `Mouse` number; `Mouse.Left` is also a touch) is down.
|
|
218
226
|
fun isButtonDown(self, b: Int) -> Bool =
|
|
219
|
-
if b == Mouse.Left then self.mouse else self.buttons.
|
|
227
|
+
if b == Mouse.Left then self.mouse else self.buttons.any(|x| x == b)
|
|
220
228
|
|
|
221
229
|
# What is held after `e`: KeyDown adds its key, KeyUp removes it, a pointer down or up
|
|
222
|
-
# sets `mouse`, a ButtonDown or ButtonUp adds or removes its button
|
|
230
|
+
# sets `mouse`, a ButtonDown or ButtonUp adds or removes its button, and each pointer
|
|
231
|
+
# event moves `pointer`; the wheel holds nothing.
|
|
223
232
|
fun after(self, e: InputEvent) -> Held = match e
|
|
224
|
-
KeyDown(key) => if self.
|
|
233
|
+
KeyDown(key) => if self.isKeyDown(key) then self else Held(..self, keys: self.keys.append([key]))
|
|
225
|
-
KeyUp(key) => Held(..self, keys:
|
|
234
|
+
KeyUp(key) => Held(..self, keys: self.keys.filter(|k| k != key))
|
|
226
|
-
PointerDown(
|
|
235
|
+
PointerDown(x, y) => Held(..self, mouse: true, pointer: Vec2(x: x, y: y))
|
|
227
|
-
PointerUp(
|
|
236
|
+
PointerUp(x, y) => Held(..self, mouse: false, pointer: Vec2(x: x, y: y))
|
|
237
|
+
PointerMove(x, y) => Held(..self, pointer: Vec2(x: x, y: y))
|
|
228
|
-
ButtonDown(b,
|
|
238
|
+
ButtonDown(b, x, y) => Held(..self, buttons: self.buttons.filter(|n| n != b).append([b]), pointer: Vec2(x: x, y: y))
|
|
229
|
-
ButtonUp(b,
|
|
239
|
+
ButtonUp(b, x, y) => Held(..self, buttons: self.buttons.filter(|n| n != b), pointer: Vec2(x: x, y: y))
|
|
230
|
-
_ => self
|
|
240
|
+
Wheel(_) => self
|
|
231
241
|
|
|
232
|
-
#
|
|
242
|
+
# What is held after each of `events`, in order.
|
|
233
|
-
fun withOrWithout(xs: Slice<Int>, x: Int, add: Bool) -> Slice<Int> =
|
|
234
|
-
out := Slice<Int>()
|
|
235
|
-
for i := range xs.length()
|
|
236
|
-
if xs.at(i) != x
|
|
237
|
-
out.push(xs.at(i))
|
|
238
|
-
if add
|
|
239
|
-
out.push(x)
|
|
240
|
-
out
|
|
241
|
-
|
|
242
|
-
# A poll's inputs and what is held after them (pass it to the next poll).
|
|
243
|
-
struct Polled(inputs: Slice<InputEvent>, held: Held)
|
|
244
|
-
|
|
245
|
-
# The player's input for one tick, a value: a slice's `held(input)` receives it. The
|
|
246
|
-
# game's `Ticker` (std/game/Game) reads the host once per frame, so `events`, `isKeyDown`
|
|
247
|
-
# and the pointer reads agree for the whole tick however often they are called, and
|
|
248
|
-
# nothing in a tick reads input from the host. `pos` is where the pointer is, in screen
|
|
249
|
-
# pixels, and `wheel` how far the wheel turned this frame. `screen` is the window's size
|
|
250
|
-
# in pixels (0 by 0 unless given, or `sized`): the host's when the `Ticker` reads it, the
|
|
251
|
-
# recorded one in a replay; the game takes its window from it (`Game.update`).
|
|
252
|
-
struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float, screen: Vec2 = Vec2(x: 0.0, y: 0.0)) =
|
|
253
|
-
fun create() -> Input =
|
|
254
|
-
|
|
243
|
+
fun afterAll(self, events: List<InputEvent>) -> Held = events.fold(self, |h, e| h.after(e))
|
|
255
244
|
|
|
245
|
+
# The player's input for one tick, a value: its events, in the order they came, and what
|
|
246
|
+
# is held after them (`held`, their fold over what was held before). The game's `Ticker`
|
|
247
|
+
# (std/game/Game) reads the host once per frame, so nothing in a tick reads input from the
|
|
248
|
+
# host. `screen` is the window's size in pixels (0 by 0 unless given, or `sized`): the
|
|
249
|
+
# host's when the `Ticker` reads it, the recorded one in a replay; the game takes its
|
|
250
|
+
# window from it (`Game.update`).
|
|
251
|
+
struct Input(events: List<InputEvent> = Nil, held: Held = Held(), screen: Vec2 = Vec2(x: 0.0, y: 0.0)) =
|
|
256
252
|
# This input in a window `w` by `h` pixels.
|
|
257
253
|
fun sized(self, w: Float, h: Float) -> Input = Input(..self, screen: Vec2(x: w, y: h))
|
|
258
254
|
|
|
259
255
|
# The input of this frame: the host polled once and compared with what was held before,
|
|
260
256
|
# the keys in `skip` read as up, in the host's window.
|
|
261
257
|
fun poll(self, io: Io, skip: List<Int> = Nil) -> Input =
|
|
262
|
-
|
|
258
|
+
events := InputEvent.poll(io, self.held, skip)
|
|
263
|
-
Input(
|
|
259
|
+
Input(events: events, held: self.held.afterAll(events), screen: Vec2(x: Gfx.screenWidth(io), y: Gfx.screenHeight(io)))
|
|
264
|
-
|
|
265
|
-
# Held at the start of this frame (a `Key` code).
|
|
266
|
-
fun isKeyDown(self, key: Int) -> Bool =
|
|
267
|
-
self.held.isDown(key)
|
|
268
|
-
|
|
269
|
-
# -1, 0 or 1: the key `high` held against the key `low`, 0 when both or neither are.
|
|
270
|
-
# `input.axis(Key.Left, Key.Right)` is the horizontal steering of a ship.
|
|
271
|
-
fun axis(self, low: Int, high: Int) -> Float =
|
|
272
|
-
{if self.isKeyDown(high) then 1.0 else 0.0} - {if self.isKeyDown(low) then 1.0 else 0.0}
|
|
273
|
-
|
|
274
|
-
# Went down this frame.
|
|
275
|
-
fun isKeyPressed(self, key: Int) -> Bool =
|
|
276
|
-
self.events.any(|e| e.isKeyDownOf(key))
|
|
277
|
-
|
|
278
|
-
# The mouse button `b` (`Mouse.Left` unless given, which is also a touch) is held.
|
|
279
|
-
fun isMouseDown(self, b: Int = Mouse.Left) -> Bool =
|
|
280
|
-
self.held.isButtonDown(b)
|
|
281
|
-
|
|
282
|
-
# The mouse button `b` went down this frame.
|
|
283
|
-
fun isMousePressed(self, b: Int = Mouse.Left) -> Bool =
|
|
284
|
-
self.events.any(|e| match e
|
|
285
|
-
PointerDown(_, _) => b == Mouse.Left
|
|
286
|
-
ButtonDown(n, _, _) => n == b
|
|
287
|
-
_ => false)
|
|
288
|
-
|
|
289
|
-
# The mouse button `b` went up this frame.
|
|
290
|
-
fun isMouseReleased(self, b: Int = Mouse.Left) -> Bool =
|
|
291
|
-
self.events.any(|e| match e
|
|
292
|
-
PointerUp(_, _) => b == Mouse.Left
|
|
293
|
-
ButtonUp(n, _, _) => n == b
|
|
294
|
-
_ => false)
|
std/game/Replay.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/Option
|
|
|
8
8
|
import std/Result
|
|
9
9
|
import std/Slice
|
|
10
10
|
import std/Buffer
|
|
11
|
+
import std/collections/List
|
|
11
12
|
import std/math/Vec2
|
|
12
13
|
import std/Io
|
|
13
14
|
import std/game/Input
|
|
@@ -24,18 +25,24 @@ import std/game/Input
|
|
|
24
25
|
#
|
|
25
26
|
# The text form, one line each:
|
|
26
27
|
#
|
|
27
|
-
# plum-replay
|
|
28
|
+
# plum-replay 2 <seed, high 32 bits> <seed, low 32 bits> <screen width> <screen height>
|
|
28
|
-
# <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> <
|
|
29
|
+
# <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> <events>
|
|
29
30
|
#
|
|
31
|
+
# with one tick line per tick, its events and what is held after them (`Input.held`:
|
|
32
|
+
# a fold of the events, kept on each line so that a replay does not depend on the fold);
|
|
30
|
-
#
|
|
33
|
+
# every tick's `Input.screen` is the header's size (a tick line holds none). The mouse
|
|
31
|
-
#
|
|
34
|
+
# buttons held are a sum: 1 for the left, 2 for the right, 4 for the middle. An event is
|
|
32
|
-
# right, 4 for the middle (a replay from before the other buttons has only 0 and 1). An
|
|
33
|
-
#
|
|
35
|
+
# `K<key>` (KeyDown), `k<key>` (KeyUp), `D<x>,<y>` (PointerDown), `U<x>,<y>` (PointerUp),
|
|
34
|
-
#
|
|
36
|
+
# `M<x>,<y>` (PointerMove), `B<button>,<x>,<y>` (ButtonDown), `b<button>,<x>,<y>`
|
|
35
|
-
# `b<button>,<x>,<y>` (ButtonUp). Floats are
|
|
36
|
-
# written exactly, as `m` or `m:e` for the
|
|
37
|
+
# (ButtonUp) or `W<dy>` (Wheel). Floats are written exactly, as `m` or `m:e` for the
|
|
38
|
+
# integer m times 2^e, or as `-0`, `inf`, `-inf` or `nan` (`toStr` rounds to six digits).
|
|
37
|
-
#
|
|
39
|
+
# The screen size is the host's at the start of the recording, and the replaying host
|
|
38
|
-
#
|
|
40
|
+
# reports it to the game; 0 means not recorded.
|
|
41
|
+
#
|
|
42
|
+
# A `plum-replay 1` file, from before the wheel was an event, is read too: its tick lines
|
|
43
|
+
# have the wheel's turn after the pointer, read as a `Wheel` event after the tick's others
|
|
44
|
+
# when it is not 0 (and its mouse buttons held may be only 0 and 1, from before the other
|
|
45
|
+
# buttons).
|
|
39
46
|
|
|
40
47
|
primitive ReplayMode =
|
|
41
48
|
const Off = 0
|
|
@@ -48,6 +55,9 @@ primitive ReplayMode =
|
|
|
48
55
|
# A recorded run: the seed `io.randomSeed()` gave `main`, the screen size at the start,
|
|
49
56
|
# and the input of every tick in order.
|
|
50
57
|
struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
58
|
+
# The version of the text form a recording writes (`plum-replay 2`; a 1 is read too).
|
|
59
|
+
const Version = "2"
|
|
60
|
+
|
|
51
61
|
# Whether the host is recording or replaying this run (a `ReplayMode`, asked once a frame).
|
|
52
62
|
extern fun replayMode(io: Io) -> Int
|
|
53
63
|
# The text of the replay the host is replaying.
|
|
@@ -80,14 +90,14 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
|
80
90
|
fun decode(text: Str) -> Result<Replay, Str> =
|
|
81
91
|
lines := text.split("\n", 0)
|
|
82
92
|
head := lines.at(0).trim().split(" ", 0)
|
|
83
|
-
if head.length() != 6 || head.at(0) != "plum-replay" || head.at(1) != "1"
|
|
93
|
+
if head.length() != 6 || head.at(0) != "plum-replay" || {head.at(1) != "1" && head.at(1) != Replay.Version}
|
|
84
|
-
Err("not a plum replay: the first line must be `plum-replay
|
|
94
|
+
Err("not a plum replay: the first line must be `plum-replay {Replay.Version} <seed high> <seed low> <width> <height>`")
|
|
85
95
|
else
|
|
86
96
|
hi := Replay.headNumber(head, 2)?
|
|
87
97
|
lo := Replay.headNumber(head, 3)?
|
|
88
98
|
width := Replay.headNumber(head, 4)?
|
|
89
99
|
height := Replay.headNumber(head, 5)?
|
|
90
|
-
ticks := Replay.decodeTicks(lines, 1, Slice<Input>())?
|
|
100
|
+
ticks := Replay.decodeTicks(lines, 1, head.at(1) == "1", Slice<Input>())?
|
|
91
101
|
Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks).onScreen(width, height))
|
|
92
102
|
|
|
93
103
|
# The replay on a window `w` by `h` pixels, each tick's input in it (`Input.screen`): a
|
|
@@ -102,82 +112,66 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
|
102
112
|
fun headNumber(head: Slice<Str>, i: Int) -> Result<Int, Str> =
|
|
103
113
|
Int.parse(head.at(i)).mapErr(|e| "line 1: `{head.at(i)}` is not a whole number")
|
|
104
114
|
|
|
105
|
-
# The tick lines from `lines.at(i)` on, added to `out`.
|
|
115
|
+
# The tick lines from `lines.at(i)` on, added to `out`; `v1`, those of a `plum-replay 1`.
|
|
106
|
-
fun decodeTicks(lines: Slice<Str>, i: Int, out: Slice<Input>) -> Result<Slice<Input>, Str> =
|
|
116
|
+
fun decodeTicks(lines: Slice<Str>, i: Int, v1: Bool, out: Slice<Input>) -> Result<Slice<Input>, Str> =
|
|
107
117
|
if i >= lines.length()
|
|
108
118
|
Ok(out)
|
|
109
119
|
else
|
|
110
120
|
l := lines.at(i).trim()
|
|
111
121
|
if l.length() == 0
|
|
112
|
-
Replay.decodeTicks(lines, i + 1, out)
|
|
122
|
+
Replay.decodeTicks(lines, i + 1, v1, out)
|
|
113
123
|
else
|
|
114
|
-
match Replay.parseLine(l)
|
|
124
|
+
match Replay.parseLine(l, v1)
|
|
115
125
|
Some(input) =>
|
|
116
126
|
out.push(input)
|
|
117
|
-
Replay.decodeTicks(lines, i + 1, out)
|
|
127
|
+
Replay.decodeTicks(lines, i + 1, v1, out)
|
|
118
128
|
None => Err("line {i + 1}: `{l}` is not a tick")
|
|
119
129
|
|
|
120
130
|
fun header(seed: Int, width: Int, height: Int) -> Str =
|
|
121
|
-
"plum-replay
|
|
131
|
+
"plum-replay {Replay.Version} {seed >> 32} {seed & 0xFFFFFFFF} {width} {height}\n"
|
|
122
132
|
|
|
123
133
|
# One tick's line, ending in a newline.
|
|
124
134
|
fun line(input: Input) -> Str =
|
|
125
|
-
b := Buffer()
|
|
126
|
-
|
|
135
|
+
h := input.held
|
|
127
|
-
if keys.length() == 0
|
|
128
|
-
b.write("-")
|
|
129
|
-
for i := range keys.length()
|
|
130
|
-
if i > 0
|
|
131
|
-
b.write(",")
|
|
132
|
-
|
|
136
|
+
keys := if h.keys.isEmpty() then "-" else h.keys.map(|k| "{k}").join(",")
|
|
133
|
-
mask :=
|
|
137
|
+
mask := h.buttons.fold(if h.mouse then 1 else 0, |m, x| m | {1 << x})
|
|
134
|
-
|
|
138
|
+
events := input.events.fold("", |acc, e| "{acc} {Replay.eventCode(e)}")
|
|
135
|
-
|
|
139
|
+
"{keys} {mask} {Replay.floatCode(h.pointer.x)} {Replay.floatCode(h.pointer.y)}{events}\n"
|
|
136
|
-
for i := range input.events.length()
|
|
137
|
-
b.write(" ")
|
|
138
|
-
b.write(Replay.eventCode(input.events.at(i)))
|
|
139
|
-
b.write("\n")
|
|
140
|
-
b.toStr()
|
|
141
140
|
|
|
142
|
-
# One tick's line read back (no newline), or None
|
|
141
|
+
# One tick's line read back (no newline), or None; `v1`, a line of a `plum-replay 1`,
|
|
142
|
+
# with the wheel's turn after the pointer.
|
|
143
|
-
fun parseLine(l: Str) -> Option<Input> =
|
|
143
|
+
fun parseLine(l: Str, v1: Bool) -> Option<Input> =
|
|
144
144
|
t := l.split(" ", 0)
|
|
145
|
+
first := if v1 then 5 else 4
|
|
145
|
-
mask := if t.length() <
|
|
146
|
+
mask := if t.length() < first then -1 else Int.parse(t.at(1)).ok().unwrapOr(-1)
|
|
146
147
|
if mask < 0 || mask > 7
|
|
147
148
|
None
|
|
148
149
|
else
|
|
149
|
-
keys := if t.at(0) == "-" then Some(
|
|
150
|
+
keys := if t.at(0) == "-" then Some(Nil) else Replay.parseKeys(t.at(0).split(",", 0), 0)
|
|
150
151
|
held := keys?
|
|
151
152
|
x := Replay.parseFloatCode(t.at(2))?
|
|
152
153
|
y := Replay.parseFloatCode(t.at(3))?
|
|
154
|
+
dy := if v1 then Replay.parseFloatCode(t.at(4)) else Some(0.0)
|
|
155
|
+
wheel := dy?
|
|
153
|
-
|
|
156
|
+
events := Replay.parseEvents(t, first)?
|
|
154
|
-
|
|
157
|
+
buttons := [if {mask & 2} != 0 then Mouse.Right, if {mask & 4} != 0 then Mouse.Middle]
|
|
155
|
-
buttons := Slice<Int>()
|
|
156
|
-
if {mask & 2} != 0
|
|
157
|
-
buttons.push(Mouse.Right)
|
|
158
|
-
if {mask & 4} != 0
|
|
159
|
-
buttons.push(Mouse.Middle)
|
|
160
|
-
Some(Input(held: Held(mouse: {mask & 1} != 0, keys: held, buttons: buttons
|
|
158
|
+
Some(Input(events: events.append([if wheel != 0.0 then Wheel(dy: wheel)]), held: Held(mouse: {mask & 1} != 0, keys: held, buttons: buttons, pointer: Vec2(x: x, y: y))))
|
|
161
159
|
|
|
162
|
-
fun parseKeys(ks: Slice<Str>, i: Int
|
|
160
|
+
fun parseKeys(ks: Slice<Str>, i: Int) -> Option<List<Int>> =
|
|
163
161
|
if i >= ks.length()
|
|
164
|
-
Some(
|
|
162
|
+
Some(Nil)
|
|
165
163
|
else
|
|
166
|
-
|
|
164
|
+
k := Int.parse(ks.at(i)).ok()?
|
|
167
|
-
Some(k) =>
|
|
168
|
-
out.push(k)
|
|
169
|
-
|
|
165
|
+
rest := Replay.parseKeys(ks, i + 1)?
|
|
170
|
-
|
|
166
|
+
Some(Cons(k, rest))
|
|
171
167
|
|
|
172
|
-
fun parseEvents(t: Slice<Str>, i: Int
|
|
168
|
+
fun parseEvents(t: Slice<Str>, i: Int) -> Option<List<InputEvent>> =
|
|
173
169
|
if i >= t.length()
|
|
174
|
-
Some(
|
|
170
|
+
Some(Nil)
|
|
175
171
|
else
|
|
176
|
-
|
|
172
|
+
e := Replay.parseEvent(t.at(i))?
|
|
177
|
-
Some(e) =>
|
|
178
|
-
out.push(e)
|
|
179
|
-
|
|
173
|
+
rest := Replay.parseEvents(t, i + 1)?
|
|
180
|
-
|
|
174
|
+
Some(Cons(e, rest))
|
|
181
175
|
|
|
182
176
|
# `x` exactly, as `m` or `m:e` for the integer m times 2^e, or as `-0`, `inf`, `-inf` or
|
|
183
177
|
# `nan`.
|
|
@@ -226,6 +220,7 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
|
226
220
|
PointerMove(x, y) => "M{Replay.floatCode(x)},{Replay.floatCode(y)}"
|
|
227
221
|
ButtonDown(n, x, y) => "B{n},{Replay.floatCode(x)},{Replay.floatCode(y)}"
|
|
228
222
|
ButtonUp(n, x, y) => "b{n},{Replay.floatCode(x)},{Replay.floatCode(y)}"
|
|
223
|
+
Wheel(dy) => "W{Replay.floatCode(dy)}"
|
|
229
224
|
|
|
230
225
|
fun parseEvent(tok: Str) -> Option<InputEvent> =
|
|
231
226
|
if tok.length() < 2
|
|
@@ -235,6 +230,8 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
|
235
230
|
rest := tok.sub(1, tok.length())
|
|
236
231
|
if kind == 75 || kind == 107
|
|
237
232
|
Int.parse(rest).ok().map(|k| if kind == 75 then KeyDown(key: k) else KeyUp(key: k))
|
|
233
|
+
else if kind == 87
|
|
234
|
+
Replay.parseFloatCode(rest).map(|dy| Wheel(dy: dy))
|
|
238
235
|
else if kind == 66 || kind == 98
|
|
239
236
|
parts := rest.split(",", 2)
|
|
240
237
|
if parts.length() != 2
|
std/game/Screen.plum
CHANGED
|
@@ -78,9 +78,9 @@ import std/game/ScreenSlice
|
|
|
78
78
|
# deliver std's, not the screen's: how the game runs one tick of the screen. A
|
|
79
79
|
# plain screen's steps its actors; a slice's delivers the tick as actions
|
|
80
80
|
# and steps them before its tick action.
|
|
81
|
-
# wants std's too: whether what is held
|
|
81
|
+
# wants std's too: whether what is held after the tick's input gives an
|
|
82
|
-
# screen something to do. A plain screen's is never; a slice's
|
|
82
|
+
# `OnDemand` screen something to do. A plain screen's is never; a slice's
|
|
83
|
-
# `held(
|
|
83
|
+
# is its `held(h)` giving an action.
|
|
84
84
|
#
|
|
85
85
|
# The game keeps a screen as it is when it goes to another, so coming back shows it as it
|
|
86
86
|
# was left.
|
|
@@ -118,7 +118,7 @@ trait Screen =
|
|
|
118
118
|
|
|
119
119
|
fun deliver(self, d: Delivery) -> Delivered = Delivered(screen: d.stepScreen(self))
|
|
120
120
|
|
|
121
|
-
fun wants(self,
|
|
121
|
+
fun wants(self, h: Held) -> Bool = false
|
|
122
122
|
|
|
123
123
|
# One tick of a screen, delivered: the screen after it, the commands its actions gave for
|
|
124
124
|
# the game (std/game/Cmd), in order, the actions stepped, and whether the tick was a user
|
std/game/ScreenSlice.plum
CHANGED
|
@@ -10,6 +10,7 @@ import std/collections/List
|
|
|
10
10
|
import std/math/Vec2
|
|
11
11
|
import std/game/Input
|
|
12
12
|
import std/game/View
|
|
13
|
+
import std/game/Button
|
|
13
14
|
import std/game/Viewport
|
|
14
15
|
import std/game/Cmd
|
|
15
16
|
import std/game/Screen
|
|
@@ -54,11 +55,19 @@ import std/game/Screen
|
|
|
54
55
|
# `hud`, or else of its view, under the press that takes presses
|
|
55
56
|
# (`Sized` and `Enabled`, std/game/View's `Views.hitIn`) and the press
|
|
56
57
|
# in the world's coordinates; if it gives None, or the press is on
|
|
57
|
-
# no such item, `onPointer` is asked as for any pointer event
|
|
58
|
+
# no such item, `onPointer` is asked as for any pointer event. By
|
|
59
|
+
# default it is what the item says a press on it means: the
|
|
60
|
+
# `pressed()` of an item that `Presses<A>` (std/game/Button: a
|
|
61
|
+
# `Button(.., on: Tapped)`, or an actor of your own), None for
|
|
62
|
+
# any other
|
|
58
63
|
# a pointer event `onPointer(e, at)`, with the event's point in the world
|
|
59
64
|
# (through the screen's camera)
|
|
65
|
+
# a wheel turn `onPointer(e, at)`, at where the pointer is after the tick's
|
|
66
|
+
# events
|
|
60
|
-
# While a transition runs, the pointer events are dropped: only keys
|
|
67
|
+
# While a transition runs, the pointer events and the wheel are dropped: only keys
|
|
68
|
+
# come.
|
|
61
|
-
# 2. `held(
|
|
69
|
+
# 2. `held(h)`: an action for what is held after the events (`Held`, std/game/Input:
|
|
70
|
+
# the steering keys), every tick.
|
|
62
71
|
# 3. The game has the screen step its `Actor`s (`stepped(dt)`, std/game/Screen), unless
|
|
63
72
|
# its `steps()` is false.
|
|
64
73
|
# 4. `tick(dt)`: the tick action, which sees the actors stepped and runs the rules.
|
|
@@ -77,15 +86,17 @@ trait ScreenSlice<A>[Screen] =
|
|
|
77
86
|
|
|
78
87
|
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<A> = None
|
|
79
88
|
|
|
80
|
-
fun onPress(self, target: View, at: Vec2) -> Option<A> =
|
|
89
|
+
fun onPress(self, target: View, at: Vec2) -> Option<A> = match target
|
|
90
|
+
Presses<A> as p => Some(p.pressed())
|
|
91
|
+
_ => None
|
|
81
92
|
|
|
82
|
-
fun held(self,
|
|
93
|
+
fun held(self, h: Held) -> Option<A> = None
|
|
83
94
|
|
|
84
95
|
fun tick(self, dt: Float) -> Option<A> = None
|
|
85
96
|
|
|
86
97
|
# std's: whether what is held gives an `OnDemand` screen something to do: its `held`
|
|
87
98
|
# maps it to an action.
|
|
88
|
-
fun wants(self,
|
|
99
|
+
fun wants(self, h: Held) -> Bool = self.held(h).isSome()
|
|
89
100
|
|
|
90
101
|
# std's: one tick of the screen, delivered as actions (see the top of this file).
|
|
91
102
|
fun deliver(self, d: Delivery) -> Delivered = Delivery.deliverTo<A, Self>(self, d)
|
|
@@ -136,13 +147,13 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
136
147
|
# and its `tick` over the slice.
|
|
137
148
|
fun deliverTo<A, S: ScreenSlice<A>>(s: S, d: Delivery) -> Delivered =
|
|
138
149
|
none: Trail<A> := Trail()
|
|
139
|
-
afterEvents := d.eventsInto<A, S>(s, none,
|
|
150
|
+
afterEvents := d.eventsInto<A, S>(s, none, d.input.events)
|
|
140
151
|
match afterEvents
|
|
141
152
|
Folded(cur, trail) => d.heldInto<A, S>(cur, trail)
|
|
142
153
|
|
|
143
154
|
# The slice `s` after its `held`, its actors' step and its `tick`, delivered.
|
|
144
155
|
fun heldInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>) -> Delivered =
|
|
145
|
-
h := s.held(self.input)
|
|
156
|
+
h := s.held(self.input.held)
|
|
146
157
|
afterHeld := match h
|
|
147
158
|
Some(a) => Delivery.actIn<A, S>(s, trail.user(!self.before.same(self.input.held)), a)
|
|
148
159
|
None => Folded(state: s, trail: trail)
|
|
@@ -156,17 +167,16 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
156
167
|
Some(a) => Delivery.done<A, S>(Delivery.actIn<A, S>(s, trail, a))
|
|
157
168
|
None => Delivery.done<A, S>(Folded(state: s, trail: trail))
|
|
158
169
|
|
|
159
|
-
# The slice `s` after the tick's events
|
|
170
|
+
# The slice `s` after the tick's events `es`.
|
|
160
|
-
fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>,
|
|
171
|
+
fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, es: List<InputEvent>) -> Folded<S, A> = match es
|
|
161
|
-
if i >= self.input.events.length()
|
|
162
|
-
|
|
172
|
+
Nil => Folded(state: s, trail: trail)
|
|
163
|
-
|
|
173
|
+
Cons(e, rest) =>
|
|
164
|
-
f := self.eventInto<A, S>(s, trail,
|
|
174
|
+
f := self.eventInto<A, S>(s, trail, e)
|
|
165
175
|
match f
|
|
166
|
-
Folded(next, after) => self.eventsInto<A, S>(next, after,
|
|
176
|
+
Folded(next, after) => self.eventsInto<A, S>(next, after, rest)
|
|
167
177
|
|
|
168
|
-
# The slice `s` after the event `e`, mapped to its action; a pointer event
|
|
178
|
+
# The slice `s` after the event `e`, mapped to its action; a pointer event or a wheel
|
|
169
|
-
# transition runs is dropped.
|
|
179
|
+
# turn while a transition runs is dropped.
|
|
170
180
|
fun eventInto<A, S: ScreenSlice<A>>(self, s: S, trail: Trail<A>, e: InputEvent) -> Folded<S, A> =
|
|
171
181
|
act := match e.position()
|
|
172
182
|
Some(p) =>
|
|
@@ -179,7 +189,14 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
179
189
|
Some(t) => s.onPress(t, at)
|
|
180
190
|
None => None
|
|
181
191
|
if pressed.isSome() then pressed else s.onPointer(e, at)
|
|
182
|
-
None =>
|
|
192
|
+
None =>
|
|
193
|
+
if !e.isWheel()
|
|
194
|
+
s.onKey(e)
|
|
195
|
+
else if self.shifting
|
|
196
|
+
None
|
|
197
|
+
else
|
|
198
|
+
p := self.input.held.pointer
|
|
199
|
+
s.onPointer(e, self.camera.toWorld(p.x, p.y))
|
|
183
200
|
match act
|
|
184
201
|
Some(a) => Delivery.actIn<A, S>(s, trail.user(true), a)
|
|
185
202
|
None => Folded(state: s, trail: trail)
|
std/game/TestRig.plum
CHANGED
|
@@ -83,11 +83,11 @@ import std/game/Game
|
|
|
83
83
|
# `TestRig.playWith(io, game)` switch the game's history on. Then `rewindTo(k)`, `undo()`, `redo()`,
|
|
84
84
|
# `stepBack()`, `stepForward()`, `pause()` and `resume()` move the game through it, and
|
|
85
85
|
# `moved()` says whether the last move could.
|
|
86
|
-
# A game run headless (see the top of this file): the window's size, what is held
|
|
86
|
+
# A game run headless (see the top of this file): the window's size, what is held (the
|
|
87
|
-
# waiting for the next tick,
|
|
87
|
+
# pointer too), the input waiting for the next tick, what the last ticks gave (the actions stepped,
|
|
88
88
|
# the commands they gave), and the ticker and recording of `frame` and `record`.
|
|
89
89
|
struct TestRig<S>(
|
|
90
|
-
io: Io, game: Game, screen: S, pixels: Vec2, held: Held, events: List<InputEvent>,
|
|
90
|
+
io: Io, game: Game, screen: S, pixels: Vec2, held: Held, events: List<InputEvent>,
|
|
91
91
|
sent: List<Dispatched>, cmds: List<Cmd>, ticker: Ticker, recording: Bool, log: Replay) =
|
|
92
92
|
const DefaultW = 800.0
|
|
93
93
|
|
|
@@ -112,7 +112,7 @@ struct TestRig<S>(
|
|
|
112
112
|
fun rigOf<T>(io: Io, game: Game, screen: T) -> TestRig<T> =
|
|
113
113
|
pixels := Vec2(x: TestRig.DefaultW, y: TestRig.DefaultH)
|
|
114
114
|
TestRig(
|
|
115
|
-
io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held(), events: Nil,
|
|
115
|
+
io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held(), events: Nil,
|
|
116
116
|
sent: Nil, cmds: Nil, ticker: Ticker(), recording: false, log: Replay.create(0))
|
|
117
117
|
|
|
118
118
|
# Stops a test that clicks an actor in neither the view nor the hud.
|
|
@@ -127,9 +127,9 @@ struct TestRig<S>(
|
|
|
127
127
|
fun press(self, key: Int) -> TestRig<S> =
|
|
128
128
|
TestRig(..self, events: self.events.append([KeyDown(key: key), KeyUp(key: key)]), held: self.held.after(KeyUp(key: key)))
|
|
129
129
|
|
|
130
|
-
fun hold(self, key: Int) -> TestRig<S> = if self.held.
|
|
130
|
+
fun hold(self, key: Int) -> TestRig<S> = if self.held.isKeyDown(key) then self else self.send(KeyDown(key: key))
|
|
131
131
|
|
|
132
|
-
fun release(self, key: Int) -> TestRig<S> = if self.held.
|
|
132
|
+
fun release(self, key: Int) -> TestRig<S> = if self.held.isKeyDown(key) then self.send(KeyUp(key: key)) else self
|
|
133
133
|
|
|
134
134
|
fun click(self, a: View) -> TestRig<S> =
|
|
135
135
|
p := self.centreOf(a)
|
|
@@ -140,11 +140,11 @@ struct TestRig<S>(
|
|
|
140
140
|
fun pointerMove(self, x: Float, y: Float) -> TestRig<S> = self.send(PointerMove(x: x, y: y))
|
|
141
141
|
|
|
142
142
|
fun send(self, e: InputEvent) -> TestRig<S> =
|
|
143
|
-
TestRig(..self, events: self.events.append([e]), held: self.held.after(e)
|
|
143
|
+
TestRig(..self, events: self.events.append([e]), held: self.held.after(e))
|
|
144
144
|
|
|
145
145
|
# The next tick's input is exactly `held` and `events`, whatever was waiting.
|
|
146
146
|
fun next(self, held: Held, events: List<InputEvent>) -> TestRig<S> =
|
|
147
|
-
TestRig(..self, held: held, events: events
|
|
147
|
+
TestRig(..self, held: held, events: events)
|
|
148
148
|
|
|
149
149
|
# Where the actor `a` is clicked, in screen pixels: the centre of its bounds if it is
|
|
150
150
|
# `Sized`, else its origin, through its transform and the screen's camera (or, for an
|
|
@@ -189,7 +189,7 @@ struct TestRig<S>(
|
|
|
189
189
|
S as sl =>
|
|
190
190
|
d := Delivery.dispatchTo<A, S>(sl, a)
|
|
191
191
|
withScreen := Game(..g, screens: Game.setAt(g.screens, g.current, d.screen), wake: true, dirty: true, sent: d.sent, cmds: d.cmds)
|
|
192
|
-
TestRig(..self.forget(), game: withScreen).kept(
|
|
192
|
+
TestRig(..self.forget(), game: withScreen).kept(withScreen.obeyAll(self.io, d.cmds).travelAsked(self.io))
|
|
193
193
|
_ =>
|
|
194
194
|
crash "headless: dispatch: the screen shown is not the rig's screen"
|
|
195
195
|
|
|
@@ -198,7 +198,7 @@ struct TestRig<S>(
|
|
|
198
198
|
|
|
199
199
|
# One tick with the input waiting, keeping what it gave.
|
|
200
200
|
fun step(self, dt: Float) -> TestRig<S> =
|
|
201
|
-
input := Input(
|
|
201
|
+
input := Input(events: self.events, held: self.held)
|
|
202
202
|
TestRig(..self, events: Nil).ran1(input, dt)
|
|
203
203
|
|
|
204
204
|
# One tick of the game with `input`, recorded while recording.
|
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -154,7 +154,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
154
154
|
assert v.screen.pops == 2
|
|
155
155
|
assert PlaygroundScreenHelpers.bursting(v.screen) == bursts
|
|
156
156
|
assert v.game.tickNow() == at + 1
|
|
157
|
-
w := v.frame(Input(
|
|
157
|
+
w := v.frame(Input(events: [KeyDown(key: Key.Backspace)]), Ticker.Tick)
|
|
158
158
|
assert w.screen.pops == 1
|
|
159
159
|
assert w.game.tickNow() == at - 1
|
|
160
160
|
x := w.press(Key.Backspace).tick()
|
|
@@ -200,10 +200,7 @@ primitive PlaygroundScreenHelpers =
|
|
|
200
200
|
fun lines(t: TestRig<PlaygroundScreen>) -> Str = t.find<Label>().map(|l| l.text).join(", ")
|
|
201
201
|
|
|
202
202
|
fun runInput(i: Int) -> Input =
|
|
203
|
-
events := Slice<InputEvent>()
|
|
204
|
-
if i % 7 == 6
|
|
205
|
-
|
|
203
|
+
Input(events: [if i % 7 == 6 then PointerDown(x: Float({i * 37} % 760 + 20), y: Float({i * 53} % 500 + 50))])
|
|
206
|
-
Input(held: Held(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
207
204
|
|
|
208
205
|
fun sameField(a: PlaygroundScreen, b: PlaygroundScreen) -> Bool =
|
|
209
206
|
a.pops == b.pops && a.clock == b.clock && a.partyAt == b.partyAt && a.rng.seed == b.rng.seed
|
tests/examples/games/clicks.plum
CHANGED
|
@@ -10,6 +10,7 @@ import std/game/Input
|
|
|
10
10
|
import std/game/Place
|
|
11
11
|
import std/game/View
|
|
12
12
|
import std/game/Box
|
|
13
|
+
import std/game/Button
|
|
13
14
|
import std/game/Circle
|
|
14
15
|
import std/game/Label
|
|
15
16
|
import std/game/Screen
|
|
@@ -20,10 +21,16 @@ import examples/games/clicks
|
|
|
20
21
|
import std/Test
|
|
21
22
|
|
|
22
23
|
primitive ClicksTest[UnitTest] =
|
|
23
|
-
# a click on the
|
|
24
|
+
# a click on the button counts, one beside it does not, and Right rolls the ball
|
|
24
|
-
fun
|
|
25
|
+
fun aClickOnTheButtonCountsOneBeside() =
|
|
25
26
|
t := TestRig.mount(io, TapScreen.start())
|
|
27
|
+
on := match t.hit(400.0, 300.0).unwrap()
|
|
28
|
+
Button<TapAction> as b => b.on
|
|
29
|
+
_ => Quit
|
|
30
|
+
assert match on
|
|
31
|
+
Tapped => true
|
|
32
|
+
_ => false
|
|
26
|
-
u := t.
|
|
33
|
+
u := t.clickAt(400.0, 300.0).tick().clickAt(10.0, 10.0).tick()
|
|
27
34
|
assert u.screen.taps == 1
|
|
28
35
|
assert u.text(u.first<Label>()) == "Taps: 1"
|
|
29
36
|
v := u.hold(Key.Right).ticks(60)
|
tests/examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -199,7 +199,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
199
199
|
# the arrows and WASD steer alike, and the axes cancel when both ways are held
|
|
200
200
|
fun theArrowsAndWASDSteerAlikeAndThe() =
|
|
201
201
|
p := PlayingScreenHelpers.mounted(io, 7, 0, 3).screen
|
|
202
|
-
steer := |keys: List<Int>| p.held(
|
|
202
|
+
steer := |keys: List<Int>| p.held(Held(keys: keys)).unwrap().toStr()
|
|
203
203
|
assert steer([Key.Left, Key.KeyW]) == "Steer(-1.0, -1.0)"
|
|
204
204
|
assert steer([Key.KeyD, Key.Down]) == "Steer(1.0, 1.0)"
|
|
205
205
|
assert steer([Key.Right, Key.KeyD]) == "Steer(1.0, 0.0)"
|
|
@@ -419,21 +419,14 @@ primitive PlayingScreenHelpers =
|
|
|
419
419
|
s := p.ship.at
|
|
420
420
|
target := p.orbs.fold(p.orbs.at(0), |best, o|
|
|
421
421
|
if Math.hypot(o.at.x - s.x, o.at.y - s.y) < Math.hypot(best.at.x - s.x, best.at.y - s.y) then o else best)
|
|
422
|
-
keys :=
|
|
422
|
+
keys := [
|
|
423
|
-
|
|
423
|
+
if target.at.x > s.x + 4.0 then Key.Right
|
|
424
|
-
keys.push(Key.Right)
|
|
425
|
-
|
|
424
|
+
if target.at.x < s.x - 4.0 then Key.KeyA
|
|
426
|
-
keys.push(Key.KeyA)
|
|
427
|
-
|
|
425
|
+
if target.at.y > s.y + 4.0 then Key.Down
|
|
428
|
-
keys.push(Key.Down)
|
|
429
|
-
|
|
426
|
+
if target.at.y < s.y - 4.0 then Key.KeyW
|
|
430
|
-
keys.push(Key.KeyW)
|
|
431
|
-
events := Slice<InputEvent>()
|
|
432
|
-
|
|
427
|
+
]
|
|
433
|
-
events.push(KeyDown(key: Key.Enter))
|
|
434
428
|
pos := Vec2(x: Float(i) * 0.37, y: 300.0 - Float(i) * 0.11)
|
|
435
|
-
events.push(PointerMove(x: pos.x, y: pos.y))
|
|
436
|
-
Input(
|
|
429
|
+
Input(events: [if i % 150 == 149 then KeyDown(key: Key.Enter), PointerMove(x: pos.x, y: pos.y)], held: Held(keys: keys, pointer: pos))
|
|
437
430
|
|
|
438
431
|
fun frameDt(f: Int) -> Float = 0.0166 + Float(f % 3) * 0.004 - 0.004
|
|
439
432
|
|
tests/port/game/determinism.plum
CHANGED
|
@@ -18,9 +18,10 @@ 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
|
-
#
|
|
21
|
+
# A press of Space, what a tick saw held (from `held`), and the tick itself.
|
|
22
22
|
enum Saw =
|
|
23
|
+
| Pressed
|
|
23
|
-
| Seen(
|
|
24
|
+
| Seen(spaceHeld: Bool)
|
|
24
25
|
| Ticked(dt: Float)
|
|
25
26
|
|
|
26
27
|
# The one screen of a `Game` for these tests: it counts ticks, adds up and bounds `dt`,
|
|
@@ -31,19 +32,17 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, time: Float, minDt: Floa
|
|
|
31
32
|
|
|
32
33
|
fun name(self) -> Str = "probe"
|
|
33
34
|
|
|
35
|
+
fun onKey(self, e: InputEvent) -> Option<Saw> = if e.isKeyDownOf(Key.Space) then Some(Pressed) else None
|
|
36
|
+
|
|
34
|
-
fun held(self,
|
|
37
|
+
fun held(self, h: Held) -> Option<Saw> = Some(Seen(spaceHeld: h.isKeyDown(Key.Space)))
|
|
35
38
|
|
|
36
39
|
fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked(dt: dt))
|
|
37
40
|
|
|
38
41
|
fun reduce(self, saw: Saw) -> Probe = match saw
|
|
39
|
-
|
|
42
|
+
Pressed =>
|
|
40
43
|
r := self.rng.nextInt()
|
|
41
|
-
Probe(
|
|
42
|
-
..self,
|
|
43
|
-
rng: if pressed then r.rng else self.rng,
|
|
44
|
-
|
|
44
|
+
Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value)
|
|
45
|
-
|
|
45
|
+
Seen(spaceHeld) => Probe(..self, held: if spaceHeld then self.held + 1 else self.held)
|
|
46
|
-
roll: if pressed then self.roll ^ r.value else self.roll)
|
|
47
46
|
Ticked(dt) => Probe(..self, ticks: self.ticks + 1, time: self.time + dt, minDt: self.minDt.min(dt), maxDt: self.maxDt.max(dt))
|
|
48
47
|
|
|
49
48
|
fun same(self, o: Probe) -> Bool =
|
|
@@ -69,26 +68,17 @@ primitive Determinism =
|
|
|
69
68
|
Run(game: probeGame(seed), clock: Ticker())
|
|
70
69
|
|
|
71
70
|
fun still() -> Input =
|
|
72
|
-
Input
|
|
71
|
+
Input()
|
|
73
72
|
|
|
74
73
|
# Space held from the start, with its KeyDown when `down`.
|
|
75
74
|
fun space(down: Bool) -> Input =
|
|
76
|
-
events := Slice<InputEvent>()
|
|
77
|
-
if down
|
|
78
|
-
events.push(KeyDown(key: Key.Space))
|
|
79
|
-
Input(
|
|
75
|
+
Input(events: [if down then KeyDown(key: Key.Space)], held: Held(keys: [Key.Space]))
|
|
80
76
|
|
|
81
77
|
# Frame `i` of a scripted run: Space goes down on frames 3 and 20 and up on 10 and 25.
|
|
82
78
|
fun scripted(i: Int) -> Input =
|
|
83
|
-
events := Slice<InputEvent>()
|
|
84
|
-
if i == 3 || i == 20
|
|
85
|
-
|
|
79
|
+
events := [if i == 3 || i == 20 then KeyDown(key: Key.Space), if i == 10 || i == 25 then KeyUp(key: Key.Space)]
|
|
86
|
-
if i == 10 || i == 25
|
|
87
|
-
events.push(KeyUp(key: Key.Space))
|
|
88
|
-
keys := Slice<Int>()
|
|
89
|
-
if {i >= 3 && i < 10} || {i >= 20 && i < 25}
|
|
80
|
+
keys := if {i >= 3 && i < 10} || {i >= 20 && i < 25} then [Key.Space] else Nil
|
|
90
|
-
keys.push(Key.Space)
|
|
91
|
-
Input(
|
|
81
|
+
Input(events: events, held: Held(keys: keys))
|
|
92
82
|
|
|
93
83
|
# A jittery frame time around 1/60 s for frame `i`.
|
|
94
84
|
fun jitter(i: Int) -> Float =
|
tests/port/game/replay.plum
CHANGED
|
@@ -20,9 +20,10 @@ 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
|
-
#
|
|
23
|
+
# A press of Space or a click, what a tick saw held (from `held`), and the tick itself.
|
|
24
24
|
enum Saw =
|
|
25
|
+
| Pressed
|
|
25
|
-
| Seen(
|
|
26
|
+
| Seen(spaceHeld: Bool, x: Float, y: Float)
|
|
26
27
|
| Ticked(dt: Float)
|
|
27
28
|
|
|
28
29
|
# The one screen of a `Game` for these tests: it counts ticks, follows the pointer, counts
|
|
@@ -36,22 +37,19 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, presses: Int, held: Int,
|
|
|
36
37
|
|
|
37
38
|
fun name(self) -> Str = "probe"
|
|
38
39
|
|
|
39
|
-
fun
|
|
40
|
+
fun onKey(self, e: InputEvent) -> Option<Saw> = if e.isKeyDownOf(Key.Space) then Some(Pressed) else None
|
|
41
|
+
|
|
42
|
+
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<Saw> = if e.isPointerDown() then Some(Pressed) else None
|
|
43
|
+
|
|
40
|
-
|
|
44
|
+
fun held(self, h: Held) -> Option<Saw> = Some(Seen(spaceHeld: h.isKeyDown(Key.Space), x: h.pointer.x, y: h.pointer.y))
|
|
41
45
|
|
|
42
46
|
fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked(dt: dt))
|
|
43
47
|
|
|
44
48
|
fun reduce(self, saw: Saw) -> Probe = match saw
|
|
45
|
-
|
|
49
|
+
Pressed =>
|
|
46
50
|
r := self.rng.nextInt()
|
|
47
|
-
Probe(
|
|
48
|
-
..self,
|
|
49
|
-
rng: if pressed then r.rng else self.rng,
|
|
50
|
-
|
|
51
|
+
Probe(..self, rng: r.rng, presses: self.presses + 1, roll: self.roll ^ r.value)
|
|
51
|
-
|
|
52
|
+
Seen(spaceHeld, x, y) => Probe(..self, held: if spaceHeld then self.held + 1 else self.held, px: x, py: y)
|
|
52
|
-
roll: if pressed then self.roll ^ r.value else self.roll,
|
|
53
|
-
px: x,
|
|
54
|
-
py: y)
|
|
55
53
|
Ticked(dt) => Probe(..self, ticks: self.ticks + 1, x: self.x + self.px * dt, y: self.y + self.py * dt)
|
|
56
54
|
|
|
57
55
|
fun same(self, o: Probe) -> Bool =
|
|
@@ -69,10 +67,10 @@ primitive ReplayTest[UnitTest] =
|
|
|
69
67
|
# replay_roundtrip
|
|
70
68
|
fun replayRoundtrip() =
|
|
71
69
|
r := Replay(seed: -6917529027641081853, width: 800, height: 600, ticks: Slice<Input>())
|
|
72
|
-
r.ticks.push(Input
|
|
73
|
-
r.ticks.push(Input(
|
|
74
|
-
r.ticks.push(Input(held: Held(keys: [Key.Up]
|
|
75
|
-
r.ticks.push(Input(
|
|
70
|
+
r.ticks.push(Input())
|
|
71
|
+
r.ticks.push(Input(events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), Wheel(dy: -1.0), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)], held: Held(mouse: true, keys: [Key.Left, Key.Space], pointer: Vec2(x: 0.1, y: 1.0e-300))))
|
|
72
|
+
r.ticks.push(Input(events: [Wheel(dy: 0.1)], held: Held(keys: [Key.Up], pointer: Vec2(x: 0.3, y: 0.7))))
|
|
73
|
+
r.ticks.push(Input(events: [ButtonDown(button: Mouse.Right, x: 1.5, y: -2.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 3.0)], held: Held(mouse: true, buttons: [Mouse.Middle, Mouse.Right], pointer: Vec2(x: 1.5, y: -2.0))))
|
|
76
74
|
text := r.encode()
|
|
77
75
|
if Ok(back) := Replay.decode(text)
|
|
78
76
|
assert back.seed == r.seed
|
|
@@ -83,10 +81,12 @@ primitive ReplayTest[UnitTest] =
|
|
|
83
81
|
assert back.at(3).held.same(r.at(3).held)
|
|
84
82
|
for i := range 4
|
|
85
83
|
assert Replay.sameInput(back.at(i), r.at(i))
|
|
86
|
-
assert back.at(1).
|
|
84
|
+
assert back.at(1).held.pointer.x == 0.1
|
|
87
|
-
assert back.at(1).
|
|
85
|
+
assert back.at(1).held.pointer.y == 1.0e-300
|
|
86
|
+
assert back.at(2).events.length() == 1 && back.at(2).events.any(|e| match e
|
|
88
|
-
|
|
87
|
+
Wheel(dy) => dy == 0.1
|
|
88
|
+
_ => false)
|
|
89
|
-
if Some(p) := back.at(1).events.at(
|
|
89
|
+
if Some(p) := back.at(1).events.at(5).position()
|
|
90
90
|
assert p.x == 1.0e-300
|
|
91
91
|
else
|
|
92
92
|
assert false
|
|
@@ -114,7 +114,7 @@ primitive ReplayTest[UnitTest] =
|
|
|
114
114
|
run := recorded(io, 5, 60)
|
|
115
115
|
idle := Slice<Input>()
|
|
116
116
|
for i := range run.log.length()
|
|
117
|
-
idle.push(Input
|
|
117
|
+
idle.push(Input())
|
|
118
118
|
still := replayed(io, Replay(seed: 5, width: 0, height: 0, ticks: idle), 80)
|
|
119
119
|
assert still.probe().ticks == run.probe().ticks
|
|
120
120
|
assert !still.probe().same(run.probe())
|
|
@@ -126,7 +126,7 @@ primitive ReplayTest[UnitTest] =
|
|
|
126
126
|
assert due.length() == 3
|
|
127
127
|
assert due.at(0).events.length() == 1
|
|
128
128
|
assert due.at(1).events.length() == 0
|
|
129
|
-
assert due.at(2).isKeyDown(Key.Space)
|
|
129
|
+
assert due.at(2).held.isKeyDown(Key.Space)
|
|
130
130
|
assert c.ticks == 0
|
|
131
131
|
|
|
132
132
|
# a Float is written exactly and read back to the same value
|
|
@@ -168,11 +168,13 @@ primitive ReplayTest[UnitTest] =
|
|
|
168
168
|
assert Replay.parseFloatCode("inf").unwrapOr(0.0) == inf
|
|
169
169
|
assert Replay.parseFloatCode("-inf").unwrapOr(0.0) == -inf
|
|
170
170
|
assert Replay.parseFloatCode("nan").unwrapOr(0.0).isNaN()
|
|
171
|
-
odd := Input(
|
|
171
|
+
odd := Input(events: [PointerMove(x: negZero, y: inf), Wheel(dy: 0.0 / 0.0)], held: Held(pointer: Vec2(x: negZero, y: Float.Min)))
|
|
172
|
-
if Some(back) := Replay.parseLine(Replay.line(odd).trim())
|
|
172
|
+
if Some(back) := Replay.parseLine(Replay.line(odd).trim(), false)
|
|
173
|
-
assert 1.0 / back.
|
|
173
|
+
assert 1.0 / back.held.pointer.x < 0.0
|
|
174
|
-
assert back.
|
|
174
|
+
assert back.held.pointer.y == Float.Min
|
|
175
|
-
assert back.
|
|
175
|
+
assert back.events.any(|e| match e
|
|
176
|
+
Wheel(dy) => dy.isNaN()
|
|
177
|
+
_ => false)
|
|
176
178
|
assert Replay.line(back) == Replay.line(odd)
|
|
177
179
|
else
|
|
178
180
|
assert false
|
|
@@ -190,11 +192,17 @@ primitive ReplayTest[UnitTest] =
|
|
|
190
192
|
assert r.width == 1024
|
|
191
193
|
else
|
|
192
194
|
assert false
|
|
195
|
+
assert Replay.decode("plum-replay 2 {hi} {lo} 1024 768\n").unwrap().seed == seed
|
|
193
|
-
assert Replay.header(seed, 1, 2) == "plum-replay
|
|
196
|
+
assert Replay.header(seed, 1, 2) == "plum-replay 2 -123456789 4294967291 1 2\n"
|
|
194
197
|
|
|
195
198
|
fun aBadReplaySaysWhatIsWrong() =
|
|
196
199
|
assert Replay.decode("").isErr()
|
|
197
|
-
assert Replay.decode("plum-replay
|
|
200
|
+
assert Replay.decode("plum-replay 3 0 0 0 0\n").isErr()
|
|
201
|
+
assert Replay.decode("plum-replay 2 0 0 0 0\n- 0 0 0\n- 9 0 0\n").isErr()
|
|
202
|
+
assert Replay.decode("plum-replay 2 0 0 0 0\n- 0 0 0 B1,2\n").isErr()
|
|
203
|
+
assert Replay.decode("plum-replay 2 0 0 0 0\n- 0 0 0 Wx\n").isErr()
|
|
204
|
+
assert Replay.decode("plum-replay 2 0 0 0 0\n- 0 0 0 0\n").isErr()
|
|
205
|
+
assert Replay.decode("plum-replay 2 0 0 0 0\r\n- 0 0 0 K32 W1\r\n").isOk()
|
|
198
206
|
assert Replay.decode("plum-replay 1 0 0 x 0\n").isErr()
|
|
199
207
|
assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0\n- 9 0 0 0\n").isErr()
|
|
200
208
|
assert Replay.decode("plum-replay 1 0 0 0 0\n- 0 0 0 0 B1,2\n").isErr()
|
|
@@ -204,15 +212,25 @@ primitive ReplayTest[UnitTest] =
|
|
|
204
212
|
assert why.startsWith("line 3:")
|
|
205
213
|
else
|
|
206
214
|
assert false
|
|
215
|
+
if Err(why) := Replay.decode("plum-replay 2 0 0 0 0\n- 0 0 0\n- 0 0\n")
|
|
216
|
+
assert why.startsWith("line 3:")
|
|
217
|
+
else
|
|
218
|
+
assert false
|
|
207
219
|
|
|
208
|
-
# a replay recorded before the other mouse buttons
|
|
220
|
+
# a `plum-replay 1`, recorded before the other mouse buttons and before the wheel was an
|
|
221
|
+
# event, reads as it did: its wheel column is a `Wheel` after the tick's other events,
|
|
222
|
+
# and it is written again as a `plum-replay 2`
|
|
209
|
-
fun
|
|
223
|
+
fun aReplayOfVersionOneReadsAsItDid() =
|
|
210
224
|
old := "plum-replay 1 0 7 800 600\n32,262 1 3 4 0 D3,4 K32\n- 0 1:-1 2 -1 U1,1 k32\n"
|
|
211
225
|
r := Replay.decode(old).unwrap()
|
|
212
226
|
assert r.length() == 2
|
|
213
|
-
assert r.at(0).held.mouse && r.at(0).held.buttons.isEmpty() && r.at(0).held.
|
|
227
|
+
assert r.at(0).held.mouse && r.at(0).held.buttons.isEmpty() && r.at(0).held.isKeyDown(Key.Space)
|
|
228
|
+
assert r.at(0).events.length() == 2
|
|
214
|
-
assert !r.at(1).held.mouse && r.at(1).
|
|
229
|
+
assert !r.at(1).held.mouse && r.at(1).held.pointer.x == 0.5
|
|
230
|
+
assert r.at(1).events.length() == 3 && r.at(1).events.at(2).isWheel()
|
|
231
|
+
now := "plum-replay 2 0 7 800 600\n32,262 1 3 4 D3,4 K32\n- 0 1:-1 2 U1,1 k32 W-1\n"
|
|
215
|
-
assert r.encode() ==
|
|
232
|
+
assert r.encode() == now
|
|
233
|
+
assert Replay.decode(now).unwrap().encode() == now
|
|
216
234
|
|
|
217
235
|
# std's maths is Plum code made of IEEE 754 double operations and wasm's own `f64.sqrt`,
|
|
218
236
|
# `f64.floor`, ..., which wasm defines exactly, so every browser and the native host compute
|
|
@@ -248,21 +266,17 @@ primitive ReplayTest[UnitTest] =
|
|
|
248
266
|
# Frame `i` of a scripted run: Space goes down on frames 3 and 20 and up on 10 and 25, a
|
|
249
267
|
# click on frame 30, and a pointer that moves by fractions with no short decimal form.
|
|
250
268
|
fun scripted(i: Int) -> Input =
|
|
251
|
-
events := Slice<InputEvent>()
|
|
252
|
-
if i == 3 || i == 20
|
|
253
|
-
events.push(KeyDown(key: Key.Space))
|
|
254
|
-
if i == 10 || i == 25
|
|
255
|
-
events.push(KeyUp(key: Key.Space))
|
|
256
269
|
x := Float(i) * 0.1 + 1.0 / 3.0
|
|
257
270
|
y := 600.0 - Float(i) / 7.0
|
|
258
|
-
|
|
271
|
+
events := [
|
|
272
|
+
if i == 3 || i == 20 then KeyDown(key: Key.Space)
|
|
273
|
+
if i == 10 || i == 25 then KeyUp(key: Key.Space)
|
|
259
|
-
|
|
274
|
+
if i == 30 then PointerDown(x: x, y: y)
|
|
260
|
-
if i == 31
|
|
261
|
-
|
|
275
|
+
if i == 31 then PointerUp(x: x, y: y)
|
|
262
|
-
|
|
276
|
+
if i == 12 then Wheel(dy: 0.1)
|
|
277
|
+
]
|
|
263
|
-
if {i >= 3 && i < 10} || {i >= 20 && i < 25}
|
|
278
|
+
keys := if {i >= 3 && i < 10} || {i >= 20 && i < 25} then [Key.Space] else Nil
|
|
264
|
-
keys.push(Key.Space)
|
|
265
|
-
Input(held: Held(mouse: i == 30, keys: keys,
|
|
279
|
+
Input(events: events, held: Held(mouse: i == 30, keys: keys, pointer: Vec2(x: x, y: y)))
|
|
266
280
|
|
|
267
281
|
# A jittery frame time around 1/60 s for frame `i`.
|
|
268
282
|
fun jitter(i: Int) -> Float =
|
tests/port/game/screens.plum
CHANGED
|
@@ -20,6 +20,7 @@ import std/game/Replay
|
|
|
20
20
|
import std/game/Place
|
|
21
21
|
import std/game/View
|
|
22
22
|
import std/game/Box
|
|
23
|
+
import std/game/Button
|
|
23
24
|
import std/game/Group
|
|
24
25
|
import std/game/Touch
|
|
25
26
|
import std/game/Label
|
|
@@ -197,7 +198,11 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
|
|
|
197
198
|
|
|
198
199
|
fun view(self) -> List<View> = [self.walker]
|
|
199
200
|
|
|
201
|
+
fun hud(self, window: Vec2) -> List<View> = [
|
|
200
|
-
|
|
202
|
+
Button(x: window.x - 20.0, y: window.y - 20.0, w: 20.0, h: 20.0, on: HudPressed) {
|
|
203
|
+
Box(w: 20.0, h: 20.0, color: Color.White)
|
|
204
|
+
}
|
|
205
|
+
]
|
|
201
206
|
|
|
202
207
|
fun steps(self) -> Bool = !self.paused
|
|
203
208
|
|
|
@@ -205,12 +210,10 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
|
|
|
205
210
|
|
|
206
211
|
fun camera(self, base: Viewport) -> Viewport = if self.follow then base.lookAt(self.walker.x, 0.0, 2.0) else base
|
|
207
212
|
|
|
208
|
-
fun held(self,
|
|
213
|
+
fun held(self, h: Held) -> Option<WalkAct> = Some(Saw(x: self.walker.x))
|
|
209
214
|
|
|
210
215
|
fun tick(self, dt: Float) -> Option<WalkAct> = Some(Walked(dt: dt))
|
|
211
216
|
|
|
212
|
-
fun onPress(self, target: View, at: Vec2) -> Option<WalkAct> = Some(HudPressed)
|
|
213
|
-
|
|
214
217
|
fun onKey(self, e: InputEvent) -> Option<WalkAct> = match e
|
|
215
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
|
|
216
219
|
_ => None
|
|
@@ -299,10 +302,10 @@ primitive ScreensTest[UnitTest] =
|
|
|
299
302
|
fun pressGivesOneKeyDownHoldSteersEvery() =
|
|
300
303
|
t := Screens.probe(io).press(Key.KeyA).ticks(3)
|
|
301
304
|
assert t.screen.keys == 1 && t.screen.ticks == 3
|
|
302
|
-
assert !t.held.
|
|
305
|
+
assert !t.held.isKeyDown(Key.KeyA)
|
|
303
306
|
u := Screens.probe(io).hold(Key.KeyA)
|
|
304
|
-
assert u.held.
|
|
307
|
+
assert u.held.isKeyDown(Key.KeyA)
|
|
305
|
-
assert !u.release(Key.KeyA).held.
|
|
308
|
+
assert !u.release(Key.KeyA).held.isKeyDown(Key.KeyA)
|
|
306
309
|
|
|
307
310
|
# a command goes to another screen, which fades in, its presses dropped until it is in; the old one is kept and resumes
|
|
308
311
|
fun effectsGoToAnotherScreenWhichFadesIn() =
|
|
@@ -393,9 +396,18 @@ primitive ScreensTest[UnitTest] =
|
|
|
393
396
|
t := TestRig.mount(io, WalkScreen.create()).resize(1600.0, 600.0)
|
|
394
397
|
assert t.count<Box>() == 2
|
|
395
398
|
assert t.hit(1590.0, 590.0).isSome()
|
|
399
|
+
on := match t.hit(1590.0, 590.0).unwrap()
|
|
400
|
+
Button<WalkAct> as b => b.pressed()
|
|
401
|
+
_ => Pause
|
|
402
|
+
assert match on
|
|
403
|
+
HudPressed => true
|
|
404
|
+
_ => false
|
|
396
405
|
u := t.clickAt(1590.0, 590.0).tick()
|
|
397
406
|
assert u.screen.hudPresses == 1
|
|
407
|
+
assert u.actions<WalkAct>().any(|a| match a
|
|
408
|
+
HudPressed => true
|
|
409
|
+
_ => false)
|
|
398
|
-
assert t.drawn().length() ==
|
|
410
|
+
assert t.drawn().length() == 4
|
|
399
411
|
|
|
400
412
|
# a screen's camera looks at what it follows, zoomed, and presses and toWorld follow it
|
|
401
413
|
fun aScreensCameraLooksAtWhatItFollows() =
|
tests/std/game/Button.plum
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Bool
|
|
4
|
+
import std/Str
|
|
5
|
+
import std/Io
|
|
6
|
+
import std/Option
|
|
7
|
+
import std/collections/List
|
|
8
|
+
import std/math/Vec2
|
|
9
|
+
import std/math/Aabb
|
|
10
|
+
import std/game/Color
|
|
11
|
+
import std/game/Input
|
|
12
|
+
import std/game/Place
|
|
13
|
+
import std/game/View
|
|
14
|
+
import std/game/Sized
|
|
15
|
+
import std/game/Touch
|
|
16
|
+
import std/game/Box
|
|
17
|
+
import std/game/Group
|
|
18
|
+
import std/game/Label
|
|
19
|
+
import std/game/Button
|
|
20
|
+
import std/game/Screen
|
|
21
|
+
import std/game/ScreenSlice
|
|
22
|
+
import std/game/TestRig
|
|
23
|
+
import std/Test
|
|
24
|
+
|
|
25
|
+
enum Pick = Picked(n: Int) | Other
|
|
26
|
+
|
|
27
|
+
# An actor of its own that says what a press on it means.
|
|
28
|
+
struct Token[View, Sized, Touch, Presses<Pick>](x: Float, n: Int) =
|
|
29
|
+
fun place(self) -> Place = Place.at(self.x, 300.0)
|
|
30
|
+
|
|
31
|
+
fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, 10.0, 10.0)
|
|
32
|
+
|
|
33
|
+
fun touch(self) -> Touchable = Enabled
|
|
34
|
+
|
|
35
|
+
fun pressed(self) -> Pick = Picked(n: self.n)
|
|
36
|
+
|
|
37
|
+
# A screen whose presses are all what its items say: two buttons (one inside a group), a
|
|
38
|
+
# token, a box that takes presses but says nothing, and a button of another action type.
|
|
39
|
+
struct PickScreen[ScreenSlice<Pick>](picks: List<Int>, others: Int) =
|
|
40
|
+
fun name(self) -> Str = "pick"
|
|
41
|
+
|
|
42
|
+
fun view(self) -> List<View> = [
|
|
43
|
+
Button(x: 10.0, y: 10.0, w: 40.0, h: 20.0, on: Picked(n: 1)) {
|
|
44
|
+
Box(w: 40.0, h: 20.0, color: Color.Red)
|
|
45
|
+
Label(x: 4.0, y: 2.0, text: "one", size: 12.0)
|
|
46
|
+
}
|
|
47
|
+
Group(x: 100.0, y: 100.0) {
|
|
48
|
+
Button(w: 40.0, h: 20.0, on: Picked(n: 2))
|
|
49
|
+
}
|
|
50
|
+
Token(x: 200.0, n: 3)
|
|
51
|
+
Box(x: 300.0, y: 300.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
|
|
52
|
+
Button(x: 400.0, y: 400.0, w: 10.0, h: 10.0, on: 7)
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
fun reduce(self, a: Pick) -> PickScreen = match a
|
|
56
|
+
Picked(n) => PickScreen(..self, picks: self.picks.append([n]))
|
|
57
|
+
Other => PickScreen(..self, others: self.others + 1)
|
|
58
|
+
|
|
59
|
+
primitive ButtonTest[UnitTest] =
|
|
60
|
+
# a button is a box that takes presses, with its children placed in it
|
|
61
|
+
fun aButtonIsABoxThatTakesPresses() =
|
|
62
|
+
b := Button(x: 5.0, y: 6.0, w: 40.0, h: 20.0, on: "go") { Box(w: 40.0, h: 20.0, color: Color.Red) }
|
|
63
|
+
assert b.touch().enabled() && b.hit(Vec2(x: 40.0, y: 20.0)) && !b.hit(Vec2(x: 41.0, y: 1.0))
|
|
64
|
+
assert b.place().x == 5.0 && b.view().length() == 1 && b.pressed() == "go"
|
|
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
|
+
|
|
67
|
+
# a slice's onPress is what the item pressed says it means, by default
|
|
68
|
+
fun aPressIsWhatTheItemSaysItMeans() =
|
|
69
|
+
t := TestRig.mount(io, PickScreen(picks: Nil, others: 0))
|
|
70
|
+
u := t.clickAt(20.0, 15.0).tick().clickAt(110.0, 110.0).tick().clickAt(205.0, 305.0).tick()
|
|
71
|
+
assert u.screen.picks.map(|n| "{n}").join(" ") == "1 2 3"
|
|
72
|
+
# a press on an item that says nothing, or means another type's action, gives none
|
|
73
|
+
v := u.clickAt(305.0, 305.0).tick().clickAt(405.0, 405.0).tick().clickAt(700.0, 10.0).tick()
|
|
74
|
+
assert v.screen.picks.length() == 3 && v.screen.others == 0
|
|
75
|
+
assert v.actions<Pick>().isEmpty()
|
tests/std/game/Game.plum
CHANGED
|
@@ -19,14 +19,14 @@ import std/Test
|
|
|
19
19
|
primitive GameTest[UnitTest] =
|
|
20
20
|
# a tick takes the window from its input, and an input with no window leaves it as it was
|
|
21
21
|
fun aTickTakesTheWindowFromItsInput() =
|
|
22
|
-
g := GameHelpers.game().update(io, Input
|
|
22
|
+
g := GameHelpers.game().update(io, Input().sized(640.0, 480.0), Ticker.Tick)
|
|
23
23
|
assert g.pixels == Vec2(x: 640.0, y: 480.0)
|
|
24
|
-
assert g.update(io, Input
|
|
24
|
+
assert g.update(io, Input(), Ticker.Tick).pixels == Vec2(x: 640.0, y: 480.0)
|
|
25
|
-
assert g.update(io, Input
|
|
25
|
+
assert g.update(io, Input().sized(320.0, 200.0), Ticker.Tick).pixels == Vec2(x: 320.0, y: 200.0)
|
|
26
26
|
|
|
27
27
|
# the ticker hands each tick of a frame the window the frame was polled in
|
|
28
28
|
fun theTickerHandsEachTickTheWindow() =
|
|
29
|
-
t := Ticker().accept(Input
|
|
29
|
+
t := Ticker().accept(Input().sized(300.0, 200.0), 0.05)
|
|
30
30
|
assert t.input().screen == Vec2(x: 300.0, y: 200.0)
|
|
31
31
|
assert t.ticked().ticked().input().screen == Vec2(x: 300.0, y: 200.0)
|
|
32
32
|
assert t.dueInputs().length() == 3
|
|
@@ -38,7 +38,7 @@ primitive GameTest[UnitTest] =
|
|
|
38
38
|
assert !plain.dev && plain.history.isNone()
|
|
39
39
|
started := GameHelpers.game().devFrame(io, Ticker(mode: ReplayMode.Dev))
|
|
40
40
|
assert started.dev && started.history.isSome() && !started.paused
|
|
41
|
-
played := Range.until(0, 3).fold(started, |g, i| g.step(io, Input
|
|
41
|
+
played := Range.until(0, 3).fold(started, |g, i| g.step(io, Input(), Ticker.Tick, Vec2(x: 800.0, y: 600.0)))
|
|
42
42
|
assert played.devLine() == "tick 3 of 3"
|
|
43
43
|
back := played.devFrame(io, Ticker(mode: ReplayMode.Dev, travel: [TravelBack]))
|
|
44
44
|
assert back.paused && back.dev && back.tickNow() == 2
|
|
@@ -52,7 +52,7 @@ primitive GameTest[UnitTest] =
|
|
|
52
52
|
|
|
53
53
|
# a frame the host is about to draw counts as drawn, which lets an OnDemand screen go idle
|
|
54
54
|
fun aFrameTheHostDrawsCountsAsDrawn() =
|
|
55
|
-
g := GameHelpers.game().step(io, Input
|
|
55
|
+
g := GameHelpers.game().step(io, Input(), Ticker.Tick, Vec2(x: 800.0, y: 600.0))
|
|
56
56
|
assert !g.idle()
|
|
57
57
|
shown := g.hostFrame(io)
|
|
58
58
|
assert shown.draws == 1 && shown.idle()
|
tests/std/game/History.plum
CHANGED
|
@@ -68,4 +68,4 @@ primitive HistoryHelpers =
|
|
|
68
68
|
TravelRedo => "redo"
|
|
69
69
|
|
|
70
70
|
fun tick(user: Bool) -> HistoryTick =
|
|
71
|
-
HistoryTick(input: Input
|
|
71
|
+
HistoryTick(input: Input(), pixels: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user)
|
tests/std/game/Input.plum
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import std/Int
|
|
2
2
|
import std/Float
|
|
3
|
-
import std/Slice
|
|
4
3
|
import std/math/Vec2
|
|
5
4
|
import std/Io
|
|
6
5
|
import std/Option
|
|
@@ -15,14 +14,14 @@ primitive InputTest[UnitTest] =
|
|
|
15
14
|
# held_after_tracks_keys_and_mouse
|
|
16
15
|
fun heldAfterTracksKeysAndMouse() =
|
|
17
16
|
h := Held().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.Left)).after(PointerDown(x: 1.0, y: 2.0))
|
|
18
|
-
assert h.
|
|
17
|
+
assert h.isKeyDown(Key.KeyA)
|
|
19
|
-
assert h.
|
|
18
|
+
assert h.isKeyDown(Key.Left)
|
|
20
19
|
assert h.mouse
|
|
21
20
|
h2 := h.after(KeyUp(key: Key.KeyA)).after(PointerUp(x: 1.0, y: 2.0))
|
|
22
|
-
assert !h2.
|
|
21
|
+
assert !h2.isKeyDown(Key.KeyA)
|
|
23
|
-
assert h2.
|
|
22
|
+
assert h2.isKeyDown(Key.Left)
|
|
24
23
|
assert !h2.mouse
|
|
25
|
-
assert h.
|
|
24
|
+
assert h.isKeyDown(Key.KeyA)
|
|
26
25
|
|
|
27
26
|
# the right and middle buttons are held apart from the pointer
|
|
28
27
|
fun theRightAndMiddleButtonsAreHeldApart() =
|
|
@@ -36,10 +35,11 @@ primitive InputTest[UnitTest] =
|
|
|
36
35
|
|
|
37
36
|
# an input is in no window until it is sized, and sizing keeps the rest of it
|
|
38
37
|
fun anInputIsInNoWindowUntilSized() =
|
|
39
|
-
i := Input(
|
|
38
|
+
i := Input(events: [KeyDown(key: Key.KeyA), Wheel(dy: 1.0)], held: Held(keys: [Key.KeyA], pointer: Vec2(x: 3.0, y: 4.0)))
|
|
40
39
|
assert i.screen == Vec2(x: 0.0, y: 0.0)
|
|
41
40
|
s := i.sized(800.0, 600.0)
|
|
42
|
-
assert s.screen == Vec2(x: 800.0, y: 600.0) && s.isKeyDown(Key.KeyA) && s.
|
|
41
|
+
assert s.screen == Vec2(x: 800.0, y: 600.0) && s.held.isKeyDown(Key.KeyA) && s.events.length() == 2 && s.held.pointer.x == 3.0
|
|
42
|
+
assert Input().events.isEmpty() && Input().held.same(Held())
|
|
43
43
|
|
|
44
44
|
# a replay's ticks are in the window of its header
|
|
45
45
|
fun aReplaysTicksAreInItsWindow() =
|
|
@@ -47,7 +47,7 @@ primitive InputTest[UnitTest] =
|
|
|
47
47
|
assert r.width == 640 && r.ticks.length() == 2
|
|
48
48
|
assert r.ticks.all(|t| t.screen == Vec2(x: 640.0, y: 480.0))
|
|
49
49
|
assert r.onScreen(320, 200).ticks.at(1).screen == Vec2(x: 320.0, y: 200.0)
|
|
50
|
-
assert r.onScreen(320, 200).ticks.at(1).isKeyDown(Key.KeyA)
|
|
50
|
+
assert r.onScreen(320, 200).ticks.at(1).held.isKeyDown(Key.KeyA)
|
|
51
51
|
|
|
52
52
|
# key_down_twice_keeps_one_entry
|
|
53
53
|
fun keyDownTwiceKeepsOneEntry() =
|
|
@@ -58,14 +58,14 @@ primitive InputTest[UnitTest] =
|
|
|
58
58
|
fun keyCodesCoverEveryKeyConstant() =
|
|
59
59
|
codes := InputEvent.keyCodes()
|
|
60
60
|
assert codes.length() == 56
|
|
61
|
-
assert Held(keys: codes).
|
|
61
|
+
assert Held(keys: codes).isKeyDown(Key.Space)
|
|
62
|
-
assert Held(keys: codes).
|
|
62
|
+
assert Held(keys: codes).isKeyDown(Key.Num9)
|
|
63
|
-
assert Held(keys: codes).
|
|
63
|
+
assert Held(keys: codes).isKeyDown(Key.KeyZ)
|
|
64
|
-
assert Held(keys: codes).
|
|
64
|
+
assert Held(keys: codes).isKeyDown(Key.Backslash)
|
|
65
|
-
assert Held(keys: codes).
|
|
65
|
+
assert Held(keys: codes).isKeyDown(Key.Backspace)
|
|
66
|
-
assert Held(keys: codes).
|
|
66
|
+
assert Held(keys: codes).isKeyDown(Key.Up)
|
|
67
|
-
assert Held(keys: codes).
|
|
67
|
+
assert Held(keys: codes).isKeyDown(Key.LeftControl)
|
|
68
|
-
assert Held(keys: codes).
|
|
68
|
+
assert Held(keys: codes).isKeyDown(Key.RightSuper)
|
|
69
69
|
assert Range.until(1, codes.length()).all(|i| codes.at(i - 1) < codes.at(i))
|
|
70
70
|
|
|
71
71
|
# pointer events have a position, keys don't
|
|
@@ -75,45 +75,37 @@ primitive InputTest[UnitTest] =
|
|
|
75
75
|
assert PointerMove(x: 0.0, y: 0.0).isPointerMove()
|
|
76
76
|
assert KeyDown(key: 5).position().isNone()
|
|
77
77
|
|
|
78
|
+
# what is held is a fold of the events: each pointer event moves the pointer, and the
|
|
79
|
+
# wheel holds nothing
|
|
78
|
-
fun
|
|
80
|
+
fun heldIsAFoldOfTheEvents() =
|
|
79
|
-
held := Held(mouse: true, keys: [Key.KeyA].toSlice(), buttons: Slice<Int>())
|
|
80
|
-
|
|
81
|
+
events := [PointerDown(x: 3.0, y: 4.0), KeyDown(key: Key.KeyA), ButtonDown(button: Mouse.Right, x: 5.0, y: 6.0), Wheel(dy: 1.5), KeyDown(key: Key.KeyB), KeyUp(key: Key.KeyA)]
|
|
81
|
-
|
|
82
|
+
h := Held().afterAll(events)
|
|
83
|
+
assert h.mouse && h.isButtonDown(Mouse.Left) && h.isButtonDown(Mouse.Right) && !h.isButtonDown(Mouse.Middle)
|
|
84
|
+
assert h.isKeyDown(Key.KeyB) && !h.isKeyDown(Key.KeyA) && h.keys.length() == 1
|
|
82
|
-
assert
|
|
85
|
+
assert h.pointer == Vec2(x: 5.0, y: 6.0)
|
|
83
|
-
assert st.isKeyDown(Key.KeyA)
|
|
84
|
-
assert st.isMousePressed()
|
|
85
|
-
assert !st.isMouseReleased()
|
|
86
|
-
assert st.isMouseDown()
|
|
87
|
-
assert
|
|
86
|
+
assert h.same(events.fold(Held(), |acc, e| acc.after(e)))
|
|
88
|
-
assert st.wheel == 1.5
|
|
89
|
-
assert
|
|
87
|
+
assert Held().after(PointerMove(x: 7.0, y: 8.0)).pointer == Vec2(x: 7.0, y: 8.0)
|
|
88
|
+
assert Held().after(Wheel(dy: 2.0)).same(Held()) && Held().after(Wheel(dy: 2.0)).pointer == Vec2(x: 0.0, y: 0.0)
|
|
89
|
+
assert h.after(PointerUp(x: 1.0, y: 1.0)).after(ButtonUp(button: Mouse.Right, x: 1.0, y: 1.0)).same(Held(keys: [Key.KeyB]))
|
|
90
90
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
assert
|
|
94
|
-
assert
|
|
91
|
+
# the pointer is not part of what `same` compares
|
|
92
|
+
fun sameLeavesThePointerAside() =
|
|
93
|
+
assert Held(pointer: Vec2(x: 1.0, y: 2.0)).same(Held())
|
|
94
|
+
assert !Held(mouse: true).same(Held())
|
|
95
|
+
|
|
96
|
+
# the wheel is an event with no position, and not a key
|
|
97
|
+
fun theWheelIsAnEvent() =
|
|
98
|
+
assert Wheel(dy: -1.0).isWheel() && !Wheel(dy: -1.0).isPointer() && Wheel(dy: 1.0).position().isNone()
|
|
99
|
+
assert !KeyDown(key: Key.KeyA).isWheel() && !Wheel(dy: 1.0).isKeyDownOf(Key.KeyA)
|
|
95
100
|
|
|
96
101
|
# an axis is the high key held against the low one
|
|
97
102
|
fun anAxisIsTheHighKeyHeldAgainst() =
|
|
98
|
-
i := |keys: List<Int>|
|
|
103
|
+
i := |keys: List<Int>| Held(keys: keys)
|
|
99
104
|
assert i([Key.Right]).axis(Key.Left, Key.Right) == 1.0
|
|
100
105
|
assert i([Key.Left]).axis(Key.Left, Key.Right) == -1.0
|
|
101
106
|
assert i([Key.Left, Key.Right]).axis(Key.Left, Key.Right) == 0.0
|
|
102
107
|
assert i(Nil).axis(Key.Left, Key.Right) == 0.0
|
|
103
108
|
|
|
104
|
-
# only this frame's events count, not what lies past them
|
|
105
|
-
fun onlyThisFramesEventsCountNotWhatLies() =
|
|
106
|
-
all := [KeyDown(key: Key.KeyA), KeyDown(key: Key.KeyB), PointerDown(x: 1.0, y: 1.0), PointerUp(x: 1.0, y: 1.0)].toSlice()
|
|
107
|
-
held := Held(keys: [Key.KeyA].toSlice())
|
|
108
|
-
one := Input(held: held, events: all.slice(0, 1), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
109
|
-
assert one.isKeyPressed(Key.KeyA)
|
|
110
|
-
assert !one.isKeyPressed(Key.KeyB)
|
|
111
|
-
downOnly := Input(held: held, events: all.slice(1, 2), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
112
|
-
assert !downOnly.isMousePressed()
|
|
113
|
-
beforeUp := Input(held: held, events: all.slice(2, 3), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
114
|
-
assert beforeUp.isMousePressed()
|
|
115
|
-
assert !beforeUp.isMouseReleased()
|
|
116
|
-
|
|
117
109
|
fun keyAndMouseConstantsUseGLFWNumbering() =
|
|
118
110
|
assert Key.KeyW == 87
|
|
119
111
|
assert Key.Left == 263
|
tests/std/game/ScreenSlice.plum
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Bool
|
|
4
|
+
import std/Str
|
|
5
|
+
import std/Io
|
|
6
|
+
import std/Option
|
|
7
|
+
import std/collections/List
|
|
8
|
+
import std/math/Vec2
|
|
9
|
+
import std/game/Input
|
|
10
|
+
import std/game/Screen
|
|
11
|
+
import std/game/ScreenSlice
|
|
12
|
+
import std/game/TestRig
|
|
13
|
+
import std/Test
|
|
14
|
+
|
|
15
|
+
enum Turn = Rolled(dy: Float, x: Float) | Steered(ax: Float, x: Float)
|
|
16
|
+
|
|
17
|
+
# A screen that keeps each wheel turn with where it happened, and what `held` saw.
|
|
18
|
+
struct WheelScreen[ScreenSlice<Turn>](turns: List<Turn>) =
|
|
19
|
+
fun name(self) -> Str = "wheel"
|
|
20
|
+
|
|
21
|
+
fun onPointer(self, e: InputEvent, at: Vec2) -> Option<Turn> = match e
|
|
22
|
+
Wheel(dy) => Some(Rolled(dy: dy, x: at.x))
|
|
23
|
+
_ => None
|
|
24
|
+
|
|
25
|
+
fun held(self, h: Held) -> Option<Turn> = Some(Steered(ax: h.axis(Key.Left, Key.Right), x: h.pointer.x))
|
|
26
|
+
|
|
27
|
+
fun reduce(self, a: Turn) -> WheelScreen = WheelScreen(turns: self.turns.append([a]))
|
|
28
|
+
|
|
29
|
+
fun said(t: Turn) -> Str = match t
|
|
30
|
+
Rolled(dy, x) => "rolled {dy} at {x}"
|
|
31
|
+
Steered(ax, x) => "steered {ax} at {x}"
|
|
32
|
+
|
|
33
|
+
primitive ScreenSliceTest[UnitTest] =
|
|
34
|
+
# a wheel turn reaches `onPointer` where the pointer is, and `held` sees what is held
|
|
35
|
+
# after the tick's events, the pointer with it
|
|
36
|
+
fun aWheelTurnIsAPointerEventAtThePointer() =
|
|
37
|
+
t := TestRig.mount(io, WheelScreen(turns: Nil))
|
|
38
|
+
u := t.pointerMove(40.0, 30.0).send(Wheel(dy: -2.0)).hold(Key.Right).tick()
|
|
39
|
+
assert u.screen.turns.map(|a| WheelScreen.said(a)).join(", ") == "rolled -2.0 at 40.0, steered 1.0 at 40.0"
|
|
40
|
+
assert u.held.pointer == Vec2(x: 40.0, y: 30.0) && u.held.isKeyDown(Key.Right)
|
|
41
|
+
v := u.release(Key.Right).tick()
|
|
42
|
+
assert WheelScreen.said(v.screen.turns.at(2)) == "steered 0.0 at 40.0"
|
tests/traits/generic_trait_match.plum
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Bool
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/Test
|
|
5
|
+
import std/Option
|
|
6
|
+
import std/collections/List
|
|
7
|
+
|
|
8
|
+
# A value matched against a generic trait at a type argument (`Says<A> as s`): the arm
|
|
9
|
+
# takes a value that implements the trait at that argument, and no other.
|
|
10
|
+
|
|
11
|
+
trait Thing =
|
|
12
|
+
fun size(self) -> Int
|
|
13
|
+
|
|
14
|
+
trait Says<A> =
|
|
15
|
+
fun said(self) -> A
|
|
16
|
+
|
|
17
|
+
enum Word = Hello | Bye(n: Int)
|
|
18
|
+
|
|
19
|
+
struct Talker[Thing, Says<Word>](n: Int) =
|
|
20
|
+
fun size(self) -> Int = self.n
|
|
21
|
+
fun said(self) -> Word = Bye(n: self.n)
|
|
22
|
+
|
|
23
|
+
struct Counter[Thing, Says<Int>](n: Int) =
|
|
24
|
+
fun size(self) -> Int = 1
|
|
25
|
+
fun said(self) -> Int = self.n * 10
|
|
26
|
+
|
|
27
|
+
struct Mute[Thing](n: Int) =
|
|
28
|
+
fun size(self) -> Int = 0
|
|
29
|
+
|
|
30
|
+
primitive Hear =
|
|
31
|
+
fun of<A>(t: Thing) -> Option<A> = match t
|
|
32
|
+
Says<A> as s => Some(s.said())
|
|
33
|
+
_ => None
|
|
34
|
+
|
|
35
|
+
fun words(xs: List<Thing>) -> List<Word> = xs.fold(Nil, |acc, x| match Hear.of<Word>(x)
|
|
36
|
+
Some(w) => Cons(w, acc)
|
|
37
|
+
None => acc).reverse()
|
|
38
|
+
|
|
39
|
+
fun name(w: Word) -> Str = match w
|
|
40
|
+
Hello => "hello"
|
|
41
|
+
Bye(n) => "bye {n}"
|
|
42
|
+
|
|
43
|
+
primitive GenericTraitMatchTest[UnitTest] =
|
|
44
|
+
fun aGenericTraitMatchesAtItsArgument() =
|
|
45
|
+
ts: List<Thing> := [Talker(n: 3), Mute(n: 1), Counter(n: 4), Talker(n: 5)]
|
|
46
|
+
assert Hear.words(ts).map(|w| Hear.name(w)).join(" ") == "bye 3 bye 5"
|
|
47
|
+
assert Hear.of<Int>(Counter(n: 4)).unwrapOr(0) == 40
|
|
48
|
+
assert Hear.of<Int>(Talker(n: 4)).isNone()
|
|
49
|
+
assert Hear.of<Word>(Mute(n: 4)).isNone()
|