plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
cd2c888
— Peter John
2026-11-09T17:10:40+05:30
One way to make a game: Game, Screen and Store (actor-trait task 9)
- compiler/cli/src/program.rs +1 -1
- compiler/cli/tests/cli/game_entry_test.rs +36 -69
- compiler/cli/tests/cli/game_web_test.rs +1 -1
- compiler/core/src/game_entry.rs +74 -60
- compiler/core/src/main_result.rs +1 -1
- compiler/driver/tests/driver_tests.rs +34 -39
- compiler/game/src/host.rs +1 -1
- compiler/game/tests/fixtures/assets_fixture.plum +28 -6
- compiler/game/tests/fixtures/host_fixture.plum +30 -7
- compiler/game/tests/fixtures/main_game_fixture.plum +31 -6
- compiler/game/tests/fixtures/main_missing_fixture.plum +27 -6
- compiler/game/tests/fixtures/state_draw_keeps.plum +28 -5
- compiler/game/tests/fixtures/state_in_place.plum +29 -6
- compiler/game/tests/fixtures/state_main_alias.plum +30 -6
- compiler/game/tests/fixtures/state_reset.plum +28 -5
- compiler/game/tests/fixtures/target_fixture.plum +26 -6
- compiler/game/tests/host_test.rs +15 -7
- compiler/game/web-test/fixtures/interleave.plum +29 -7
- compiler/game/web-test/fixtures/main_game.plum +30 -8
- compiler/game/web-test/fixtures/rendertarget.plum +30 -7
- compiler/game/web-test/fixtures/stress.plum +29 -7
- compiler/game/web-test/fixtures/stress_scene_port.plum +15 -6
- compiler/game/web-test/fixtures/stress_state_view.plum +54 -50
- compiler/game/web-test/fixtures/stress_world.plum +42 -31
- compiler/game/web-test/fixtures/text_sizes.plum +29 -7
- docs/game.md +94 -73
- docs/std.md +2 -2
- examples/games/clicks.plum +79 -0
- examples/games/kids/balloon_pop.plum +170 -142
- examples/games/orb_run.plum +524 -487
- std/game/Game.plum +367 -0
- std/game/Store.plum +4 -4
- std/game/audio.plum +12 -5
- std/game/input.plum +0 -11
- std/game/scene/Actor.plum +6 -0
- std/game/scene/Ctx.plum +65 -17
- std/game/scene/SceneTree.plum +46 -6
- std/game/ui.plum +87 -195
- tests/port/game/determinism.plum +69 -32
- tests/port/game/replay.plum +56 -19
compiler/cli/src/program.rs
CHANGED
|
@@ -73,7 +73,7 @@ pub fn tryCompileProgram(
|
|
|
73
73
|
render(&ds, true)
|
|
74
74
|
})?;
|
|
75
75
|
if !out.isGame && hasLegacyGameExports(&ast) {
|
|
76
|
-
return Err(Failure { codegen: false, text: format!("{}: the `export fun init/update/draw` game entry is gone; a game
|
|
76
|
+
return Err(Failure { codegen: false, text: format!("{}: the `export fun init/update/draw` game entry is gone; a game's `main` returns `Game[S, M]`, made by `Game.start(screen, state)` (std/game/Game)", file.display()) });
|
|
77
77
|
}
|
|
78
78
|
Ok(Program { isGame: out.isGame, wasm: out.wasm, resultMain })
|
|
79
79
|
}
|
compiler/cli/tests/cli/game_entry_test.rs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#![allow(non_snake_case)]
|
|
2
|
-
//! What a `main` return type compiles to: a game when it
|
|
2
|
+
//! What a `main` return type compiles to: a game when it is `Game[S, M]` (std/game/Game), an
|
|
3
|
+
//! error naming `Game.start` for a type of its own with `update` and `draw` (the old game shape),
|
|
3
|
-
//!
|
|
4
|
+
//! and a plain program otherwise.
|
|
4
5
|
use std::process::Command;
|
|
5
6
|
|
|
6
7
|
fn plumBin() -> std::path::PathBuf {
|
|
@@ -62,89 +63,55 @@ fn compileSource(name: &str, text: &str) -> (bool, String) {
|
|
|
62
63
|
|
|
63
64
|
const HEAD: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/input\n\nstruct Counter(n: Int) =\n";
|
|
64
65
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
66
|
+
/// A whole game: one screen with one actor over a state that counts its messages.
|
|
67
|
+
const GAME: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/input\n\
|
|
68
|
+
import std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\nimport std/game/scene/Ctx\nimport std/game/scene/SceneTree\n\n\
|
|
69
|
+
struct Count(n: Int) is Reducer[Int] =\n fun update(self, msg: Int) -> Count = Count(n: self.n + msg)\n\n\
|
|
70
|
+
struct Ticker(id: Int) is Actor[Int] =\n fun key(self) -> Int = self.id\n fun place(self) -> Place = place.at(0.0, 0.0)\n \
|
|
71
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Ticker =\n ctx.send(1)\n self\n\n\
|
|
72
|
+
struct Only(t: SceneTree[Int]) is Screen[Count, Int] =\n fun tree(self) -> SceneTree[Int] = self.t\n fun withTree(self, t: SceneTree[Int]) -> Only = Only(t: t)\n\n\
|
|
73
|
+
fun main(io: Io) -> Game[Count, Int] =\n Game.start(Only(t: SceneTree.of(Ticker(id: 0))), Count(n: 0))\n";
|
|
71
74
|
|
|
72
75
|
#[test]
|
|
73
|
-
fn
|
|
76
|
+
fn aMainReturningAGameIsAGame() {
|
|
74
|
-
let src = format!("{HEAD} fun update(self, io: Io, input: Input, dt: Float) -> Counter =\n self\n\nfun main(io: Io) -> Counter =\n Counter(n: 0)\n");
|
|
75
|
-
let (ok, err) = compileSource("
|
|
77
|
+
let (ok, err) = compileSource("game", GAME);
|
|
76
|
-
assert!(
|
|
78
|
+
assert!(ok, "{err}");
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
#[test]
|
|
80
|
-
fn
|
|
82
|
+
fn aGameWithoutItsTypeArgumentsIsAnError() {
|
|
81
|
-
let src =
|
|
83
|
+
let src = GAME.replace("fun main(io: Io) -> Game[Count, Int] =", "fun main(io: Io) -> Game =");
|
|
82
|
-
let (ok, err) = compileSource("
|
|
84
|
+
let (ok, err) = compileSource("bareGame", &src);
|
|
83
|
-
assert!(!ok && err.contains("
|
|
85
|
+
assert!(!ok && err.contains("a game's `main` returns `Game[S, M]`"), "{err}");
|
|
84
86
|
}
|
|
85
87
|
|
|
88
|
+
/// The old game shape, a type of its own with `update` and `draw`, is no longer a game: the
|
|
89
|
+
/// error says what a game is now.
|
|
86
90
|
#[test]
|
|
87
|
-
fn
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
fn theOldUpdateAndDrawShapeNamesGameStart() {
|
|
92
|
+
for update in ["fun update(self, io: Io, input: Input, dt: Float) -> Counter =", "fun update(self, io: Io, dt: Float) -> Counter ="] {
|
|
93
|
+
let src = format!("{HEAD} {update}\n Counter(n: self.n + 1)\n\n fun draw(self, io: Io) =\n io.printLn(\"x\")\n\nfun main(io: Io) -> Counter =\n Counter(n: 0)\n");
|
|
94
|
+
let (ok, err) = compileSource("oldShape", &src);
|
|
95
|
+
assert!(!ok, "{err}");
|
|
96
|
+
assert!(err.contains("`Counter` has `update` and `draw`, but a game is no longer a type of its own"), "{err}");
|
|
97
|
+
assert!(err.contains("Game.start(screen, state)"), "{err}");
|
|
98
|
+
}
|
|
91
99
|
}
|
|
92
100
|
|
|
101
|
+
/// A type with only one of the two methods is an ordinary result of `main`, not a game.
|
|
93
102
|
#[test]
|
|
94
|
-
fn
|
|
95
|
-
let src = format!("{HEAD} fun
|
|
96
|
-
let
|
|
97
|
-
assert!(!ok && err.contains("a game's update is `fun update(self, io: Io, input: Input, dt: Float) -> Counter`"), "{err}");
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/// `plum build --explain-fusion` on a game: the fusion notes it prints.
|
|
101
|
-
fn explainGame(name: &str, text: &str) -> String {
|
|
102
|
-
let dir = std::env::temp_dir().join(format!("plum_gameentry_{}_{name}", std::process::id()));
|
|
103
|
+
fn aTypeWithOnlyUpdateOrDrawIsAProgram() {
|
|
104
|
+
let src = format!("{HEAD} fun draw(self, io: Io) =\n io.printLn(\"x\")\n\nfun main(io: Io) -> Counter =\n Counter(n: 0)\n");
|
|
105
|
+
let dir = std::env::temp_dir().join(format!("plum_gameentry_{}_onlyDraw", std::process::id()));
|
|
103
106
|
std::fs::create_dir_all(&dir).unwrap();
|
|
104
|
-
let
|
|
107
|
+
let path = dir.join("app.plum");
|
|
105
|
-
std::fs::write(&
|
|
108
|
+
std::fs::write(&path, &src).unwrap();
|
|
106
109
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
107
110
|
let out = Command::new(plumBin())
|
|
108
111
|
.current_dir(root)
|
|
109
|
-
.args(["
|
|
112
|
+
.args(["compile", path.to_str().unwrap(), "-o", dir.join("app.wasm").to_str().unwrap()])
|
|
110
113
|
.output()
|
|
111
114
|
.unwrap();
|
|
112
115
|
let _ = std::fs::remove_dir_all(&dir);
|
|
113
|
-
|
|
116
|
+
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
114
|
-
assert!(out.status.success(), "{text}");
|
|
115
|
-
text
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/// A game whose `update` is also called on a shared value elsewhere (`bump`), whose `main` ends in
|
|
119
|
-
/// a local, and whose `draw` calls a method that copies `self`.
|
|
120
|
-
fn wrappedGame(draw: &str) -> String {
|
|
121
|
-
format!(
|
|
122
|
-
"module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/game/input\n\n\
|
|
123
|
-
Start = Counter(n: 0, m: 0, log: Log(last: None))\nIdle = Input.create()\n\n\
|
|
124
|
-
struct Log(mut last: Option[Counter])\n\n\
|
|
125
|
-
struct Counter(n: Int, m: Int, log: Log) =\n fun update(self, io: Io, input: Input, dt: Float) -> Counter =\n Counter(..self, n: self.n + 1)\n\n\
|
|
126
|
-
\x20 fun shown(self) -> Counter = Counter(..self, m: 9)\n\n\
|
|
127
|
-
\x20 fun draw(self, io: Io) =\n{draw} io.printLn(\"{{self.shown().m}} {{self.n}}\")\n\n\
|
|
128
|
-
fun bump(c: Counter, io: Io) -> Counter = c.update(io, Idle, 0.0)\n\n\
|
|
129
|
-
fun main(io: Io) -> Counter =\n g := Counter(n: bump(Start, io).n, m: 0, log: Log(last: None))\n g\n"
|
|
130
|
-
)
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/// The host's state is a `GameRun` holding the game: the game's `update` still runs in place for
|
|
134
|
-
/// the host, as when the host held the game itself (a `main` ending in a local, a `draw` that is
|
|
135
|
-
/// not read-only and an `io` that other calls hand over must not stop it).
|
|
136
|
-
#[test]
|
|
137
|
-
fn theGameUpdatesInPlaceInsideTheWrapper() {
|
|
138
|
-
let notes = explainGame("inPlace", &wrappedGame(""));
|
|
139
|
-
assert!(notes.contains("`Counter.update$unique` takes the 1 unique call(s) (from gameTick)"), "{notes}");
|
|
140
|
-
assert!(notes.contains("unique spread at Counter.update$unique"), "{notes}");
|
|
141
|
-
assert!(!notes.contains("unique spread at Counter.shown"), "draw must not write the state: {notes}");
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/// A `draw` that keeps its `self` keeps the host's game too: the next `update` copies it.
|
|
145
|
-
#[test]
|
|
146
|
-
fn aDrawThatKeepsTheGameStopsTheInPlaceUpdate() {
|
|
147
|
-
let notes = explainGame("drawKeeps", &wrappedGame(" self.log.last = Some(self)\n"));
|
|
148
|
-
assert!(!notes.contains("Counter.update$unique"), "{notes}");
|
|
149
|
-
assert!(notes.contains("not in place Counter.update"), "{notes}");
|
|
150
117
|
}
|
compiler/cli/tests/cli/game_web_test.rs
CHANGED
|
@@ -172,7 +172,7 @@ fn oldInitEntryIsRejectedWithAPointer() {
|
|
|
172
172
|
let out = Command::new(plumBin()).current_dir(root()).args([cmd]).arg(&file).args(["--lib-path", "."]).output().unwrap();
|
|
173
173
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
174
174
|
assert!(!out.status.success(), "{cmd} should fail");
|
|
175
|
-
assert!(err.contains("
|
|
175
|
+
assert!(err.contains("Game.start(screen, state)"), "{cmd}: {err}");
|
|
176
176
|
}
|
|
177
177
|
let _ = std::fs::remove_dir_all(&scratch);
|
|
178
178
|
}
|
compiler/core/src/game_entry.rs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
//! A game is
|
|
1
|
+
//! A game is a `main` returning `Game[S, M]` (std/game/Game), made by `Game.start(screen, state)`:
|
|
2
|
-
//!
|
|
2
|
+
//! there is no other kind of game. This lowering (run before checking) renames the game's `main`
|
|
3
|
-
//! `gameUserMain` and appends the state the host holds, `GameRun(game, clock)` with the
|
|
3
|
+
//! to `gameUserMain` and appends the state the host holds, `GameRun(game, clock)` with the
|
|
4
|
-
//! std/game/input, a `main` that builds it, and the two frame entry points the host
|
|
4
|
+
//! `Clock` of std/game/input, a `main` that builds it, and the two frame entry points the host
|
|
5
|
-
//! `gameUpdate(io, r, dt)` polls the input once and runs the fixed 1/60 s ticks the frame
|
|
5
|
+
//! calls: `gameUpdate(io, r, dt)` polls the input once and runs the fixed 1/60 s ticks the frame
|
|
6
|
-
//! (at most 8, in `gameTicks`), and `gameDraw(io, r)`
|
|
6
|
+
//! covers (at most 8, in `gameTicks`), each one `Game.update`, and `gameDraw(io, r)` runs
|
|
7
|
-
//! as `update(state, dt) -> state` and `draw(state)`.
|
|
7
|
+
//! `Game.draw`. The wasm module exports them as `update(state, dt) -> state` and `draw(state)`.
|
|
8
|
-
//!
|
|
8
|
+
//! A `main` returning anything else is a command line program, except a type with its own
|
|
9
|
+
//! `update` and `draw` (the old game shape), which is an error that names `Game.start`.
|
|
9
10
|
use crate::ast::*;
|
|
10
11
|
use crate::diag::{DiagKind, Diagnostic};
|
|
11
12
|
use crate::main_result::parseItems;
|
|
@@ -21,54 +22,41 @@ pub const GAME_TICKS: &str = "gameTicks";
|
|
|
21
22
|
/// One tick: the game's `update` with the clock's input, and the clock moved on.
|
|
22
23
|
pub const GAME_TICK: &str = "gameTick";
|
|
23
24
|
|
|
24
|
-
|
|
25
|
+
/// The name of std/game/Game's game type.
|
|
25
|
-
|
|
26
|
+
pub const GAME_TYPE: &str = "Game";
|
|
26
|
-
Item::Fn(f) if f.name == name && f.has_self && f.type_param.as_deref() == Some(ty) => Some(f),
|
|
27
|
-
_ => None,
|
|
28
|
-
})
|
|
29
|
-
}
|
|
30
27
|
|
|
31
|
-
fn
|
|
28
|
+
fn hasMethod(source: &Source, ty: &str, name: &str) -> bool {
|
|
32
|
-
matches!(f.params.get(i), Some(p) if p.name == name
|
|
33
|
-
|
|
29
|
+
source.items.iter().any(|i| matches!(i, Item::Fn(f) if f.name == name && f.has_self && f.type_param.as_deref() == Some(ty)))
|
|
34
30
|
}
|
|
35
31
|
|
|
36
|
-
/// The game type `main` returns: `Ok(None)` for a program that is
|
|
32
|
+
/// The game type `main` returns (`Game[S, M]`, as written): `Ok(None)` for a program that is
|
|
33
|
+
/// not a game, an error for the old game shape (a type of the program's own with `update` and
|
|
37
|
-
///
|
|
34
|
+
/// `draw`) or a `Game` without its two type arguments.
|
|
38
|
-
pub fn gameType(source: &Source) -> Result<Option<
|
|
35
|
+
pub fn gameType(source: &Source) -> Result<Option<Type>, Diagnostic> {
|
|
39
36
|
let Some(main) = source.items.iter().find_map(|i| match i {
|
|
40
37
|
Item::Fn(f) if f.name == "main" && f.type_param.is_none() => Some(f),
|
|
41
38
|
_ => None,
|
|
42
39
|
}) else {
|
|
43
40
|
return Ok(None);
|
|
44
41
|
};
|
|
45
|
-
let Some(ret) = main.returns.as_ref()
|
|
42
|
+
let Some(ret) = main.returns.as_ref() else { return Ok(None) };
|
|
43
|
+
let at = |msg: String| Diagnostic::new(DiagKind::Type, main.file.clone(), main.line, main.column, msg);
|
|
44
|
+
let isStdGame = source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == GAME_TYPE && e.generics.len() == 2));
|
|
45
|
+
if ret.name == GAME_TYPE && isStdGame {
|
|
46
|
+
if ret.generics.len() != 2 {
|
|
47
|
+
return Err(at(format!("a game's `main` returns `Game[S, M]` (its state and message types), not `{}`", crate::main_result::typeText(ret))));
|
|
48
|
+
}
|
|
49
|
+
return Ok(Some(ret.clone()));
|
|
50
|
+
}
|
|
46
51
|
let ty = ret.name.as_str();
|
|
47
52
|
let declared = source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == ty));
|
|
48
|
-
if !declared {
|
|
49
|
-
return Ok(None);
|
|
50
|
-
}
|
|
51
|
-
|
|
53
|
+
if declared && hasMethod(source, ty, "update") && hasMethod(source, ty, "draw") {
|
|
52
|
-
let at = |f: &Fn, msg: String| Diagnostic::new(DiagKind::Type, f.file.clone(), f.line, f.column, msg);
|
|
53
|
-
|
|
54
|
+
return Err(at(format!(
|
|
54
|
-
(None, None) => Ok(None),
|
|
55
|
-
|
|
55
|
+
"`{ty}` has `update` and `draw`, but a game is no longer a type of its own: \
|
|
56
|
-
(None, Some(d)) => Err(at(d, format!("`{ty}` has `draw` but no `update`: a game needs `fun update(self, io: Io, input: Input, dt: Float) -> {ty}` as well"))),
|
|
57
|
-
(Some(u), Some(d)) => {
|
|
58
|
-
let updateOk = u.params.len() == 3
|
|
59
|
-
&& isParam(u, 0, "io", "Io")
|
|
60
|
-
&& isParam(u, 1, "input", "Input")
|
|
61
|
-
&& isParam(u, 2, "dt", "Float")
|
|
62
|
-
&& u.returns.as_ref().is_some_and(|r| r.name == ty && r.generics.is_empty());
|
|
63
|
-
if !updateOk {
|
|
64
|
-
|
|
56
|
+
a game's `main` returns `Game[S, M]`, made by `Game.start(screen, state)` (import std/game/Game; see docs/game.md)"
|
|
65
|
-
}
|
|
66
|
-
if d.params.len() != 1 || !isParam(d, 0, "io", "Io") {
|
|
67
|
-
return Err(at(d, "a game's draw is `fun draw(self, io: Io)`".to_string()));
|
|
68
|
-
}
|
|
69
|
-
|
|
57
|
+
)));
|
|
70
|
-
}
|
|
71
58
|
}
|
|
59
|
+
Ok(None)
|
|
72
60
|
}
|
|
73
61
|
|
|
74
62
|
/// Is `source` a lowered game: does it have the frame entry points?
|
|
@@ -80,7 +68,8 @@ pub fn isLoweredGame(source: &Source) -> bool {
|
|
|
80
68
|
/// If `main` returns a game type, renames `main`, appends the host's state and the frame entry
|
|
81
69
|
/// points, and numbers the new nodes. Returns whether `source` is a game.
|
|
82
70
|
pub fn lowerGame(source: &mut Source) -> Result<bool, Diagnostic> {
|
|
83
|
-
let Some(
|
|
71
|
+
let Some(gameTy) = gameType(source)? else { return Ok(false) };
|
|
72
|
+
let ty = crate::main_result::typeText(&gameTy);
|
|
84
73
|
let mut file = String::new();
|
|
85
74
|
let mut mainTakesIo = false;
|
|
86
75
|
for item in &mut source.items {
|
|
@@ -107,7 +96,7 @@ pub fn lowerGame(source: &mut Source) -> Result<bool, Diagnostic> {
|
|
|
107
96
|
// several wasm values, so the state is always boxed (and the game inside it too).
|
|
108
97
|
for item in &mut source.items {
|
|
109
98
|
if let Item::Enum(e) = item {
|
|
110
|
-
if e.name ==
|
|
99
|
+
if e.name == GAME_TYPE || e.name == GAME_RUN {
|
|
111
100
|
if let Some(info) = e.structInfoMut() {
|
|
112
101
|
info.forceBoxed = true;
|
|
113
102
|
}
|
|
@@ -122,39 +111,64 @@ pub fn lowerGame(source: &mut Source) -> Result<bool, Diagnostic> {
|
|
|
122
111
|
mod tests {
|
|
123
112
|
use super::*;
|
|
124
113
|
|
|
125
|
-
fn
|
|
114
|
+
fn parse(text: &str) -> Source {
|
|
126
|
-
let text = format!(
|
|
127
|
-
"struct G(n: Int) =\n {update}\n G(n: self.n + 1)\n\n fun draw(self, io: Io) =\n io.printLn(\"x\")\n\nfun main(io: Io) -> G =\n G(n: 0)\n"
|
|
128
|
-
);
|
|
129
115
|
let mut parser = tree_sitter::Parser::new();
|
|
130
116
|
parser.set_language(&tree_sitter_plum::LANGUAGE.into()).expect("plum grammar");
|
|
131
|
-
let tree = parser.parse(
|
|
117
|
+
let tree = parser.parse(text, None).expect("parse");
|
|
132
118
|
assert!(!tree.root_node().has_error(), "{text}");
|
|
133
|
-
crate::AstParser::new(
|
|
119
|
+
crate::AstParser::new(text).parseSourceRaw(tree.root_node())
|
|
134
120
|
}
|
|
135
121
|
|
|
122
|
+
/// A stand-in for std/game/Game's `Game[S, M]` and a `main` returning `ret`.
|
|
123
|
+
fn game(ret: &str) -> Source {
|
|
136
|
-
|
|
124
|
+
parse(&format!("struct Game[S, M](n: Int)\n\nfun main(io: Io) -> {ret} =\n todo\n"))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// The old shape: a type of its own with `update` and `draw`.
|
|
128
|
+
fn oldShape(update: &str) -> Source {
|
|
129
|
+
parse(&format!(
|
|
130
|
+
"struct G(n: Int) =\n {update}\n G(n: self.n + 1)\n\n fun draw(self, io: Io) =\n io.printLn(\"x\")\n\nfun main(io: Io) -> G =\n G(n: 0)\n"
|
|
131
|
+
))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#[test]
|
|
135
|
+
fn aMainReturningGameIsAGame() {
|
|
136
|
+
let t = gameType(&game("Game[RunState, Msg]")).expect("a game").expect("is a game");
|
|
137
|
+
assert_eq!(crate::main_result::typeText(&t), "Game[RunState, Msg]");
|
|
138
|
+
}
|
|
137
139
|
|
|
138
140
|
#[test]
|
|
139
|
-
fn
|
|
141
|
+
fn aGameWithoutItsTypeArgumentsIsAnError() {
|
|
140
|
-
|
|
142
|
+
let e = gameType(&game("Game")).expect_err("no arguments");
|
|
143
|
+
assert!(e.message.contains("`Game[S, M]`"), "{}", e.message);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#[test]
|
|
147
|
+
fn theOldUpdateAndDrawShapeIsAnErrorNamingGameStart() {
|
|
148
|
+
for update in ["fun update(self, io: Io, input: Input, dt: Float) -> G =", "fun update(self, io: Io, dt: Float) -> G ="] {
|
|
149
|
+
let e = gameType(&oldShape(update)).expect_err("old shape");
|
|
150
|
+
assert!(e.message.contains("`G` has `update` and `draw`") && e.message.contains("Game.start(screen, state)"), "{}", e.message);
|
|
151
|
+
}
|
|
141
152
|
}
|
|
142
153
|
|
|
143
154
|
#[test]
|
|
144
|
-
fn
|
|
155
|
+
fn otherMainsAreNotGames() {
|
|
156
|
+
assert!(gameType(&parse("struct G(n: Int)\n\nfun main(io: Io) -> G =\n G(n: 0)\n")).expect("ok").is_none());
|
|
145
|
-
|
|
157
|
+
assert!(gameType(&parse("fun main(io: Io) -> Int =\n 0\n")).expect("ok").is_none());
|
|
158
|
+
// a type named Game that is not std's two-parameter one
|
|
146
|
-
assert!(
|
|
159
|
+
assert!(gameType(&parse("struct Game(n: Int)\n\nfun main(io: Io) -> Game =\n Game(n: 0)\n")).expect("ok").is_none());
|
|
147
160
|
}
|
|
148
161
|
|
|
149
162
|
#[test]
|
|
150
163
|
fn loweringWrapsTheGameAndItsClock() {
|
|
151
|
-
let mut src =
|
|
164
|
+
let mut src = game("Game[RunState, Msg]");
|
|
152
165
|
assert!(lowerGame(&mut src).expect("lowers"));
|
|
153
166
|
let fns: Vec<&str> = src.items.iter().filter_map(|i| if let Item::Fn(f) = i { Some(f.name.as_str()) } else { None }).collect();
|
|
154
167
|
for name in [GAME_USER_MAIN, "main", GAME_UPDATE, GAME_TICKS, GAME_TICK, GAME_DRAW] {
|
|
155
168
|
assert_eq!(fns.iter().filter(|n| **n == name).count(), 1, "{name} in {fns:?}");
|
|
156
169
|
}
|
|
157
170
|
let run = src.items.iter().find_map(|i| if let Item::Enum(e) = i { (e.name == GAME_RUN).then_some(e) } else { None });
|
|
171
|
+
let run = run.expect("GameRun");
|
|
158
|
-
assert!(run.
|
|
172
|
+
assert!(run.structInfo().is_some_and(|s| s.forceBoxed));
|
|
159
173
|
}
|
|
160
174
|
}
|
compiler/core/src/main_result.rs
CHANGED
|
@@ -10,7 +10,7 @@ use crate::visit::{stmtBlocks, visitBlock, visitExpr};
|
|
|
10
10
|
/// What the user's `main` is called once the wrapper is the program's `main`.
|
|
11
11
|
pub const USER_MAIN: &str = "userMainResult";
|
|
12
12
|
|
|
13
|
-
fn typeText(t: &Type) -> String {
|
|
13
|
+
pub(crate) fn typeText(t: &Type) -> String {
|
|
14
14
|
if t.generics.is_empty() {
|
|
15
15
|
t.name.clone()
|
|
16
16
|
} else {
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -213,64 +213,59 @@ fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
|
|
|
213
213
|
assert!(!spreadInPlace(&info, "Orb", "update"), "`o` is stored in `b` as well");
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
-
// ---- a game
|
|
216
|
+
// ---- a game: the host is the caller the proof cannot see ----
|
|
217
217
|
|
|
218
|
-
///
|
|
218
|
+
/// A game (std/game/Game) of one screen, `Pane`, holding one actor, `Stress`; `step`, `draw`
|
|
219
|
+
/// and `main` are the bodies of the actor's step, the screen's draw and the game's start.
|
|
219
|
-
fn
|
|
220
|
+
fn gameSource(name: &str, main: &str, step: &str, draw: &str) -> Source {
|
|
220
221
|
let text = format!(
|
|
221
222
|
"module {name}\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/input\n\
|
|
223
|
+
import std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\n\
|
|
224
|
+
import std/game/scene/Ctx\nimport std/game/scene/SceneTree\n\
|
|
222
225
|
Start = Stress(label: \"s\", t: 0)\n\
|
|
226
|
+
struct Quiet(n: Int) is Reducer[Int] =\n fun update(self, msg: Int) -> Quiet = self\n\
|
|
223
|
-
struct Stress(label: Str, t: Int) =\n \
|
|
227
|
+
struct Stress(label: Str, t: Int) is Actor[Int] =\n \
|
|
228
|
+
fun key(self) -> Int = 1\n \
|
|
229
|
+
fun place(self) -> Place = place.at(0.0, 0.0)\n \
|
|
224
|
-
fun
|
|
230
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Stress =\n {step}\n\
|
|
231
|
+
struct Pane(t: SceneTree[Int], n: Int) is Screen[Quiet, Int] =\n \
|
|
232
|
+
fun tree(self) -> SceneTree[Int] = self.t\n \
|
|
233
|
+
fun withTree(self, t: SceneTree[Int]) -> Pane = Pane(..self, t: t)\n \
|
|
234
|
+
fun later(self) -> Pane = Pane(..self, n: 99)\n \
|
|
225
235
|
fun draw(self, io: Io) =\n {draw}\n\
|
|
226
|
-
fun main(io: Io) ->
|
|
236
|
+
fun main(io: Io) -> Game[Quiet, Int] = Game.start(Pane(t: SceneTree.of({main}), n: 0), Quiet(n: 0))\n"
|
|
227
237
|
);
|
|
228
238
|
let mut src = load(name, &text);
|
|
229
239
|
assert!(plum_core::game_entry::lowerGame(&mut src).expect("lowers"), "{name} is a game");
|
|
230
|
-
let info = check(&src, &PassOptions::default()).expect("checks");
|
|
231
|
-
|
|
240
|
+
src
|
|
232
241
|
}
|
|
233
242
|
|
|
234
|
-
const
|
|
243
|
+
const FRESH_ACTOR: &str = "Stress(label: \"s\", t: 0)";
|
|
235
244
|
const SPREAD_T: &str = "Stress(..self, t: self.t + 1)";
|
|
236
|
-
const
|
|
245
|
+
const DRAW_N: &str = "io.printLn(\"{self.n}\")";
|
|
237
|
-
|
|
238
|
-
#[test]
|
|
239
|
-
fn gameStateFromAFreshMainUpdatesInPlace() {
|
|
240
|
-
assert!(gameUpdateInPlace("g_fresh", FRESH_MAIN, SPREAD_T, DRAW_T));
|
|
241
|
-
}
|
|
242
246
|
|
|
247
|
+
/// The game holds the constant itself: writing the actor in place would overwrite `Start`.
|
|
243
248
|
#[test]
|
|
244
|
-
fn
|
|
249
|
+
fn gameStartingFromAConstantActorCopies() {
|
|
245
|
-
|
|
250
|
+
let info = check(&gameSource("g_const", "Start", SPREAD_T, DRAW_N), &PassOptions::default()).expect("checks");
|
|
251
|
+
assert!(!spreadInPlace(&info, "Stress", "step"));
|
|
246
252
|
}
|
|
247
253
|
|
|
248
|
-
///
|
|
254
|
+
/// A step may hand the game the constant on any tick, and the next tick would write into it.
|
|
249
255
|
#[test]
|
|
250
|
-
fn
|
|
256
|
+
fn gameStepReturningAConstantCopies() {
|
|
257
|
+
let step = format!("if self.t > 5 then Start else {SPREAD_T}");
|
|
258
|
+
let info = check(&gameSource("g_reset", FRESH_ACTOR, &step, DRAW_N), &PassOptions::default()).expect("checks");
|
|
251
|
-
assert!(!
|
|
259
|
+
assert!(!spreadInPlace(&info, "Stress", "step"));
|
|
252
260
|
}
|
|
253
261
|
|
|
254
|
-
///
|
|
262
|
+
/// The host reads the game again next frame, so the screen's `draw` must not write it, even
|
|
263
|
+
/// when it is the only caller of a method with a spread.
|
|
255
264
|
#[test]
|
|
256
|
-
fn gameUpdateReturningAConstantCopies() {
|
|
257
|
-
assert!(!gameUpdateInPlace("g_reset", FRESH_MAIN, &format!("if self.t > 5 then Start else {SPREAD_T}"), DRAW_T));
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/// The host reads the state again next frame, so `draw` must not write it, even when it is the
|
|
261
|
-
/// only caller of a method with a spread.
|
|
262
|
-
#[test]
|
|
263
|
-
fn
|
|
265
|
+
fn gameDrawNeverWritesTheScreenInPlace() {
|
|
264
|
-
let text = "module g_draw\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/input\n\
|
|
265
|
-
struct Stress(label: Str, t: Int) =\n \
|
|
266
|
-
fun update(self, io: Io, input: Input, dt: Float) -> Stress = Stress(label: self.label, t: self.t + 1)\n \
|
|
267
|
-
fun later(self) -> Stress = Stress(..self, t: 99)\n \
|
|
268
|
-
|
|
266
|
+
let draw = "x := self.later()\n io.printLn(\"{x.n}\")";
|
|
269
|
-
fun main(io: Io) -> Stress = Stress(label: \"s\", t: 0)\n";
|
|
270
|
-
let mut src = load("g_draw", text);
|
|
271
|
-
assert!(plum_core::game_entry::lowerGame(&mut src).expect("lowers"));
|
|
272
|
-
let info = check(&
|
|
267
|
+
let info = check(&gameSource("g_draw", FRESH_ACTOR, SPREAD_T, draw), &PassOptions::default()).expect("checks");
|
|
273
|
-
assert!(!spreadInPlace(&info, "
|
|
268
|
+
assert!(!spreadInPlace(&info, "Pane", "later"));
|
|
274
269
|
}
|
|
275
270
|
|
|
276
271
|
/// Purity keys a method by the receiver's type: `Orb.bump` writes a field of its argument, so it
|
compiler/game/src/host.rs
CHANGED
|
@@ -263,7 +263,7 @@ impl<B: Backend> PlumGame<B> {
|
|
|
263
263
|
for name in ["main", "update", "draw"] {
|
|
264
264
|
if module.get_export(name).is_none() {
|
|
265
265
|
let old = if name == "main" && module.get_export("init").is_some() {
|
|
266
|
-
" (the `export fun init` entry is gone: write `fun main(io: Io) ->
|
|
266
|
+
" (the `export fun init` entry is gone: write `fun main(io: Io) -> Game[S, M]` returning `Game.start(screen, state)`)"
|
|
267
267
|
} else {
|
|
268
268
|
""
|
|
269
269
|
};
|
compiler/game/tests/fixtures/assets_fixture.plum
CHANGED
|
@@ -9,15 +9,25 @@ import std/game/Color
|
|
|
9
9
|
import std/game/gfx
|
|
10
10
|
import std/Io
|
|
11
11
|
import std/game/input
|
|
12
|
+
import std/game/Affine
|
|
13
|
+
import std/game/Store
|
|
14
|
+
import std/game/Game
|
|
15
|
+
import std/game/scene/Place
|
|
16
|
+
import std/game/scene/Actor
|
|
17
|
+
import std/game/scene/Ctx
|
|
18
|
+
import std/game/scene/SceneTree
|
|
12
19
|
|
|
13
20
|
# Loads through the raw `io` (a missing file answers -1 or empty, where `Texture.load`
|
|
14
21
|
# would crash) and draws through it.
|
|
15
|
-
struct State(frames: Int) =
|
|
22
|
+
struct State(frames: Int) is Actor[Int] =
|
|
23
|
+
fun key(self) -> Int = 1
|
|
24
|
+
|
|
25
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
26
|
+
|
|
16
|
-
fun
|
|
27
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> State = State(frames: self.frames + 1)
|
|
17
|
-
State(frames: self.frames + 1)
|
|
18
28
|
|
|
19
29
|
# Loads a texture and files from the asset root and reports what came back as text.
|
|
20
|
-
fun
|
|
30
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
21
31
|
t := Texture(id: gfx.textureLoad(io, "sprites.png"))
|
|
22
32
|
gfx.drawText(io, "size {gfx.textureWidth(io, t.id)}x{gfx.textureHeight(io, t.id)}", 0.0, 0.0, 8.0, Color.White)
|
|
23
33
|
t.setSmooth(io, true)
|
|
@@ -30,5 +40,17 @@ struct State(frames: Int) =
|
|
|
30
40
|
gfx.drawText(io, "escape {gfx.textureLoad(io, "../sprites.png")} {gfx.fileExists(io, "../hello.txt")} [{gfx.fileLoad(io, "../hello.txt")}]", 0.0, 0.0, 8.0, Color.White)
|
|
31
41
|
gfx.drawText(io, "abs {gfx.textureLoad(io, "/etc/hosts")} {gfx.fileExists(io, "/etc/hosts")}", 0.0, 0.0, 8.0, Color.White)
|
|
32
42
|
|
|
33
|
-
fun main(io: Io) ->
|
|
43
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
44
|
+
Game.start(Page(t: SceneTree.of(State(frames: 0))), Quiet(n: 0))
|
|
45
|
+
|
|
46
|
+
# The game sends no messages, so its state never changes.
|
|
47
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
34
|
-
|
|
48
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
49
|
+
|
|
50
|
+
# The one screen: its tree drawn in screen pixels.
|
|
51
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
52
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
53
|
+
|
|
54
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
55
|
+
|
|
56
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/host_fixture.plum
CHANGED
|
@@ -9,13 +9,24 @@ import std/game/Color
|
|
|
9
9
|
import std/game/gfx
|
|
10
10
|
import std/Io
|
|
11
11
|
import std/game/input
|
|
12
|
+
import std/game/Affine
|
|
13
|
+
import std/game/Store
|
|
14
|
+
import std/game/Game
|
|
15
|
+
import std/game/scene/Place
|
|
16
|
+
import std/game/scene/Actor
|
|
17
|
+
import std/game/scene/Ctx
|
|
18
|
+
import std/game/scene/SceneTree
|
|
12
19
|
|
|
13
|
-
# One raw host read in `draw` (`mousePos`), so the recorded call order is fixed.
|
|
20
|
+
# One raw host read in `draw` (`mousePos`), so the recorded call order is fixed. The
|
|
21
|
+
# game is one actor on one screen, counting the ticks.
|
|
14
|
-
struct State(frames: Int) =
|
|
22
|
+
struct State(frames: Int) is Actor[Int] =
|
|
15
|
-
fun update(self, io: Io, input: Input, dt: Float) -> State =
|
|
16
|
-
|
|
23
|
+
fun key(self) -> Int = 1
|
|
17
24
|
|
|
25
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
26
|
+
|
|
27
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> State = State(frames: self.frames + 1)
|
|
28
|
+
|
|
18
|
-
fun
|
|
29
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
19
30
|
gfx.clear(io, Color.Black)
|
|
20
31
|
gfx.drawRect(io, 1.0, 2.0, 3.0, 4.0, Color.Red)
|
|
21
32
|
gfx.drawCircle(io, 5.0, 6.0, 7.0, Color.Green)
|
|
@@ -24,5 +35,17 @@ struct State(frames: Int) =
|
|
|
24
35
|
if self.frames > 0
|
|
25
36
|
gfx.drawText(io, "frames {self.frames}", 0.0, 0.0, 8.0, Color.White)
|
|
26
37
|
|
|
27
|
-
fun main(io: Io) ->
|
|
38
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
39
|
+
Game.start(Page(t: SceneTree.of(State(frames: 0))), Quiet(n: 0))
|
|
40
|
+
|
|
41
|
+
# The game sends no messages, so its state never changes.
|
|
42
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
28
|
-
|
|
43
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
44
|
+
|
|
45
|
+
# The one screen: its tree drawn in screen pixels.
|
|
46
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
47
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
48
|
+
|
|
49
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
50
|
+
|
|
51
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/main_game_fixture.plum
CHANGED
|
@@ -9,18 +9,43 @@ import std/game/Vec2
|
|
|
9
9
|
import std/game/Color
|
|
10
10
|
import std/game/gfx
|
|
11
11
|
import std/game/input
|
|
12
|
+
import std/game/Affine
|
|
13
|
+
import std/game/Store
|
|
14
|
+
import std/game/Game
|
|
15
|
+
import std/game/scene/Place
|
|
16
|
+
import std/game/scene/Actor
|
|
17
|
+
import std/game/scene/Ctx
|
|
18
|
+
import std/game/scene/SceneTree
|
|
12
19
|
import std/Io
|
|
13
20
|
|
|
14
|
-
# A game whose entry is `main`, declared to return `
|
|
21
|
+
# A game whose entry is `main`, declared to return a `Game`: one actor, `Orbs`, that
|
|
22
|
+
# keeps the input of its last step and moves while Right is held.
|
|
15
|
-
struct Orbs(x: Float, ship: Texture, input: Input, frame: Int) =
|
|
23
|
+
struct Orbs(x: Float, ship: Texture, input: Input, frame: Int) is Actor[Int] =
|
|
24
|
+
fun key(self) -> Int = 1
|
|
25
|
+
|
|
26
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
27
|
+
|
|
16
|
-
fun
|
|
28
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Orbs =
|
|
29
|
+
input := ctx.input
|
|
17
30
|
x := if input.isKeyDown(Key.Right) then self.x + 100.0 * dt else self.x
|
|
18
31
|
Orbs(..self, x: x, input: input, frame: self.frame + 1)
|
|
19
32
|
|
|
20
|
-
fun
|
|
33
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
21
34
|
first := self.input.events.length()
|
|
22
35
|
second := self.input.events.length()
|
|
23
36
|
gfx.drawText(io, "frame {self.frame} ev {first} {second} x {self.x} tex {self.ship.id} w {gfx.screenWidth(io)}", 0.0, 0.0, 8.0, Color.White)
|
|
24
37
|
|
|
25
|
-
fun main(io: Io) ->
|
|
38
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
26
|
-
Orbs(x: 0.0, ship: gfx.loadTexture(io, "sprites.png"), input: Input.create(), frame: 0)
|
|
39
|
+
Game.start(Page(t: SceneTree.of(Orbs(x: 0.0, ship: gfx.loadTexture(io, "sprites.png"), input: Input.create(), frame: 0))), Quiet(n: 0))
|
|
40
|
+
|
|
41
|
+
# The game sends no messages, so its state never changes.
|
|
42
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
43
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
44
|
+
|
|
45
|
+
# The one screen: its tree drawn in screen pixels.
|
|
46
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
47
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
48
|
+
|
|
49
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
50
|
+
|
|
51
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/main_missing_fixture.plum
CHANGED
|
@@ -7,13 +7,34 @@ import std/game/Color
|
|
|
7
7
|
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
18
|
+
# Its texture is missing: `main` crashes naming it.
|
|
11
|
-
struct Broken(tex: Texture) =
|
|
19
|
+
struct Broken(tex: Texture) is Actor[Int] =
|
|
12
|
-
fun
|
|
20
|
+
fun key(self) -> Int = 1
|
|
13
|
-
self
|
|
14
21
|
|
|
22
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
23
|
+
|
|
15
|
-
fun
|
|
24
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
16
25
|
gfx.clear(io, Color.Black)
|
|
17
26
|
|
|
18
|
-
fun main(io: Io) ->
|
|
27
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
19
|
-
Broken(tex: gfx.loadTexture(io, "nope.png"))
|
|
28
|
+
Game.start(Page(t: SceneTree.of(Broken(tex: gfx.loadTexture(io, "nope.png")))), Quiet(n: 0))
|
|
29
|
+
|
|
30
|
+
# The game sends no messages, so its state never changes.
|
|
31
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
32
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
33
|
+
|
|
34
|
+
# The one screen: its tree drawn in screen pixels.
|
|
35
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
36
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
37
|
+
|
|
38
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
39
|
+
|
|
40
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/state_draw_keeps.plum
CHANGED
|
@@ -7,18 +7,41 @@ import std/game/Color
|
|
|
7
7
|
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
11
|
-
# `
|
|
18
|
+
# `paint` keeps the actor it is given: the next `step` must not write that object in place.
|
|
12
19
|
struct Log(mut last: Option[Run])
|
|
13
20
|
|
|
14
|
-
struct Run(label: Str, log: Log, t: Int) =
|
|
21
|
+
struct Run(label: Str, log: Log, t: Int) is Actor[Int] =
|
|
15
|
-
fun
|
|
22
|
+
fun key(self) -> Int = 1
|
|
16
23
|
|
|
24
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
25
|
+
|
|
26
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Run = Run(..self, t: self.t + 1)
|
|
27
|
+
|
|
17
|
-
fun
|
|
28
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
18
29
|
before := match self.log.last
|
|
19
30
|
Some(r) => r.t
|
|
20
31
|
None => -1
|
|
21
32
|
self.log.last = Some(self)
|
|
22
33
|
gfx.drawText(io, "{before} {self.t}", 0.0, 0.0, 8.0, Color.White)
|
|
23
34
|
|
|
24
|
-
fun main(io: Io) ->
|
|
35
|
+
fun main(io: Io) -> Game[Quiet, Int] = Game.start(Page(t: SceneTree.of(Run(label: "r", log: Log(last: None), t: 0))), Quiet(n: 0))
|
|
36
|
+
|
|
37
|
+
# The game sends no messages, so its state never changes.
|
|
38
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
39
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
40
|
+
|
|
41
|
+
# The one screen: its tree drawn in screen pixels.
|
|
42
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
43
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
44
|
+
|
|
45
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
46
|
+
|
|
47
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/state_in_place.plum
CHANGED
|
@@ -7,20 +7,43 @@ import std/game/Color
|
|
|
7
7
|
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
11
18
|
struct Part(label: Str, x: Int) =
|
|
12
19
|
fun step(self) -> Part = Part(..self, x: self.x + 1)
|
|
13
20
|
|
|
14
|
-
# `
|
|
21
|
+
# `step` writes the actor and its field in place; `paint` updates a value of its own, which
|
|
15
|
-
# must not reach the
|
|
22
|
+
# must not reach the actor the game keeps for the next frame.
|
|
16
|
-
struct Run(part: Part, t: Int) =
|
|
23
|
+
struct Run(part: Part, t: Int) is Actor[Int] =
|
|
24
|
+
fun key(self) -> Int = 1
|
|
25
|
+
|
|
26
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
27
|
+
|
|
17
|
-
fun
|
|
28
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Run =
|
|
18
29
|
Run(..self, part: self.part.step(), t: self.t + 1)
|
|
19
30
|
|
|
20
31
|
fun drawn(self) -> Run = Run(..self, t: 99)
|
|
21
32
|
|
|
22
|
-
fun
|
|
33
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
23
34
|
d := self.drawn()
|
|
24
35
|
gfx.drawText(io, "{d.t} {self.t} {self.part.x}", 0.0, 0.0, 8.0, Color.White)
|
|
25
36
|
|
|
26
|
-
fun main(io: Io) ->
|
|
37
|
+
fun main(io: Io) -> Game[Quiet, Int] = Game.start(Page(t: SceneTree.of(Run(part: Part(label: "p", x: 0), t: 0))), Quiet(n: 0))
|
|
38
|
+
|
|
39
|
+
# The game sends no messages, so its state never changes.
|
|
40
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
41
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
42
|
+
|
|
43
|
+
# The one screen: its tree drawn in screen pixels.
|
|
44
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
45
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
46
|
+
|
|
47
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
48
|
+
|
|
49
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/state_main_alias.plum
CHANGED
|
@@ -7,16 +7,40 @@ import std/game/Color
|
|
|
7
7
|
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
11
|
-
# `main`
|
|
18
|
+
# `main` starts the game with a local, but the local is a constant: `step` must not write
|
|
19
|
+
# it in place.
|
|
12
20
|
Start = Run(label: "start", t: 0)
|
|
13
21
|
|
|
14
|
-
struct Run(label: Str, t: Int) =
|
|
22
|
+
struct Run(label: Str, t: Int) is Actor[Int] =
|
|
15
|
-
fun
|
|
23
|
+
fun key(self) -> Int = 1
|
|
16
24
|
|
|
25
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
26
|
+
|
|
27
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Run = Run(..self, t: self.t + 1)
|
|
28
|
+
|
|
17
|
-
fun
|
|
29
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
18
30
|
gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
|
|
19
31
|
|
|
20
|
-
fun main(io: Io) ->
|
|
32
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
21
33
|
s := Start
|
|
34
|
+
Game.start(Page(t: SceneTree.of(s)), Quiet(n: 0))
|
|
35
|
+
|
|
36
|
+
# The game sends no messages, so its state never changes.
|
|
22
|
-
|
|
37
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
38
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
39
|
+
|
|
40
|
+
# The one screen: its tree drawn in screen pixels.
|
|
41
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
42
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
43
|
+
|
|
44
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
45
|
+
|
|
46
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/state_reset.plum
CHANGED
|
@@ -7,15 +7,38 @@ import std/game/Color
|
|
|
7
7
|
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
11
|
-
# The
|
|
18
|
+
# The actor goes back to a constant: writing it in place would overwrite the constant.
|
|
12
19
|
Start = Run(label: "start", t: 0)
|
|
13
20
|
|
|
14
|
-
struct Run(label: Str, t: Int) =
|
|
21
|
+
struct Run(label: Str, t: Int) is Actor[Int] =
|
|
22
|
+
fun key(self) -> Int = 1
|
|
23
|
+
|
|
24
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
25
|
+
|
|
15
|
-
fun
|
|
26
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Run =
|
|
16
27
|
if self.t >= 2 then Start else Run(..self, t: self.t + 1)
|
|
17
28
|
|
|
18
|
-
fun
|
|
29
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
19
30
|
gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
|
|
20
31
|
|
|
32
|
+
fun main(io: Io) -> Game[Quiet, Int] = Game.start(Page(t: SceneTree.of(Start)), Quiet(n: 0))
|
|
33
|
+
|
|
34
|
+
# The game sends no messages, so its state never changes.
|
|
35
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
21
|
-
fun
|
|
36
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
37
|
+
|
|
38
|
+
# The one screen: its tree drawn in screen pixels.
|
|
39
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
40
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
41
|
+
|
|
42
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
43
|
+
|
|
44
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/fixtures/target_fixture.plum
CHANGED
|
@@ -8,14 +8,22 @@ import std/game/Color
|
|
|
8
8
|
import std/game/gfx
|
|
9
9
|
import std/Io
|
|
10
10
|
import std/game/input
|
|
11
|
+
import std/game/Affine
|
|
12
|
+
import std/game/Store
|
|
13
|
+
import std/game/Game
|
|
14
|
+
import std/game/scene/Place
|
|
15
|
+
import std/game/scene/Actor
|
|
16
|
+
import std/game/scene/Ctx
|
|
17
|
+
import std/game/scene/SceneTree
|
|
11
18
|
|
|
12
19
|
# `bad` is a raw `io.textureCreate` of an impossible size: it answers -1 where
|
|
13
20
|
# `Texture.create` would crash.
|
|
14
|
-
struct State(target: Texture, bad: Int) =
|
|
21
|
+
struct State(target: Texture, bad: Int) is Actor[Int] =
|
|
15
|
-
fun
|
|
22
|
+
fun key(self) -> Int = 1
|
|
16
|
-
self
|
|
17
23
|
|
|
24
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
25
|
+
|
|
18
|
-
fun
|
|
26
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
19
27
|
self.target.renderTarget(io)
|
|
20
28
|
gfx.clear(io, Color.Transparent)
|
|
21
29
|
gfx.drawRect(io, 0.0, 0.0, 10.0, 10.0, Color.Red)
|
|
@@ -25,5 +33,17 @@ struct State(target: Texture, bad: Int) =
|
|
|
25
33
|
gfx.blendMode(io, Blend.Normal)
|
|
26
34
|
gfx.drawText(io, "size {self.target.width(io)}x{self.target.height(io)} bad {self.bad}", 0.0, 0.0, 8.0, Color.White)
|
|
27
35
|
|
|
28
|
-
fun main(io: Io) ->
|
|
36
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
29
|
-
State(target: gfx.createTexture(io, 64, 32), bad: gfx.textureCreate(io, 0, 5))
|
|
37
|
+
Game.start(Page(t: SceneTree.of(State(target: gfx.createTexture(io, 64, 32), bad: gfx.textureCreate(io, 0, 5)))), Quiet(n: 0))
|
|
38
|
+
|
|
39
|
+
# The game sends no messages, so its state never changes.
|
|
40
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
41
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
42
|
+
|
|
43
|
+
# The one screen: its tree drawn in screen pixels.
|
|
44
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
45
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
46
|
+
|
|
47
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
48
|
+
|
|
49
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -141,7 +141,7 @@ fn oldInitEntryIsRejected() {
|
|
|
141
141
|
let out = plum_wasm_codegen::compile(&source, &plum_wasm_codegen::CompileOptions::default()).expect("compile");
|
|
142
142
|
assert!(!out.isGame);
|
|
143
143
|
let err = PlumGame::load(&out.wasm, Recorder::new()).err().expect("should fail");
|
|
144
|
-
assert!(err.to_string().contains("`main`") && err.to_string().contains("fun main(io: Io) ->
|
|
144
|
+
assert!(err.to_string().contains("`main`") && err.to_string().contains("fun main(io: Io) -> Game[S, M]"), "{err}");
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
#[test]
|
|
@@ -151,7 +151,7 @@ fn unknownImportTraps() {
|
|
|
151
151
|
let path = dir.join("m.plum");
|
|
152
152
|
std::fs::write(
|
|
153
153
|
&path,
|
|
154
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/gfx\nimport std/game/input\nstruct
|
|
154
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/game/Vec2\nimport std/game/Affine\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\nimport std/game/scene/Ctx\nimport std/game/scene/SceneTree\nstruct Quiet(n: Int) is Reducer[Int] =\n fun update(self, msg: Int) -> Quiet = self\nstruct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =\n fun tree(self) -> SceneTree[Int] = self.t\n fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)\n fun draw(self, io: Io) = self.t.paint(io)\nstruct State(n: Int) is Actor[Int] =\n fun key(self) -> Int = 1\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paint(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nfun main(io: Io) -> Game[Quiet, Int] =\n Game.start(Page(t: SceneTree.of(State(n: 0))), Quiet(n: 0))\n",
|
|
155
155
|
)
|
|
156
156
|
.unwrap();
|
|
157
157
|
let wasm = compile(&path);
|
|
@@ -255,6 +255,13 @@ fn exampleGameRunsFrames() {
|
|
|
255
255
|
let wasm = compile(&root().join("examples/games/orb_run.plum"));
|
|
256
256
|
let mut g = PlumGame::load(&wasm, Recorder::with_assets(examples_assets())).expect("load game");
|
|
257
257
|
g.init().expect("init");
|
|
258
|
+
// The title screen, then Enter starts a run.
|
|
259
|
+
g.update(1.0 / 60.0).expect("update");
|
|
260
|
+
g.draw().expect("draw");
|
|
261
|
+
assert!(g.backend().calls.contains(&"drawText(\"Orb Run\",280,200,64,1,0.8,0.3,1)".to_string()), "{:?}", g.backend().calls);
|
|
262
|
+
g.backend_mut().keys_down.insert(257);
|
|
263
|
+
g.update(1.0 / 60.0).expect("update");
|
|
264
|
+
g.backend_mut().keys_down.clear();
|
|
258
265
|
for _ in 0..60 {
|
|
259
266
|
g.update(1.0 / 60.0).expect("update");
|
|
260
267
|
}
|
|
@@ -359,7 +366,7 @@ fn randomSeedProvidedByHost() {
|
|
|
359
366
|
let path = dir.join("m.plum");
|
|
360
367
|
std::fs::write(
|
|
361
368
|
&path,
|
|
362
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nstruct
|
|
369
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/game/Vec2\nimport std/game/Affine\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\nimport std/game/scene/Ctx\nimport std/game/scene/SceneTree\nstruct Quiet(n: Int) is Reducer[Int] =\n fun update(self, msg: Int) -> Quiet = self\nstruct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =\n fun tree(self) -> SceneTree[Int] = self.t\n fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)\n fun draw(self, io: Io) = self.t.paint(io)\nstruct State(seed: Int) is Actor[Int] =\n fun key(self) -> Int = 1\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun paint(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"seed {self.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game[Quiet, Int] =\n Game.start(Page(t: SceneTree.of(State(seed: io.randomSeed()))), Quiet(n: 0))\n",
|
|
363
370
|
)
|
|
364
371
|
.unwrap();
|
|
365
372
|
let wasm = compile(&path);
|
|
@@ -383,7 +390,7 @@ fn seedGame(name: &str) -> Vec<u8> {
|
|
|
383
390
|
let path = dir.join("m.plum");
|
|
384
391
|
std::fs::write(
|
|
385
392
|
&path,
|
|
386
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nstruct State(seed: Int, ticks: Int, keys: Int, x: Float, w: Float) =\n fun
|
|
393
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/game/Vec2\nimport std/game/Affine\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\nimport std/game/scene/Ctx\nimport std/game/scene/SceneTree\nstruct Quiet(n: Int) is Reducer[Int] =\n fun update(self, msg: Int) -> Quiet = self\nstruct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =\n fun tree(self) -> SceneTree[Int] = self.t\n fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)\n fun draw(self, io: Io) = self.t.paint(io)\nstruct State(seed: Int, ticks: Int, keys: Int, x: Float, w: Float) is Actor[Int] =\n fun key(self) -> Int = 1\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun step(self, ctx: Ctx[Int], dt: Float) -> State =\n State(..self, ticks: self.ticks + 1, keys: self.keys + ctx.input.held.keys.length(), x: ctx.input.pos.x, w: ctx.view.x)\n fun paint(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"seed {self.seed} ticks {self.ticks} keys {self.keys} x {self.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game[Quiet, Int] =\n Game.start(Page(t: SceneTree.of(State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0, w: 0.0))), Quiet(n: 0))\n",
|
|
387
394
|
)
|
|
388
395
|
.unwrap();
|
|
389
396
|
let wasm = compile(&path);
|
|
@@ -449,7 +456,8 @@ fn derivedHalvesMatchTheBrowsers() {
|
|
|
449
456
|
assert_eq!(derived_half(1, 2, 1000000), 1266057807);
|
|
450
457
|
}
|
|
451
458
|
|
|
452
|
-
/// A game that takes a seed twice in `main` and once more in each tick
|
|
459
|
+
/// A game that takes a seed twice in `main` and once more in each tick (in the effects of the
|
|
460
|
+
/// tick's message, `handle`) replays all of them.
|
|
453
461
|
#[test]
|
|
454
462
|
fn everySeedOfARecordedRunReplays() {
|
|
455
463
|
let dir = std::env::temp_dir().join(format!("plum_game_replayseeds_{}", std::process::id()));
|
|
@@ -457,7 +465,7 @@ fn everySeedOfARecordedRunReplays() {
|
|
|
457
465
|
let path = dir.join("m.plum");
|
|
458
466
|
std::fs::write(
|
|
459
467
|
&path,
|
|
460
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nstruct
|
|
468
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/game/Vec2\nimport std/game/Affine\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\nimport std/game/Store\nimport std/game/Game\nimport std/game/scene/Place\nimport std/game/scene/Actor\nimport std/game/scene/Ctx\nimport std/game/scene/SceneTree\nstruct Seeds(mut c: Int)\nstruct Mixed(seeds: Seeds) is Reducer[Int] =\n fun update(self, msg: Int) -> Mixed = self\n fun handle(self, io: Io, msg: Int) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\nstruct Page(t: SceneTree[Int]) is Screen[Mixed, Int] =\n fun tree(self) -> SceneTree[Int] = self.t\n fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)\n fun draw(self, io: Io) = self.t.paint(io)\nstruct State(a: Int, b: Int, seeds: Seeds) is Actor[Int] =\n fun key(self) -> Int = 1\n fun place(self) -> Place = place.at(0.0, 0.0)\n fun step(self, ctx: Ctx[Int], dt: Float) -> State =\n ctx.send(1)\n self\n fun paint(self, io: Io, m: Affine, alpha: Float) =\n gfx.drawText(io, \"{self.a} {self.b} {self.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> Game[Mixed, Int] =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n Game.start(Page(t: SceneTree.of(State(a: a, b: io.randomSeed(), seeds: seeds))), Mixed(seeds: seeds))\n",
|
|
461
469
|
)
|
|
462
470
|
.unwrap();
|
|
463
471
|
let wasm = compile(&path);
|
|
@@ -508,7 +516,7 @@ fn mainGame(rec: Recorder) -> PlumGame<Recorder> {
|
|
|
508
516
|
}
|
|
509
517
|
|
|
510
518
|
#[test]
|
|
511
|
-
fn
|
|
519
|
+
fn mainReturningAGameIsAGame() {
|
|
512
520
|
assert!(fixtureOut("main_game_fixture.plum").isGame);
|
|
513
521
|
assert!(!fixtureOut("main_cli_fixture.plum").isGame);
|
|
514
522
|
assert!(fixtureOut("host_fixture.plum").isGame);
|
compiler/game/web-test/fixtures/interleave.plum
CHANGED
|
@@ -11,24 +11,46 @@ import std/game/Color
|
|
|
11
11
|
import std/game/gfx
|
|
12
12
|
import std/Io
|
|
13
13
|
import std/game/input
|
|
14
|
+
import std/game/Affine
|
|
15
|
+
import std/game/Store
|
|
16
|
+
import std/game/Game
|
|
17
|
+
import std/game/scene/Place
|
|
18
|
+
import std/game/scene/Actor
|
|
19
|
+
import std/game/scene/Ctx
|
|
20
|
+
import std/game/scene/SceneTree
|
|
14
21
|
|
|
15
22
|
Sprites = 4000
|
|
16
23
|
Textures = 8
|
|
17
24
|
WorldW = 1264
|
|
18
25
|
WorldH = 704
|
|
19
26
|
|
|
27
|
+
# The game sends no messages, so its state never changes.
|
|
20
|
-
struct
|
|
28
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
21
|
-
fun update(self,
|
|
29
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
22
|
-
Interleave(..self, t: self.t + 1)
|
|
23
30
|
|
|
31
|
+
# All the sprites, one tick on each tick.
|
|
32
|
+
struct Interleave(tex: Array[Texture], t: Int) is Actor[Int] =
|
|
24
|
-
fun
|
|
33
|
+
fun key(self) -> Int = 1
|
|
25
|
-
drawSprites(io, self.tex, self.t)
|
|
26
34
|
|
|
35
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
36
|
+
|
|
37
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Interleave = Interleave(..self, t: self.t + 1)
|
|
38
|
+
|
|
39
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) = drawSprites(io, self.tex, self.t)
|
|
40
|
+
|
|
41
|
+
# The one screen, drawn in screen pixels.
|
|
42
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
43
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
44
|
+
|
|
45
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
46
|
+
|
|
47
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
|
48
|
+
|
|
27
|
-
fun main(io: Io) ->
|
|
49
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
28
50
|
tex := Array.filled(Textures, Texture(id: -1))
|
|
29
51
|
for i := range Textures
|
|
30
52
|
tex.set(i, gfx.loadTexture(io, "tex{i}.png"))
|
|
31
|
-
Interleave(tex: tex, t: 0)
|
|
53
|
+
Game.start(Page(t: SceneTree.of(Interleave(tex: tex, t: 0))), Quiet(n: 0))
|
|
32
54
|
|
|
33
55
|
fun drawSprites(io: Io, tex: Array[Texture], t: Int) =
|
|
34
56
|
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
compiler/game/web-test/fixtures/main_game.plum
CHANGED
|
@@ -3,21 +3,43 @@ module main_game
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
+
import std/Io
|
|
6
7
|
import std/game/Vec2
|
|
8
|
+
import std/game/Affine
|
|
7
9
|
import std/game/Color
|
|
8
10
|
import std/game/gfx
|
|
9
|
-
import std/Io
|
|
10
11
|
import std/game/input
|
|
12
|
+
import std/game/Store
|
|
13
|
+
import std/game/Game
|
|
14
|
+
import std/game/scene/Place
|
|
15
|
+
import std/game/scene/Actor
|
|
16
|
+
import std/game/scene/Ctx
|
|
17
|
+
import std/game/scene/SceneTree
|
|
18
|
+
|
|
19
|
+
# A game whose `main` returns a `Game`: one screen holding one actor, a square that moves
|
|
20
|
+
# with the tick count. It sends no messages, so its state never changes.
|
|
21
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
22
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
23
|
+
|
|
24
|
+
struct Mover(frame: Int) is Actor[Int] =
|
|
25
|
+
fun key(self) -> Int = 1
|
|
11
26
|
|
|
12
|
-
# A game whose entry is `main` returning a type with `update` and `draw`; draws a square that moves with the frame count.
|
|
13
|
-
struct Mover(frame: Int) =
|
|
14
|
-
fun
|
|
27
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
15
|
-
Mover(frame: self.frame + 1)
|
|
16
28
|
|
|
29
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Mover = Mover(frame: self.frame + 1)
|
|
30
|
+
|
|
17
|
-
fun
|
|
31
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
18
32
|
gfx.clear(io, Color.rgb(0.2, 0.2, 0.2))
|
|
19
33
|
gfx.drawRect(io, Float(self.frame % 600), 100.0, 40.0, 40.0, Color.Yellow)
|
|
20
34
|
gfx.drawText(io, "frame {self.frame}", 20.0, 20.0, 16.0, Color.White)
|
|
21
35
|
|
|
36
|
+
# The one screen, drawn in screen pixels.
|
|
37
|
+
struct Only(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
38
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
39
|
+
|
|
40
|
+
fun withTree(self, t: SceneTree[Int]) -> Only = Only(t: t)
|
|
41
|
+
|
|
42
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
|
43
|
+
|
|
22
|
-
fun main(io: Io) ->
|
|
44
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
23
|
-
Mover(frame: 0)
|
|
45
|
+
Game.start(Only(t: SceneTree.of(Mover(frame: 0))), Quiet(n: 0))
|
compiler/game/web-test/fixtures/rendertarget.plum
CHANGED
|
@@ -19,16 +19,39 @@ import std/game/Color
|
|
|
19
19
|
import std/game/gfx
|
|
20
20
|
import std/Io
|
|
21
21
|
import std/game/input
|
|
22
|
+
import std/game/Affine
|
|
23
|
+
import std/game/Store
|
|
24
|
+
import std/game/Game
|
|
25
|
+
import std/game/scene/Place
|
|
26
|
+
import std/game/scene/Actor
|
|
27
|
+
import std/game/scene/Ctx
|
|
28
|
+
import std/game/scene/SceneTree
|
|
22
29
|
|
|
23
|
-
|
|
30
|
+
# The game sends no messages, so its state never changes.
|
|
31
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
24
|
-
fun update(self,
|
|
32
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
25
|
-
Targets(..self, t: self.t + 1)
|
|
26
33
|
|
|
34
|
+
# The targets and the tick count.
|
|
35
|
+
struct Targets(big: Texture, small: Texture, glass: Texture, t: Int) is Actor[Int] =
|
|
27
|
-
fun
|
|
36
|
+
fun key(self) -> Int = 1
|
|
28
|
-
drawTargets(io, self)
|
|
29
37
|
|
|
38
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
39
|
+
|
|
40
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Targets = Targets(..self, t: self.t + 1)
|
|
41
|
+
|
|
42
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) = drawTargets(io, self)
|
|
43
|
+
|
|
44
|
+
# The one screen, drawn in screen pixels.
|
|
45
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
46
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
47
|
+
|
|
48
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
49
|
+
|
|
50
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
|
51
|
+
|
|
30
|
-
fun main(io: Io) ->
|
|
52
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
31
|
-
Targets(big: gfx.createTexture(io, 64, 64), small: gfx.createTexture(io, 16, 16), glass: gfx.createTexture(io, 16, 16), t: 0)
|
|
53
|
+
targets := Targets(big: gfx.createTexture(io, 64, 64), small: gfx.createTexture(io, 16, 16), glass: gfx.createTexture(io, 16, 16), t: 0)
|
|
54
|
+
Game.start(Page(t: SceneTree.of(targets)), Quiet(n: 0))
|
|
32
55
|
|
|
33
56
|
fun drawTargets(io: Io, g: Targets) =
|
|
34
57
|
gfx.setCamera(io, 10.0, 0.0, 2.0)
|
compiler/game/web-test/fixtures/stress.plum
CHANGED
|
@@ -11,6 +11,13 @@ import std/game/Color
|
|
|
11
11
|
import std/game/gfx
|
|
12
12
|
import std/Io
|
|
13
13
|
import std/game/input
|
|
14
|
+
import std/game/Affine
|
|
15
|
+
import std/game/Store
|
|
16
|
+
import std/game/Game
|
|
17
|
+
import std/game/scene/Place
|
|
18
|
+
import std/game/scene/Actor
|
|
19
|
+
import std/game/scene/Ctx
|
|
20
|
+
import std/game/scene/SceneTree
|
|
14
21
|
|
|
15
22
|
Sprites = 5000
|
|
16
23
|
Rects = 500
|
|
@@ -19,15 +26,30 @@ Texts = 50
|
|
|
19
26
|
WorldW = 1600
|
|
20
27
|
WorldH = 900
|
|
21
28
|
|
|
29
|
+
# The game sends no messages, so its state never changes.
|
|
22
|
-
struct
|
|
30
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
23
|
-
fun update(self,
|
|
31
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
24
|
-
Stress(..self, t: self.t + 1)
|
|
25
32
|
|
|
33
|
+
# The whole scene, drawn from the tick count.
|
|
34
|
+
struct Stress(sheet: Texture, t: Int) is Actor[Int] =
|
|
26
|
-
fun
|
|
35
|
+
fun key(self) -> Int = 1
|
|
27
|
-
drawStress(io, self.sheet, self.t)
|
|
28
36
|
|
|
37
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
38
|
+
|
|
39
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Stress = Stress(..self, t: self.t + 1)
|
|
40
|
+
|
|
41
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) = drawStress(io, self.sheet, self.t)
|
|
42
|
+
|
|
43
|
+
# The one screen, drawn in screen pixels.
|
|
44
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
45
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
46
|
+
|
|
47
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
48
|
+
|
|
49
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
|
50
|
+
|
|
29
|
-
fun main(io: Io) ->
|
|
51
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
30
|
-
Stress(sheet: gfx.loadTexture(io, "sprites.png"), t: 0)
|
|
52
|
+
Game.start(Page(t: SceneTree.of(Stress(sheet: gfx.loadTexture(io, "sprites.png"), t: 0))), Quiet(n: 0))
|
|
31
53
|
|
|
32
54
|
fun hue(i: Int) -> Color =
|
|
33
55
|
Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
|
compiler/game/web-test/fixtures/stress_scene_port.plum
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
# fixed step in its own `step` (a spread), and the tree's `draw` paints them. Motion is
|
|
6
6
|
# per frame, as in the original. The text is rebuilt in the step and input is polled
|
|
7
7
|
# every frame, also as in the original, so the update and draw split stays comparable.
|
|
8
|
+
# It is a `Game` with one screen and a state that never changes.
|
|
8
9
|
# Written the plain way and not tuned for speed.
|
|
9
10
|
module stress_scene_port
|
|
10
11
|
import std/Str
|
|
@@ -17,6 +18,8 @@ import std/game/Color
|
|
|
17
18
|
import std/game/gfx
|
|
18
19
|
import std/game/input
|
|
19
20
|
import std/collections/functional/FRoseTree
|
|
21
|
+
import std/game/Store
|
|
22
|
+
import std/game/Game
|
|
20
23
|
import std/game/scene/Place
|
|
21
24
|
import std/game/scene/Actor
|
|
22
25
|
import std/game/scene/Ctx
|
|
@@ -112,16 +115,22 @@ fun newTree(sheet: Texture) -> SceneTree[Int] =
|
|
|
112
115
|
kids := build(Groups, |gi| newSpin(sheet, gi)).append(rects).append(circles).append(counts)
|
|
113
116
|
SceneTree(root: FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), kids), camX: 0.0, camY: 0.0, camScale: 0.8)
|
|
114
117
|
|
|
118
|
+
# The game sends no messages, so its state never changes.
|
|
119
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
120
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
121
|
+
|
|
122
|
+
# The one screen: the tree, drawn through its camera.
|
|
115
|
-
struct World(
|
|
123
|
+
struct World(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
124
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
125
|
+
|
|
116
|
-
fun
|
|
126
|
+
fun withTree(self, t: SceneTree[Int]) -> World = World(t: t)
|
|
117
|
-
World(tree: self.tree.step(Ctx[Int](), dt), input: input)
|
|
118
127
|
|
|
119
128
|
fun draw(self, io: Io) =
|
|
120
129
|
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
121
|
-
self.
|
|
130
|
+
self.t.draw(io)
|
|
122
131
|
|
|
123
|
-
fun main(io: Io) ->
|
|
132
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
124
|
-
World(
|
|
133
|
+
Game.start(World(t: newTree(gfx.loadTexture(io, "sprites.png"))), Quiet(n: 0))
|
|
125
134
|
|
|
126
135
|
test "the tree holds every actor and steps them"
|
|
127
136
|
t := newTree(Texture(id: -1))
|
compiler/game/web-test/fixtures/stress_state_view.plum
CHANGED
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
# Entity counts: 5000 sprites (50 groups x 100), 500 rects, 200 circles, 50 texts,
|
|
8
8
|
# plus 200 animated sprites (Pulsers, pose = Anim.at(anim, clock - start)) and
|
|
9
9
|
# 20 ui buttons (ids 40000..40019, screen space, outside the scaled world).
|
|
10
|
-
# `State.ui` is a ui.UiState fed by mouse input: update turns the mouse into a shared
|
|
11
|
-
#
|
|
10
|
+
# It is a `Game` with one screen: the game routes each pointer event to the button under
|
|
11
|
+
# it (`Actor.input`), and a click sends the button's id to the store, which counts the
|
|
12
|
+
# clicks.
|
|
12
13
|
module stress_state_view
|
|
13
14
|
import std/Str
|
|
14
15
|
import std/Int
|
|
@@ -24,6 +25,8 @@ import std/game/Anim
|
|
|
24
25
|
import std/game/ui
|
|
25
26
|
import std/game/input
|
|
26
27
|
import std/collections/functional/FRoseTree
|
|
28
|
+
import std/game/Store
|
|
29
|
+
import std/game/Game
|
|
27
30
|
import std/game/scene/Place
|
|
28
31
|
import std/game/scene/Actor
|
|
29
32
|
import std/game/scene/Ctx
|
|
@@ -109,7 +112,21 @@ struct Pulser(id: Int, x: Float, y: Float, start: Float, srcX: Float, clock: Flo
|
|
|
109
112
|
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
110
113
|
actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
|
|
111
114
|
|
|
115
|
+
# The one screen: the tree and its clock.
|
|
112
|
-
struct
|
|
116
|
+
struct View(t: SceneTree[Int], clock: Float) is Screen[Clicks, Int] =
|
|
117
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
118
|
+
|
|
119
|
+
fun withTree(self, t: SceneTree[Int]) -> View = View(..self, t: t)
|
|
120
|
+
|
|
121
|
+
fun rules(self, ctx: Ctx[Int], state: Clicks, dt: Float) -> View = View(..self, clock: self.clock + dt)
|
|
122
|
+
|
|
123
|
+
fun draw(self, io: Io) =
|
|
124
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
125
|
+
self.t.draw(io)
|
|
126
|
+
|
|
127
|
+
# The state: how many buttons were clicked (each click sends the button's id).
|
|
128
|
+
struct Clicks(n: Int) is Reducer[Int] =
|
|
129
|
+
fun update(self, msg: Int) -> Clicks = Clicks(n: self.n + 1)
|
|
113
130
|
|
|
114
131
|
fun pulseAnim() -> Anim =
|
|
115
132
|
Forever(anim: Seq(steps: [
|
|
@@ -133,9 +150,9 @@ fun newSpinner(sheet: Texture, gi: Int) -> FRoseTree[Actor[Int]] =
|
|
|
133
150
|
FRoseTree.of(Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0), rangeLink(0, Sprites / Groups, |j| newDancer(sheet, gi, j)))
|
|
134
151
|
|
|
135
152
|
fun newButton(i: Int) -> FRoseTree[Actor[Int]] =
|
|
136
|
-
FRoseTree.leaf(
|
|
153
|
+
FRoseTree.leaf(ui.button(40000 + i, Float(i % 10 * 70 + 10), Float(i / 10 * 30 + 10), 64.0, 24.0, "b{i}", 40000 + i))
|
|
137
154
|
|
|
138
|
-
fun
|
|
155
|
+
fun newView(sheet: Texture, white: Texture) -> View =
|
|
139
156
|
rects := rangeLink(0, Rects, |i| newDrifter(white, 10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
|
|
140
157
|
circles := rangeLink(0, Circles, |i| newDrifter(white, 20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
|
|
141
158
|
counters: List[FRoseTree[Actor[Int]]] := rangeLink(0, Texts, |i| FRoseTree.leaf(Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)))
|
|
@@ -145,7 +162,7 @@ fun newState(sheet: Texture, white: Texture) -> State =
|
|
|
145
162
|
world: FRoseTree[Actor[Int]] := FRoseTree.of(Scaled(id: WorldId, scale: 0.8), worldKids)
|
|
146
163
|
buttons: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: ButtonLayer, x: 0.0, y: 0.0), rangeLink(0, Buttons, |i| newButton(i)))
|
|
147
164
|
root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [world, buttons])
|
|
148
|
-
|
|
165
|
+
View(t: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), clock: 0.0)
|
|
149
166
|
|
|
150
167
|
# The world layer: everything in it scaled by `scale`.
|
|
151
168
|
struct Scaled(id: Int, scale: Float) is Actor[Int] =
|
|
@@ -153,24 +170,7 @@ struct Scaled(id: Int, scale: Float) is Actor[Int] =
|
|
|
153
170
|
|
|
154
171
|
fun place(self) -> Place = place.at(0.0, 0.0).scaleTo(self.scale, self.scale)
|
|
155
172
|
|
|
156
|
-
# ---
|
|
173
|
+
# --- the game ---
|
|
157
|
-
|
|
158
|
-
fun step(s: State, dt: Float) -> State =
|
|
159
|
-
State(..s, tree: s.tree.step(Ctx[Int](), dt), clock: s.clock + dt)
|
|
160
|
-
|
|
161
|
-
fun countClicks(es: List[UiEvent]) -> Int = match es
|
|
162
|
-
Nil => 0
|
|
163
|
-
Cons(e, t) => {if e.kind == Click then 1 else 0} + countClicks(t)
|
|
164
|
-
|
|
165
|
-
# Feeds one pointer input through ui.step against the tree.
|
|
166
|
-
fun stepUi(s: State, input: InputEvent) -> State =
|
|
167
|
-
po := input.position()
|
|
168
|
-
if po.isNone()
|
|
169
|
-
s
|
|
170
|
-
else
|
|
171
|
-
pos := po.unwrap()
|
|
172
|
-
r := ui.step(s.ui, input, s.tree.hitId(pos.x, pos.y))
|
|
173
|
-
State(..s, tree: ui.styled(s.tree, r.ui), ui: r.ui, clicks: s.clicks + countClicks(r.events))
|
|
174
174
|
|
|
175
175
|
fun whiteTexture(io: Io) -> Texture =
|
|
176
176
|
t := gfx.createTexture(io, 1, 1)
|
|
@@ -179,39 +179,43 @@ fun whiteTexture(io: Io) -> Texture =
|
|
|
179
179
|
gfx.renderToScreen(io)
|
|
180
180
|
t
|
|
181
181
|
|
|
182
|
-
|
|
182
|
+
fun main(io: Io) -> Game[Clicks, Int] =
|
|
183
|
-
fun update(self, io: Io, input: Input, dt: Float) -> World =
|
|
184
|
-
inputs := input.events
|
|
185
|
-
|
|
183
|
+
Game.start(newView(gfx.loadTexture(io, "sprites.png"), whiteTexture(io)), Clicks(n: 0))
|
|
186
|
-
World(state: s, input: input)
|
|
187
184
|
|
|
188
|
-
|
|
185
|
+
# --- tests ---
|
|
186
|
+
|
|
189
|
-
|
|
187
|
+
Screen800 = Vec2(x: 800.0, y: 600.0)
|
|
188
|
+
|
|
189
|
+
fun newGame() -> Game[Clicks, Int] = Game.start(newView(Texture(id: 0), Texture(id: 0)), Clicks(n: 0))
|
|
190
|
+
|
|
190
|
-
|
|
191
|
+
fun pointer(x: Float, y: Float, down: Bool, e: InputEvent) -> Input =
|
|
192
|
+
Input(held: Held(mouse: down, keys: Slice[Int]()), events: [e].toSlice(), pos: Vec2(x: x, y: y), wheel: 0.0)
|
|
191
193
|
|
|
194
|
+
fun viewOf(g: Game[Clicks, Int]) -> View = match g.screen
|
|
192
|
-
|
|
195
|
+
View as v => v
|
|
193
|
-
|
|
196
|
+
_ => newView(Texture(id: 0), Texture(id: 0))
|
|
194
197
|
|
|
195
198
|
test "ten frames of step run"
|
|
196
|
-
|
|
199
|
+
g := 0.until(10).fold(newGame(), |current, _| current.step(io, Input.create(), 0.016, Screen800))
|
|
200
|
+
s := viewOf(g)
|
|
201
|
+
assert {s.clock - 0.16}.abs() < 0.000001
|
|
197
|
-
assert s.
|
|
202
|
+
assert s.t.findAs[Counter](30003).unwrap().n == 13
|
|
198
|
-
assert {s.
|
|
203
|
+
assert {s.t.findAs[Drifter](10000).unwrap().x - 20.0}.abs() < 0.000001
|
|
199
|
-
assert {s.
|
|
204
|
+
assert {s.t.findAs[Dancer](1000).unwrap().rotation - 0.192}.abs() < 0.000001
|
|
200
205
|
|
|
201
206
|
test "the tree has one actor per entity"
|
|
202
|
-
s :=
|
|
207
|
+
s := newView(Texture(id: 0), Texture(id: 0))
|
|
203
|
-
assert s.
|
|
208
|
+
assert s.t.root.kids().chain().length() == 2
|
|
204
|
-
assert s.
|
|
209
|
+
assert s.t.root.kids().kids().chain().length() == 50 + 500 + 200 + 50 + 200
|
|
205
|
-
assert s.
|
|
210
|
+
assert s.t.root.kids().rest().kids().chain().length() == 20
|
|
206
|
-
assert s.
|
|
211
|
+
assert s.t.count() == 1 + 1 + 50 + 5000 + 500 + 200 + 50 + 200 + 1 + 20
|
|
207
212
|
|
|
208
213
|
test "button click counts and pulsers animate"
|
|
209
|
-
s := newState(Texture(id: 0), Texture(id: 0))
|
|
210
|
-
down :=
|
|
214
|
+
down := newGame().step(io, pointer(20.0, 20.0, true, PointerDown(x: 20.0, y: 20.0)), 0.016, Screen800)
|
|
211
|
-
assert down.
|
|
215
|
+
assert viewOf(down).t.findAs[Button[Int]](40000).unwrap().look == 2
|
|
212
|
-
up :=
|
|
216
|
+
up := down.step(io, pointer(20.0, 20.0, false, PointerUp(x: 20.0, y: 20.0)), 0.016, Screen800)
|
|
213
|
-
assert up.
|
|
217
|
+
assert up.state().n == 1
|
|
214
|
-
assert ui.hovered(up.ui, 40000)
|
|
215
|
-
assert up.
|
|
218
|
+
assert viewOf(up).t.findAs[Button[Int]](40000).unwrap().look == 1
|
|
219
|
+
assert down.state().n == 0
|
|
216
220
|
a := Anim.at(pulseAnim(), 0.5 - 0.0)
|
|
217
221
|
assert a.dx > 14.9 && a.dx < 15.1
|
compiler/game/web-test/fixtures/stress_world.plum
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
# children are sorted by y, and only the sprites in the view are drawn. The tree is a
|
|
4
4
|
# `SceneTree[Int]` whose root is the camera (a `Group` at minus the camera's position);
|
|
5
5
|
# each sprite is an `Spr` actor that walks in its own `step` and paints itself only when
|
|
6
|
-
# it is in the view.
|
|
6
|
+
# it is in the view. It is a `Game` with one screen, `World`, whose `rules` sort the
|
|
7
|
+
# layer and move the camera after the steps; its state never changes.
|
|
7
8
|
module stress_world
|
|
8
9
|
import std/Str
|
|
9
10
|
import std/Int
|
|
@@ -17,6 +18,8 @@ import std/game/Affine
|
|
|
17
18
|
import std/game/Color
|
|
18
19
|
import std/game/gfx
|
|
19
20
|
import std/collections/functional/FRoseTree
|
|
21
|
+
import std/game/Store
|
|
22
|
+
import std/game/Game
|
|
20
23
|
import std/game/scene/Place
|
|
21
24
|
import std/game/scene/Actor
|
|
22
25
|
import std/game/scene/Ctx
|
|
@@ -51,7 +54,31 @@ struct Spr(id: Int, x: Float, y: Float, srcX: Float, walker: Int, frame: Int, sh
|
|
|
51
54
|
if p.x + 16.0 >= 0.0 && p.x <= ViewW && p.y + 16.0 >= 0.0 && p.y <= ViewH
|
|
52
55
|
actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
|
|
53
56
|
|
|
57
|
+
# The one screen: the tree, the frame and the camera.
|
|
54
|
-
struct
|
|
58
|
+
struct World(t: SceneTree[Int], frame: Int, camX: Float, camY: Float) is Screen[Quiet, Int] =
|
|
59
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
60
|
+
|
|
61
|
+
fun withTree(self, t: SceneTree[Int]) -> World = World(..self, t: t)
|
|
62
|
+
|
|
63
|
+
# After the walkers walked: the camera drifts and the layer is sorted by y.
|
|
64
|
+
fun rules(self, ctx: Ctx[Int], state: Quiet, dt: Float) -> World =
|
|
65
|
+
frame := self.frame + 1
|
|
66
|
+
t := Float(frame) * 0.01
|
|
67
|
+
camX := 1300.0 + 600.0 * math.sin(t)
|
|
68
|
+
camY := 800.0 + 350.0 * math.cos(t * 0.7)
|
|
69
|
+
sorted := match self.t.root
|
|
70
|
+
FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: sortedByY(k), nextSibling: n)
|
|
71
|
+
FRoseEmpty => self.t.root
|
|
72
|
+
moved := self.t.withRoot(sorted).updateAs[Group[Int]](0, |g| Group(..g, x: 0.0 - camX, y: 0.0 - camY))
|
|
73
|
+
World(t: moved, frame: frame, camX: camX, camY: camY)
|
|
74
|
+
|
|
75
|
+
fun draw(self, io: Io) =
|
|
76
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
77
|
+
self.t.draw(io)
|
|
78
|
+
|
|
79
|
+
# The game sends no messages, so its state never changes.
|
|
80
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
81
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
55
82
|
|
|
56
83
|
fun walkerOf(i: Int) -> Int =
|
|
57
84
|
if i % 37 == 0 && i / 37 < Walkers then i / 37 else -1
|
|
@@ -62,9 +89,9 @@ fun spriteAt(sheet: Texture, i: Int) -> FRoseTree[Actor[Int]] =
|
|
|
62
89
|
fun spritesFrom(sheet: Texture, i: Int) -> List[FRoseTree[Actor[Int]]] =
|
|
63
90
|
if i >= Sprites then Nil else Cons(head: spriteAt(sheet, i), tail: spritesFrom(sheet, i + 1))
|
|
64
91
|
|
|
65
|
-
fun
|
|
92
|
+
fun newWorld(sheet: Texture) -> World =
|
|
66
93
|
root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), spritesFrom(sheet, 0))
|
|
67
|
-
|
|
94
|
+
World(t: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), frame: 0, camX: 0.0, camY: 0.0)
|
|
68
95
|
|
|
69
96
|
fun yOf(n: FRoseTree[Actor[Int]]) -> Float = match n
|
|
70
97
|
FRoseNode(a, _, _) => a.place().y
|
|
@@ -74,41 +101,25 @@ fun yOf(n: FRoseTree[Actor[Int]]) -> Float = match n
|
|
|
74
101
|
fun sortedByY(t: FRoseTree[Actor[Int]]) -> FRoseTree[Actor[Int]] =
|
|
75
102
|
FRoseTree.chainOf(List.fromSlice(t.chain().toSlice().sort(|a, b| yOf(a) < yOf(b))))
|
|
76
103
|
|
|
77
|
-
# One frame: the camera drifts, the walkers walk, the layer is sorted by y.
|
|
78
|
-
fun step(s: State) -> State =
|
|
79
|
-
frame := s.frame + 1
|
|
80
|
-
t := Float(frame) * 0.01
|
|
81
|
-
camX := 1300.0 + 600.0 * math.sin(t)
|
|
82
|
-
camY := 800.0 + 350.0 * math.cos(t * 0.7)
|
|
83
|
-
stepped := s.tree.step(Ctx[Int](), 1.0 / 60.0)
|
|
84
|
-
sorted := match stepped.root
|
|
85
|
-
FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: sortedByY(k), nextSibling: n)
|
|
86
|
-
FRoseEmpty => stepped.root
|
|
87
|
-
moved := stepped.withRoot(sorted).updateAs[Group[Int]](0, |g| Group(..g, x: 0.0 - camX, y: 0.0 - camY))
|
|
88
|
-
State(tree: moved, frame: frame, camX: camX, camY: camY)
|
|
89
|
-
|
|
90
|
-
fun inView(s:
|
|
104
|
+
fun inView(s: World, a: Actor[Int]) -> Bool =
|
|
91
105
|
p := a.place()
|
|
92
106
|
p.x + 16.0 >= s.camX && p.x <= s.camX + ViewW && p.y + 16.0 >= s.camY && p.y <= s.camY + ViewH
|
|
93
107
|
|
|
94
|
-
struct Demo(state: State) =
|
|
95
|
-
fun update(self, io: Io, input: Input, dt: Float) -> Demo =
|
|
96
|
-
Demo(state: step(self.state))
|
|
97
|
-
|
|
98
|
-
fun draw(self, io: Io) =
|
|
99
|
-
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
100
|
-
self.state.tree.draw(io)
|
|
101
|
-
|
|
102
|
-
fun main(io: Io) ->
|
|
108
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
103
|
-
|
|
109
|
+
Game.start(newWorld(gfx.loadTexture(io, "sprites.png")), Quiet(n: 0))
|
|
104
110
|
|
|
105
111
|
# --- tests ---
|
|
106
112
|
|
|
107
113
|
test "about 2000 of the 20000 sprites are in view, sorted by y"
|
|
114
|
+
g0: Game[Quiet, Int] := Game.start(newWorld(Texture(id: -1)), Quiet(n: 0))
|
|
115
|
+
g := g0.step(io, Input.create(), 1.0 / 60.0, Vec2(x: 1280.0, y: 720.0))
|
|
116
|
+
s := match g.screen
|
|
117
|
+
World as w => w
|
|
108
|
-
|
|
118
|
+
_ => newWorld(Texture(id: -1))
|
|
119
|
+
assert s.frame == 1
|
|
109
|
-
kids := s.
|
|
120
|
+
kids := s.t.root.kids().chain().toSlice()
|
|
110
121
|
assert kids.length() == 20000
|
|
111
122
|
for i := range 19999
|
|
112
123
|
assert yOf(kids.at(i)) <= yOf(kids.at(i + 1))
|
|
113
|
-
shown := s.
|
|
124
|
+
shown := s.t.root.kids().fold(0, |n, a| if inView(s, a) then n + 1 else n)
|
|
114
125
|
assert shown > 1500 && shown < 2600
|
compiler/game/web-test/fixtures/text_sizes.plum
CHANGED
|
@@ -10,16 +10,38 @@ import std/game/Color
|
|
|
10
10
|
import std/game/gfx
|
|
11
11
|
import std/Io
|
|
12
12
|
import std/game/input
|
|
13
|
+
import std/game/Affine
|
|
14
|
+
import std/game/Store
|
|
15
|
+
import std/game/Game
|
|
16
|
+
import std/game/scene/Place
|
|
17
|
+
import std/game/scene/Actor
|
|
18
|
+
import std/game/scene/Ctx
|
|
19
|
+
import std/game/scene/SceneTree
|
|
13
20
|
|
|
21
|
+
# The game sends no messages, so its state never changes.
|
|
14
|
-
struct
|
|
22
|
+
struct Quiet(n: Int) is Reducer[Int] =
|
|
15
|
-
fun update(self,
|
|
23
|
+
fun update(self, msg: Int) -> Quiet = self
|
|
16
|
-
Sizes(t: self.t + 1)
|
|
17
24
|
|
|
25
|
+
# The text, one tick older each tick.
|
|
26
|
+
struct Sizes(t: Int) is Actor[Int] =
|
|
18
|
-
fun
|
|
27
|
+
fun key(self) -> Int = 1
|
|
19
|
-
drawSizes(io, self.t)
|
|
20
28
|
|
|
29
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
30
|
+
|
|
31
|
+
fun step(self, ctx: Ctx[Int], dt: Float) -> Sizes = Sizes(t: self.t + 1)
|
|
32
|
+
|
|
33
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) = drawSizes(io, self.t)
|
|
34
|
+
|
|
35
|
+
# The one screen, drawn in screen pixels.
|
|
36
|
+
struct Page(t: SceneTree[Int]) is Screen[Quiet, Int] =
|
|
37
|
+
fun tree(self) -> SceneTree[Int] = self.t
|
|
38
|
+
|
|
39
|
+
fun withTree(self, t: SceneTree[Int]) -> Page = Page(t: t)
|
|
40
|
+
|
|
41
|
+
fun draw(self, io: Io) = self.t.paint(io)
|
|
42
|
+
|
|
21
|
-
fun main(io: Io) ->
|
|
43
|
+
fun main(io: Io) -> Game[Quiet, Int] =
|
|
22
|
-
Sizes(t: 0)
|
|
44
|
+
Game.start(Page(t: SceneTree.of(Sizes(t: 0))), Quiet(n: 0))
|
|
23
45
|
|
|
24
46
|
fun drawSizes(io: Io, t: Int) =
|
|
25
47
|
gfx.clear(io, Color.rgb(0.08, 0.09, 0.14))
|
docs/game.md
CHANGED
|
@@ -10,55 +10,113 @@ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It
|
|
|
10
10
|
plum run examples/games/orb_run.plum
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
This builds the game, starts a local server and opens your browser.
|
|
13
|
+
This builds the game, starts a local server and opens your browser. Press Enter or click Play, then steer with the arrow keys or WASD, collect the orbs and dodge the mines. Press a key first, because browsers only start sound after you interact with the page.
|
|
14
14
|
|
|
15
15
|
## A minimal game
|
|
16
16
|
|
|
17
|
-
A game is
|
|
17
|
+
There is one way to make a game: `main` returns a `Game[S, M]` ([`std/game/Game.plum`](../std/game/Game.plum)), made by `Game.start(screen, state)`. A game is three things you write, and `Game` runs the loop:
|
|
18
18
|
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
|
|
22
|
-
Each frame the host runs the ticks the frame covers, calling `update` once per tick, and then calls `draw` once on what the last `update` returned. Nothing is changed in place.
|
|
19
|
+
- **Actors.** Each thing on the screen is its own struct that `is Actor[M]` ([Scenes](#scenes)), with its own `step` (its next version, every tick), `paint`, and `input` (a pointer event on it).
|
|
20
|
+
- **Screens.** A screen (a title, the play, a game over) is a struct that `is Screen[S, M]`: a tree of actors (`tree`, `withTree`) and what it does with the state. Its `rules` run after the actors stepped (collisions, keys), its `react` shows a new state after each message, its `next` switches to another screen, and its `draw` draws it (its tree by default).
|
|
21
|
+
- **A reducer.** The game's state `S` is a `Reducer[M]` ([`std/game/Store.plum`](../std/game/Store.plum)). `update(self, msg)` is the rules of the state: pure, with no `io`. `handle(self, io, msg)` is the effects of a message (a sound, a save), run after the tick. `M` is the game's message type: actors and rules send messages with `ctx.send(msg)`, and a button sends its `onClick`.
|
|
23
22
|
|
|
24
23
|
```plum
|
|
25
24
|
import std/Int
|
|
26
25
|
import std/Float
|
|
27
26
|
import std/Str
|
|
27
|
+
import std/Option
|
|
28
28
|
import std/Io
|
|
29
|
+
import std/game/Affine
|
|
30
|
+
import std/game/Color
|
|
29
31
|
import std/game/gfx
|
|
30
|
-
import std/game/audio
|
|
31
32
|
import std/game/input
|
|
33
|
+
import std/game/ui
|
|
32
|
-
import std/game/
|
|
34
|
+
import std/game/Store
|
|
35
|
+
import std/game/Game
|
|
36
|
+
import std/collections/functional/FRoseTree
|
|
37
|
+
import std/game/scene/Place
|
|
38
|
+
import std/game/scene/Actor
|
|
39
|
+
import std/game/scene/Ctx
|
|
40
|
+
import std/game/scene/SceneTree
|
|
41
|
+
|
|
42
|
+
# What can happen to the state.
|
|
43
|
+
enum Msg = Clicked | Cleared
|
|
44
|
+
|
|
45
|
+
# The state: the clicks so far.
|
|
46
|
+
struct Clicks(n: Int) is Reducer[Msg] =
|
|
47
|
+
fun update(self, msg: Msg) -> Clicks = match msg
|
|
48
|
+
Clicked => Clicks(n: self.n + 1)
|
|
49
|
+
Cleared => Clicks(n: 0)
|
|
33
50
|
|
|
51
|
+
# A ball that rolls right while the Right key is held.
|
|
34
|
-
struct Ball(x: Float,
|
|
52
|
+
struct Ball(id: Int, x: Float, y: Float) is Actor[Msg] =
|
|
53
|
+
fun key(self) -> Int = self.id
|
|
54
|
+
|
|
55
|
+
fun place(self) -> Place = place.at(self.x, self.y)
|
|
56
|
+
|
|
35
|
-
fun
|
|
57
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> Ball =
|
|
58
|
+
if ctx.input.isKeyDown(Key.Right) then Ball(..self, x: self.x + 100.0 * dt) else self
|
|
59
|
+
|
|
60
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
61
|
+
actor.circlePaint(io, m, alpha, 0.0, 0.0, 10.0, Color.Yellow)
|
|
62
|
+
|
|
63
|
+
# The one screen: the ball, a button that sends `Clicked`, and a label with the count.
|
|
64
|
+
struct Room(t: SceneTree[Msg]) is Screen[Clicks, Msg] =
|
|
65
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
66
|
+
|
|
67
|
+
fun withTree(self, t: SceneTree[Msg]) -> Room = Room(t: t)
|
|
68
|
+
|
|
69
|
+
# Escape clears the count.
|
|
70
|
+
fun rules(self, ctx: Ctx[Msg], state: Clicks, dt: Float) -> Room =
|
|
36
|
-
if input.
|
|
71
|
+
if ctx.input.isKeyPressed(Key.Escape)
|
|
37
|
-
|
|
72
|
+
ctx.send(Cleared)
|
|
38
|
-
else
|
|
39
|
-
|
|
73
|
+
self
|
|
74
|
+
|
|
75
|
+
# After each message: the label shows the new count.
|
|
76
|
+
fun react(self, state: Clicks, msg: Msg) -> Room =
|
|
77
|
+
Room(t: self.t.updateAs[Label[Msg]](3, |l| l.relabel("clicks {state.n}")))
|
|
40
78
|
|
|
41
79
|
fun draw(self, io: Io) =
|
|
42
80
|
gfx.clear(io, Color.Black)
|
|
43
|
-
self.
|
|
81
|
+
self.t.draw(io)
|
|
82
|
+
|
|
83
|
+
fun main(io: Io) -> Game[Clicks, Msg] = start()
|
|
44
84
|
|
|
45
|
-
fun
|
|
85
|
+
fun start() -> Game[Clicks, Msg] =
|
|
86
|
+
root: FRoseTree[Actor[Msg]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [
|
|
87
|
+
FRoseTree.leaf(Ball(id: 1, x: 20.0, y: 150.0)),
|
|
46
|
-
|
|
88
|
+
FRoseTree.leaf(ui.button(2, 20.0, 20.0, 120.0, 40.0, "Click", Clicked)),
|
|
89
|
+
FRoseTree.leaf(Label(id: 3, x: 20.0, y: 80.0, text: "clicks 0", size: 16.0, color: Color.White))])
|
|
90
|
+
Game.start(Room(t: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)), Clicks(n: 0))
|
|
47
91
|
```
|
|
48
92
|
|
|
49
|
-
`main` runs once, after your assets have loaded.
|
|
93
|
+
This is [`examples/games/clicks.plum`](../examples/games/clicks.plum). `main` runs once, after your assets have loaded. If `main` returns anything else, `plum run` runs it as an ordinary program. A type of your own with `update` and `draw` was the old way to make a game; `main` returning one is now a compile error that names `Game.start`.
|
|
94
|
+
|
|
95
|
+
### One tick
|
|
96
|
+
|
|
97
|
+
Each tick, `Game.update(io, input, dt)` does this, in this order:
|
|
98
|
+
|
|
99
|
+
1. Each pointer event of the tick goes to the topmost shown actor under it that says it is hit (`hit`), through its `input`, then to each of its parents. Each gets the event in its own coordinates. A `PointerMove` that leaves the pointer where it was goes to no actor.
|
|
100
|
+
2. Every actor steps (`step`), parents before children, then the screen's `rules` run. Both see the tick's input in `ctx.input` (held keys, the pointer) and the screen's size in `ctx.view`.
|
|
101
|
+
3. The spawns and kills apply (`ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`): those pushed by `input`, then by the steps, then by the rules.
|
|
102
|
+
4. Each message sent, in order: the store reduces it (`update`), then the screen `react`s to the new state and is asked for its `next` screen. The first `next` that gives a screen wins; the old screen takes the rest of the tick.
|
|
103
|
+
5. After the tick: `handle(io, msg)` runs for each message, in order, with the state after the tick. Then the screen switches. Then `ctx.out.push(Restart)` starts the game over from its first screen and state, and `ctx.out.push(Exit)` ends it: no tick runs after it, and the last screen stays drawn.
|
|
104
|
+
|
|
105
|
+
`Game.draw(io)` draws the current screen once a frame. Nothing is changed in place: each tick returns the next game.
|
|
106
|
+
|
|
107
|
+
[`orb_run.plum`](../examples/games/orb_run.plum) is a whole game this way, with a title, a play and a game-over screen; its header comment explains how it is put together.
|
|
50
108
|
|
|
51
109
|
## Fixed timestep and determinism
|
|
52
110
|
|
|
53
|
-
The host adds up the time between frames and
|
|
111
|
+
The host adds up the time between frames and runs one tick (`Game.update`) for each whole tick, always with the same `dt` of 1/60 s. A slow frame runs several ticks (a 50 ms frame runs 3) and a fast one, on a 120 Hz screen say, may run none. A frame runs at most eight ticks: after a longer stall the rest is dropped, so the game slows down for a moment instead of falling ever further behind. The clock that does this is `Clock` in [`std/game/input.plum`](../std/game/input.plum).
|
|
54
112
|
|
|
55
|
-
|
|
113
|
+
The tick's `Input` (`ctx.input`) is read from the host once per frame, before the ticks. A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. Actors and rules have no `io`, so they can't read input any other way.
|
|
56
114
|
|
|
57
|
-
Keep randomness in the
|
|
115
|
+
Keep randomness in the state `S`: a `Random` ([`std/Random.plum`](../std/Random.plum)) seeded once in `main` from `io.randomSeed()`, drawn from only in `update` (`r := self.rng.nextFloat()`, then keep `r.rng` in the next state). Then the same seed and the same inputs give the same game, tick for tick, and a test can play one: `game.step(io, input, 1.0 / 60.0, view)` from one seed and one list of inputs gives the same game each time. Orb Run's `same_seed_same_game` test does exactly this.
|
|
58
116
|
|
|
59
|
-
The maths is the same everywhere too. std's maths (`math.sin`, `math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a
|
|
117
|
+
The maths is the same everywhere too. std's maths (`math.sin`, `math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick reads is the screen size (`ctx.view`), and a replay records it (see below).
|
|
60
118
|
|
|
61
|
-
Keep your rules in plain functions over plain data, like `
|
|
119
|
+
Keep the rest of your rules in plain functions over plain data, like `ship.moved(ax, ay, dt)`. Those need no browser to test.
|
|
62
120
|
|
|
63
121
|
## Record and replay
|
|
64
122
|
|
|
@@ -74,7 +132,7 @@ The text is one line for the seed and screen size, then one line per tick (the h
|
|
|
74
132
|
|
|
75
133
|
## What `io` gives you
|
|
76
134
|
|
|
77
|
-
The host's calls are module functions that take `io` first: drawing and textures in [`std/game/gfx.plum`](../std/game/gfx.plum) (`gfx.clear(io, Color.Black)`, `gfx.loadTexture(io, "sprites.png")`), keys and the mouse in [`std/game/input.plum`](../std/game/input.plum) (
|
|
135
|
+
The host's calls are module functions that take `io` first: drawing and textures in [`std/game/gfx.plum`](../std/game/gfx.plum) (`gfx.clear(io, Color.Black)`, `gfx.loadTexture(io, "sprites.png")`), keys and the mouse in [`std/game/input.plum`](../std/game/input.plum) (actors and rules read them from the tick's `Input`, as `ctx.input.isKeyDown(Key.Right)`; the raw calls below are for `draw`), sound in [`std/game/audio.plum`](../std/game/audio.plum). General calls such as `io.printLn` stay methods of `io` ([`std/Io.plum`](../std/Io.plum)).
|
|
78
136
|
|
|
79
137
|
| Group | Functions |
|
|
80
138
|
|---|---|
|
|
@@ -83,11 +141,11 @@ The host's calls are module functions that take `io` first: drawing and textures
|
|
|
83
141
|
| Text | `drawText(s, x, y, size, c)` |
|
|
84
142
|
| Camera | `setCamera(x, y, scale)`, `resetCamera()` |
|
|
85
143
|
| Blending | `blendMode(m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` |
|
|
86
|
-
| Keyboard (raw;
|
|
144
|
+
| Keyboard (raw; a tick uses `ctx.input`) | `isKeyDown(k)`, `isKeyPressed(k)`, with `Key.Space`, `Key.KeyA`, `Key.Up`, `Key.Enter`, ... |
|
|
87
|
-
| Mouse and touch (raw;
|
|
145
|
+
| Mouse and touch (raw; a tick uses `ctx.input`) | `mousePos()`, `isMouseDown(b)`, `isMousePressed(b)`, `mouseWheel()`, with `Mouse.Left`, `Mouse.Right`, `Mouse.Middle` |
|
|
88
146
|
| Random | `randomSeed()` |
|
|
89
147
|
|
|
90
|
-
Images and sounds are handles you load once, in `main`, and keep in your game. Do not load them every frame.
|
|
148
|
+
Images and sounds are handles you load once, in `main`, and keep in your game (in an actor or in the state, which plays sounds in `handle`). Do not load them every frame. `Sound.Silent` is a sound that plays nothing, for tests.
|
|
91
149
|
|
|
92
150
|
| Handle | Functions |
|
|
93
151
|
|---|---|
|
|
@@ -102,7 +160,7 @@ Colors come from `Color.White`, `Color.Red` and so on, or `Color.rgb(r, g, b)`.
|
|
|
102
160
|
|
|
103
161
|
### Input as events
|
|
104
162
|
|
|
105
|
-
`InputEvent.poll(io, prev)` in [`std/game/input.plum`](../std/game/input.plum) is the one place that reads input, and the game's clock calls it once a frame. The tick's `Input` has its `events` (`PointerDown`, `PointerUp`, `PointerMove`, `KeyDown`, `KeyUp`) and the keys held, with `isKeyDown(k)`, `isKeyPressed(k)`, `pointer()`, `mousePos()` and `mouseWheel()`.
|
|
163
|
+
`InputEvent.poll(io, prev)` in [`std/game/input.plum`](../std/game/input.plum) is the one place that reads input, and the game's clock calls it once a frame. The tick's `Input` has its `events` (`PointerDown`, `PointerUp`, `PointerMove`, `KeyDown`, `KeyUp`) and the keys held, with `isKeyDown(k)`, `isKeyPressed(k)`, `pointer()`, `mousePos()` and `mouseWheel()`. `Game` routes the pointer events to the actors under them, and the actors and rules read the rest from `ctx.input`; a game reads nothing else, so a recorded list of inputs replays it exactly (see [Record and replay](#record-and-replay)).
|
|
106
164
|
|
|
107
165
|
## Assets
|
|
108
166
|
|
|
@@ -116,62 +174,25 @@ If the new code has a compile error, the old game keeps running and the error ap
|
|
|
116
174
|
|
|
117
175
|
## Scenes
|
|
118
176
|
|
|
119
|
-
|
|
177
|
+
A screen's actors live in a scene tree from [`std/game/scene`](../std/game/scene): a `SceneTree[M]` ([`SceneTree.plum`](../std/game/scene/SceneTree.plum)) is a tree of actors that lives from frame to frame, and `M` is the game's message type. It is a value like the rest of your game: every change returns a new tree, and a kept old tree stays as it was. When nothing holds the old one, the compiler writes the new one into its cells.
|
|
120
178
|
|
|
121
179
|
Each kind of actor is its own struct, with only its own fields, that `is Actor[M]` ([`Actor.plum`](../std/game/scene/Actor.plum)). It must say which actor it is (`key`, the id the tree finds it by) and where it is in its parent (`place`, a `Place` with a position, scale, rotation and origin). Everything else has a default that it may override:
|
|
122
180
|
|
|
123
|
-
- `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/scene/Ctx.plum)) has its parent's world transform and alpha, and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`
|
|
181
|
+
- `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/scene/Ctx.plum)) has its parent's world transform and alpha, the tick's input (`ctx.input`) and the screen's size (`ctx.view`), and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`, `ctx.send(msg)`, `ctx.out.push(Restart)` and `ctx.out.push(Exit)`.
|
|
182
|
+
- `input(self, ctx, e)` returns its next version after a pointer event on it or on one of its children, before the tick's steps. `e` is in its own coordinates.
|
|
124
183
|
- `paint(self, io, m, alpha)` draws it in its own coordinates seen through `m`. `Actor.plum` has helpers for boxes, circles, lines, sprites and text (`actor.boxPaint(io, m, alpha, w, h, color)`, ...).
|
|
125
|
-
- `hit(self, p)` says whether a point in its own coordinates is on it. Only an actor that says so is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first.
|
|
184
|
+
- `hit(self, p)` says whether a point in its own coordinates is on it. Only an actor that says so gets pointer events, and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first.
|
|
126
185
|
- `shown`, `gone` and `opacity`: a hidden actor isn't drawn or hit, a gone one is dropped with its subtree, and opacities multiply down the tree.
|
|
127
186
|
|
|
128
|
-
Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. std gives `Group` (a parent that paints nothing) and `Box`; [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button`,
|
|
129
|
-
|
|
130
|
-
The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills. `add`, `update`, `kill` and `find` work by id, and `updateAs[T](id, f)` and `findAs[T](id)` act on an actor of the type `T` only. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
|
|
131
|
-
|
|
132
|
-
```plum
|
|
133
|
-
import std/Int
|
|
134
|
-
import std/Float
|
|
135
|
-
import std/Str
|
|
136
|
-
import std/Option
|
|
137
|
-
import std/List
|
|
138
|
-
import std/Io
|
|
139
|
-
import std/game/gfx
|
|
140
|
-
import std/game/input
|
|
141
|
-
import std/game/Color
|
|
142
|
-
import std/game/ui
|
|
143
|
-
import std/collections/functional/FRoseTree
|
|
144
|
-
import std/game/scene/Actor
|
|
145
|
-
import std/game/scene/Ctx
|
|
146
|
-
import std/game/scene/SceneTree
|
|
147
|
-
|
|
148
|
-
struct Counter(tree: SceneTree[Int], clicks: Int) =
|
|
149
|
-
fun update(self, io: Io, input: Input, dt: Float) -> Counter =
|
|
150
|
-
t := self.tree.step(Ctx[Int](), dt)
|
|
151
|
-
p := input.mousePos()
|
|
152
|
-
if input.isMousePressed() && t.hitId(p.x, p.y).isSome()
|
|
153
|
-
n := self.clicks + 1
|
|
154
|
-
Counter(tree: t.updateAs[Label[Int]](2, |l| l.relabel("clicks {n}")), clicks: n)
|
|
155
|
-
else
|
|
156
|
-
Counter(..self, tree: t)
|
|
187
|
+
Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. std gives `Group` (a parent that paints nothing) and `Box`; [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button` (`ui.button(id, x, y, w, h, label, onClick)`). A button shows the pointer over it and a press on it, and a press and a release on it send its `onClick` message.
|
|
157
188
|
|
|
158
|
-
|
|
159
|
-
gfx.clear(io, Color.Black)
|
|
160
|
-
self.tree.draw(io)
|
|
161
|
-
|
|
162
|
-
fun main(io: Io) -> Counter =
|
|
163
|
-
root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [
|
|
164
|
-
FRoseTree.leaf(Box(id: 1, x: 20.0, y: 20.0, w: 100.0, h: 40.0, color: Color.Red)),
|
|
165
|
-
FRoseTree.leaf(Label(id: 2, x: 20.0, y: 80.0, text: "clicks 0", size: 16.0, color: Color.White))
|
|
166
|
-
])
|
|
167
|
-
Counter(tree: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), clicks: 0)
|
|
168
|
-
```
|
|
189
|
+
The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills; `input(ctx, e)` routes one pointer event. `Game` calls both. `add`, `update`, `kill` and `find` work by id, and `updateAs[T](id, f)` and `findAs[T](id)` act on an actor of the type `T` only, which is how a screen's `rules` and `react` read and change one kind's own fields. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
|
|
169
190
|
|
|
170
|
-
[`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time.
|
|
191
|
+
[`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time.
|
|
171
192
|
|
|
172
193
|
## Testing a game
|
|
173
194
|
|
|
174
|
-
Put your rules in plain functions with `test` blocks, and `plum test` runs them with no browser. Calling a drawing function under `plum test` stops with an error, so keep those calls out of the code you test.
|
|
195
|
+
Put your rules in plain functions with `test` blocks, and `plum test` runs them with no browser. A test can run whole ticks of a game with `game.step(io, input, dt, view)`, which is `update` with the screen's size given (`update` asks the host for it). Build the game in a function of its own that `main` calls, since a test that calls `main` gets the host's wrapper. Calling a drawing or sound function under `plum test` stops with an error, so keep those calls out of the code you test: draw only in `paint` and `draw`, and give the state `Sound.Silent` in tests.
|
|
175
196
|
|
|
176
197
|
To check a game actually renders, the browser test tool runs it in headless Chromium. See [its README](../compiler/game/web-test/README.md).
|
|
177
198
|
|
docs/std.md
CHANGED
|
@@ -215,6 +215,6 @@ fun main(io: Io) =
|
|
|
215
215
|
```
|
|
216
216
|
|
|
217
217
|
- **`Store[S: Reducer[M], M]`**: `Store.of(state)`, `dispatch(msg)` (reduces now and queues the message), `dispatchAll(msgs)`, `pending()` (the queued messages, oldest first), `flush(io)` (calls `handle` on the state for each queued message in order, then empties the queue), and the field `state`. A store is a value: `dispatch` and `flush` return a new one.
|
|
218
|
-
- **`store.
|
|
218
|
+
- **`store.reduceAll(s, msgs)`**: the state after `msgs`, with no store and no effects.
|
|
219
219
|
|
|
220
|
-
Only
|
|
220
|
+
Only `Game` ([`std/game/Game`](game.md#a-minimal-game)) drives a store: it dispatches each message its actors and screens send, and flushes the store after the tick. A game writes its `Reducer`.
|
examples/games/clicks.plum
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# A minimal game (see docs/game.md): a ball the arrow key rolls, a button that counts its
|
|
2
|
+
# clicks, and a label that shows the count. `plum run examples/games/clicks.plum`.
|
|
3
|
+
module clicks
|
|
4
|
+
import std/Int
|
|
5
|
+
import std/Float
|
|
6
|
+
import std/Str
|
|
7
|
+
import std/Option
|
|
8
|
+
import std/Io
|
|
9
|
+
import std/game/Affine
|
|
10
|
+
import std/game/Color
|
|
11
|
+
import std/game/gfx
|
|
12
|
+
import std/game/input
|
|
13
|
+
import std/game/ui
|
|
14
|
+
import std/game/Store
|
|
15
|
+
import std/game/Game
|
|
16
|
+
import std/collections/functional/FRoseTree
|
|
17
|
+
import std/game/scene/Place
|
|
18
|
+
import std/game/scene/Actor
|
|
19
|
+
import std/game/scene/Ctx
|
|
20
|
+
import std/game/scene/SceneTree
|
|
21
|
+
|
|
22
|
+
# What can happen to the state.
|
|
23
|
+
enum Msg = Clicked | Cleared
|
|
24
|
+
|
|
25
|
+
# The state: the clicks so far.
|
|
26
|
+
struct Clicks(n: Int) is Reducer[Msg] =
|
|
27
|
+
fun update(self, msg: Msg) -> Clicks = match msg
|
|
28
|
+
Clicked => Clicks(n: self.n + 1)
|
|
29
|
+
Cleared => Clicks(n: 0)
|
|
30
|
+
|
|
31
|
+
# A ball that rolls right while the Right key is held.
|
|
32
|
+
struct Ball(id: Int, x: Float, y: Float) is Actor[Msg] =
|
|
33
|
+
fun key(self) -> Int = self.id
|
|
34
|
+
|
|
35
|
+
fun place(self) -> Place = place.at(self.x, self.y)
|
|
36
|
+
|
|
37
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> Ball =
|
|
38
|
+
if ctx.input.isKeyDown(Key.Right) then Ball(..self, x: self.x + 100.0 * dt) else self
|
|
39
|
+
|
|
40
|
+
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
41
|
+
actor.circlePaint(io, m, alpha, 0.0, 0.0, 10.0, Color.Yellow)
|
|
42
|
+
|
|
43
|
+
# The one screen: the ball, a button that sends `Clicked`, and a label with the count.
|
|
44
|
+
struct Room(t: SceneTree[Msg]) is Screen[Clicks, Msg] =
|
|
45
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
46
|
+
|
|
47
|
+
fun withTree(self, t: SceneTree[Msg]) -> Room = Room(t: t)
|
|
48
|
+
|
|
49
|
+
# Escape clears the count.
|
|
50
|
+
fun rules(self, ctx: Ctx[Msg], state: Clicks, dt: Float) -> Room =
|
|
51
|
+
if ctx.input.isKeyPressed(Key.Escape)
|
|
52
|
+
ctx.send(Cleared)
|
|
53
|
+
self
|
|
54
|
+
|
|
55
|
+
# After each message: the label shows the new count.
|
|
56
|
+
fun react(self, state: Clicks, msg: Msg) -> Room =
|
|
57
|
+
Room(t: self.t.updateAs[Label[Msg]](3, |l| l.relabel("clicks {state.n}")))
|
|
58
|
+
|
|
59
|
+
fun draw(self, io: Io) =
|
|
60
|
+
gfx.clear(io, Color.Black)
|
|
61
|
+
self.t.draw(io)
|
|
62
|
+
|
|
63
|
+
fun main(io: Io) -> Game[Clicks, Msg] = start()
|
|
64
|
+
|
|
65
|
+
fun start() -> Game[Clicks, Msg] =
|
|
66
|
+
root: FRoseTree[Actor[Msg]] := FRoseTree.of(Group(id: 0, x: 0.0, y: 0.0), [
|
|
67
|
+
FRoseTree.leaf(Ball(id: 1, x: 20.0, y: 150.0)),
|
|
68
|
+
FRoseTree.leaf(ui.button(2, 20.0, 20.0, 120.0, 40.0, "Click", Clicked)),
|
|
69
|
+
FRoseTree.leaf(Label(id: 3, x: 20.0, y: 80.0, text: "clicks 0", size: 16.0, color: Color.White))])
|
|
70
|
+
Game.start(Room(t: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)), Clicks(n: 0))
|
|
71
|
+
|
|
72
|
+
test "a click on the button counts, and Escape clears"
|
|
73
|
+
g := start()
|
|
74
|
+
click := Input(held: Held.none(), events: [PointerDown(x: 30.0, y: 30.0), PointerUp(x: 30.0, y: 30.0)].toSlice(), pos: Vec2(x: 30.0, y: 30.0), wheel: 0.0)
|
|
75
|
+
view := Vec2(x: 800.0, y: 600.0)
|
|
76
|
+
g2 := g.step(io, click, 1.0 / 60.0, view).step(io, click, 1.0 / 60.0, view)
|
|
77
|
+
assert g2.state().n == 2
|
|
78
|
+
esc := Input(held: Held.none(), events: [KeyDown(key: Key.Escape)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
79
|
+
assert g2.step(io, esc, 1.0 / 60.0, view).state().n == 0
|
examples/games/kids/balloon_pop.plum
CHANGED
|
@@ -4,14 +4,16 @@
|
|
|
4
4
|
# child hears the pop and sees the word. Every 10 pops a "Hooray!" party with
|
|
5
5
|
# confetti. There is no way to lose and no timer.
|
|
6
6
|
#
|
|
7
|
-
# The game is a
|
|
7
|
+
# The game is a `Game` (std/game/Game) with one screen, `Sky`, whose tree of actors
|
|
8
|
-
# from frame to frame
|
|
8
|
+
# (std/game/scene) lives from frame to frame. Each balloon is a `Balloon` actor that rises
|
|
9
|
-
#
|
|
9
|
+
# in its own `step` and is the only actor that is ever hit: the game routes a pointer
|
|
10
|
-
#
|
|
10
|
+
# press to the balloon under it (`input`), which bursts and sends `Popped(id)` to the
|
|
11
|
+
# store. The screen's `rules` send the tick (`Tick`) and ask for every balloon that is
|
|
12
|
+
# done to come back (`Renew(id)`). `State` is the store's state: the pops, the party, the
|
|
13
|
+
# clock and the `Random`; it says where a renewed balloon goes, and the screen `react`s by
|
|
11
|
-
#
|
|
14
|
+
# putting it in the tree and showing the pops on the hud and the party. The sounds are the
|
|
12
|
-
# the pops `State` gives them. `Msg` is everything that can happen to the state, and
|
|
13
|
-
#
|
|
15
|
+
# effects of the messages (`handle`). A press pops at once: small children tap, they do
|
|
14
|
-
#
|
|
16
|
+
# not click.
|
|
15
17
|
#
|
|
16
18
|
# 0 root (the camera that fits the arena on screen)
|
|
17
19
|
# ├─ 1 sky
|
|
@@ -35,6 +37,8 @@ import std/game/gfx
|
|
|
35
37
|
import std/game/audio
|
|
36
38
|
import std/game/Anim
|
|
37
39
|
import std/game/input
|
|
40
|
+
import std/game/Store
|
|
41
|
+
import std/game/Game
|
|
38
42
|
import std/collections/functional/FRoseTree
|
|
39
43
|
import std/game/scene/Place
|
|
40
44
|
import std/game/scene/Actor
|
|
@@ -100,11 +104,14 @@ fun zoomOf(sw: Float, sh: Float) -> Float =
|
|
|
100
104
|
# --- the actors ---
|
|
101
105
|
|
|
102
106
|
# The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
|
|
107
|
+
# It fits the screen in its step.
|
|
103
108
|
struct Camera(id: Int, x: Float, y: Float, zoom: Float) is Actor[Msg] =
|
|
104
109
|
fun key(self) -> Int = self.id
|
|
105
110
|
|
|
106
111
|
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
|
|
107
112
|
|
|
113
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> Camera = self.fitted(ctx.view.x, ctx.view.y)
|
|
114
|
+
|
|
108
115
|
# Fitting a `sw` by `sh` screen.
|
|
109
116
|
fun fitted(self, sw: Float, sh: Float) -> Camera =
|
|
110
117
|
z := zoomOf(sw, sh)
|
|
@@ -131,6 +138,16 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
131
138
|
fun place(self) -> Place =
|
|
132
139
|
if self.popped() then place.at(self.x, self.y) else place.at(self.swayX(self.clock), self.y)
|
|
133
140
|
|
|
141
|
+
# A press on a whole balloon bursts it, at its clock (the game's), and tells the store.
|
|
142
|
+
fun input(self, ctx: Ctx[Msg], e: InputEvent) -> Balloon = match e
|
|
143
|
+
PointerDown(_, _) =>
|
|
144
|
+
if self.popped()
|
|
145
|
+
self
|
|
146
|
+
else
|
|
147
|
+
ctx.send(Popped(id: self.id))
|
|
148
|
+
self.poppedAtClock(self.clock)
|
|
149
|
+
_ => self
|
|
150
|
+
|
|
134
151
|
# Rises while whole.
|
|
135
152
|
fun step(self, ctx: Ctx[Msg], dt: Float) -> Balloon =
|
|
136
153
|
if self.popped() then Balloon(..self, clock: self.clock + dt) else Balloon(..self, y: self.y - self.speed * dt, clock: self.clock + dt)
|
|
@@ -184,12 +201,12 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
184
201
|
struct Spawned(balloon: Balloon, rng: Random)
|
|
185
202
|
|
|
186
203
|
# Sky, two drifting clouds and the grass. `clock` is the game's clock.
|
|
187
|
-
struct
|
|
204
|
+
struct SkyBox(id: Int, clock: Float) is Actor[Msg] =
|
|
188
205
|
fun key(self) -> Int = self.id
|
|
189
206
|
|
|
190
207
|
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
191
208
|
|
|
192
|
-
fun step(self, ctx: Ctx[Msg], dt: Float) ->
|
|
209
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> SkyBox = SkyBox(..self, clock: self.clock + dt)
|
|
193
210
|
|
|
194
211
|
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
195
212
|
actor.rectPaint(io, m, 1.0, 0.0, 0.0, ArenaW, ArenaH, Color.rgb(0.55, 0.8, 1.0))
|
|
@@ -248,178 +265,189 @@ fun paintConfetti(io: Io, m: Affine, age: Float) =
|
|
|
248
265
|
wob := 10.0 * math.sin(age * 4.0 + Float(i))
|
|
249
266
|
actor.rectPaint(io, m, 1.0, x + wob, y, 12.0, 12.0, Hue.of(i).color)
|
|
250
267
|
|
|
251
|
-
# What can happen to the game.
|
|
268
|
+
# What can happen to the game: a tick of time, a balloon popped, a balloon to bring back.
|
|
252
269
|
enum Msg =
|
|
253
270
|
| Tick(dt: Float)
|
|
254
|
-
| Resize(w: Float, h: Float)
|
|
255
|
-
| Event(input: InputEvent)
|
|
256
|
-
|
|
|
271
|
+
| Popped(id: Int)
|
|
272
|
+
| Renew(id: Int)
|
|
257
273
|
|
|
274
|
+
# The store's state: the pops, when the last party began, the game's clock, the
|
|
275
|
+
# randomness, the balloon the last `Renew` made, and the sounds its effects play.
|
|
258
|
-
struct State(
|
|
276
|
+
struct State(rng: Random, pops: Int, clock: Float, partyAt: Float, renewed: Balloon, popSound: Sound, partySound: Sound) is Reducer[Msg] =
|
|
259
277
|
|
|
260
|
-
fun start(seed: Int,
|
|
278
|
+
fun start(seed: Int, popSound: Sound, partySound: Sound) -> State =
|
|
261
|
-
root: FRoseTree[Actor[Msg]] := FRoseTree.of(Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(sw, sh), [
|
|
262
|
-
FRoseTree.leaf(Sky(id: SkyId, clock: 0.0)),
|
|
263
|
-
FRoseTree.leaf(Group(id: BalloonLayer, x: 0.0, y: 0.0)),
|
|
264
|
-
FRoseTree.leaf(Hud(id: HudId, pops: 0)),
|
|
265
|
-
FRoseTree.leaf(Party(id: PartyId, partyAt: -100.0, clock: 0.0, pops: 0))])
|
|
266
|
-
|
|
279
|
+
none := Balloon(id: -1, x: 0.0, y: 0.0, speed: 0.0, hue: 0, phase: 0.0, poppedAt: -1.0, clock: 0.0)
|
|
267
|
-
State(
|
|
280
|
+
State(rng: Random.seeded(seed), pops: 0, clock: 0.0, partyAt: -100.0, renewed: none, popSound: popSound, partySound: partySound)
|
|
281
|
+
|
|
282
|
+
fun update(self, msg: Msg) -> State = match msg
|
|
283
|
+
Tick(dt) => State(..self, clock: self.clock + dt)
|
|
284
|
+
Popped(_) =>
|
|
285
|
+
pops := self.pops + 1
|
|
286
|
+
State(..self, pops: pops, partyAt: if pops % PartyEvery == 0 then self.clock else self.partyAt)
|
|
287
|
+
Renew(id) =>
|
|
288
|
+
sp := Balloon.spawn(id, self.rng, 0.0, self.clock)
|
|
289
|
+
State(..self, renewed: sp.balloon, rng: sp.rng)
|
|
290
|
+
|
|
291
|
+
# A pop, and a fanfare when it starts a party (a tick has at most one pop).
|
|
292
|
+
fun handle(self, io: Io, msg: Msg) = match msg
|
|
293
|
+
Popped(_) =>
|
|
294
|
+
self.popSound.play(io, 0.9)
|
|
295
|
+
if self.pops % PartyEvery == 0
|
|
296
|
+
self.partySound.play(io, 0.6)
|
|
297
|
+
_ => Unit
|
|
268
298
|
|
|
269
|
-
# Balloons `i` and up, spread out below the screen.
|
|
270
|
-
fun
|
|
299
|
+
fun partying(self) -> Bool =
|
|
300
|
+
self.clock - self.partyAt < PartyTime
|
|
301
|
+
|
|
302
|
+
# The first balloons, spread out below the screen, and the generator after them.
|
|
303
|
+
fun firstBalloons(self, i: Int, acc: List[FRoseTree[Actor[Msg]]]) -> Filled =
|
|
271
304
|
if i >= Count
|
|
272
|
-
self
|
|
305
|
+
Filled(nodes: acc.reverse(), state: self)
|
|
273
306
|
else
|
|
274
307
|
sp := Balloon.spawn(BalloonId + i, self.rng, Float(i) * 110.0 - ArenaH * 0.6, self.clock)
|
|
275
|
-
State(..self,
|
|
308
|
+
State(..self, rng: sp.rng).firstBalloons(i + 1, Cons(head: FRoseTree.leaf(sp.balloon), tail: acc))
|
|
309
|
+
|
|
310
|
+
struct Filled(nodes: List[FRoseTree[Actor[Msg]]], state: State)
|
|
311
|
+
|
|
312
|
+
# The one screen: the sky, the balloons, the hud and the party.
|
|
313
|
+
struct Sky(t: SceneTree[Msg]) is Screen[State, Msg] =
|
|
314
|
+
# The screen and the state of a new game: the balloons spread out below the screen.
|
|
315
|
+
fun start(state: State) -> Play =
|
|
316
|
+
filled := state.firstBalloons(0, Nil)
|
|
317
|
+
root: FRoseTree[Actor[Msg]] := FRoseTree.of(Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(ArenaW, ArenaH), [
|
|
318
|
+
FRoseTree.leaf(SkyBox(id: SkyId, clock: 0.0)),
|
|
319
|
+
FRoseTree.of(Group(id: BalloonLayer, x: 0.0, y: 0.0), filled.nodes),
|
|
320
|
+
FRoseTree.leaf(Hud(id: HudId, pops: 0)),
|
|
321
|
+
FRoseTree.leaf(Party(id: PartyId, partyAt: -100.0, clock: 0.0, pops: 0))])
|
|
322
|
+
Play(sky: Sky(t: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)), state: filled.state)
|
|
323
|
+
|
|
324
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
325
|
+
|
|
326
|
+
fun withTree(self, t: SceneTree[Msg]) -> Sky = Sky(t: t)
|
|
327
|
+
|
|
328
|
+
# The tick, then a `Renew` for each balloon that is done, in tree order.
|
|
329
|
+
fun rules(self, ctx: Ctx[Msg], state: State, dt: Float) -> Sky =
|
|
330
|
+
ctx.send(Tick(dt: dt))
|
|
331
|
+
for b := range self.balloons()
|
|
332
|
+
if b.done(b.clock)
|
|
333
|
+
ctx.send(Renew(id: b.id))
|
|
334
|
+
self
|
|
335
|
+
|
|
336
|
+
fun react(self, state: State, msg: Msg) -> Sky = match msg
|
|
337
|
+
Popped(_) =>
|
|
338
|
+
pops := state.pops
|
|
339
|
+
partyAt := state.partyAt
|
|
340
|
+
Sky(t: self.t.updateAs[Hud](HudId, |h| Hud(..h, pops: pops)).updateAs[Party](PartyId, |p| Party(..p, partyAt: partyAt, pops: pops)))
|
|
341
|
+
Renew(id) =>
|
|
342
|
+
b := state.renewed
|
|
343
|
+
Sky(t: self.t.updateAs[Balloon](id, |x| b))
|
|
344
|
+
_ => self
|
|
345
|
+
|
|
346
|
+
fun draw(self, io: Io) =
|
|
347
|
+
gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
|
|
348
|
+
self.t.draw(io)
|
|
276
349
|
|
|
277
350
|
# The balloons, in tree order.
|
|
278
351
|
fun balloons(self) -> List[Balloon] =
|
|
279
|
-
self.
|
|
352
|
+
self.t.root.fold(Nil, |acc, a| match a
|
|
280
353
|
Balloon as b => Cons(head: b, tail: acc)
|
|
281
354
|
_ => acc).reverse()
|
|
282
355
|
|
|
283
|
-
fun update(self, msg: Msg) -> State = match msg
|
|
284
|
-
Tick(dt) => self.tick(dt)
|
|
285
|
-
Resize(w, h) => State(..self, sw: w, sh: h, tree: self.tree.updateAs[Camera](RootId, |c| c.fitted(w, h)))
|
|
286
|
-
Event(input) => self.onInput(input)
|
|
287
|
-
Pop(id) => self.pop(id)
|
|
288
|
-
|
|
289
|
-
fun tick(self, dt: Float) -> State =
|
|
290
|
-
moved := State(..self, clock: self.clock + dt, tree: self.tree.step(Ctx[Msg](), dt))
|
|
291
|
-
moved.balloons().fold(moved, |s, b| s.renew(b))
|
|
292
|
-
|
|
293
|
-
# A balloon that is gone comes back at the bottom with a new colour.
|
|
294
|
-
|
|
356
|
+
# A new game's screen and state.
|
|
295
|
-
if !b.done(self.clock)
|
|
296
|
-
self
|
|
297
|
-
else
|
|
298
|
-
sp := Balloon.spawn(b.id, self.rng, 0.0, self.clock)
|
|
299
|
-
State(..self, tree: self.tree.updateAs[Balloon](b.id, |x| sp.balloon), rng: sp.rng)
|
|
300
|
-
|
|
301
|
-
|
|
357
|
+
struct Play(sky: Sky, state: State)
|
|
302
|
-
whole := match self.tree.findAs[Balloon](id)
|
|
303
|
-
Some(b) => !b.popped()
|
|
304
|
-
None => false
|
|
305
|
-
if !whole
|
|
306
|
-
self
|
|
307
|
-
else
|
|
308
|
-
pops := self.pops + 1
|
|
309
|
-
partyAt := if pops % PartyEvery == 0 then self.clock else self.partyAt
|
|
310
|
-
clock := self.clock
|
|
311
|
-
tree := self.tree.updateAs[Balloon](id, |b| b.poppedAtClock(clock)).updateAs[Hud](HudId, |h| Hud(..h, pops: pops))
|
|
312
|
-
State(..self, pops: pops, partyAt: partyAt, tree: tree.updateAs[Party](PartyId, |p| Party(..p, partyAt: partyAt, pops: pops)))
|
|
313
|
-
|
|
314
|
-
fun partying(self) -> Bool =
|
|
315
|
-
self.clock - self.partyAt < PartyTime
|
|
316
358
|
|
|
317
|
-
# A press pops the balloon under it; everything else is ignored.
|
|
318
|
-
|
|
359
|
+
fun main(io: Io) -> Game[State, Msg] =
|
|
360
|
+
play := Sky.start(State.start(io.randomSeed(), audio.loadSound(io, "pickup.wav"), audio.loadSound(io, "gameover.wav")))
|
|
361
|
+
music := audio.loadSound(io, "music.wav")
|
|
362
|
+
music.loop(io, 0.2)
|
|
319
|
-
|
|
363
|
+
Game.start(play.sky, play.state)
|
|
320
|
-
_ => self
|
|
321
364
|
|
|
322
|
-
fun pressAt(self, x: Float, y: Float) -> State =
|
|
323
|
-
if Some(id) := self.tree.hitId(x, y)
|
|
324
|
-
|
|
365
|
+
# --- tests ---
|
|
325
|
-
else
|
|
326
|
-
self
|
|
327
366
|
|
|
328
|
-
|
|
367
|
+
Screen = Vec2(x: 800.0, y: 600.0)
|
|
329
368
|
|
|
369
|
+
fun newGame() -> Game[State, Msg] =
|
|
330
|
-
|
|
370
|
+
play := Sky.start(State.start(3, Sound.Silent, Sound.Silent))
|
|
371
|
+
Game.start(play.sky, play.state)
|
|
331
372
|
|
|
332
|
-
# Sends the tick's inputs to the state, then one tick of time; plays a pop for each new
|
|
333
|
-
# pop and a fanfare when a party starts. Returns the game with the next state.
|
|
334
|
-
|
|
373
|
+
fun skyOf(g: Game[State, Msg]) -> Sky = match g.screen
|
|
335
|
-
before := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
|
|
336
|
-
|
|
374
|
+
Sky as s => s
|
|
337
|
-
s := 0.until(inputs.length()).fold(before, |current, i| current.update(Event(input: inputs.at(i))))
|
|
338
|
-
if s.pops > before.pops
|
|
339
|
-
self.popSound.play(io, 0.9)
|
|
340
|
-
if s.partyAt != before.partyAt
|
|
341
|
-
self.partySound.play(io, 0.6)
|
|
342
|
-
|
|
375
|
+
_ => Sky(t: SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)))
|
|
343
376
|
|
|
344
|
-
fun draw(self, io: Io) =
|
|
345
|
-
gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
|
|
346
|
-
self.state.tree.draw(io)
|
|
347
|
-
|
|
348
|
-
fun
|
|
377
|
+
fun first(g: Game[State, Msg]) -> Balloon =
|
|
349
|
-
|
|
378
|
+
skyOf(g).balloons().at(0)
|
|
350
|
-
state: State.start(io.randomSeed(), ArenaW, ArenaH),
|
|
351
|
-
popSound: audio.loadSound(io, "pickup.wav"),
|
|
352
|
-
partySound: audio.loadSound(io, "gameover.wav"),
|
|
353
|
-
musicSound: audio.loadSound(io, "music.wav")
|
|
354
|
-
)
|
|
355
|
-
game.musicSound.loop(io, 0.2)
|
|
356
|
-
game
|
|
357
379
|
|
|
358
|
-
#
|
|
380
|
+
# A tick of `dt` with `events` on a `view` screen.
|
|
381
|
+
fun tickOn(io: Io, g: Game[State, Msg], events: List[InputEvent], dt: Float, view: Vec2) -> Game[State, Msg] =
|
|
382
|
+
g.step(io, Input(held: Held.none(), events: events.toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0), dt, view)
|
|
359
383
|
|
|
360
|
-
fun
|
|
384
|
+
fun tick(io: Io, g: Game[State, Msg], events: List[InputEvent], dt: Float) -> Game[State, Msg] = tickOn(io, g, events, dt, Screen)
|
|
361
|
-
State.start(3, ArenaW, ArenaH)
|
|
362
385
|
|
|
363
|
-
# A
|
|
386
|
+
# A game whose first balloon is still and in the middle of the screen.
|
|
364
|
-
fun withCentred(
|
|
387
|
+
fun withCentred(g: Game[State, Msg]) -> Game[State, Msg] =
|
|
388
|
+
s := skyOf(g)
|
|
365
|
-
State
|
|
389
|
+
centred: Screen[State, Msg] := Sky(t: s.t.updateAs[Balloon](BalloonId, |b| Balloon(..b, x: 400.0, y: 300.0, speed: 0.0, phase: 0.0)))
|
|
390
|
+
Game(..g, screen: centred)
|
|
366
391
|
|
|
367
|
-
fun
|
|
392
|
+
fun pressAt(x: Float, y: Float) -> List[InputEvent] = [PointerDown(x: x, y: y)]
|
|
368
|
-
s.balloons().at(0)
|
|
369
393
|
|
|
370
394
|
test "a new game has its balloons below the screen and no pops"
|
|
371
|
-
|
|
395
|
+
g := newGame()
|
|
396
|
+
bs := skyOf(g).balloons()
|
|
372
|
-
assert
|
|
397
|
+
assert bs.length() == Count
|
|
373
|
-
assert
|
|
398
|
+
assert g.state().pops == 0
|
|
374
|
-
assert
|
|
399
|
+
assert bs.fold(true, |ok, b| ok && b.y > ArenaH * 0.4)
|
|
375
400
|
|
|
376
401
|
test "balloons rise"
|
|
377
|
-
|
|
402
|
+
g := newGame()
|
|
378
|
-
t :=
|
|
403
|
+
t := tick(io, g, Nil, 1.0)
|
|
379
|
-
assert first(t).y < first(
|
|
404
|
+
assert first(t).y < first(g).y
|
|
380
|
-
assert first(
|
|
405
|
+
assert first(g).y == first(newGame()).y
|
|
406
|
+
assert t.state().clock == 1.0
|
|
381
407
|
|
|
382
408
|
test "pressing a balloon pops it and counts"
|
|
383
|
-
|
|
409
|
+
g := withCentred(newGame())
|
|
384
|
-
t :=
|
|
410
|
+
t := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
385
|
-
assert t.pops == 1
|
|
411
|
+
assert t.state().pops == 1
|
|
386
412
|
assert first(t).popped()
|
|
387
|
-
again :=
|
|
413
|
+
again := tick(io, t, pressAt(400.0, 300.0), 0.01)
|
|
388
|
-
assert again.pops == 1
|
|
414
|
+
assert again.state().pops == 1
|
|
389
415
|
|
|
390
416
|
test "pressing the sky does nothing"
|
|
391
|
-
|
|
417
|
+
g := withCentred(newGame())
|
|
392
|
-
t :=
|
|
418
|
+
t := tick(io, g, pressAt(50.0, 560.0), 0.01)
|
|
393
|
-
assert t.pops == 0
|
|
419
|
+
assert t.state().pops == 0
|
|
394
420
|
|
|
395
421
|
test "a popped balloon comes back at the bottom"
|
|
396
|
-
|
|
422
|
+
g := tick(io, withCentred(newGame()), pressAt(400.0, 300.0), 0.01)
|
|
423
|
+
assert first(g).popped()
|
|
397
|
-
t :=
|
|
424
|
+
t := tick(io, g, Nil, PopTime + 0.1)
|
|
398
425
|
assert !first(t).popped()
|
|
399
426
|
assert first(t).y > ArenaH
|
|
400
427
|
|
|
401
428
|
test "every tenth pop starts a party that ends"
|
|
402
|
-
fresh :=
|
|
429
|
+
fresh := withCentred(newGame())
|
|
430
|
+
nine: Store[State, Msg] := Store.of(State(..fresh.state(), pops: 9))
|
|
403
|
-
|
|
431
|
+
g := Game(..fresh, store: nine)
|
|
404
|
-
assert !
|
|
432
|
+
assert !g.state().partying()
|
|
405
|
-
assert !
|
|
433
|
+
assert !skyOf(g).t.find(PartyId).unwrap().shown()
|
|
406
|
-
t :=
|
|
434
|
+
t := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
407
|
-
assert t.pops == 10
|
|
435
|
+
assert t.state().pops == 10
|
|
408
|
-
assert t.partying()
|
|
436
|
+
assert t.state().partying()
|
|
409
|
-
assert t.tree.find(PartyId).unwrap().shown()
|
|
410
|
-
u := t.update(Tick(dt: PartyTime + 0.1))
|
|
411
|
-
assert !u.partying()
|
|
412
|
-
assert
|
|
437
|
+
assert skyOf(t).t.find(PartyId).unwrap().shown()
|
|
438
|
+
u := tick(io, t, Nil, PartyTime + 0.1)
|
|
439
|
+
assert !u.state().partying()
|
|
440
|
+
assert !skyOf(u).t.find(PartyId).unwrap().shown()
|
|
413
441
|
|
|
414
442
|
test "the press is found through the camera"
|
|
415
|
-
|
|
443
|
+
g := tickOn(io, withCentred(newGame()), Nil, 0.01, Vec2(x: 1600.0, y: 600.0))
|
|
416
|
-
miss :=
|
|
444
|
+
miss := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
417
|
-
assert miss.pops == 0
|
|
445
|
+
assert miss.state().pops == 0
|
|
418
|
-
hit :=
|
|
446
|
+
hit := tick(io, g, pressAt(800.0, 300.0), 0.01)
|
|
419
|
-
assert hit.pops == 1
|
|
447
|
+
assert hit.state().pops == 1
|
|
420
448
|
|
|
421
449
|
test "the same seed gives the same balloons"
|
|
422
|
-
a := State.start(9,
|
|
450
|
+
a := Sky.start(State.start(9, Sound.Silent, Sound.Silent))
|
|
423
|
-
b := State.start(9,
|
|
451
|
+
b := Sky.start(State.start(9, Sound.Silent, Sound.Silent))
|
|
424
|
-
assert
|
|
452
|
+
assert a.sky.balloons().at(0).x == b.sky.balloons().at(0).x
|
|
425
|
-
assert
|
|
453
|
+
assert a.sky.balloons().at(0).hue == b.sky.balloons().at(0).hue
|
examples/games/orb_run.plum
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
# Orb Run (`plum run examples/games/orb_run.plum`). Steer the ship with the arrow keys or
|
|
2
|
-
# WASD, collect the drifting orbs and avoid the mines. Three lives
|
|
2
|
+
# WASD, collect the drifting orbs and avoid the mines. Three lives. Enter, R or the "Play"
|
|
3
|
+
# button starts a run from the title; Enter, R or the "Again" button starts another after
|
|
3
|
-
#
|
|
4
|
+
# the game is over, and Escape goes back to the title.
|
|
4
5
|
#
|
|
6
|
+
# The game is a `Game` (std/game/Game) of three screens, `Title`, `Play` and `Over`, over
|
|
5
|
-
#
|
|
7
|
+
# a store of `State` (std/game/Store). Each screen is a tree of actors (std/game/scene)
|
|
6
|
-
#
|
|
8
|
+
# that lives from frame to frame. Every kind of body is its own struct (`Ship`, `Orb`,
|
|
7
|
-
# `
|
|
9
|
+
# `Mine`, `Star`, `Icon`, ..) with only its own fields, and `is Actor[Msg]`: it says which
|
|
8
|
-
#
|
|
10
|
+
# actor it is (`key`) and where (`place`, made from its plain `x` and `y`), and writes
|
|
9
|
-
#
|
|
11
|
+
# only the behaviour it has: its next version (`step`), its drawing (`paint`), its hit
|
|
10
|
-
#
|
|
12
|
+
# test (`hit`). The ship steers itself from the tick's held keys (`ctx.input`) and the
|
|
13
|
+
# root camera fits itself to the screen (`ctx.view`). The backdrop and the dimmer are
|
|
11
|
-
# `
|
|
14
|
+
# std's `Box`, the layers std's `Group`, the text std/game/ui's `Label` and the buttons
|
|
12
|
-
# whose `onClick` is the message `RestartClicked`. The tree's `step` walks it once a tick
|
|
13
|
-
#
|
|
15
|
+
# ui's `Button`, which send their `onClick` message when clicked.
|
|
16
|
+
#
|
|
14
|
-
#
|
|
17
|
+
# The play screen's tree:
|
|
15
18
|
#
|
|
16
19
|
# 0 root (the camera that fits the arena on screen)
|
|
17
20
|
# ├─ 1 backdrop
|
|
@@ -19,24 +22,21 @@
|
|
|
19
22
|
# ├─ 3 mines ─ 200..
|
|
20
23
|
# ├─ 4 orbs ─ 100..102
|
|
21
24
|
# ├─ 5 ship
|
|
22
|
-
#
|
|
25
|
+
# └─ 6 hud ─ 8 score, 9 best, 300..302 lives
|
|
23
|
-
# └─ 7 panel (hidden while playing) ─ 13 dim, 11 title, 12 prompt, 14 "Again"
|
|
24
26
|
#
|
|
27
|
+
# and game over adds `7 panel ─ 13 dim, 11 title, 12 prompt, 14 "Again"` on top, with the
|
|
25
|
-
#
|
|
28
|
+
# ship hidden and the bodies stopped. The title screen is the camera, the backdrop, the
|
|
26
|
-
# lives) stays in `State`, which reads actors after the step with `SceneTree.findAs` and
|
|
27
|
-
# changes one kind's own fields with `updateAs` (`tree.updateAs[Ship](ShipId, |s|
|
|
28
|
-
# s.steered(ax, ay))`), and adds and removes them with `add` and `kill`. The tree is a
|
|
29
|
-
# value like the rest of `State`: a kept old state still has its old tree. `Msg` is what
|
|
30
|
-
# can happen to the state (a tick of time, a resize, a restart, a player input, a click);
|
|
31
|
-
# `State.update(msg)` is a short sequence of named steps. A pointer input finds the actor
|
|
32
|
-
# under it with `hitId` and runs `ui.step`; a click on the button sends its message
|
|
33
|
-
#
|
|
29
|
+
# stars, the name, the help and the "Play" button.
|
|
34
30
|
#
|
|
35
|
-
#
|
|
31
|
+
# What is between bodies is in the play screen's `rules`, after every actor stepped: the
|
|
36
|
-
#
|
|
32
|
+
# orbs the ship touches (`Collected`), the mines to add as the score grows (`Grow`), a
|
|
33
|
+
# mine that hits the ship (`Hurt`). Those are messages to the store: `State.update` is
|
|
37
|
-
# the
|
|
34
|
+
# the rules of the score, the lives and every random spot (all the randomness is the
|
|
38
|
-
#
|
|
35
|
+
# `Random` in `State`, seeded once in `main`, so one seed and one list of inputs give the
|
|
36
|
+
# same game). The screen `react`s to the new state: an orb moves to its new spot, the
|
|
37
|
+
# hud shows the score, a mine is added, the ship flashes and loses an icon. `next` goes
|
|
38
|
+
# from the title to play (`Start`), from play to game over (the last `Hurt`) and back to
|
|
39
|
-
#
|
|
39
|
+
# play (`Again`). The sounds are the messages' effects (`State.handle`).
|
|
40
40
|
module orb_run
|
|
41
41
|
import std/Str
|
|
42
42
|
import std/Int
|
|
@@ -55,6 +55,8 @@ import std/game/audio
|
|
|
55
55
|
import std/game/Anim
|
|
56
56
|
import std/game/ui
|
|
57
57
|
import std/game/input
|
|
58
|
+
import std/game/Store
|
|
59
|
+
import std/game/Game
|
|
58
60
|
import std/collections/functional/FRoseTree
|
|
59
61
|
import std/game/scene/Place
|
|
60
62
|
import std/game/scene/Actor
|
|
@@ -94,6 +96,9 @@ TitleId = 11
|
|
|
94
96
|
PromptId = 12
|
|
95
97
|
DimId = 13
|
|
96
98
|
RestartId = 14
|
|
99
|
+
NameId = 15
|
|
100
|
+
HelpId = 16
|
|
101
|
+
PlayId = 17
|
|
97
102
|
StarId = 20
|
|
98
103
|
OrbId = 100
|
|
99
104
|
MineId = 200
|
|
@@ -105,7 +110,7 @@ struct Motion(x: Float, y: Float, vx: Float, vy: Float)
|
|
|
105
110
|
# A random spot and the generator to continue from.
|
|
106
111
|
struct Spawned(at: Motion, rng: Random)
|
|
107
112
|
|
|
108
|
-
# --- small pure helpers
|
|
113
|
+
# --- small pure helpers ---
|
|
109
114
|
|
|
110
115
|
# Which of `count` animation frames is showing after `clock` seconds at `fps` frames per second.
|
|
111
116
|
fun frameOf(clock: Float, count: Int, fps: Float) -> Int =
|
|
@@ -196,14 +201,17 @@ fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Floa
|
|
|
196
201
|
# (`hit`), and whether it is shown and how opaque it is. A kind writes only what differs
|
|
197
202
|
# from the trait's defaults. Orbs, mines and the ship are centred on their (x, y) and turn
|
|
198
203
|
# about it. The backdrop and the dimmer are std's `Box`, the layers and the hud std's
|
|
199
|
-
# `Group`, the
|
|
204
|
+
# `Group`, the text ui's `Label` and the buttons ui's `Button`.
|
|
200
205
|
|
|
201
206
|
# The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
|
|
207
|
+
# It fits the screen in its step.
|
|
202
208
|
struct Camera(id: Int, x: Float, y: Float, zoom: Float) is Actor[Msg] =
|
|
203
209
|
fun key(self) -> Int = self.id
|
|
204
210
|
|
|
205
211
|
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
|
|
206
212
|
|
|
213
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> Camera = self.fitted(ctx.view.x, ctx.view.y)
|
|
214
|
+
|
|
207
215
|
# Fitting a `sw` by `sh` screen.
|
|
208
216
|
fun fitted(self, sw: Float, sh: Float) -> Camera = Camera(..self, x: fitX(sw, sh), y: fitY(sw, sh), zoom: fitZoom(sw, sh))
|
|
209
217
|
|
|
@@ -263,11 +271,11 @@ struct Mine(id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float,
|
|
|
263
271
|
# Stopped and no longer turning; it still animates.
|
|
264
272
|
fun still(self) -> Mine = Mine(..self, vx: 0.0, vy: 0.0, spin: 0.0)
|
|
265
273
|
|
|
266
|
-
# The player, at (x, y) turned by `rotation`
|
|
274
|
+
# The player, at (x, y) turned by `rotation`, steered by the held arrow or WASD keys;
|
|
267
|
-
# next step, set by the game before it; `hurt` is the time left of its hurt flash and
|
|
268
|
-
# `
|
|
275
|
+
# `hurt` is the time left of its hurt flash and `hurtAge` the time since the hit. Hidden
|
|
276
|
+
# at game over, when it stops.
|
|
269
277
|
struct Ship(
|
|
270
|
-
id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float,
|
|
278
|
+
id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float,
|
|
271
279
|
hurt: Float, hurtAge: Float, clock: Float, sheet: Texture, visible: Bool) is Actor[Msg] =
|
|
272
280
|
|
|
273
281
|
fun key(self) -> Int = self.id
|
|
@@ -276,15 +284,20 @@ struct Ship(
|
|
|
276
284
|
|
|
277
285
|
fun shown(self) -> Bool = self.visible
|
|
278
286
|
|
|
279
|
-
# It accelerates by the axes, drag slows it and the walls stop it.
|
|
280
287
|
fun step(self, ctx: Ctx[Msg], dt: Float) -> Ship =
|
|
288
|
+
held := ctx.input.held
|
|
289
|
+
self.moved(axisX(held), axisY(held), dt)
|
|
290
|
+
|
|
291
|
+
# Steered by the axes `ax` and `ay` for `dt`: it accelerates by them, drag slows it and
|
|
292
|
+
# the walls stop it.
|
|
293
|
+
fun moved(self, ax: Float, ay: Float, dt: Float) -> Ship =
|
|
281
294
|
if !self.visible
|
|
282
295
|
self
|
|
283
296
|
else
|
|
284
297
|
keep := {1.0 - Drag * dt}.max(0.0)
|
|
285
298
|
r := ShipRadius
|
|
286
|
-
vx0 := {self.vx +
|
|
299
|
+
vx0 := {self.vx + ax * Thrust * dt} * keep
|
|
287
|
-
vy0 := {self.vy +
|
|
300
|
+
vy0 := {self.vy + ay * Thrust * dt} * keep
|
|
288
301
|
x0 := self.x + vx0 * dt
|
|
289
302
|
y0 := self.y + vy0 * dt
|
|
290
303
|
x := x0.max(r).min(ArenaW - r)
|
|
@@ -304,9 +317,6 @@ struct Ship(
|
|
|
304
317
|
# It blinks off while hurt.
|
|
305
318
|
fun blinking(self) -> Bool = self.hurt > 0.0 && flashPose(self.hurtAge).scaleX < 0.7
|
|
306
319
|
|
|
307
|
-
# Steered by the axes for its next step.
|
|
308
|
-
fun steered(self, ax: Float, ay: Float) -> Ship = Ship(..self, ax: ax, ay: ay)
|
|
309
|
-
|
|
310
320
|
# Just hit: hurt for `HurtTime`, its flash from the start.
|
|
311
321
|
fun struck(self) -> Ship = Ship(..self, hurt: HurtTime, hurtAge: 0.0)
|
|
312
322
|
|
|
@@ -322,38 +332,30 @@ struct Icon(id: Int, x: Float, y: Float, size: Float, col: Int, row: Int, sheet:
|
|
|
322
332
|
fun paint(self, io: Io, m: Affine, alpha: Float) = paintCell(io, m, alpha, self.sheet, 0.0, 0.0, self.size, self.col, self.row)
|
|
323
333
|
|
|
324
334
|
# The game-over title centred on (x, y): its scale is `titlePose` of its age.
|
|
325
|
-
struct
|
|
335
|
+
struct Banner(id: Int, x: Float, y: Float, scaleX: Float, scaleY: Float, age: Float, color: Color) is Actor[Msg] =
|
|
326
336
|
fun key(self) -> Int = self.id
|
|
327
337
|
|
|
328
338
|
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.scaleX, self.scaleY)
|
|
329
339
|
|
|
330
|
-
fun step(self, ctx: Ctx[Msg], dt: Float) ->
|
|
340
|
+
fun step(self, ctx: Ctx[Msg], dt: Float) -> Banner =
|
|
331
341
|
p := titlePose(self.age + dt)
|
|
332
|
-
|
|
342
|
+
Banner(..self, scaleX: p.scaleX, scaleY: p.scaleY, age: self.age + dt)
|
|
333
343
|
|
|
334
344
|
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
335
345
|
actor.textPaint(io, m, alpha, "Game over", -100.0, -24.0, 48.0, self.color.withAlpha(1.0))
|
|
336
346
|
|
|
337
|
-
# Unscaled, its clock from 0: as it comes up at game over.
|
|
338
|
-
fun revealed(self) -> Title = Title(..self, scaleX: 1.0, scaleY: 1.0, age: 0.0)
|
|
339
|
-
|
|
340
|
-
# The game-over panel
|
|
347
|
+
# The game-over panel: its opacity fades in over half a second of its age, and so do its
|
|
341
|
-
#
|
|
348
|
+
# children.
|
|
342
|
-
struct Panel(id: Int, age: Float, alpha: Float
|
|
349
|
+
struct Panel(id: Int, age: Float, alpha: Float) is Actor[Msg] =
|
|
343
350
|
fun key(self) -> Int = self.id
|
|
344
351
|
|
|
345
352
|
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
346
353
|
|
|
347
|
-
fun shown(self) -> Bool = self.visible
|
|
348
|
-
|
|
349
354
|
fun opacity(self) -> Float = self.alpha
|
|
350
355
|
|
|
351
356
|
fun step(self, ctx: Ctx[Msg], dt: Float) -> Panel =
|
|
352
357
|
Panel(..self, alpha: {{self.age + dt} * 2.0}.min(1.0), age: self.age + dt)
|
|
353
358
|
|
|
354
|
-
# Shown, faded out, its clock from 0.
|
|
355
|
-
fun revealed(self) -> Panel = Panel(..self, visible: true, alpha: 0.0, age: 0.0)
|
|
356
|
-
|
|
357
359
|
# An orb or a mine stopped (the others as they are): what game over does to every body.
|
|
358
360
|
fun stilled(a: Actor[Msg]) -> Actor[Msg] = match a
|
|
359
361
|
Orb as o => o.still()
|
|
@@ -366,7 +368,32 @@ fun placedAt(a: Actor[Msg], to: Motion) -> Actor[Msg] = match a
|
|
|
366
368
|
Mine as m => m.placed(to)
|
|
367
369
|
_ => a
|
|
368
370
|
|
|
371
|
+
# The steering axes from the held arrow or WASD keys.
|
|
372
|
+
fun axisX(held: Held) -> Float =
|
|
373
|
+
axis(held.isDown(Key.Left) || held.isDown(Key.KeyA), held.isDown(Key.Right) || held.isDown(Key.KeyD))
|
|
374
|
+
|
|
375
|
+
fun axisY(held: Held) -> Float =
|
|
376
|
+
axis(held.isDown(Key.Up) || held.isDown(Key.KeyW), held.isDown(Key.Down) || held.isDown(Key.KeyS))
|
|
377
|
+
|
|
378
|
+
fun axis(negative: Bool, positive: Bool) -> Float =
|
|
379
|
+
if negative && !positive
|
|
380
|
+
-1.0
|
|
381
|
+
else if positive && !negative
|
|
382
|
+
1.0
|
|
383
|
+
else
|
|
384
|
+
0.0
|
|
385
|
+
|
|
386
|
+
# Enter or R going down.
|
|
387
|
+
fun isRestartKey(e: InputEvent) -> Bool = match e
|
|
388
|
+
KeyDown(k) => k == Key.Enter || k == Key.KeyR
|
|
389
|
+
_ => false
|
|
390
|
+
|
|
391
|
+
# Whether the tick's input has one of the restart keys going down, or Escape.
|
|
392
|
+
fun pressedRestart(input: Input) -> Bool = 0.until(input.events.length()).find(|i| isRestartKey(input.events.at(i))).isSome()
|
|
393
|
+
|
|
394
|
+
fun pressedEscape(input: Input) -> Bool = input.isKeyPressed(Key.Escape)
|
|
395
|
+
|
|
369
|
-
# --- building the
|
|
396
|
+
# --- building the trees ---
|
|
370
397
|
|
|
371
398
|
fun group(id: Int, kids: List[FRoseTree[Actor[Msg]]]) -> FRoseTree[Actor[Msg]] =
|
|
372
399
|
FRoseTree.of(Group(id: id, x: 0.0, y: 0.0), kids)
|
|
@@ -390,281 +417,352 @@ fun lifeNodes(i: Int, sheet: Texture) -> List[FRoseTree[Actor[Msg]]] =
|
|
|
390
417
|
Cons(head: FRoseTree.leaf(icon), tail: lifeNodes(i + 1, sheet))
|
|
391
418
|
|
|
392
419
|
fun shipActor(x: Float, y: Float, sheet: Texture) -> Ship =
|
|
393
|
-
Ship(
|
|
394
|
-
|
|
420
|
+
Ship(id: ShipId, x: x, y: y, rotation: 0.0, vx: 0.0, vy: 0.0, hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet, visible: true)
|
|
395
|
-
hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet, visible: true)
|
|
396
421
|
|
|
422
|
+
# The camera fitted to a `sw` by `sh` screen.
|
|
423
|
+
fun fittedCamera(sw: Float, sh: Float) -> Camera = Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(sw, sh)
|
|
424
|
+
|
|
425
|
+
# A tree whose root is the camera `c` over `kids`.
|
|
426
|
+
fun cameraTree(c: Camera, kids: List[FRoseTree[Actor[Msg]]]) -> SceneTree[Msg] =
|
|
427
|
+
root: FRoseTree[Actor[Msg]] := FRoseTree.of(c, kids)
|
|
428
|
+
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
429
|
+
|
|
430
|
+
fun backdrop() -> FRoseTree[Actor[Msg]] =
|
|
431
|
+
FRoseTree.leaf(Box(id: BackId, x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16)))
|
|
432
|
+
|
|
397
|
-
# The tree of a fresh run
|
|
433
|
+
# The tree of a fresh run under the camera `c`, with the run's first orbs and mines
|
|
434
|
+
# (`State.run` places them).
|
|
398
|
-
fun
|
|
435
|
+
fun playTree(s: State, c: Camera) -> SceneTree[Msg] =
|
|
436
|
+
orbs: List[FRoseTree[Actor[Msg]]] := s.newOrbs.map(|o| FRoseTree.leaf(o))
|
|
437
|
+
mines: List[FRoseTree[Actor[Msg]]] := s.newMines.map(|m| FRoseTree.leaf(m))
|
|
399
438
|
hud := group(HudId, Cons(
|
|
400
|
-
head: label(ScoreId, "Score
|
|
439
|
+
head: label(ScoreId, "Score {s.score}", 16.0, 12.0, 28.0, Color.White),
|
|
401
|
-
tail: Cons(head: label(BestId, "Best
|
|
440
|
+
tail: Cons(head: label(BestId, "Best {s.best.max(s.score)}", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, s.sheet))))
|
|
441
|
+
cameraTree(c, [
|
|
442
|
+
backdrop(),
|
|
443
|
+
group(StarLayer, starNodes(0)),
|
|
444
|
+
group(MineLayer, mines),
|
|
445
|
+
group(OrbLayer, orbs),
|
|
446
|
+
FRoseTree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, s.sheet)),
|
|
447
|
+
hud])
|
|
448
|
+
|
|
449
|
+
# The game-over panel that comes up over the play screen.
|
|
450
|
+
fun panelNode() -> FRoseTree[Actor[Msg]] =
|
|
402
|
-
|
|
451
|
+
FRoseTree.of(Panel(id: PanelId, age: 0.0, alpha: 0.0), [
|
|
403
452
|
FRoseTree.leaf(Box(id: DimId, x: 0.0, y: 230.0, w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6))),
|
|
404
|
-
FRoseTree.leaf(
|
|
453
|
+
FRoseTree.leaf(Banner(id: TitleId, x: 400.0, y: 268.0, scaleX: 1.0, scaleY: 1.0, age: 0.0, color: Color.Red)),
|
|
405
454
|
label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
|
|
406
|
-
FRoseTree.leaf(
|
|
455
|
+
FRoseTree.leaf(ui.button(RestartId, 340.0, 342.0, 120.0, 44.0, "Again", Again))])
|
|
456
|
+
|
|
407
|
-
|
|
457
|
+
# The title screen's tree.
|
|
408
|
-
|
|
458
|
+
fun titleTree() -> SceneTree[Msg] =
|
|
409
|
-
|
|
459
|
+
cameraTree(fittedCamera(ArenaW, ArenaH), [
|
|
460
|
+
backdrop(),
|
|
410
461
|
group(StarLayer, starNodes(0)),
|
|
411
|
-
group(MineLayer, Nil),
|
|
412
|
-
|
|
462
|
+
label(NameId, "Orb Run", 280.0, 200.0, 64.0, Color.rgb(1.0, 0.8, 0.3)),
|
|
463
|
+
label(HelpId, "Steer with the arrows or WASD, collect the orbs, dodge the mines", 90.0, 290.0, 20.0, Color.White),
|
|
413
|
-
FRoseTree.leaf(
|
|
464
|
+
FRoseTree.leaf(ui.button(PlayId, 340.0, 342.0, 120.0, 44.0, "Play", Start))])
|
|
414
|
-
hud,
|
|
415
|
-
panel])
|
|
416
|
-
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
417
465
|
|
|
418
466
|
# --- the game ---
|
|
419
467
|
|
|
468
|
+
# What can happen to the state: a run starts from the title or again after game over, the
|
|
469
|
+
# ship at (x, y) touches the orb `id`, the mines grow to the score with the ship at
|
|
420
|
-
#
|
|
470
|
+
# (x, y), a mine hits the ship.
|
|
421
471
|
enum Msg =
|
|
472
|
+
| Start
|
|
473
|
+
| Again
|
|
422
|
-
|
|
|
474
|
+
| Collected(id: Int, x: Float, y: Float)
|
|
423
|
-
|
|
|
475
|
+
| Grow(x: Float, y: Float)
|
|
424
|
-
| Restart(seed: Int)
|
|
425
|
-
| Event(input: InputEvent)
|
|
426
|
-
|
|
|
476
|
+
| Hurt
|
|
427
|
-
|
|
477
|
+
|
|
428
|
-
# The
|
|
478
|
+
# The run between the bodies: the randomness, the score, the lives, how many mines are out
|
|
429
|
-
# one's id is `MineId + mines`)
|
|
479
|
+
# (the next one's id is `MineId + mines`), and where the last message put things: the
|
|
480
|
+
# run's first orbs and mines, the spot of a collected orb, the mines just added. The
|
|
481
|
+
# sprite sheet and the sounds are for the screens and the effects.
|
|
430
482
|
struct State(
|
|
431
|
-
|
|
483
|
+
seed: Int,
|
|
432
484
|
rng: Random,
|
|
433
485
|
score: Int,
|
|
434
486
|
best: Int,
|
|
435
487
|
lives: Int,
|
|
436
488
|
over: Bool,
|
|
437
|
-
clock: Float,
|
|
438
489
|
mines: Int,
|
|
490
|
+
newOrbs: List[Orb],
|
|
439
|
-
|
|
491
|
+
newMines: List[Mine],
|
|
440
|
-
held: Held,
|
|
441
|
-
|
|
492
|
+
spot: Motion,
|
|
442
|
-
sh: Float,
|
|
443
|
-
sheet: Texture
|
|
493
|
+
sheet: Texture,
|
|
494
|
+
sounds: Sounds
|
|
444
|
-
) =
|
|
495
|
+
) is Reducer[Msg] =
|
|
445
|
-
|
|
496
|
+
|
|
446
|
-
#
|
|
497
|
+
# The state on the title screen: no run yet. The first run is seeded with `seed`.
|
|
447
|
-
fun
|
|
498
|
+
fun create(seed: Int, sheet: Texture, sounds: Sounds) -> State =
|
|
448
499
|
State(
|
|
449
|
-
tree: buildTree(sheet, sw, sh),
|
|
450
|
-
rng: Random.seeded(seed),
|
|
500
|
+
seed: seed, rng: Random.seeded(seed), score: 0, best: 0, lives: StartLives, over: false, mines: 0,
|
|
451
|
-
score: 0,
|
|
452
|
-
best: best,
|
|
453
|
-
lives: StartLives,
|
|
454
|
-
over: false,
|
|
455
|
-
clock: 0.0,
|
|
456
|
-
mines: 0,
|
|
457
|
-
ui: ui.init(),
|
|
458
|
-
held: Held.none(),
|
|
459
|
-
sw: sw,
|
|
460
|
-
sh: sh,
|
|
461
|
-
sheet: sheet
|
|
462
|
-
|
|
501
|
+
newOrbs: Nil, newMines: Nil, spot: Motion(x: 0.0, y: 0.0, vx: 0.0, vy: 0.0), sheet: sheet, sounds: sounds)
|
|
463
502
|
|
|
464
503
|
fun update(self, msg: Msg) -> State = match msg
|
|
465
|
-
Tick(dt, ax, ay) => self.tick(dt, ax, ay)
|
|
466
|
-
Resize(w, h) => State(..self, sw: w, sh: h, tree: self.tree.updateAs[Camera](RootId, |c| c.fitted(w, h)))
|
|
467
|
-
|
|
504
|
+
Start => self.run(self.seed, self.best)
|
|
468
|
-
Event(input) => self.onInput(input)
|
|
469
|
-
|
|
505
|
+
Again => if self.over then self.run(self.rng.nextInt().value, self.best.max(self.score)) else self
|
|
506
|
+
Collected(_, x, y) =>
|
|
507
|
+
sp := spawn(self.rng, x, y, 120.0, 40.0)
|
|
508
|
+
State(..self, rng: sp.rng, spot: sp.at, score: self.score + OrbPoints)
|
|
509
|
+
Grow(x, y) => self.grown(x, y, Nil)
|
|
510
|
+
Hurt =>
|
|
511
|
+
lives := self.lives - 1
|
|
512
|
+
done := lives <= 0
|
|
513
|
+
State(..self, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best)
|
|
514
|
+
|
|
515
|
+
# A fresh run seeded with `seed`, keeping `best`: its orbs and mines spread over the
|
|
516
|
+
# arena away from the ship in the middle.
|
|
517
|
+
fun run(self, seed: Int, best: Int) -> State =
|
|
518
|
+
fresh := State(..self, rng: Random.seeded(seed), score: 0, best: best, lives: StartLives, over: false, mines: 0, newOrbs: Nil)
|
|
519
|
+
orbs := fresh.orbsFrom(0, Nil)
|
|
520
|
+
orbs.grown(ArenaW / 2.0, ArenaH / 2.0, Nil)
|
|
521
|
+
|
|
522
|
+
# Orbs `i` and up to `OrbCount`, each at a random spot away from the ship.
|
|
523
|
+
fun orbsFrom(self, i: Int, acc: List[Orb]) -> State =
|
|
524
|
+
if i >= OrbCount
|
|
525
|
+
State(..self, newOrbs: acc.reverse())
|
|
526
|
+
else
|
|
527
|
+
sp := spawn(self.rng, ArenaW / 2.0, ArenaH / 2.0, 120.0, 40.0)
|
|
528
|
+
orb := Orb(id: OrbId + i, x: sp.at.x, y: sp.at.y, vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet)
|
|
529
|
+
State(..self, rng: sp.rng).orbsFrom(i + 1, Cons(head: orb, tail: acc))
|
|
530
|
+
|
|
531
|
+
# Mines added (on top of the others) until there are as many as the score asks for, away
|
|
532
|
+
# from the ship at (x, y).
|
|
533
|
+
fun grown(self, x: Float, y: Float, acc: List[Mine]) -> State =
|
|
534
|
+
if self.mines >= mineCount(self.score)
|
|
535
|
+
State(..self, newMines: acc.reverse())
|
|
536
|
+
else
|
|
537
|
+
sp := spawn(self.rng, x, y, 220.0, 90.0)
|
|
538
|
+
mine := Mine(id: MineId + self.mines, x: sp.at.x, y: sp.at.y, rotation: 0.0, vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet)
|
|
539
|
+
State(..self, rng: sp.rng, mines: self.mines + 1).grown(x, y, Cons(head: mine, tail: acc))
|
|
540
|
+
|
|
541
|
+
# The sounds, with the state after the tick.
|
|
542
|
+
fun handle(self, io: Io, msg: Msg) = match msg
|
|
543
|
+
Again => self.sounds.startMusic(io)
|
|
544
|
+
Collected(_, _, _) => self.sounds.pickup.play(io, 0.8)
|
|
545
|
+
Hurt =>
|
|
546
|
+
if self.over
|
|
547
|
+
self.sounds.music.stop(io)
|
|
548
|
+
self.sounds.over.play(io, 1.0)
|
|
549
|
+
else
|
|
550
|
+
self.sounds.hit.play(io, 1.0)
|
|
551
|
+
_ => Unit
|
|
552
|
+
|
|
553
|
+
struct Sounds(pickup: Sound, hit: Sound, over: Sound, music: Sound) =
|
|
554
|
+
# Restarts the music loop from the top.
|
|
555
|
+
fun startMusic(self, io: Io) =
|
|
556
|
+
self.music.stop(io)
|
|
557
|
+
self.music.loop(io, musicVolume())
|
|
558
|
+
|
|
559
|
+
fun silent() -> Sounds = Sounds(pickup: Sound.Silent, hit: Sound.Silent, over: Sound.Silent, music: Sound.Silent)
|
|
560
|
+
|
|
561
|
+
fun musicVolume() -> Float =
|
|
562
|
+
0.3
|
|
563
|
+
|
|
564
|
+
# The title: Enter, R or the "Play" button start the first run.
|
|
565
|
+
struct Title(t: SceneTree[Msg]) is Screen[State, Msg] =
|
|
566
|
+
fun create() -> Title = Title(t: titleTree())
|
|
567
|
+
|
|
568
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
569
|
+
|
|
570
|
+
fun withTree(self, t: SceneTree[Msg]) -> Title = Title(t: t)
|
|
571
|
+
|
|
572
|
+
fun rules(self, ctx: Ctx[Msg], state: State, dt: Float) -> Title =
|
|
573
|
+
if pressedRestart(ctx.input)
|
|
574
|
+
ctx.send(Start)
|
|
575
|
+
self
|
|
576
|
+
|
|
577
|
+
fun next(self, state: State, msg: Msg) -> Option[Screen[State, Msg]] = match msg
|
|
578
|
+
Start => Some(Play.fresh(state, self.t))
|
|
579
|
+
_ => None
|
|
470
580
|
|
|
471
|
-
# One frame: the tree steps every actor (the ship with this frame's axes), then the
|
|
472
|
-
# game looks at what they did. Once the game is over the actors only animate.
|
|
473
|
-
fun
|
|
581
|
+
fun draw(self, io: Io) = drawTree(io, self.t)
|
|
474
|
-
stepped := self.tree.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay)).step(Ctx[Msg](), dt)
|
|
475
|
-
moved := State(..self, tree: stepped, clock: self.clock + dt)
|
|
476
|
-
if self.over then moved else moved.collect().growMines().hurt().settle()
|
|
477
582
|
|
|
583
|
+
# A run: the bodies, the hud and the rules between them.
|
|
584
|
+
struct Play(t: SceneTree[Msg]) is Screen[State, Msg] =
|
|
478
|
-
# The
|
|
585
|
+
# The screen of the run `state` just started, under the camera of `from` (the screen
|
|
586
|
+
# before).
|
|
479
|
-
fun
|
|
587
|
+
fun fresh(state: State, from: SceneTree[Msg]) -> Screen[State, Msg] =
|
|
588
|
+
c := from.findAs[Camera](RootId).unwrapOr(fittedCamera(ArenaW, ArenaH))
|
|
589
|
+
screen: Screen[State, Msg] := Play(t: playTree(state, c))
|
|
590
|
+
screen
|
|
480
591
|
|
|
592
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
593
|
+
|
|
594
|
+
fun withTree(self, t: SceneTree[Msg]) -> Play = Play(t: t)
|
|
595
|
+
|
|
481
|
-
fun ship(self) -> Ship = self.
|
|
596
|
+
fun ship(self) -> Ship = self.t.findAs[Ship](ShipId).unwrap()
|
|
482
597
|
|
|
483
598
|
# The orbs and the mines, in tree order.
|
|
484
599
|
fun orbs(self) -> List[Orb] =
|
|
485
|
-
self.
|
|
600
|
+
self.t.root.fold(Nil, |acc, a| match a
|
|
486
601
|
Orb as o => Cons(head: o, tail: acc)
|
|
487
602
|
_ => acc).reverse()
|
|
488
603
|
|
|
489
604
|
fun mineList(self) -> List[Mine] =
|
|
490
|
-
self.
|
|
605
|
+
self.t.root.fold(Nil, |acc, a| match a
|
|
491
606
|
Mine as m => Cons(head: m, tail: acc)
|
|
492
607
|
_ => acc).reverse()
|
|
493
608
|
|
|
609
|
+
# After every actor stepped: the orbs the ship touches, the mines to grow, a mine that
|
|
610
|
+
# hits the ship (unless it is still flashing from the last).
|
|
494
|
-
fun
|
|
611
|
+
fun rules(self, ctx: Ctx[Msg], state: State, dt: Float) -> Play =
|
|
495
612
|
sh := self.ship()
|
|
613
|
+
for o := range self.orbs()
|
|
496
|
-
|
|
614
|
+
if overlaps(sh.x, sh.y, ShipRadius, o.x, o.y, OrbRadius)
|
|
615
|
+
ctx.send(Collected(id: o.id, x: sh.x, y: sh.y))
|
|
616
|
+
ctx.send(Grow(x: sh.x, y: sh.y))
|
|
617
|
+
if sh.hurt <= 0.0 && self.mineList().find(|m| overlaps(sh.x, sh.y, ShipRadius, m.x, m.y, MineRadius)).isSome()
|
|
618
|
+
ctx.send(Hurt)
|
|
619
|
+
self
|
|
620
|
+
|
|
621
|
+
fun react(self, state: State, msg: Msg) -> Play = match msg
|
|
622
|
+
Collected(id, _, _) =>
|
|
623
|
+
spot := state.spot
|
|
624
|
+
Play(t: self.t.updateAs[Orb](id, |o| o.placed(spot))).showScore(state)
|
|
625
|
+
Grow(_, _) => Play(t: state.newMines.fold(self.t, |t, m| t.add(MineLayer, FRoseTree.leaf(m))))
|
|
626
|
+
Hurt => Play(t: self.t.updateAs[Ship](ShipId, |sh| sh.struck()).kill(LifeId + state.lives))
|
|
627
|
+
_ => self
|
|
497
628
|
|
|
498
|
-
# The
|
|
629
|
+
# The hud's labels from the score.
|
|
630
|
+
fun showScore(self, state: State) -> Play =
|
|
631
|
+
score := "Score {state.score}"
|
|
632
|
+
best := "Best {state.best.max(state.score)}"
|
|
633
|
+
Play(t: self.t.updateAs[Label[Msg]](ScoreId, |l| l.relabel(score)).updateAs[Label[Msg]](BestId, |l| l.relabel(best)))
|
|
634
|
+
|
|
635
|
+
fun next(self, state: State, msg: Msg) -> Option[Screen[State, Msg]] = match msg
|
|
636
|
+
Hurt =>
|
|
637
|
+
if state.over
|
|
638
|
+
screen: Screen[State, Msg] := Over.of(self.t)
|
|
639
|
+
Some(screen)
|
|
640
|
+
else
|
|
641
|
+
None
|
|
642
|
+
_ => None
|
|
643
|
+
|
|
644
|
+
fun draw(self, io: Io) = drawTree(io, self.t)
|
|
645
|
+
|
|
646
|
+
# Game over: the run's tree with the ship gone, the bodies stopped (they still animate) and
|
|
647
|
+
# the panel up. Enter, R or "Again" start another run; Escape goes back to the title.
|
|
648
|
+
struct Over(t: SceneTree[Msg]) is Screen[State, Msg] =
|
|
649
|
+
fun of(play: SceneTree[Msg]) -> Over =
|
|
650
|
+
hidden := play.updateAs[Ship](ShipId, |sh| sh.hidden())
|
|
651
|
+
Over(t: hidden.withRoot(hidden.root.map(stilled)).add(RootId, panelNode()))
|
|
652
|
+
|
|
653
|
+
fun tree(self) -> SceneTree[Msg] = self.t
|
|
654
|
+
|
|
655
|
+
fun withTree(self, t: SceneTree[Msg]) -> Over = Over(t: t)
|
|
656
|
+
|
|
657
|
+
fun rules(self, ctx: Ctx[Msg], state: State, dt: Float) -> Over =
|
|
658
|
+
if pressedRestart(ctx.input)
|
|
659
|
+
ctx.send(Again)
|
|
660
|
+
else if pressedEscape(ctx.input)
|
|
661
|
+
ctx.out.push(Restart)
|
|
662
|
+
self
|
|
663
|
+
|
|
664
|
+
fun next(self, state: State, msg: Msg) -> Option[Screen[State, Msg]] = match msg
|
|
665
|
+
Again => Some(Play.fresh(state, self.t))
|
|
666
|
+
_ => None
|
|
667
|
+
|
|
668
|
+
fun draw(self, io: Io) = drawTree(io, self.t)
|
|
669
|
+
|
|
670
|
+
# Every screen clears to the night, then draws its tree.
|
|
671
|
+
fun drawTree(io: Io, t: SceneTree[Msg]) =
|
|
672
|
+
gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
|
|
673
|
+
t.draw(io)
|
|
674
|
+
|
|
499
|
-
|
|
675
|
+
fun main(io: Io) -> Game[State, Msg] =
|
|
676
|
+
sounds := Sounds(
|
|
677
|
+
pickup: audio.loadSound(io, "pickup.wav"),
|
|
678
|
+
hit: audio.loadSound(io, "hit.wav"),
|
|
679
|
+
over: audio.loadSound(io, "gameover.wav"),
|
|
680
|
+
music: audio.loadSound(io, "music.wav"))
|
|
500
|
-
|
|
681
|
+
state := State.create(io.randomSeed(), gfx.loadTexture(io, "sprites.png"), sounds)
|
|
682
|
+
sounds.startMusic(io)
|
|
683
|
+
Game.start(Title.create(), state)
|
|
501
684
|
|
|
502
|
-
# Scores the orb `id` and puts it at a new random spot.
|
|
503
|
-
fun respawnOrb(self, id: Int) -> State =
|
|
504
|
-
sh := self.ship()
|
|
505
|
-
sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
|
|
506
|
-
State(..self, tree: self.tree.updateAs[Orb](id, |o| o.placed(sp.at)), rng: sp.rng, score: self.score + OrbPoints).showScore()
|
|
507
685
|
|
|
508
|
-
# The hud's labels from the score.
|
|
509
|
-
|
|
686
|
+
# --- tests ---
|
|
510
|
-
score := "Score {self.score}"
|
|
511
|
-
best := "Best {self.best.max(self.score)}"
|
|
512
|
-
State(..self, tree: self.tree.updateAs[Label[Msg]](ScoreId, |l| l.relabel(score)).updateAs[Label[Msg]](BestId, |l| l.relabel(best)))
|
|
513
687
|
|
|
514
|
-
# Orbs `i` and up to OrbCount, each at a random spot away from the ship.
|
|
515
|
-
|
|
688
|
+
View = Vec2(x: 800.0, y: 600.0)
|
|
516
|
-
if i >= OrbCount then self else self.addOrb(i).fillOrbs(i + 1)
|
|
517
689
|
|
|
518
|
-
|
|
690
|
+
fun newGame(seed: Int) -> Game[State, Msg] =
|
|
519
|
-
sh := self.ship()
|
|
520
|
-
sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
|
|
521
|
-
orb := Orb(id: OrbId + i, x: sp.at.x, y: sp.at.y, vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet)
|
|
522
|
-
|
|
691
|
+
Game.start(Title.create(), State.create(seed, Texture(id: -1), Sounds.silent()))
|
|
523
692
|
|
|
524
|
-
# Mines are added (on top of the others) until there are as many as the score asks for.
|
|
525
|
-
fun growMines(self) -> State =
|
|
526
|
-
|
|
693
|
+
fun inputOf(keys: List[Int], events: List[InputEvent]) -> Input =
|
|
694
|
+
Input(held: Held(mouse: false, keys: keys.toSlice()), events: events.toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
527
695
|
|
|
528
|
-
fun addMine(self) -> State =
|
|
529
|
-
sh := self.ship()
|
|
530
|
-
sp := spawn(self.rng, sh.x, sh.y, 220.0, 90.0)
|
|
531
|
-
mine := Mine(id: MineId + self.mines, x: sp.at.x, y: sp.at.y, rotation: 0.0, vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet)
|
|
532
|
-
State(..self, tree: self.tree.add(MineLayer, FRoseTree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
|
|
533
|
-
|
|
534
|
-
fun touchesMine(self) -> Bool =
|
|
535
|
-
self.mineList().fold(false, |hit, m| hit || self.touches(m.x, m.y, MineRadius))
|
|
536
|
-
|
|
537
|
-
# A mine costs a life (and its icon), makes the ship flash and, at the last life, ends
|
|
538
|
-
# the game: the ship goes and the panel comes up.
|
|
539
|
-
fun hurt(self) -> State =
|
|
540
|
-
if self.ship().hurt <= 0.0 && self.touchesMine() then self.struck() else self
|
|
541
|
-
|
|
542
|
-
fun struck(self) -> State =
|
|
543
|
-
lives := self.lives - 1
|
|
544
|
-
done := lives <= 0
|
|
545
|
-
hit := self.tree.updateAs[Ship](ShipId, |sh| sh.struck()).kill(LifeId + lives)
|
|
546
|
-
tree := if done then gameOver(hit) else hit
|
|
547
|
-
State(..self, tree: tree, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best)
|
|
548
|
-
|
|
549
|
-
# After game over the orbs and mines stop: they only animate.
|
|
550
|
-
fun settle(self) -> State =
|
|
551
|
-
if self.over then State(..self, tree: self.tree.withRoot(self.tree.root.map(stilled))) else self
|
|
552
|
-
|
|
553
|
-
# A fresh run that keeps the best score, the Ui and the held keys; the button shows the
|
|
554
|
-
# Ui's state.
|
|
555
|
-
fun restarted(self, seed: Int) -> State =
|
|
556
|
-
fresh := State.start(seed, self.best.max(self.score), self.sheet, self.sw, self.sh)
|
|
557
|
-
State(..fresh, ui: self.ui, held: self.held, tree: ui.styled(fresh.tree, self.ui))
|
|
558
|
-
|
|
559
|
-
# A player input: keys update the held keys (Enter or R restarts a finished game),
|
|
560
|
-
# a pointer input goes through the Ui.
|
|
561
|
-
|
|
696
|
+
fun press(k: Int) -> List[InputEvent] = [KeyDown(key: k)]
|
|
562
|
-
s := State(..self, held: self.held.after(e))
|
|
563
|
-
if e.isPointer()
|
|
564
|
-
s.feed(e)
|
|
565
|
-
else if s.over && isRestartKey(e)
|
|
566
|
-
s.restarted(s.rng.nextInt().value)
|
|
567
|
-
else
|
|
568
|
-
s
|
|
569
697
|
|
|
570
|
-
# The steering axes from the held arrow or WASD keys.
|
|
571
|
-
fun axisX(self) -> Float =
|
|
572
|
-
|
|
698
|
+
fun click(x: Float, y: Float) -> List[InputEvent] = [PointerDown(x: x, y: y), PointerUp(x: x, y: y)]
|
|
573
699
|
|
|
574
|
-
|
|
700
|
+
# One tick of 1/60 s (or `dt`) with `keys` held and `events`, on an 800 by 600 screen.
|
|
575
|
-
|
|
701
|
+
fun tickOf(io: Io, g: Game[State, Msg], keys: List[Int], events: List[InputEvent]) -> Game[State, Msg] =
|
|
702
|
+
g.step(io, inputOf(keys, events), 1.0 / 60.0, View)
|
|
576
703
|
|
|
577
|
-
|
|
704
|
+
fun ticksOf(io: Io, g: Game[State, Msg], n: Int, keys: List[Int], dt: Float) -> Game[State, Msg] =
|
|
578
|
-
# the Ui turns that into press, hover and click, the button shows the result, and a
|
|
579
|
-
# click on it restarts.
|
|
580
|
-
fun feed(self, input: InputEvent) -> State =
|
|
581
|
-
po := input.position()
|
|
582
|
-
if po.isNone()
|
|
583
|
-
self
|
|
584
|
-
else
|
|
585
|
-
pos := po.unwrap()
|
|
586
|
-
r := ui.step(self.ui, input, self.tree.hitId(pos.x, pos.y))
|
|
587
|
-
|
|
705
|
+
0.until(n).fold(g, |cur, _| cur.step(io, inputOf(keys, Nil), dt, View))
|
|
588
|
-
ui.messages(s.tree, r.events).fold(s, |t, msg| t.update(msg))
|
|
589
706
|
|
|
590
|
-
|
|
707
|
+
# A game on the play screen: the title, then Enter.
|
|
591
|
-
|
|
708
|
+
fun started(io: Io, seed: Int) -> Game[State, Msg] = tickOf(io, newGame(seed), Nil, press(Key.Enter))
|
|
592
|
-
self.tree.hitId(x, y).unwrapOr(-1) == RestartId
|
|
593
709
|
|
|
594
|
-
# The tree at game over: the ship hidden, the panel and its title coming up.
|
|
595
|
-
fun
|
|
710
|
+
fun treeOf(g: Game[State, Msg]) -> SceneTree[Msg] = g.screen.tree()
|
|
596
|
-
s.updateAs[Ship](ShipId, |sh| sh.hidden()).updateAs[Panel](PanelId, |p| p.revealed()).updateAs[Title](TitleId, |t| t.revealed())
|
|
597
711
|
|
|
598
|
-
# Enter or R going down.
|
|
599
|
-
fun
|
|
712
|
+
fun onScreen(g: Game[State, Msg]) -> Str = match g.screen
|
|
713
|
+
Title as t1 => "title"
|
|
714
|
+
Play as p1 => "play"
|
|
600
|
-
|
|
715
|
+
Over as o1 => "over"
|
|
601
|
-
_ =>
|
|
716
|
+
_ => "?"
|
|
602
717
|
|
|
603
|
-
fun
|
|
718
|
+
fun shipOf(g: Game[State, Msg]) -> Ship = treeOf(g).findAs[Ship](ShipId).unwrap()
|
|
604
|
-
if negative && !positive
|
|
605
|
-
-1.0
|
|
606
|
-
else if positive && !negative
|
|
607
|
-
1.0
|
|
608
|
-
else
|
|
609
|
-
0.0
|
|
610
719
|
|
|
611
|
-
|
|
720
|
+
fun orbAt(g: Game[State, Msg], id: Int) -> Orb = treeOf(g).findAs[Orb](id).unwrap()
|
|
612
721
|
|
|
613
|
-
|
|
722
|
+
fun mineAt(g: Game[State, Msg], id: Int) -> Mine = treeOf(g).findAs[Mine](id).unwrap()
|
|
614
723
|
|
|
615
|
-
# Restarts the music loop from the top.
|
|
616
|
-
fun startMusic(self, io: Io) =
|
|
617
|
-
self.musicSound.stop(io)
|
|
618
|
-
self.musicSound.loop(io, musicVolume())
|
|
619
|
-
|
|
620
|
-
# One tick of `playTick` on the state, after this frame's screen size; plays sounds for
|
|
621
|
-
# what changed. Returns the game with the next state.
|
|
622
|
-
fun update(self, io: Io, input: Input, dt: Float) -> OrbGame =
|
|
623
|
-
s := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
|
|
624
|
-
t := playTick(s, input, dt)
|
|
625
|
-
if s.over && !t.over
|
|
626
|
-
self.startMusic(io)
|
|
627
|
-
else
|
|
628
|
-
if t.score > s.score
|
|
629
|
-
self.pickupSound.play(io, 0.8)
|
|
630
|
-
if t.lives < s.lives
|
|
631
|
-
if t.over
|
|
632
|
-
self.musicSound.stop(io)
|
|
633
|
-
self.overSound.play(io, 1.0)
|
|
634
|
-
else
|
|
635
|
-
self.hitSound.play(io, 1.0)
|
|
636
|
-
OrbGame(..self, state: t)
|
|
637
|
-
|
|
638
|
-
fun draw(self, io: Io) =
|
|
639
|
-
gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
|
|
640
|
-
self.state.tree.draw(io)
|
|
641
|
-
|
|
642
|
-
|
|
724
|
+
fun labelText(g: Game[State, Msg], id: Int) -> Str = treeOf(g).findAs[Label[Msg]](id).unwrap().text
|
|
643
|
-
# then, unless they restarted a finished game, one tick of time steered by the held keys.
|
|
644
|
-
fun playTick(s: State, input: Input, dt: Float) -> State =
|
|
645
|
-
inputs := input.events
|
|
646
|
-
clicked := 0.until(inputs.length()).fold(s, |current, i| current.update(Event(input: inputs.at(i))))
|
|
647
|
-
if s.over && !clicked.over
|
|
648
|
-
clicked
|
|
649
|
-
else
|
|
650
|
-
clicked.update(Tick(dt: dt, ax: clicked.axisX(), ay: clicked.axisY()))
|
|
651
725
|
|
|
726
|
+
fun mineCountOf(g: Game[State, Msg]) -> Int = treeOf(g).root.fold(0, |n, a| match a
|
|
652
|
-
|
|
727
|
+
Mine as m1 => n + 1
|
|
653
|
-
|
|
728
|
+
_ => n)
|
|
654
729
|
|
|
655
|
-
|
|
730
|
+
# The game with every actor of its screen's tree through `f`.
|
|
656
|
-
|
|
731
|
+
fun mapped(g: Game[State, Msg], f: fn(Actor[Msg]) -> Actor[Msg]) -> Game[State, Msg] =
|
|
657
|
-
|
|
732
|
+
t := treeOf(g)
|
|
658
|
-
state: s,
|
|
659
|
-
|
|
733
|
+
screen: Screen[State, Msg] := g.screen.withTree(t.withRoot(t.root.map(f)))
|
|
660
|
-
hitSound: audio.loadSound(io, "hit.wav"),
|
|
661
|
-
overSound: audio.loadSound(io, "gameover.wav"),
|
|
662
|
-
musicSound: audio.loadSound(io, "music.wav")
|
|
663
|
-
)
|
|
664
|
-
|
|
734
|
+
Game(..g, screen: screen)
|
|
665
|
-
game
|
|
666
735
|
|
|
736
|
+
# The game with the actor `id` through `f`.
|
|
737
|
+
fun moved(g: Game[State, Msg], id: Int, m: Motion) -> Game[State, Msg] =
|
|
738
|
+
screen: Screen[State, Msg] := g.screen.withTree(treeOf(g).update(id, |a| placedAt(a, m)))
|
|
739
|
+
Game(..g, screen: screen)
|
|
740
|
+
|
|
741
|
+
fun away() -> Motion =
|
|
742
|
+
Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
|
|
743
|
+
|
|
744
|
+
fun onShip(g: Game[State, Msg]) -> Motion =
|
|
745
|
+
Motion(x: shipOf(g).x, y: shipOf(g).y, vx: 0.0, vy: 0.0)
|
|
746
|
+
|
|
747
|
+
# A game on the play screen with the orbs and mines moved out of the way.
|
|
748
|
+
fun emptyGame(io: Io) -> Game[State, Msg] = mapped(started(io, 7), |a| placedAt(a, away()))
|
|
749
|
+
|
|
750
|
+
fun withState(g: Game[State, Msg], s: State) -> Game[State, Msg] =
|
|
751
|
+
store: Store[State, Msg] := Store.of(s)
|
|
752
|
+
Game(..g, store: store)
|
|
753
|
+
|
|
754
|
+
# A game over with the score `score`: the one life left lost to a mine.
|
|
755
|
+
fun overWith(io: Io, score: Int) -> Game[State, Msg] =
|
|
756
|
+
e := emptyGame(io)
|
|
757
|
+
g := withState(e, State(..e.state(), lives: 1, score: score))
|
|
758
|
+
tickOf(io, moved(g, MineId, onShip(g)), Nil, Nil)
|
|
759
|
+
|
|
760
|
+
fun lone(sh: Ship) -> SceneTree[Msg] = SceneTree.of(sh)
|
|
761
|
+
|
|
762
|
+
fun shipAt(x: Float, y: Float) -> Ship = shipActor(x, y, Texture(id: -1))
|
|
763
|
+
|
|
764
|
+
fun near(a: Float, b: Float) -> Bool =
|
|
667
|
-
|
|
765
|
+
{a - b}.abs() < 0.01
|
|
668
766
|
|
|
669
767
|
# Tick `i` of a scripted run: Right held over ticks 10..59 and Up over 30..89, with a
|
|
670
768
|
# KeyDown and a KeyUp on the ticks they change.
|
|
@@ -686,87 +784,54 @@ fun scriptedInput(i: Int) -> Input =
|
|
|
686
784
|
Input(held: input.inHeld(keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
687
785
|
|
|
688
786
|
# 120 ticks of 1/60 s from `seed` with the scripted inputs.
|
|
689
|
-
fun scriptedRun(seed: Int) -> State =
|
|
787
|
+
fun scriptedRun(io: Io, seed: Int) -> Game[State, Msg] =
|
|
690
|
-
0.until(120).fold(
|
|
788
|
+
0.until(120).fold(started(io, seed), |g, i| g.step(io, scriptedInput(i), 1.0 / 60.0, View))
|
|
691
|
-
|
|
789
|
+
|
|
692
|
-
fun sameRun(a: State, b: State) -> Bool =
|
|
790
|
+
fun sameRun(a: Game[State, Msg], b: Game[State, Msg]) -> Bool =
|
|
693
|
-
|
|
791
|
+
sum := |g: Game[State, Msg]| treeOf(g).root.fold(0.0, |t, x| match x
|
|
694
|
-
|
|
792
|
+
Orb as o => t + o.x + o.y * 1000.0
|
|
793
|
+
_ => t)
|
|
794
|
+
a.state().rng.seed == b.state().rng.seed && a.state().score == b.state().score && a.state().lives == b.state().lives
|
|
695
|
-
|
|
795
|
+
&& shipOf(a).x == shipOf(b).x && shipOf(a).y == shipOf(b).y && sum(a) == sum(b) && a.ticks == b.ticks
|
|
696
|
-
|
|
697
|
-
|
|
796
|
+
|
|
698
|
-
{a - b}.abs() < 0.01
|
|
699
|
-
|
|
700
|
-
fun tickOf(s: State, ax: Float, ay: Float, dt: Float) -> State =
|
|
701
|
-
s.update(Tick(dt: dt, ax: ax, ay: ay))
|
|
702
|
-
|
|
703
|
-
# `n` ticks in a row with the same steering.
|
|
704
|
-
fun ticksOf(s: State, n: Int, ax: Float, ay: Float, dt: Float) -> State =
|
|
705
|
-
0.until(n).fold(s, |current, _| tickOf(current, ax, ay, dt))
|
|
706
|
-
|
|
707
|
-
# How many frames the ship was hidden and shown while ticking `state`.
|
|
708
|
-
struct Blinks(state: State, hidden: Int, shown: Int)
|
|
709
|
-
|
|
710
|
-
fun away() -> Motion =
|
|
711
|
-
Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
|
|
712
|
-
|
|
713
|
-
fun newState(seed: Int) -> State =
|
|
714
|
-
State.start(seed, 0, Texture(id: -1), ArenaW, ArenaH)
|
|
715
|
-
|
|
716
|
-
fun moveBody(s: State, id: Int, m: Motion) -> State =
|
|
717
|
-
State(..s, tree: s.tree.update(id, |a| placedAt(a, m)))
|
|
718
|
-
|
|
719
|
-
|
|
797
|
+
test "the title starts a run on Enter or on its Play button"
|
|
720
|
-
fun emptyState() -> State =
|
|
721
|
-
|
|
798
|
+
g := newGame(7)
|
|
722
|
-
State(..s, tree: s.tree.withRoot(s.tree.root.map(|a| placedAt(a, away()))))
|
|
723
|
-
|
|
724
|
-
|
|
799
|
+
assert onScreen(g) == "title"
|
|
725
|
-
|
|
800
|
+
assert onScreen(tickOf(io, g, Nil, Nil)) == "title"
|
|
726
|
-
|
|
727
|
-
fun forceOver(s: State) -> State =
|
|
728
|
-
|
|
801
|
+
assert onScreen(tickOf(io, g, Nil, press(Key.Enter))) == "play"
|
|
729
|
-
|
|
802
|
+
# the Play button is at (340, 342), 120 by 44
|
|
730
|
-
|
|
803
|
+
assert onScreen(tickOf(io, g, Nil, click(400.0, 364.0))) == "play"
|
|
731
|
-
|
|
732
|
-
|
|
804
|
+
assert onScreen(tickOf(io, g, Nil, click(100.0, 100.0))) == "title"
|
|
733
|
-
|
|
734
|
-
|
|
805
|
+
|
|
735
|
-
|
|
736
|
-
fun steer(s: SceneTree[Msg], ax: Float, ay: Float) -> SceneTree[Msg] = s.updateAs[Ship](ShipId, |sh| sh.steered(ax, ay))
|
|
737
|
-
|
|
738
|
-
fun labelText(s: State, id: Int) -> Str = s.tree.findAs[Label[Msg]](id).unwrap().text
|
|
739
|
-
|
|
740
|
-
fun buttonLookOf(s: State) -> Int = s.tree.findAs[Button[Msg]](RestartId).unwrap().look
|
|
741
|
-
|
|
742
|
-
fun mineAt(s: State, id: Int) -> Mine = s.tree.findAs[Mine](id).unwrap()
|
|
743
|
-
|
|
744
|
-
fun orbAt(s: State, id: Int) -> Orb = s.tree.findAs[Orb](id).unwrap()
|
|
745
|
-
|
|
746
|
-
test "
|
|
806
|
+
test "a run's tree has 58 actors, all drawn; game over adds the panel"
|
|
747
|
-
|
|
807
|
+
g := started(io, 7)
|
|
748
|
-
assert
|
|
808
|
+
assert treeOf(g).count() == 58
|
|
749
|
-
assert
|
|
809
|
+
assert treeOf(g).flatten().length() == 58
|
|
750
|
-
over :=
|
|
810
|
+
over := overWith(io, 0)
|
|
811
|
+
assert onScreen(over) == "over"
|
|
812
|
+
# the last life icon went, the ship is hidden, the panel's five actors came
|
|
813
|
+
assert treeOf(over).count() == 58 - 1 + 5
|
|
751
|
-
assert over.
|
|
814
|
+
assert treeOf(over).flatten().length() == 58 - 1 - 1 + 5
|
|
752
815
|
|
|
753
816
|
test "steering accelerates and drag slows the ship"
|
|
754
|
-
|
|
817
|
+
sh := shipAt(ArenaW / 2.0, ArenaH / 2.0).moved(1.0, 0.0, 0.1)
|
|
755
|
-
sh := shipOf(s)
|
|
756
818
|
assert sh.x > ArenaW / 2.0
|
|
757
819
|
assert sh.vx > 0.0
|
|
758
|
-
coast := steer(s, 0.0, 0.0)
|
|
759
|
-
t := 0.until(30).fold(
|
|
820
|
+
t := 0.until(30).fold(sh, |cur, _| cur.moved(0.0, 0.0, 0.1))
|
|
760
|
-
assert
|
|
821
|
+
assert t.vx < sh.vx / 4.0
|
|
761
|
-
assert
|
|
822
|
+
assert t.x - sh.x < 50.0
|
|
823
|
+
|
|
824
|
+
test "the held keys steer the ship in its step"
|
|
825
|
+
g := ticksOf(io, emptyGame(io), 10, [Key.Left, Key.KeyS], 1.0 / 60.0)
|
|
826
|
+
assert shipOf(g).x < ArenaW / 2.0
|
|
827
|
+
assert shipOf(g).y > ArenaH / 2.0
|
|
828
|
+
assert axisX(Held(mouse: false, keys: [Key.Left, Key.Right].toSlice())) == 0.0
|
|
762
829
|
|
|
763
830
|
test "the ship stops at the arena walls"
|
|
764
|
-
start := steer(lone(shipAt(20.0, 20.0)), -1.0, -1.0)
|
|
765
|
-
s := 0.until(20).fold(
|
|
831
|
+
s := 0.until(20).fold(shipAt(20.0, 20.0), |cur, _| cur.moved(-1.0, -1.0, 0.1))
|
|
766
|
-
sh := shipOf(s)
|
|
767
|
-
assert
|
|
832
|
+
assert s.x == ShipRadius
|
|
768
|
-
assert
|
|
833
|
+
assert s.y == ShipRadius
|
|
769
|
-
assert
|
|
834
|
+
assert s.vx == 0.0
|
|
770
835
|
|
|
771
836
|
test "orbs bounce off the walls and mines spin as they drift"
|
|
772
837
|
orb := Orb(id: OrbId, x: 795.0, y: 300.0, vx: 100.0, vy: 0.0, phase: 0.0, clock: 0.0, sheet: Texture(id: -1))
|
|
@@ -779,167 +844,139 @@ test "orbs bounce off the walls and mines spin as they drift"
|
|
|
779
844
|
assert near(mine.rotation, 0.0)
|
|
780
845
|
|
|
781
846
|
test "collecting an orb scores, respawns it elsewhere and updates the hud"
|
|
782
|
-
e :=
|
|
847
|
+
e := emptyGame(io)
|
|
783
|
-
|
|
848
|
+
g := moved(e, OrbId, onShip(e))
|
|
784
|
-
t := tickOf(
|
|
849
|
+
t := tickOf(io, g, Nil, Nil)
|
|
785
850
|
orb := orbAt(t, OrbId)
|
|
786
|
-
assert t.score == OrbPoints
|
|
851
|
+
assert t.state().score == OrbPoints
|
|
787
|
-
assert math.hypot(orb.x -
|
|
852
|
+
assert math.hypot(orb.x - shipOf(t).x, orb.y - shipOf(t).y) >= 120.0
|
|
788
853
|
assert orb.x < 5000.0
|
|
789
|
-
assert t.orbs().length() == OrbCount
|
|
790
854
|
assert labelText(t, ScoreId) == "Score 10"
|
|
791
|
-
assert labelText(
|
|
855
|
+
assert labelText(g, ScoreId) == "Score 0"
|
|
792
856
|
|
|
793
857
|
test "a mine costs one life and its icon, and makes the ship flash"
|
|
794
|
-
e :=
|
|
858
|
+
e := emptyGame(io)
|
|
795
|
-
|
|
859
|
+
hit := tickOf(io, moved(e, MineId, onShip(e)), Nil, Nil)
|
|
796
|
-
hit := tickOf(s, 0.0, 0.0, 0.016)
|
|
797
|
-
assert hit.lives == StartLives - 1
|
|
860
|
+
assert hit.state().lives == StartLives - 1
|
|
798
|
-
assert
|
|
861
|
+
assert shipOf(hit).hurt > 0.0
|
|
799
|
-
assert hit.
|
|
862
|
+
assert treeOf(hit).find(LifeId + 2).isNone()
|
|
800
|
-
assert hit.
|
|
863
|
+
assert treeOf(hit).find(LifeId + 1).isSome()
|
|
801
|
-
|
|
864
|
+
safe := moved(hit, MineId, away())
|
|
802
|
-
blinks := 0.until(100).fold(
|
|
865
|
+
blinks := 0.until(100).fold(Slice[Bool](), |acc, i|
|
|
803
|
-
|
|
866
|
+
acc.push(shipOf(ticksOf(io, safe, i, Nil, 0.016)).blinking())
|
|
804
|
-
if next.ship().blinking()
|
|
805
|
-
Blinks(state: next, hidden: b.hidden + 1, shown: b.shown)
|
|
806
|
-
|
|
867
|
+
acc
|
|
807
|
-
Blinks(state: next, hidden: b.hidden, shown: b.shown + 1)
|
|
808
868
|
)
|
|
869
|
+
assert blinks.contains(true) && blinks.contains(false)
|
|
809
|
-
|
|
870
|
+
later := ticksOf(io, safe, 100, Nil, 0.016)
|
|
810
|
-
assert blinks.shown > 0
|
|
811
|
-
assert
|
|
871
|
+
assert shipOf(later).hurt == 0.0
|
|
812
|
-
assert !blinks.state.ship().blinking()
|
|
813
|
-
assert
|
|
872
|
+
assert later.state().lives == StartLives - 1
|
|
814
873
|
|
|
815
874
|
test "the ship is briefly safe after a hit"
|
|
816
|
-
e :=
|
|
875
|
+
e := emptyGame(io)
|
|
817
|
-
hit := tickOf(
|
|
876
|
+
hit := tickOf(io, moved(e, MineId, onShip(e)), Nil, Nil)
|
|
818
|
-
assert tickOf(
|
|
877
|
+
assert tickOf(io, hit, Nil, Nil).state().lives == StartLives - 1
|
|
819
|
-
|
|
878
|
+
|
|
820
|
-
test "the game ends at zero lives: the ship goes, the panel comes up,
|
|
879
|
+
test "the game ends at zero lives: the ship goes, the panel comes up, the bodies stop"
|
|
821
|
-
|
|
880
|
+
t := overWith(io, 40)
|
|
822
|
-
s := State(..e, lives: 1, score: 40)
|
|
823
|
-
t := tickOf(moveBody(s, MineId, onShip(s)), 0.0, 0.0, 0.016)
|
|
824
|
-
assert t.over
|
|
881
|
+
assert t.state().over
|
|
825
|
-
assert t.lives == 0
|
|
882
|
+
assert t.state().lives == 0
|
|
826
|
-
assert t.best == 40
|
|
883
|
+
assert t.state().best == 40
|
|
827
|
-
assert !
|
|
884
|
+
assert !shipOf(t).shown()
|
|
828
|
-
assert t.
|
|
885
|
+
assert treeOf(t).find(PanelId).unwrap().shown()
|
|
829
|
-
x :=
|
|
886
|
+
x := shipOf(t).x
|
|
830
|
-
assert tickOf(t, 1.0, 0.0, 0.5).ship().x == x
|
|
831
|
-
|
|
832
|
-
test "after game over nothing moves but the animations keep running"
|
|
833
|
-
e := emptyState()
|
|
834
|
-
s := State(..e, lives: 1)
|
|
835
|
-
ended := tickOf(moveBody(s, MineId, Motion(x: s.ship().x, y: s.ship().y, vx: 10.0, vy: 0.0)), 0.0, 0.0, 0.016)
|
|
836
|
-
assert ended.over
|
|
837
|
-
mine := mineAt(
|
|
887
|
+
mine := mineAt(t, MineId)
|
|
838
|
-
|
|
888
|
+
u := ticksOf(io, t, 10, [Key.Right], 0.1)
|
|
889
|
+
assert shipOf(u).x == x
|
|
839
|
-
after := mineAt(
|
|
890
|
+
after := mineAt(u, MineId)
|
|
840
|
-
assert after.x == mine.x
|
|
841
|
-
assert after.rotation == mine.rotation
|
|
891
|
+
assert after.x == mine.x && after.rotation == mine.rotation
|
|
842
|
-
assert t.ship().x == ArenaW / 2.0
|
|
843
892
|
assert after.clock > mine.clock + 0.9
|
|
844
|
-
assert orbAt(
|
|
893
|
+
assert orbAt(u, OrbId).clock > 0.9
|
|
894
|
+
assert onScreen(u) == "over"
|
|
895
|
+
|
|
896
|
+
test "again starts a fresh run and keeps the best score; escape goes back to the title"
|
|
897
|
+
over := overWith(io, 90)
|
|
898
|
+
r := tickOf(io, over, Nil, press(Key.Enter))
|
|
899
|
+
assert onScreen(r) == "play"
|
|
845
|
-
assert
|
|
900
|
+
assert !r.state().over
|
|
846
|
-
assert
|
|
901
|
+
assert r.state().score == 0
|
|
847
|
-
|
|
848
|
-
test "restart builds a fresh tree and keeps the best score"
|
|
849
|
-
e := emptyState()
|
|
850
|
-
s := forceOver(State(..e, score: 90))
|
|
851
|
-
r := s.update(Restart(seed: 5))
|
|
852
|
-
assert !r.over
|
|
853
|
-
assert r.score == 0
|
|
854
|
-
assert r.best == 90
|
|
902
|
+
assert r.state().best == 90
|
|
855
|
-
assert r.lives == StartLives
|
|
903
|
+
assert r.state().lives == StartLives
|
|
856
|
-
assert
|
|
904
|
+
assert shipOf(r).x == ArenaW / 2.0 && shipOf(r).shown()
|
|
857
|
-
assert r.ship().shown()
|
|
858
|
-
assert
|
|
905
|
+
assert treeOf(r).find(PanelId).isNone()
|
|
859
|
-
assert
|
|
906
|
+
assert mineCountOf(r) == mineCount(0)
|
|
860
907
|
assert labelText(r, BestId) == "Best 90"
|
|
908
|
+
# a click on "Again" does the same
|
|
909
|
+
c := tickOf(io, over, Nil, click(400.0, 364.0))
|
|
910
|
+
assert onScreen(c) == "play" && c.state().best == 90
|
|
911
|
+
assert onScreen(tickOf(io, over, Nil, click(100.0, 100.0))) == "over"
|
|
912
|
+
# Escape restarts the whole game: the title and the first state
|
|
913
|
+
t := tickOf(io, over, Nil, press(Key.Escape))
|
|
914
|
+
assert onScreen(t) == "title"
|
|
915
|
+
assert t.state().best == 0
|
|
916
|
+
# while playing, Enter and the buttons do nothing
|
|
917
|
+
assert tickOf(io, emptyGame(io), Nil, press(Key.Enter)).state().score == 0
|
|
918
|
+
assert onScreen(tickOf(io, emptyGame(io), Nil, press(Key.Escape))) == "play"
|
|
861
919
|
|
|
862
920
|
test "more mines are added to the tree as the score grows"
|
|
863
921
|
assert mineCount(0) == 3
|
|
864
922
|
assert mineCount(100) == 5
|
|
865
923
|
assert mineCount(10000) == 8
|
|
866
|
-
e :=
|
|
924
|
+
e := emptyGame(io)
|
|
867
|
-
t := tickOf(State(..e, score: 100),
|
|
925
|
+
t := tickOf(io, withState(e, State(..e.state(), score: 100)), Nil, Nil)
|
|
868
|
-
assert
|
|
926
|
+
assert mineCountOf(t) == 5
|
|
869
|
-
assert t.
|
|
927
|
+
assert treeOf(t).find(MineId + 4).isSome()
|
|
870
|
-
assert t.
|
|
928
|
+
assert t.state().mines == 5
|
|
871
929
|
|
|
872
930
|
test "the same seed plays out the same way"
|
|
873
|
-
a := ticksOf(
|
|
931
|
+
a := ticksOf(io, started(io, 11), 120, [Key.Right, Key.Up], 0.016)
|
|
874
|
-
b := ticksOf(
|
|
932
|
+
b := ticksOf(io, started(io, 11), 120, [Key.Right, Key.Up], 0.016)
|
|
875
|
-
assert
|
|
933
|
+
assert shipOf(a).x == shipOf(b).x
|
|
876
|
-
assert a.score == b.score
|
|
934
|
+
assert a.state().score == b.state().score
|
|
877
935
|
assert mineAt(a, MineId).x == mineAt(b, MineId).x
|
|
878
|
-
assert orbAt(
|
|
936
|
+
assert orbAt(started(io, 12), OrbId).x != orbAt(started(io, 11), OrbId).x
|
|
879
|
-
|
|
937
|
+
|
|
880
|
-
test "a kept old
|
|
938
|
+
test "a kept old game still has its old tree"
|
|
881
|
-
|
|
939
|
+
g := emptyGame(io)
|
|
882
|
-
x :=
|
|
940
|
+
x := shipOf(g).x
|
|
883
|
-
t :=
|
|
941
|
+
t := ticksOf(io, g, 6, [Key.Right], 1.0 / 60.0)
|
|
884
|
-
assert
|
|
942
|
+
assert shipOf(t).x > x
|
|
885
|
-
assert
|
|
943
|
+
assert shipOf(g).x == x
|
|
886
|
-
|
|
944
|
+
|
|
887
|
-
test "the root fits the arena on the screen"
|
|
945
|
+
test "the root camera fits the arena on the screen"
|
|
888
|
-
|
|
946
|
+
g := emptyGame(io).step(io, inputOf(Nil, Nil), 1.0 / 60.0, Vec2(x: 1600.0, y: 600.0))
|
|
889
|
-
root :=
|
|
947
|
+
root := treeOf(g).find(RootId).unwrap().place().local()
|
|
890
948
|
assert near(root.a, 1.0)
|
|
891
949
|
assert near(root.e, 400.0)
|
|
892
950
|
assert near(root.f, 0.0)
|
|
893
951
|
|
|
894
|
-
test "the
|
|
952
|
+
test "the again button is found through the root's camera"
|
|
895
|
-
|
|
953
|
+
o := overWith(io, 0)
|
|
896
|
-
assert
|
|
954
|
+
assert treeOf(o).hitId(400.0, 364.0).unwrapOr(-1) == RestartId
|
|
897
|
-
o := forceOver(s)
|
|
898
|
-
assert o.onRestart(400.0, 364.0)
|
|
899
|
-
assert
|
|
955
|
+
assert treeOf(o).hitId(100.0, 100.0).unwrapOr(-1) == BackId
|
|
900
|
-
assert
|
|
956
|
+
assert treeOf(emptyGame(io)).hitId(400.0, 364.0).unwrapOr(-1) != RestartId
|
|
901
|
-
wide := o.
|
|
957
|
+
wide := o.step(io, inputOf(Nil, Nil), 1.0 / 60.0, Vec2(x: 1600.0, y: 600.0))
|
|
902
|
-
assert wide.
|
|
958
|
+
assert treeOf(wide).hitId(800.0, 364.0).unwrapOr(-1) == RestartId
|
|
903
|
-
assert
|
|
959
|
+
assert onScreen(tickOf(io, wide, Nil, click(800.0, 364.0))) == "play"
|
|
904
|
-
|
|
960
|
+
|
|
905
|
-
test "a
|
|
961
|
+
test "a press on the button shows it pressed, and a release elsewhere does not click"
|
|
906
|
-
|
|
962
|
+
o := overWith(io, 90)
|
|
907
|
-
s := forceOver(State(..e, score: 90))
|
|
908
|
-
down :=
|
|
963
|
+
down := o.step(io, Input(held: Held(mouse: true, keys: Slice[Int]()), events: [PointerDown(x: 400.0, y: 364.0)].toSlice(), pos: Vec2(x: 400.0, y: 364.0), wheel: 0.0), 1.0 / 60.0, View)
|
|
909
|
-
assert down.over
|
|
910
|
-
assert
|
|
964
|
+
assert onScreen(down) == "over"
|
|
911
|
-
assert
|
|
965
|
+
assert treeOf(down).findAs[Button[Msg]](RestartId).unwrap().look == 2
|
|
912
|
-
up :=
|
|
966
|
+
up := tickOf(io, down, Nil, [PointerUp(x: 100.0, y: 100.0)])
|
|
913
|
-
assert !up.over
|
|
914
|
-
assert up.score == 0
|
|
915
|
-
assert up.best == 90
|
|
916
|
-
assert up
|
|
967
|
+
assert onScreen(up) == "over"
|
|
917
|
-
assert
|
|
968
|
+
assert treeOf(up).findAs[Button[Msg]](RestartId).unwrap().look == 0
|
|
918
|
-
assert s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0)).over
|
|
919
969
|
|
|
920
970
|
test "the title pulses and the panel fades in by their own clocks"
|
|
921
|
-
t := ticksOf(
|
|
971
|
+
t := ticksOf(io, overWith(io, 0), 15, Nil, 0.02)
|
|
922
|
-
assert near(t.
|
|
972
|
+
assert near(treeOf(t).find(PanelId).unwrap().opacity(), 0.6)
|
|
923
|
-
assert near(t.
|
|
973
|
+
assert near(treeOf(t).find(TitleId).unwrap().place().local().a, 1.3)
|
|
924
974
|
assert near(titlePose(0.8).scaleX, 1.17)
|
|
925
975
|
assert near(flashPose(0.05).scaleX, 0.4)
|
|
926
976
|
|
|
927
|
-
test "held keys steer, and enter restarts a finished game and nothing else"
|
|
928
|
-
s := emptyState().update(Event(input: KeyDown(key: Key.Left))).update(Event(input: KeyDown(key: Key.KeyS)))
|
|
929
|
-
assert s.axisX() == -1.0
|
|
930
|
-
assert s.axisY() == 1.0
|
|
931
|
-
assert s.update(Event(input: KeyUp(key: Key.Left))).axisX() == 0.0
|
|
932
|
-
playing := emptyState().update(Event(input: KeyDown(key: Key.Enter)))
|
|
933
|
-
assert !playing.over
|
|
934
|
-
e := emptyState()
|
|
935
|
-
r := forceOver(State(..e, score: 40)).update(Event(input: KeyDown(key: Key.Enter)))
|
|
936
|
-
assert !r.over
|
|
937
|
-
assert r.best == 40
|
|
938
|
-
assert r.held.isDown(Key.Enter)
|
|
939
|
-
|
|
940
977
|
test "same_seed_same_game: one seed and one input list give the same run"
|
|
941
|
-
a := scriptedRun(42)
|
|
978
|
+
a := scriptedRun(io, 42)
|
|
942
|
-
b := scriptedRun(42)
|
|
979
|
+
b := scriptedRun(io, 42)
|
|
943
980
|
assert sameRun(a, b)
|
|
944
|
-
assert
|
|
981
|
+
assert shipOf(a).x != shipOf(started(io, 42)).x
|
|
945
|
-
assert !sameRun(a, scriptedRun(43))
|
|
982
|
+
assert !sameRun(a, scriptedRun(io, 43))
|
std/game/Game.plum
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Bool
|
|
6
|
+
import std/Str
|
|
7
|
+
import std/Option
|
|
8
|
+
import std/List
|
|
9
|
+
import std/Slice
|
|
10
|
+
import std/Io
|
|
11
|
+
import std/game/Vec2
|
|
12
|
+
import std/game/Affine
|
|
13
|
+
import std/game/Color
|
|
14
|
+
import std/game/gfx
|
|
15
|
+
import std/game/input
|
|
16
|
+
import std/collections/functional/FRoseTree
|
|
17
|
+
import std/game/Store
|
|
18
|
+
import std/game/scene/Place
|
|
19
|
+
import std/game/scene/Actor
|
|
20
|
+
import std/game/scene/Ctx
|
|
21
|
+
import std/game/scene/SceneTree
|
|
22
|
+
|
|
23
|
+
# The one way to make a game: a `Game[S, M]` over a store of the state `S` (a
|
|
24
|
+
# `Reducer[M]`, std/game/Store), made of screens (`Screen[S, M]`), each a tree of actors
|
|
25
|
+
# (`SceneTree[M]` of `Actor[M]`, std/game/scene). `M` is the game's message type. A game
|
|
26
|
+
# writes its actors, its screens and its reducer; `Game` runs the loop:
|
|
27
|
+
#
|
|
28
|
+
# fun main(io: Io) -> Game[RunState, Msg] =
|
|
29
|
+
# Game.start(Title.create(), RunState.create(io.randomSeed()))
|
|
30
|
+
#
|
|
31
|
+
# A `main` that returns a `Game` is a game (the compiler adds the frame entry points the
|
|
32
|
+
# host calls, which call `update` once per fixed 1/60 s tick and `draw` once a frame).
|
|
33
|
+
#
|
|
34
|
+
# One tick (`update`), always in this order:
|
|
35
|
+
#
|
|
36
|
+
# 1. Each pointer event of the tick goes to the topmost shown actor under it that says
|
|
37
|
+
# it is hit, through `input`, then to each of its parents (`SceneTree.input`). A
|
|
38
|
+
# `PointerMove` that leaves the pointer where it was (the host reports one every
|
|
39
|
+
# frame) goes to no actor.
|
|
40
|
+
# 2. Every actor steps (`step`), then the screen's `rules` run. The actors and the
|
|
41
|
+
# rules see the tick's input (held keys, the pointer) in `ctx.input`.
|
|
42
|
+
# 3. `Spawn` and `Kill` apply: those pushed by `input` in the step's own walk, those of
|
|
43
|
+
# the steps after it, those of the rules after that (`SceneTree.step`, `apply`).
|
|
44
|
+
# 4. Each `Send(msg)`, in the order pushed: the store reduces it (`update`), then the
|
|
45
|
+
# screen `react`s to the new state and is asked for its `next` screen. The first
|
|
46
|
+
# `next` that gives a screen wins; the old screen takes the rest of the tick.
|
|
47
|
+
# 5. After the tick: the store's `flush(io)` runs `handle(io, msg)` for each message in
|
|
48
|
+
# order, then the screen switch, then `Restart` (the first screen and state again)
|
|
49
|
+
# or `Exit` (no tick runs after it; the last screen keeps being drawn).
|
|
50
|
+
#
|
|
51
|
+
# `draw` draws the current screen. All randomness belongs in `S` and changes only in
|
|
52
|
+
# `update`, so one seed and one list of inputs replay the same game.
|
|
53
|
+
|
|
54
|
+
# One screen of a game (a title, the play, the game over): its tree of actors and what it
|
|
55
|
+
# does with the state. `S` is the game's state and `M` its message type.
|
|
56
|
+
#
|
|
57
|
+
# tree, withTree the screen's tree, and the screen with another one
|
|
58
|
+
# rules rules over the whole screen after its actors stepped (collisions);
|
|
59
|
+
# they act through `ctx` (`ctx.send(msg)`, `ctx.out.push(Kill(..))`)
|
|
60
|
+
# react the screen after a message was reduced: show the new state (a label)
|
|
61
|
+
# next the screen to switch to after this message, if any
|
|
62
|
+
# draw draws it: its tree by default
|
|
63
|
+
trait Screen[S, M] =
|
|
64
|
+
fun tree(self) -> SceneTree[M]
|
|
65
|
+
|
|
66
|
+
fun withTree(self, t: SceneTree[M]) -> Self
|
|
67
|
+
|
|
68
|
+
fun rules(self, ctx: Ctx[M], state: S, dt: Float) -> Self = self
|
|
69
|
+
|
|
70
|
+
fun react(self, state: S, msg: M) -> Self = self
|
|
71
|
+
|
|
72
|
+
fun next(self, state: S, msg: M) -> Option[Screen[S, M]] = None
|
|
73
|
+
|
|
74
|
+
fun draw(self, io: Io) = self.tree().draw(io)
|
|
75
|
+
|
|
76
|
+
# A running game: its screen, its store, the first screen and state (for `Restart`),
|
|
77
|
+
# whether it has exited, the ticks it has run, and where the last pointer event was.
|
|
78
|
+
struct Game[S: Reducer[M], M](screen: Screen[S, M], store: Store[S, M], first: Screen[S, M], initial: S, exited: Bool, ticks: Int, pointer: Vec2) =
|
|
79
|
+
|
|
80
|
+
# The only way to make a game: `screen` showing, `state` in the store.
|
|
81
|
+
fun start(screen: Screen[S, M], state: S) -> Game[S, M] =
|
|
82
|
+
Game(screen: screen, store: Store.of(state), first: screen, initial: state, exited: false, ticks: 0, pointer: NoPointer)
|
|
83
|
+
|
|
84
|
+
# The state now.
|
|
85
|
+
fun state(self) -> S = self.store.state
|
|
86
|
+
|
|
87
|
+
# One tick of `dt` seconds with `input` on the host's screen: what the host runs.
|
|
88
|
+
fun update(self, io: Io, input: Input, dt: Float) -> Game[S, M] =
|
|
89
|
+
self.step(io, input, dt, Vec2(x: gfx.screenWidth(io), y: gfx.screenHeight(io)))
|
|
90
|
+
|
|
91
|
+
# One tick of `dt` seconds with `input` on a screen of `view` pixels (see the top of
|
|
92
|
+
# this file); a test runs ticks with it. An exited game stays as it is.
|
|
93
|
+
fun step(self, io: Io, input: Input, dt: Float, view: Vec2) -> Game[S, M] =
|
|
94
|
+
if self.exited then self else self.tick(io, input, dt, view)
|
|
95
|
+
|
|
96
|
+
fun tick(self, io: Io, input: Input, dt: Float, view: Vec2) -> Game[S, M] =
|
|
97
|
+
ctx: Ctx[M] := Ctx.of(input, view)
|
|
98
|
+
routed := routeAll(self.screen.tree(), ctx, input.events, 0, self.pointer)
|
|
99
|
+
stepped := routed.step(ctx, dt)
|
|
100
|
+
ruled := self.screen.withTree(stepped).rules(ctx, self.store.state, dt)
|
|
101
|
+
applied := ruled.withTree(ruled.tree().apply(ctx.out))
|
|
102
|
+
ctx.keepOnly(true)
|
|
103
|
+
begin: Turn[S, M] := Turn(screen: applied, store: self.store, next: None, restart: false, exit: false)
|
|
104
|
+
turn := 0.until(ctx.out.length()).fold(begin, |tu, i| tu.take(ctx.out.at(i)))
|
|
105
|
+
flushed := turn.store.flush(io)
|
|
106
|
+
shown := match turn.next
|
|
107
|
+
Some(s) => s
|
|
108
|
+
None => turn.screen
|
|
109
|
+
pointer := lastPointer(input.events, self.pointer)
|
|
110
|
+
if turn.restart && !turn.exit
|
|
111
|
+
Game(..self, screen: self.first, store: Store.of(self.initial), ticks: self.ticks + 1, pointer: pointer)
|
|
112
|
+
else
|
|
113
|
+
Game(..self, screen: shown, store: flushed, exited: turn.exit, ticks: self.ticks + 1, pointer: pointer)
|
|
114
|
+
|
|
115
|
+
fun draw(self, io: Io) = self.screen.draw(io)
|
|
116
|
+
|
|
117
|
+
# Where the pointer is before a game's first pointer event: nowhere on any screen.
|
|
118
|
+
NoPointer = Vec2(x: -1.0e18, y: -1.0e18)
|
|
119
|
+
|
|
120
|
+
# The tree after the pointer events of `evs` from `i` on, in order; `at` is where the
|
|
121
|
+
# pointer was before them. A move to where it was is skipped.
|
|
122
|
+
fun routeAll[M](t: SceneTree[M], ctx: Ctx[M], evs: Slice[InputEvent], i: Int, at: Vec2) -> SceneTree[M] =
|
|
123
|
+
if i >= evs.length()
|
|
124
|
+
t
|
|
125
|
+
else
|
|
126
|
+
e := evs.at(i)
|
|
127
|
+
next := e.position().unwrapOr(at)
|
|
128
|
+
still := match e
|
|
129
|
+
PointerMove(x, y) => x == at.x && y == at.y
|
|
130
|
+
_ => false
|
|
131
|
+
routeAll(if still then t else t.input(ctx, e), ctx, evs, i + 1, next)
|
|
132
|
+
|
|
133
|
+
# Where the pointer is after the events of `evs`, from `at`.
|
|
134
|
+
fun lastPointer(evs: Slice[InputEvent], at: Vec2) -> Vec2 =
|
|
135
|
+
0.until(evs.length()).fold(at, |p, j| evs.at(j).position().unwrapOr(p))
|
|
136
|
+
|
|
137
|
+
# A tick's game commands taken so far: the screen and store after the messages, the
|
|
138
|
+
# first screen asked for, and whether a `Restart` or an `Exit` came.
|
|
139
|
+
struct Turn[S: Reducer[M], M](screen: Screen[S, M], store: Store[S, M], next: Option[Screen[S, M]], restart: Bool, exit: Bool) =
|
|
140
|
+
fun take(self, c: Cmd[M]) -> Turn[S, M] = match c
|
|
141
|
+
Send(m) =>
|
|
142
|
+
store := self.store.dispatch(m)
|
|
143
|
+
screen := self.screen.react(store.state, m)
|
|
144
|
+
next := if self.next.isSome() then self.next else screen.next(store.state, m)
|
|
145
|
+
Turn(..self, screen: screen, store: store, next: next)
|
|
146
|
+
Restart => Turn(..self, restart: true)
|
|
147
|
+
Exit => Turn(..self, exit: true)
|
|
148
|
+
_ => self
|
|
149
|
+
|
|
150
|
+
# --- tests ---
|
|
151
|
+
|
|
152
|
+
# A state that notes what happened to it in a shared log, and counts.
|
|
153
|
+
enum GMsg = GHit(id: Int) | GStep(id: Int) | GRule | GGo | GBack | GAgain | GQuit
|
|
154
|
+
|
|
155
|
+
struct GState(n: Int, log: Slice[Str]) is Reducer[GMsg] =
|
|
156
|
+
fun update(self, msg: GMsg) -> GState =
|
|
157
|
+
self.log.push("update {gname(msg)}")
|
|
158
|
+
GState(..self, n: self.n + 1)
|
|
159
|
+
|
|
160
|
+
fun handle(self, io: Io, msg: GMsg) = self.log.push("handle {gname(msg)} n {self.n}")
|
|
161
|
+
|
|
162
|
+
fun gname(m: GMsg) -> Str = match m
|
|
163
|
+
GHit(id) => "hit {id}"
|
|
164
|
+
GStep(id) => "step {id}"
|
|
165
|
+
GRule => "rule"
|
|
166
|
+
GGo => "go"
|
|
167
|
+
GBack => "back"
|
|
168
|
+
GAgain => "again"
|
|
169
|
+
GQuit => "quit"
|
|
170
|
+
|
|
171
|
+
# A 10 by 10 box at (x, 0) that notes its pointer events and its steps, and sends one of
|
|
172
|
+
# each to the store; on its step it sends `GGo` once `go` is set.
|
|
173
|
+
struct GProbe(id: Int, x: Float, log: Slice[Str], go: Bool) is Actor[GMsg] =
|
|
174
|
+
fun key(self) -> Int = self.id
|
|
175
|
+
|
|
176
|
+
fun place(self) -> Place = place.at(self.x, 0.0)
|
|
177
|
+
|
|
178
|
+
fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
|
|
179
|
+
|
|
180
|
+
fun input(self, ctx: Ctx[GMsg], e: InputEvent) -> GProbe =
|
|
181
|
+
p := e.position().unwrap()
|
|
182
|
+
self.log.push("input {self.id} at {p.x}")
|
|
183
|
+
ctx.send(GHit(id: self.id))
|
|
184
|
+
self
|
|
185
|
+
|
|
186
|
+
fun step(self, ctx: Ctx[GMsg], dt: Float) -> GProbe =
|
|
187
|
+
self.log.push("step {self.id}")
|
|
188
|
+
ctx.send(GStep(id: self.id))
|
|
189
|
+
if self.go
|
|
190
|
+
ctx.send(GGo)
|
|
191
|
+
self
|
|
192
|
+
|
|
193
|
+
# The first screen: a group (id 0) at (5, 0) holding probe 1, then probe 2 on top of it.
|
|
194
|
+
# Its rules note themselves and send `GRule`; it goes to `GPlay` on `GGo`.
|
|
195
|
+
struct GTitle(t: SceneTree[GMsg], log: Slice[Str], reacted: Int) is Screen[GState, GMsg] =
|
|
196
|
+
fun tree(self) -> SceneTree[GMsg] = self.t
|
|
197
|
+
|
|
198
|
+
fun withTree(self, t: SceneTree[GMsg]) -> GTitle = GTitle(..self, t: t)
|
|
199
|
+
|
|
200
|
+
fun rules(self, ctx: Ctx[GMsg], state: GState, dt: Float) -> GTitle =
|
|
201
|
+
self.log.push("rules")
|
|
202
|
+
ctx.send(GRule)
|
|
203
|
+
self
|
|
204
|
+
|
|
205
|
+
fun react(self, state: GState, msg: GMsg) -> GTitle =
|
|
206
|
+
self.log.push("react {gname(msg)} n {state.n}")
|
|
207
|
+
GTitle(..self, reacted: self.reacted + 1)
|
|
208
|
+
|
|
209
|
+
fun next(self, state: GState, msg: GMsg) -> Option[Screen[GState, GMsg]] = match msg
|
|
210
|
+
GGo =>
|
|
211
|
+
self.log.push("next")
|
|
212
|
+
s: Screen[GState, GMsg] := GPlay(t: gtree(self.log, 9, false), log: self.log)
|
|
213
|
+
Some(s)
|
|
214
|
+
_ => None
|
|
215
|
+
|
|
216
|
+
# The second screen, with the defaults but for `next`: back to a title on `GBack`.
|
|
217
|
+
struct GPlay(t: SceneTree[GMsg], log: Slice[Str]) is Screen[GState, GMsg] =
|
|
218
|
+
fun tree(self) -> SceneTree[GMsg] = self.t
|
|
219
|
+
|
|
220
|
+
fun withTree(self, t: SceneTree[GMsg]) -> GPlay = GPlay(..self, t: t)
|
|
221
|
+
|
|
222
|
+
fun next(self, state: GState, msg: GMsg) -> Option[Screen[GState, GMsg]] = match msg
|
|
223
|
+
GBack =>
|
|
224
|
+
s: Screen[GState, GMsg] := GTitle(t: gtree(self.log, 1, false), log: self.log, reacted: 0)
|
|
225
|
+
Some(s)
|
|
226
|
+
_ => None
|
|
227
|
+
|
|
228
|
+
# An actor that sends `msg` from its step once, on the tick its `at` comes.
|
|
229
|
+
struct GSender(id: Int, at: Int, ticks: Int, cmd: Int) is Actor[GMsg] =
|
|
230
|
+
fun key(self) -> Int = self.id
|
|
231
|
+
|
|
232
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
233
|
+
|
|
234
|
+
fun step(self, ctx: Ctx[GMsg], dt: Float) -> GSender =
|
|
235
|
+
if self.ticks == self.at
|
|
236
|
+
if self.cmd == 0
|
|
237
|
+
ctx.out.push(Restart)
|
|
238
|
+
else if self.cmd == 1
|
|
239
|
+
ctx.out.push(Exit)
|
|
240
|
+
else
|
|
241
|
+
ctx.send(GBack)
|
|
242
|
+
GSender(..self, ticks: self.ticks + 1)
|
|
243
|
+
|
|
244
|
+
fun gtree(log: Slice[Str], first: Int, go: Bool) -> SceneTree[GMsg] =
|
|
245
|
+
root: FRoseTree[Actor[GMsg]] := FRoseTree.of(Group(id: 0, x: 5.0, y: 0.0), [
|
|
246
|
+
FRoseTree.leaf(GProbe(id: first, x: 0.0, log: log, go: go)),
|
|
247
|
+
FRoseTree.leaf(GProbe(id: first + 1, x: 0.0, log: log, go: false))])
|
|
248
|
+
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
249
|
+
|
|
250
|
+
fun gtitle(log: Slice[Str], go: Bool) -> GTitle = GTitle(t: gtree(log, 1, go), log: log, reacted: 0)
|
|
251
|
+
|
|
252
|
+
GameTestView = Vec2(x: 800.0, y: 600.0)
|
|
253
|
+
|
|
254
|
+
fun ginput(events: List[InputEvent]) -> Input =
|
|
255
|
+
Input(held: Held.none(), events: events.toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
256
|
+
|
|
257
|
+
fun gstart(log: Slice[Str], go: Bool) -> Game[GState, GMsg] = Game.start(gtitle(log, go), GState(n: 0, log: log))
|
|
258
|
+
|
|
259
|
+
fun gonScreen(g: Game[GState, GMsg]) -> Str = match g.screen
|
|
260
|
+
GTitle as t => "title {t.reacted}"
|
|
261
|
+
GPlay as p => "play"
|
|
262
|
+
_ => "?"
|
|
263
|
+
|
|
264
|
+
fun gcount(log: Slice[Str], prefix: Str) -> Int = 0.until(log.length()).fold(0, |n, i| if log.at(i).startsWith(prefix) then n + 1 else n)
|
|
265
|
+
|
|
266
|
+
test "one tick: input up the parents, steps, rules, then each message reduced and reacted to, then handled"
|
|
267
|
+
log := Slice[Str]()
|
|
268
|
+
g := gstart(log, false)
|
|
269
|
+
# (7, 5) is on probe 2 (on top of probe 1); a key event goes to no actor
|
|
270
|
+
g1 := g.step(io, ginput([KeyDown(key: Key.Space), PointerDown(x: 7.0, y: 5.0)]), 0.5, GameTestView)
|
|
271
|
+
want := [
|
|
272
|
+
"input 2 at 2.0",
|
|
273
|
+
"step 1", "step 2", "rules",
|
|
274
|
+
"update hit 2", "react hit 2 n 1",
|
|
275
|
+
"update step 1", "react step 1 n 2",
|
|
276
|
+
"update step 2", "react step 2 n 3",
|
|
277
|
+
"update rule", "react rule n 4",
|
|
278
|
+
"handle hit 2 n 4", "handle step 1 n 4", "handle step 2 n 4", "handle rule n 4"]
|
|
279
|
+
assert log.length() == want.length()
|
|
280
|
+
for i := range want.length()
|
|
281
|
+
assert log.at(i) == want.get(i).unwrap()
|
|
282
|
+
assert g1.state().n == 4
|
|
283
|
+
assert g1.ticks == 1
|
|
284
|
+
assert gonScreen(g1) == "title 4"
|
|
285
|
+
assert g.state().n == 0
|
|
286
|
+
|
|
287
|
+
test "a pointer event goes to the hit actor's parents too, and misses go nowhere"
|
|
288
|
+
log := Slice[Str]()
|
|
289
|
+
t := gtree(log, 1, false)
|
|
290
|
+
ctx: Ctx[GMsg] := Ctx.of(ginput(Nil), GameTestView)
|
|
291
|
+
t1 := t.input(ctx, PointerUp(x: 100.0, y: 5.0))
|
|
292
|
+
assert log.length() == 0
|
|
293
|
+
assert t1 == t
|
|
294
|
+
# the group is never hit itself, but gets the event on its way up (it ignores it)
|
|
295
|
+
_ := t.input(ctx, PointerUp(x: 6.0, y: 5.0))
|
|
296
|
+
assert log.length() == 1 && log.at(0) == "input 2 at 1.0"
|
|
297
|
+
assert ctx.takeSends().length() == 1
|
|
298
|
+
|
|
299
|
+
test "a move that leaves the pointer where it was goes to no actor"
|
|
300
|
+
log := Slice[Str]()
|
|
301
|
+
g := gstart(log, false)
|
|
302
|
+
g1 := g.step(io, ginput([PointerMove(x: 7.0, y: 5.0)]), 0.1, GameTestView)
|
|
303
|
+
assert gcount(log, "input") == 1
|
|
304
|
+
g2 := g1.step(io, ginput([PointerMove(x: 7.0, y: 5.0)]), 0.1, GameTestView)
|
|
305
|
+
assert gcount(log, "input") == 1
|
|
306
|
+
_ := g2.step(io, ginput([PointerDown(x: 7.0, y: 5.0), PointerMove(x: 7.0, y: 5.0), PointerMove(x: 8.0, y: 5.0)]), 0.1, GameTestView)
|
|
307
|
+
assert gcount(log, "input") == 3
|
|
308
|
+
assert g2.pointer.x == 7.0
|
|
309
|
+
|
|
310
|
+
test "next switches the screen after the tick, and the old screen takes the rest of the tick"
|
|
311
|
+
log := Slice[Str]()
|
|
312
|
+
g := gstart(log, true)
|
|
313
|
+
g1 := g.step(io, ginput(Nil), 0.1, GameTestView)
|
|
314
|
+
assert gonScreen(g1) == "play"
|
|
315
|
+
# GGo came after probe 1's step message: the title reacted to all four
|
|
316
|
+
assert gcount(log, "react") == 4
|
|
317
|
+
assert gcount(log, "next") == 1
|
|
318
|
+
assert gcount(log, "handle") == 4
|
|
319
|
+
# the play screen's probes are 9 and 10, and its default rules and react do nothing
|
|
320
|
+
g2 := g1.step(io, ginput(Nil), 0.1, GameTestView)
|
|
321
|
+
assert gcount(log, "step 9") == 1 && gcount(log, "step 10") == 1
|
|
322
|
+
assert gcount(log, "react") == 4
|
|
323
|
+
assert g2.state().n == 4 + 2
|
|
324
|
+
assert gonScreen(g2) == "play"
|
|
325
|
+
|
|
326
|
+
test "a screen with only the defaults goes back on its own message"
|
|
327
|
+
log := Slice[Str]()
|
|
328
|
+
t := gtree(log, 1, false).add(0, FRoseTree.leaf(GSender(id: 50, at: 1, ticks: 0, cmd: 2)))
|
|
329
|
+
s: Screen[GState, GMsg] := GPlay(t: t, log: log)
|
|
330
|
+
g: Game[GState, GMsg] := Game.start(s, GState(n: 0, log: log))
|
|
331
|
+
g1 := g.step(io, ginput(Nil), 0.1, GameTestView)
|
|
332
|
+
assert gonScreen(g1) == "play"
|
|
333
|
+
g2 := g1.step(io, ginput(Nil), 0.1, GameTestView)
|
|
334
|
+
assert gonScreen(g2) == "title 0"
|
|
335
|
+
|
|
336
|
+
test "restart brings back the first screen and state after the tick's effects"
|
|
337
|
+
log := Slice[Str]()
|
|
338
|
+
t := gtree(log, 1, false).add(0, FRoseTree.leaf(GSender(id: 50, at: 2, ticks: 0, cmd: 0)))
|
|
339
|
+
first := GTitle(t: t, log: log, reacted: 0)
|
|
340
|
+
g: Game[GState, GMsg] := Game.start(first, GState(n: 0, log: log))
|
|
341
|
+
g2 := g.step(io, ginput(Nil), 0.1, GameTestView).step(io, ginput(Nil), 0.1, GameTestView)
|
|
342
|
+
assert g2.state().n == 6
|
|
343
|
+
assert gonScreen(g2) == "title 6"
|
|
344
|
+
g3 := g2.step(io, ginput(Nil), 0.1, GameTestView)
|
|
345
|
+
# the restart tick's messages were reduced and handled, then the game started over
|
|
346
|
+
assert gcount(log, "handle") == 9
|
|
347
|
+
assert g3.state().n == 0
|
|
348
|
+
assert gonScreen(g3) == "title 0"
|
|
349
|
+
assert g3.ticks == 3
|
|
350
|
+
# the first screen's sender counts from 0 again
|
|
351
|
+
g5 := g3.step(io, ginput(Nil), 0.1, GameTestView).step(io, ginput(Nil), 0.1, GameTestView).step(io, ginput(Nil), 0.1, GameTestView)
|
|
352
|
+
assert g5.state().n == 0
|
|
353
|
+
|
|
354
|
+
test "exit stops the ticks after the tick's effects"
|
|
355
|
+
log := Slice[Str]()
|
|
356
|
+
t := gtree(log, 1, false).add(0, FRoseTree.leaf(GSender(id: 50, at: 1, ticks: 0, cmd: 1)))
|
|
357
|
+
g: Game[GState, GMsg] := Game.start(GTitle(t: t, log: log, reacted: 0), GState(n: 0, log: log))
|
|
358
|
+
g2 := g.step(io, ginput(Nil), 0.1, GameTestView).step(io, ginput(Nil), 0.1, GameTestView)
|
|
359
|
+
assert g2.exited
|
|
360
|
+
assert g2.state().n == 6
|
|
361
|
+
assert gcount(log, "handle") == 6
|
|
362
|
+
steps := gcount(log, "step")
|
|
363
|
+
assert g2.pointer.x == NoPointer.x
|
|
364
|
+
g3 := g2.step(io, ginput([PointerDown(x: 7.0, y: 5.0)]), 0.1, GameTestView)
|
|
365
|
+
assert gcount(log, "step") == steps
|
|
366
|
+
assert gcount(log, "input") == 0
|
|
367
|
+
assert g3.ticks == 2
|
std/game/Store.plum
CHANGED
|
@@ -48,7 +48,7 @@ struct Store[S: Reducer[M], M](state: S, queue: List[M]) =
|
|
|
48
48
|
|
|
49
49
|
# The state after each of `msgs` in order, with no effects: what a recorded run of
|
|
50
50
|
# messages leads to.
|
|
51
|
-
fun
|
|
51
|
+
fun reduceAll[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
|
|
52
52
|
|
|
53
53
|
enum StoreTestMsg = Add(n: Int) | Reset | Note(n: Int)
|
|
54
54
|
|
|
@@ -100,8 +100,8 @@ test "a reducer without handle has no effects"
|
|
|
100
100
|
assert s.flush(io).state.n == 6
|
|
101
101
|
assert s.flush(io).pending().isEmpty()
|
|
102
102
|
|
|
103
|
-
test "
|
|
103
|
+
test "reduceAll reduces messages with no store"
|
|
104
|
-
assert
|
|
104
|
+
assert reduceAll(StoreQuiet(n: 0), [1, 2, 3]).n == 6
|
|
105
|
-
t :=
|
|
105
|
+
t := reduceAll(StoreTally(total: 0, count: 0, log: Slice()), [Add(n: 4), Reset, Add(n: 1)])
|
|
106
106
|
assert t.total == 1 && t.count == 3
|
|
107
107
|
assert t.log.length() == 0
|
std/game/audio.plum
CHANGED
|
@@ -22,19 +22,26 @@ extern fun soundStop(io: Io, s: Int)
|
|
|
22
22
|
# Changes the volume of a sound that is playing or looping.
|
|
23
23
|
extern fun soundSetVolume(io: Io, s: Int, volume: Float)
|
|
24
24
|
|
|
25
|
-
# A sound handle; the id is the host's.
|
|
25
|
+
# A sound handle; the id is the host's. `Sound.Silent` (id -1) is no sound: it plays
|
|
26
|
+
# nothing and never calls the host, so a test can run a game's effects.
|
|
26
27
|
struct Sound(id: Int) =
|
|
28
|
+
Silent = Sound(id: -1)
|
|
29
|
+
|
|
27
30
|
fun play(self, io: Io, volume: Float = 1.0) =
|
|
31
|
+
if self.id >= 0
|
|
28
|
-
|
|
32
|
+
soundPlay(io, self.id, volume)
|
|
29
33
|
|
|
30
34
|
fun loop(self, io: Io, volume: Float = 1.0) =
|
|
35
|
+
if self.id >= 0
|
|
31
|
-
|
|
36
|
+
soundLoop(io, self.id, volume)
|
|
32
37
|
|
|
33
38
|
fun stop(self, io: Io) =
|
|
39
|
+
if self.id >= 0
|
|
34
|
-
|
|
40
|
+
soundStop(io, self.id)
|
|
35
41
|
|
|
36
42
|
fun setVolume(self, io: Io, volume: Float) =
|
|
43
|
+
if self.id >= 0
|
|
37
|
-
|
|
44
|
+
soundSetVolume(io, self.id, volume)
|
|
38
45
|
|
|
39
46
|
# Loads a sound relative to the asset root; crashes naming the file if it is missing.
|
|
40
47
|
fun loadSound(io: Io, name: Str) -> Sound =
|
std/game/input.plum
CHANGED
|
@@ -355,17 +355,6 @@ struct Clock(pending: Input, acc: Float, n: Int, ticks: Int, mode: Int, played:
|
|
|
355
355
|
else
|
|
356
356
|
out
|
|
357
357
|
|
|
358
|
-
# What happened to a UI element: pressed on it, released after a press on it,
|
|
359
|
-
# clicked (pressed and released on it), or the pointer entered or left it.
|
|
360
|
-
enum UiKind =
|
|
361
|
-
| Press
|
|
362
|
-
| Release
|
|
363
|
-
| Click
|
|
364
|
-
| Enter
|
|
365
|
-
| Exit
|
|
366
|
-
|
|
367
|
-
struct UiEvent(id: Int, kind: UiKind)
|
|
368
|
-
|
|
369
358
|
fun inHeld(keys: Slice[Int]) -> Held =
|
|
370
359
|
Held(mouse: false, keys: keys)
|
|
371
360
|
|
std/game/scene/Actor.plum
CHANGED
|
@@ -10,6 +10,7 @@ import std/game/Vec2
|
|
|
10
10
|
import std/game/Affine
|
|
11
11
|
import std/game/Color
|
|
12
12
|
import std/game/gfx
|
|
13
|
+
import std/game/input
|
|
13
14
|
import std/game/scene/Place
|
|
14
15
|
import std/game/scene/Ctx
|
|
15
16
|
|
|
@@ -20,6 +21,9 @@ import std/game/scene/Ctx
|
|
|
20
21
|
# default:
|
|
21
22
|
#
|
|
22
23
|
# step the next version of it, once a tick (`ctx` is its parent's context)
|
|
24
|
+
# input the next version of it after a pointer event on it or on one of its
|
|
25
|
+
# children (`e` in its own coordinates, `ctx` its parent's context); it
|
|
26
|
+
# runs before the tick's steps
|
|
23
27
|
# paint draws it, seen through `m` (its own coordinates to the tree's) at `alpha`
|
|
24
28
|
# (the accumulated alpha, its own `opacity` included)
|
|
25
29
|
# hit whether `p`, in its own coordinates, is on it
|
|
@@ -46,6 +50,8 @@ trait Actor[M] =
|
|
|
46
50
|
|
|
47
51
|
fun step(self, ctx: Ctx[M], dt: Float) -> Self = self
|
|
48
52
|
|
|
53
|
+
fun input(self, ctx: Ctx[M], e: InputEvent) -> Self = self
|
|
54
|
+
|
|
49
55
|
fun paint(self, io: Io, m: Affine, alpha: Float) = Unit
|
|
50
56
|
|
|
51
57
|
fun hit(self, p: Vec2) -> Bool = false
|
std/game/scene/Ctx.plum
CHANGED
|
@@ -5,19 +5,30 @@ import std/Float
|
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/List
|
|
7
7
|
import std/Slice
|
|
8
|
+
import std/game/Vec2
|
|
8
9
|
import std/game/Affine
|
|
10
|
+
import std/game/input
|
|
9
11
|
import std/collections/functional/FRoseTree
|
|
10
12
|
import std/game/scene/Actor
|
|
11
13
|
|
|
12
|
-
# What a step changes besides the actors. `Spawn` and `Kill` are
|
|
14
|
+
# What a step changes besides the actors. `Spawn` and `Kill` are the tree's: they are
|
|
13
|
-
# walk is over (`SceneTree.apply`): a new node under the actor
|
|
15
|
+
# applied once the step's walk is over (`SceneTree.apply`): a new node under the actor
|
|
14
|
-
# of its children, or the end of the actor `id` and its subtree.
|
|
16
|
+
# `parent` (by id), on top of its children, or the end of the actor `id` and its subtree.
|
|
15
|
-
# the game's
|
|
17
|
+
# The rest are the game's (std/game/Game), and the tree leaves them in `ctx.out`, in
|
|
18
|
+
# order: `Send` is a message of the game's type `M` for its store, `Restart` starts the
|
|
16
|
-
# game
|
|
19
|
+
# game over from its first screen and state, and `Exit` ends it (no tick runs after).
|
|
17
20
|
enum Cmd[M] =
|
|
18
21
|
| Spawn(parent: Int, node: FRoseTree[Actor[M]])
|
|
19
22
|
| Kill(id: Int)
|
|
20
23
|
| Send(msg: M)
|
|
24
|
+
| Restart
|
|
25
|
+
| Exit
|
|
26
|
+
|
|
27
|
+
# Whether it is the game's (`Send`, `Restart`, `Exit`) rather than the tree's.
|
|
28
|
+
fun isGame(self) -> Bool = match self
|
|
29
|
+
Spawn(_, _) => false
|
|
30
|
+
Kill(_) => false
|
|
31
|
+
_ => true
|
|
21
32
|
|
|
22
33
|
fun isSend(self) -> Bool = match self
|
|
23
34
|
Send(_) => true
|
|
@@ -26,9 +37,10 @@ enum Cmd[M] =
|
|
|
26
37
|
# What the step hands each actor in place of a parent link: the context of the actor's
|
|
27
38
|
# parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so an
|
|
28
39
|
# actor's own world transform is `ctx.worldOf(self.place().local())` and its alpha
|
|
29
|
-
# `ctx.alphaOf(self.opacity())`, computed only when it asks. `
|
|
40
|
+
# `ctx.alphaOf(self.opacity())`, computed only when it asks. `input` is the tick's input
|
|
41
|
+
# (held keys, the pointer, the events) and `view` the size of the screen in pixels. `out` takes the commands an actor pushes for after
|
|
30
|
-
#
|
|
42
|
+
# the walk (`ctx.out.push(Spawn(..))`, `ctx.out.push(Kill(..))`, `ctx.send(msg)`,
|
|
31
|
-
# `ctx.
|
|
43
|
+
# `ctx.out.push(Restart)`).
|
|
32
44
|
#
|
|
33
45
|
# fun step(self, ctx: Ctx[Msg], dt: Float) -> Gun =
|
|
34
46
|
# ctx.out.push(Spawn(parent: 0, node: FRoseTree.leaf(Bullet(id: self.next, x: self.x, y: self.y))))
|
|
@@ -36,11 +48,15 @@ enum Cmd[M] =
|
|
|
36
48
|
#
|
|
37
49
|
# A context is a value. The walk makes one for each parent with children (`under`), with
|
|
38
50
|
# one multiply, and hands it to every child.
|
|
39
|
-
struct Ctx[M](up: Affine, alpha: Float, out: Slice[Cmd[M]]) =
|
|
51
|
+
struct Ctx[M](up: Affine, alpha: Float, input: Input, view: Vec2, out: Slice[Cmd[M]]) =
|
|
52
|
+
|
|
53
|
+
# The context above a tree's root: the identity transform, full opacity, no input, no
|
|
54
|
+
# screen and no commands.
|
|
55
|
+
fun init() -> Ctx[M] = Ctx.of(Input.create(), Vec2(x: 0.0, y: 0.0))
|
|
40
56
|
|
|
41
|
-
# The context above a tree's root
|
|
57
|
+
# The context above a tree's root for a tick with `input` on a screen of `view` pixels.
|
|
42
|
-
fun
|
|
58
|
+
fun of(input: Input, view: Vec2) -> Ctx[M] =
|
|
43
|
-
Ctx(up: Affine.Identity, alpha: 1.0, out: Slice[Cmd[M]]())
|
|
59
|
+
Ctx(up: Affine.Identity, alpha: 1.0, input: input, view: view, out: Slice[Cmd[M]]())
|
|
44
60
|
|
|
45
61
|
# The world transform of a child whose own transform is `local`.
|
|
46
62
|
fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
|
|
@@ -51,7 +67,7 @@ struct Ctx[M](up: Affine, alpha: Float, out: Slice[Cmd[M]]) =
|
|
|
51
67
|
# The context for the children of a child with the transform `local` and opacity `a`:
|
|
52
68
|
# the same commands, the child's world transform above them.
|
|
53
69
|
fun under(self, local: Affine, a: Float) -> Ctx[M] =
|
|
54
|
-
Ctx(up: self.up.mul(local), alpha: self.alpha * a
|
|
70
|
+
Ctx(..self, up: self.up.mul(local), alpha: self.alpha * a)
|
|
55
71
|
|
|
56
72
|
# Sends `msg` to the game after the step.
|
|
57
73
|
fun send(self, msg: M) = self.out.push(Send(msg: msg))
|
|
@@ -66,18 +82,30 @@ struct Ctx[M](up: Affine, alpha: Float, out: Slice[Cmd[M]]) =
|
|
|
66
82
|
for c := range self.out
|
|
67
83
|
if Send(m) := c
|
|
68
84
|
msgs.push(m)
|
|
85
|
+
kept := Slice[Cmd[M]]()
|
|
86
|
+
for c := range self.out
|
|
87
|
+
if !c.isSend()
|
|
88
|
+
kept.push(c)
|
|
69
|
-
self.
|
|
89
|
+
self.out.clear()
|
|
90
|
+
self.out.add(kept)
|
|
70
91
|
List.fromSlice(msgs)
|
|
71
92
|
|
|
72
|
-
# Keeps in `out` only
|
|
93
|
+
# Keeps in `out` only the game's commands (`game` true) or only the tree's, in order.
|
|
73
|
-
fun keepOnly(self,
|
|
94
|
+
fun keepOnly(self, game: Bool) =
|
|
74
95
|
kept := Slice[Cmd[M]]()
|
|
75
96
|
for c := range self.out
|
|
76
|
-
if c.
|
|
97
|
+
if c.isGame() == game
|
|
77
98
|
kept.push(c)
|
|
78
99
|
self.out.clear()
|
|
79
100
|
self.out.add(kept)
|
|
80
101
|
|
|
102
|
+
fun cmdName[M](c: Cmd[M]) -> Str = match c
|
|
103
|
+
Spawn(_, _) => "Spawn"
|
|
104
|
+
Kill(_) => "Kill"
|
|
105
|
+
Send(_) => "Send"
|
|
106
|
+
Restart => "Restart"
|
|
107
|
+
Exit => "Exit"
|
|
108
|
+
|
|
81
109
|
test "under multiplies the child's transform into the parent's"
|
|
82
110
|
c := Ctx[Int]()
|
|
83
111
|
m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
|
|
@@ -99,3 +127,23 @@ test "sends are taken out in order and the other commands stay"
|
|
|
99
127
|
assert c.out.length() == 2
|
|
100
128
|
assert c.takeSends().isEmpty()
|
|
101
129
|
assert c.out.length() == 2
|
|
130
|
+
|
|
131
|
+
test "restart and exit are the game's, and stay with the sends"
|
|
132
|
+
c := Ctx[Str]()
|
|
133
|
+
c.out.push(Kill(id: 1))
|
|
134
|
+
c.out.push(Restart)
|
|
135
|
+
c.send("a")
|
|
136
|
+
c.out.push(Exit)
|
|
137
|
+
c.keepOnly(true)
|
|
138
|
+
assert c.out.length() == 3
|
|
139
|
+
assert c.takeSends().length() == 1
|
|
140
|
+
assert c.out.length() == 2
|
|
141
|
+
assert cmdName(c.out.at(0)) == "Restart" && cmdName(c.out.at(1)) == "Exit"
|
|
142
|
+
|
|
143
|
+
test "a context carries the tick's input down the tree"
|
|
144
|
+
i := Input(held: Held(mouse: true, keys: Slice[Int]()), events: Slice[InputEvent](), pos: Vec2(x: 3.0, y: 4.0), wheel: 0.0)
|
|
145
|
+
c: Ctx[Int] := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
|
|
146
|
+
assert c.under(Affine.Identity, 1.0).input.pos.x == 3.0
|
|
147
|
+
assert c.under(Affine.Identity, 1.0).view.y == 600.0
|
|
148
|
+
assert c.input.isMouseDown()
|
|
149
|
+
assert !Ctx[Int]().input.isMouseDown()
|
std/game/scene/SceneTree.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/Vec2
|
|
|
16
16
|
import std/game/Affine
|
|
17
17
|
import std/game/Color
|
|
18
18
|
import std/game/gfx
|
|
19
|
+
import std/game/input
|
|
19
20
|
import std/collections/functional/FRoseTree
|
|
20
21
|
import std/game/scene/Actor
|
|
21
22
|
import std/game/scene/Place
|
|
@@ -107,8 +108,8 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
|
|
|
107
108
|
# dropped without its step, and a spawned node goes on top of its parent's children
|
|
108
109
|
# unstepped. Those pushed during the step (by the actors) are applied by `apply` once
|
|
109
110
|
# the walk is over, as a second batch. Hidden actors are stepped too. `ctx.out` is left
|
|
110
|
-
# with only the `Send`
|
|
111
|
+
# with only the game's commands (`Send`, `Restart`, `Exit`), those pushed before the
|
|
111
|
-
# take (`ctx.takeSends()`).
|
|
112
|
+
# step first, in order, for the game to take (`ctx.takeSends()`).
|
|
112
113
|
fun step(self, ctx: Ctx[M], dt: Float) -> SceneTree[M] =
|
|
113
114
|
w := TreeWalk.of(ctx.out)
|
|
114
115
|
ctx.keepOnly(true)
|
|
@@ -121,7 +122,7 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
|
|
|
121
122
|
# The tree with the commands applied, in one pass over the tree: every `Kill` actor
|
|
122
123
|
# goes with its subtree, and every `Spawn` node goes on top of its parent's children,
|
|
123
124
|
# in the order pushed. A spawn whose parent is not on the tree, or is killed by the
|
|
124
|
-
# same batch, is dropped. `Send`
|
|
125
|
+
# same batch, is dropped. The game's commands (`Send`, `Restart`, `Exit`) are skipped.
|
|
125
126
|
fun apply(self, cmds: Slice[Cmd[M]]) -> SceneTree[M] =
|
|
126
127
|
if cmds.length() == 0
|
|
127
128
|
self
|
|
@@ -133,6 +134,19 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
|
|
|
133
134
|
empty: FRoseTree[Actor[M]] := FRoseEmpty
|
|
134
135
|
SceneTree(..self, root: applyChain(self.root, w, empty))
|
|
135
136
|
|
|
137
|
+
# The tree after the pointer event `e` (in tree coordinates; a key event changes
|
|
138
|
+
# nothing): the topmost shown actor under it that says it is hit (as `hit` finds it)
|
|
139
|
+
# gets it through `input`, then each of its parents up to the root. Each gets `e` in its
|
|
140
|
+
# own coordinates (as `hit` gets its point) and its parent's context under `ctx` (as
|
|
141
|
+
# `step` gives it). With no actor under the pointer the tree is returned as it was.
|
|
142
|
+
fun input(self, ctx: Ctx[M], e: InputEvent) -> SceneTree[M] = match e.position()
|
|
143
|
+
None => self
|
|
144
|
+
Some(p) =>
|
|
145
|
+
if hitChain(self.root, p).isNone()
|
|
146
|
+
self
|
|
147
|
+
else
|
|
148
|
+
SceneTree(..self, root: inputChain(self.root, ctx, p, e).t)
|
|
149
|
+
|
|
136
150
|
# What `draw` would draw, in order: each shown actor with its tree transform and alpha,
|
|
137
151
|
# a parent before its children, siblings first to last.
|
|
138
152
|
fun flatten(self) -> Slice[Drawn[M]] =
|
|
@@ -147,11 +161,16 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
|
|
|
147
161
|
# The id of that actor, if any.
|
|
148
162
|
fun hitId(self, x: Float, y: Float) -> Option[Int] = self.hit(x, y).map(|a| a.key())
|
|
149
163
|
|
|
164
|
+
# Draws the tree through its camera.
|
|
150
165
|
fun draw(self, io: Io) =
|
|
151
166
|
gfx.setCamera(io, self.camX, self.camY, self.camScale)
|
|
152
|
-
|
|
167
|
+
self.paint(io)
|
|
153
168
|
gfx.resetCamera(io)
|
|
154
169
|
|
|
170
|
+
# Draws the tree as `draw` does, without setting the camera: for a screen that sets its
|
|
171
|
+
# own, or draws in screen pixels.
|
|
172
|
+
fun paint(self, io: Io) = drawChain(self.root, io, Affine.Identity, 1.0)
|
|
173
|
+
|
|
155
174
|
# One entry of the draw list: a shown actor, its tree transform and its alpha.
|
|
156
175
|
struct Drawn[M](actor: Actor[M], m: Affine, alpha: Float)
|
|
157
176
|
|
|
@@ -185,7 +204,6 @@ struct TreeWalk[M](
|
|
|
185
204
|
Kill(id) =>
|
|
186
205
|
kills.add(id)
|
|
187
206
|
scan.see(id)
|
|
188
|
-
Send(_) => Unit
|
|
189
207
|
Spawn(parent, node) =>
|
|
190
208
|
scan.see(parent)
|
|
191
209
|
if Some(xs) := spawns.get(parent)
|
|
@@ -194,6 +212,7 @@ struct TreeWalk[M](
|
|
|
194
212
|
ys := Slice[FRoseTree[Actor[M]]]()
|
|
195
213
|
ys.push(node)
|
|
196
214
|
spawns.set(parent, ys)
|
|
215
|
+
_ => Unit
|
|
197
216
|
words := if scan.ok && {kills.length() > 0 || spawns.length() > 0} then scan.top / 64 + 1 else 0
|
|
198
217
|
killBits := Array[Int]().resize(words)
|
|
199
218
|
spawnBits := Array[Int]().resize(words)
|
|
@@ -202,7 +221,7 @@ struct TreeWalk[M](
|
|
|
202
221
|
match c
|
|
203
222
|
Kill(id) => bitSet(killBits, id)
|
|
204
223
|
Spawn(parent, _) => bitSet(spawnBits, parent)
|
|
205
|
-
|
|
224
|
+
_ => Unit
|
|
206
225
|
TreeWalk(
|
|
207
226
|
kills: kills, spawns: spawns,
|
|
208
227
|
hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
|
|
@@ -298,6 +317,27 @@ fun drawChain[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
|
|
|
298
317
|
drawChain(k, io, m, al)
|
|
299
318
|
drawChain(n, io, parent, alpha)
|
|
300
319
|
|
|
320
|
+
# The chain `t` after the pointer event `e` at `p` (in the chain's parent's coordinates),
|
|
321
|
+
# found as `hitChain` finds it: the hit actor's `input`, then its parents' on the way
|
|
322
|
+
# back up. `hit` says whether this chain held the actor.
|
|
323
|
+
struct TreeRouted[M](t: FRoseTree[Actor[M]], hit: Bool)
|
|
324
|
+
|
|
325
|
+
fun inputChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent) -> TreeRouted[M] = match t
|
|
326
|
+
FRoseEmpty => TreeRouted(t: t, hit: false)
|
|
327
|
+
FRoseNode(a, k, n) =>
|
|
328
|
+
rn := inputChain(n, ctx, p, e)
|
|
329
|
+
if rn.hit || !isShown(a)
|
|
330
|
+
TreeRouted(t: FRoseNode(value: a, firstChild: k, nextSibling: rn.t), hit: rn.hit)
|
|
331
|
+
else
|
|
332
|
+
local := a.place().local()
|
|
333
|
+
q := local.inverse().apply(p)
|
|
334
|
+
rk := inputChain(k, ctx.under(local, a.opacity()), q, e)
|
|
335
|
+
if rk.hit || a.hit(q)
|
|
336
|
+
na := a.input(ctx, InputEvent.pointerAt(e, q))
|
|
337
|
+
TreeRouted(t: FRoseNode(value: na, firstChild: rk.t, nextSibling: rn.t), hit: true)
|
|
338
|
+
else
|
|
339
|
+
TreeRouted(t: FRoseNode(value: a, firstChild: rk.t, nextSibling: rn.t), hit: false)
|
|
340
|
+
|
|
301
341
|
# The topmost shown actor under `p` (a point in the chain's parent's coordinates) that
|
|
302
342
|
# says it is hit: later siblings first, and in each, its children before itself.
|
|
303
343
|
fun hitChain[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
|
std/game/ui.plum
CHANGED
|
@@ -14,93 +14,20 @@ import std/game/input
|
|
|
14
14
|
import std/collections/functional/FRoseTree
|
|
15
15
|
import std/game/scene/Place
|
|
16
16
|
import std/game/scene/Actor
|
|
17
|
+
import std/game/scene/Ctx
|
|
17
18
|
import std/game/scene/SceneTree
|
|
18
19
|
|
|
19
|
-
# Widgets for a scene tree, and the pointer rules that drive them. `Button[M]` and
|
|
20
|
-
#
|
|
20
|
+
# Widgets for a scene tree: actors (`is Actor[M]`), so any game's `SceneTree[M]` takes
|
|
21
|
+
# them. A `Button[M]` sends its `onClick: M` to the game when it is clicked: pressed (a
|
|
22
|
+
# pointer down on it, which `SceneTree.input` routes to it through `input`) and released
|
|
21
|
-
#
|
|
23
|
+
# on it. It shows the pointer by its own `step`: hovered while the pointer is over it,
|
|
22
|
-
# `tree.hitId(x, y)`) and returns the new state plus the UiEvents it raised; `messages`
|
|
23
|
-
# turns the Clicks among them into the game's own messages, each button's `onClick`, and
|
|
24
|
-
# `styled` gives every button the look of the state. Down captures the pressed id; while
|
|
25
|
-
#
|
|
24
|
+
# pressed while it is held down after a press on it. Releasing elsewhere sends nothing;
|
|
26
|
-
|
|
27
|
-
struct UiState(x: Float, y: Float, down: Bool, hot: Option[Int], captured: Option[Int])
|
|
28
|
-
|
|
29
|
-
struct UiStep(ui: UiState, events: List[UiEvent])
|
|
30
|
-
|
|
31
|
-
fun uiSame(a: Option[Int], b: Option[Int]) -> Bool = match a
|
|
32
|
-
Some(va) => match b
|
|
33
|
-
Some(vb) => va == vb
|
|
34
|
-
None => false
|
|
35
|
-
None => b.isNone()
|
|
36
|
-
|
|
37
|
-
#
|
|
25
|
+
# dragging off and back while held, then releasing on it, still clicks.
|
|
38
|
-
|
|
26
|
+
|
|
39
|
-
if !uiSame(old, now)
|
|
40
|
-
if Some(o) := old
|
|
41
|
-
out.push(UiEvent(id: o, kind: Exit))
|
|
42
|
-
if Some(n) := now
|
|
43
|
-
out.push(UiEvent(id: n, kind: Enter))
|
|
44
|
-
|
|
45
|
-
fun init() -> UiState =
|
|
46
|
-
UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: None)
|
|
47
|
-
|
|
48
|
-
# The state after one pointer input, pushing the events it raises onto `out`.
|
|
49
|
-
# A capture left over without a held button is stale.
|
|
50
|
-
fun uiTransition(out: Slice[UiEvent], ui: UiState, input: InputEvent, hit: Option[Int]) -> UiState =
|
|
51
|
-
cap: Option[Int] := if ui.down then ui.captured else None
|
|
52
|
-
match input
|
|
53
|
-
PointerDown(_, _) =>
|
|
54
|
-
uiHover(out, ui.hot, hit)
|
|
55
|
-
newCap := match hit
|
|
56
|
-
Some(h) =>
|
|
57
|
-
out.push(UiEvent(id: h, kind: Press))
|
|
58
|
-
Some(h)
|
|
59
|
-
None => None
|
|
60
|
-
UiState(..ui, down: true, hot: hit, captured: newCap)
|
|
61
|
-
PointerMove(_, _) => match cap
|
|
62
|
-
Some(c) =>
|
|
63
|
-
now: Option[Int] := if uiSame(hit, cap) then cap else None
|
|
64
|
-
uiHover(out, ui.hot, now)
|
|
65
|
-
UiState(..ui, hot: now, captured: cap)
|
|
66
|
-
None =>
|
|
67
|
-
uiHover(out, ui.hot, hit)
|
|
68
|
-
UiState(..ui, hot: hit, captured: cap)
|
|
69
|
-
PointerUp(_, _) =>
|
|
70
|
-
match cap
|
|
71
|
-
Some(c) =>
|
|
72
|
-
out.push(UiEvent(id: c, kind: Release))
|
|
73
|
-
if uiSame(hit, cap)
|
|
74
|
-
out.push(UiEvent(id: c, kind: Click))
|
|
75
|
-
None =>
|
|
76
|
-
uiHover(out, ui.hot, hit)
|
|
77
|
-
UiState(..ui, down: false, hot: hit, captured: None)
|
|
78
|
-
_ => UiState(..ui, captured: cap)
|
|
79
|
-
|
|
80
|
-
# A key changes nothing here (keys go to the game).
|
|
81
|
-
fun step(ui: UiState, input: InputEvent, hit: Option[Int]) -> UiStep =
|
|
82
|
-
maybePos := input.position()
|
|
83
|
-
if maybePos.isNone()
|
|
84
|
-
UiStep(ui: ui, events: Nil)
|
|
85
|
-
else
|
|
86
|
-
pos := maybePos!
|
|
87
|
-
out := Slice[UiEvent]()
|
|
88
|
-
next := uiTransition(out, ui, input, hit)
|
|
89
|
-
UiStep(ui: UiState(..next, x: pos.x, y: pos.y), events: List.fromSlice(out))
|
|
90
|
-
|
|
91
|
-
fun pressed(ui: UiState, id: Int) -> Bool =
|
|
92
|
-
match ui.captured
|
|
93
|
-
Some(c) => c == id && uiSame(ui.hot, ui.captured)
|
|
94
|
-
None => false
|
|
95
|
-
|
|
96
|
-
fun hovered(ui: UiState, id: Int) -> Bool =
|
|
97
|
-
match ui.hot
|
|
98
|
-
Some(h) => h == id
|
|
99
|
-
None => false
|
|
100
|
-
|
|
101
|
-
# A button `w` by `h` with its top-left at (x, y) that sends `onClick` when clicked
|
|
27
|
+
# A button `w` by `h` with its top-left at (x, y) that sends `onClick` when clicked.
|
|
102
|
-
#
|
|
28
|
+
# `look` is how it shows the pointer, 0 idle, 1 hovered, 2 pressed; `armed` is whether a
|
|
29
|
+
# press on it is held. Make one with `ui.button`.
|
|
103
|
-
struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int) is Actor[M] =
|
|
30
|
+
struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int, armed: Bool) is Actor[M] =
|
|
104
31
|
fun key(self) -> Int = self.id
|
|
105
32
|
|
|
106
33
|
fun place(self) -> Place = place.at(self.x, self.y)
|
|
@@ -111,8 +38,25 @@ struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, on
|
|
|
111
38
|
|
|
112
39
|
fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.h, p)
|
|
113
40
|
|
|
41
|
+
# A press on it arms it; a release on it while armed sends `onClick`.
|
|
42
|
+
fun input(self, ctx: Ctx[M], e: InputEvent) -> Button[M] = match e
|
|
43
|
+
PointerDown(_, _) => Button(..self, armed: true, look: 2)
|
|
44
|
+
PointerUp(_, _) =>
|
|
45
|
+
if self.armed
|
|
46
|
+
ctx.send(self.onClick)
|
|
114
|
-
|
|
47
|
+
Button(..self, armed: false, look: 1)
|
|
48
|
+
_ => self
|
|
49
|
+
|
|
50
|
+
# Its look from the tick's pointer; a release anywhere disarms it.
|
|
51
|
+
fun step(self, ctx: Ctx[M], dt: Float) -> Button[M] =
|
|
52
|
+
over := self.hit(ctx.worldOf(self.place().local()).inverse().apply(ctx.input.pos))
|
|
53
|
+
armed := self.armed && ctx.input.held.mouse
|
|
54
|
+
look := if armed && over then 2 else if over then 1 else 0
|
|
115
|
-
|
|
55
|
+
if armed == self.armed && look == self.look then self else Button(..self, armed: armed, look: look)
|
|
56
|
+
|
|
57
|
+
# A button, idle.
|
|
58
|
+
fun button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M) -> Button[M] =
|
|
59
|
+
Button(id: id, x: x, y: y, w: w, h: h, label: label, onClick: onClick, look: 0, armed: false)
|
|
116
60
|
|
|
117
61
|
# A line of text in `color` with its top-left at (x, y), `size` high. Its opacity is its
|
|
118
62
|
# colour's alpha.
|
|
@@ -128,15 +72,6 @@ struct Label[M](id: Int, x: Float, y: Float, text: Str, size: Float, color: Colo
|
|
|
128
72
|
|
|
129
73
|
fun relabel(self, t: Str) -> Label[M] = Label(..self, text: t)
|
|
130
74
|
|
|
131
|
-
# The look of the button `id` in `ui`: 2 pressed, 1 hovered, 0 idle.
|
|
132
|
-
fun lookOf(ui: UiState, id: Int) -> Int =
|
|
133
|
-
if pressed(ui, id)
|
|
134
|
-
2
|
|
135
|
-
else if hovered(ui, id)
|
|
136
|
-
1
|
|
137
|
-
else
|
|
138
|
-
0
|
|
139
|
-
|
|
140
75
|
fun lookColor(look: Int) -> Color =
|
|
141
76
|
if look == 2
|
|
142
77
|
uiPressedColor()
|
|
@@ -145,125 +80,82 @@ fun lookColor(look: Int) -> Color =
|
|
|
145
80
|
else
|
|
146
81
|
uiIdleColor()
|
|
147
82
|
|
|
148
|
-
# The messages of the buttons that `events` clicked, in order, read from `tree`.
|
|
149
|
-
fun messages[M](tree: SceneTree[M], events: List[UiEvent]) -> List[M] = match events
|
|
150
|
-
Nil => Nil
|
|
151
|
-
Cons(e, rest) =>
|
|
152
|
-
later := messages(tree, rest)
|
|
153
|
-
if e.kind != Click
|
|
154
|
-
later
|
|
155
|
-
else
|
|
156
|
-
match tree.findAs[Button[M]](e.id)
|
|
157
|
-
Some(b) => Cons(head: b.onClick, tail: later)
|
|
158
|
-
None => later
|
|
159
|
-
|
|
160
|
-
# `tree` with every button showing `ui`.
|
|
161
|
-
fun styled[M](tree: SceneTree[M], ui: UiState) -> SceneTree[M] =
|
|
162
|
-
tree.withRoot(tree.root.map(|a| match a
|
|
163
|
-
Button as b =>
|
|
164
|
-
c: Actor[M] := b.styled(ui)
|
|
165
|
-
c
|
|
166
|
-
_ => a))
|
|
167
|
-
|
|
168
83
|
fun uiIdleColor() -> Color = Color.rgb(0.2, 0.2, 0.3)
|
|
169
84
|
|
|
170
85
|
fun uiHoverColor() -> Color = Color.rgb(0.35, 0.35, 0.5)
|
|
171
86
|
|
|
172
87
|
fun uiPressedColor() -> Color = Color.rgb(0.6, 0.2, 0.2)
|
|
173
88
|
|
|
174
|
-
fun uiKinds(s: UiStep) -> List[UiKind] = s.events.map(|e| e.kind)
|
|
175
|
-
|
|
176
|
-
fun uiDown(x: Float) -> InputEvent = PointerDown(x: x, y: 0.0)
|
|
177
|
-
|
|
178
|
-
fun uiUp(x: Float) -> InputEvent = PointerUp(x: x, y: 0.0)
|
|
179
|
-
|
|
180
|
-
fun uiMove(x: Float) -> InputEvent = PointerMove(x: x, y: 0.0)
|
|
181
|
-
|
|
182
|
-
|
|
89
|
+
# --- tests ---
|
|
183
|
-
s.events.fold(0, |n, e| if e.kind == k then n + 1 else n)
|
|
184
|
-
|
|
185
|
-
fun uiIs(e: UiEvent, id: Int, kind: UiKind) -> Bool = e.id == id && e.kind == kind
|
|
186
90
|
|
|
187
91
|
fun uiButton(id: Int, msg: Int, label: Str, x: Float, y: Float) -> FRoseTree[Actor[Int]] =
|
|
188
|
-
FRoseTree.leaf(
|
|
92
|
+
FRoseTree.leaf(button(id, x, y, 10.0, 10.0, label, msg))
|
|
189
93
|
|
|
94
|
+
# Two buttons in a group at (100, 0): 3 sends 30, 4 sends 40.
|
|
190
95
|
fun uiTree() -> SceneTree[Int] =
|
|
191
|
-
root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x:
|
|
96
|
+
root: FRoseTree[Actor[Int]] := FRoseTree.of(Group(id: 0, x: 100.0, y: 0.0), [uiButton(3, 30, "Go", 0.0, 0.0), uiButton(4, 40, "Stop", 20.0, 0.0)])
|
|
192
97
|
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
193
98
|
|
|
194
99
|
fun uiLook(t: SceneTree[Int], id: Int) -> Int = t.findAs[Button[Int]](id).unwrap().look
|
|
195
100
|
|
|
196
|
-
test "press_sets_capture"
|
|
197
|
-
s1 := step(init(), uiDown(1.0), Some(5))
|
|
198
|
-
assert s1.events.length() == 2
|
|
199
|
-
assert uiIs(s1.events.at(0), 5, Enter)
|
|
200
|
-
assert uiIs(s1.events.at(1), 5, Press)
|
|
201
|
-
assert pressed(s1.ui, 5)
|
|
202
|
-
s2 := step(s1.ui, uiUp(1.0), Some(5))
|
|
203
|
-
assert s2.events.length() == 2
|
|
204
|
-
assert uiIs(s2.events.at(0), 5, Release)
|
|
205
|
-
assert uiIs(s2.events.at(1), 5, Click)
|
|
206
|
-
assert !pressed(s2.ui, 5)
|
|
207
|
-
assert hovered(s2.ui, 5)
|
|
208
|
-
|
|
209
|
-
test "release_elsewhere_no_click"
|
|
210
|
-
s1 := step(init(), uiDown(1.0), Some(5))
|
|
211
|
-
s2 := step(s1.ui, uiMove(99.0), None)
|
|
212
|
-
assert s2.events.length() == 1
|
|
213
|
-
assert uiIs(s2.events.at(0), 5, Exit)
|
|
214
|
-
s3 := step(s2.ui, uiUp(99.0), None)
|
|
215
|
-
assert s3.events.length() == 1
|
|
216
|
-
assert uiIs(s3.events.at(0), 5, Release)
|
|
217
|
-
assert uiCount(s3, Click) == 0
|
|
218
|
-
|
|
219
|
-
test "drag_off_and_back_one_click"
|
|
220
|
-
s1 := step(init(), uiDown(1.0), Some(5))
|
|
221
|
-
s2 := step(s1.ui, uiMove(99.0), None)
|
|
222
|
-
s3 := step(s2.ui, uiMove(1.0), Some(5))
|
|
223
|
-
assert s3.events.length() == 1
|
|
224
|
-
assert uiIs(s3.events.at(0), 5, Enter)
|
|
225
|
-
s4 := step(s3.ui, uiUp(1.0), Some(5))
|
|
226
|
-
assert uiCount(s4, Click) == 1
|
|
227
|
-
assert uiCount(s4, Release) == 1
|
|
228
|
-
|
|
229
|
-
test "stale_capture_dropped"
|
|
230
|
-
|
|
101
|
+
# A tick of the pointer at (x, 5) with the mouse `down` and `events`: the events routed
|
|
102
|
+
# through the tree, then a step, as `Game` does; the messages sent go to `out`.
|
|
103
|
+
fun uiTick(t: SceneTree[Int], x: Float, down: Bool, events: List[InputEvent], out: Slice[Int]) -> SceneTree[Int] =
|
|
104
|
+
i := Input(held: Held(mouse: down, keys: Slice[Int]()), events: events.toSlice(), pos: Vec2(x: x, y: 5.0), wheel: 0.0)
|
|
105
|
+
ctx: Ctx[Int] := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
|
|
106
|
+
routed := events.fold(t, |tr, e| tr.input(ctx, e))
|
|
231
|
-
s := step(
|
|
107
|
+
s := routed.step(ctx, 1.0 / 60.0)
|
|
108
|
+
ctx.takeSends().each(|m| out.push(m))
|
|
109
|
+
s
|
|
110
|
+
|
|
111
|
+
test "a press and a release on a button sends its message"
|
|
112
|
+
out := Slice[Int]()
|
|
113
|
+
t := uiTree()
|
|
114
|
+
down := uiTick(t, 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
115
|
+
assert uiLook(down, 3) == 2 && uiLook(down, 4) == 0
|
|
232
|
-
assert
|
|
116
|
+
assert out.length() == 0
|
|
233
|
-
if Some(c) := s.ui.captured
|
|
234
|
-
assert false
|
|
235
|
-
assert !pressed(s.ui, 5)
|
|
236
|
-
|
|
237
|
-
|
|
117
|
+
up := uiTick(down, 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
238
|
-
|
|
118
|
+
assert out.length() == 1 && out.at(0) == 30
|
|
239
|
-
assert
|
|
119
|
+
assert uiLook(up, 3) == 1
|
|
240
|
-
assert
|
|
120
|
+
assert !up.findAs[Button[Int]](3).unwrap().armed
|
|
121
|
+
|
|
122
|
+
test "a release elsewhere sends nothing and disarms"
|
|
123
|
+
out := Slice[Int]()
|
|
124
|
+
down := uiTick(uiTree(), 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
125
|
+
off := uiTick(down, 150.0, true, [PointerMove(x: 150.0, y: 5.0)], out)
|
|
241
|
-
assert
|
|
126
|
+
assert uiLook(off, 3) == 0
|
|
242
|
-
|
|
127
|
+
up := uiTick(off, 150.0, false, [PointerUp(x: 150.0, y: 5.0)], out)
|
|
243
|
-
assert
|
|
128
|
+
assert out.length() == 0
|
|
129
|
+
assert !up.findAs[Button[Int]](3).unwrap().armed
|
|
244
|
-
|
|
130
|
+
# a later release on it is not a click
|
|
131
|
+
again := uiTick(uiTick(up, 105.0, false, [PointerMove(x: 105.0, y: 5.0)], out), 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
245
|
-
assert
|
|
132
|
+
assert out.length() == 0
|
|
246
|
-
assert
|
|
133
|
+
assert uiLook(again, 3) == 1
|
|
134
|
+
|
|
135
|
+
test "dragging off and back while held, then releasing on it, clicks once"
|
|
136
|
+
out := Slice[Int]()
|
|
137
|
+
down := uiTick(uiTree(), 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
138
|
+
off := uiTick(down, 150.0, true, [PointerMove(x: 150.0, y: 5.0)], out)
|
|
139
|
+
back := uiTick(off, 105.0, true, [PointerMove(x: 105.0, y: 5.0)], out)
|
|
247
|
-
assert
|
|
140
|
+
assert uiLook(back, 3) == 2
|
|
141
|
+
_ := uiTick(back, 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
142
|
+
assert out.length() == 1 && out.at(0) == 30
|
|
143
|
+
|
|
144
|
+
test "a press and release between two ticks still clicks"
|
|
145
|
+
out := Slice[Int]()
|
|
146
|
+
_ := uiTick(uiTree(), 125.0, false, [PointerDown(x: 125.0, y: 5.0), PointerUp(x: 125.0, y: 5.0)], out)
|
|
147
|
+
assert out.length() == 1 && out.at(0) == 40
|
|
248
148
|
|
|
249
149
|
test "buttons show the pointer and are hit in their box"
|
|
150
|
+
out := Slice[Int]()
|
|
250
151
|
t := uiTree()
|
|
251
|
-
hov :=
|
|
152
|
+
hov := uiTick(t, 101.0, false, [PointerMove(x: 101.0, y: 5.0)], out)
|
|
252
|
-
prs := styled(t, step(init(), uiDown(1.0), Some(3)).ui)
|
|
253
153
|
assert uiLook(t, 3) == 0
|
|
254
154
|
assert uiLook(hov, 3) == 1 && uiLook(hov, 4) == 0
|
|
255
|
-
assert uiLook(prs, 3) == 2
|
|
256
155
|
assert lookColor(2).eq(uiPressedColor()) && lookColor(1).eq(uiHoverColor()) && lookColor(0).eq(uiIdleColor())
|
|
257
|
-
assert t.hitId(
|
|
156
|
+
assert t.hitId(105.0, 5.0).unwrapOr(-1) == 3
|
|
258
|
-
assert t.hitId(
|
|
157
|
+
assert t.hitId(125.0, 5.0).unwrapOr(-1) == 4
|
|
259
|
-
assert t.hitId(
|
|
158
|
+
assert t.hitId(115.0, 5.0).isNone()
|
|
260
|
-
|
|
261
|
-
test "messages_are_the_clicked_buttons_messages"
|
|
262
|
-
evs := [UiEvent(id: 4, kind: Press), UiEvent(id: 4, kind: Click), UiEvent(id: 9, kind: Click), UiEvent(id: 3, kind: Click)]
|
|
263
|
-
ms := messages(uiTree(), evs)
|
|
264
|
-
assert ms.length() == 2
|
|
265
|
-
assert ms.get(0).unwrapOr(-1) == 40
|
|
266
|
-
assert ms.get(1).unwrapOr(-1) == 30
|
|
267
159
|
|
|
268
160
|
test "a label relabels and its alpha is its opacity"
|
|
269
161
|
l: Label[Int] := Label(id: 1, x: 0.0, y: 0.0, text: "a", size: 10.0, color: Color.White.withAlpha(0.5))
|
tests/port/game/determinism.plum
CHANGED
|
@@ -7,19 +7,28 @@ import std/Io
|
|
|
7
7
|
import std/Random
|
|
8
8
|
import std/game/Vec2
|
|
9
9
|
import std/game/input
|
|
10
|
+
import std/game/Affine
|
|
11
|
+
import std/game/Store
|
|
12
|
+
import std/game/Game
|
|
13
|
+
import std/game/scene/Place
|
|
14
|
+
import std/game/scene/Actor
|
|
15
|
+
import std/game/scene/Ctx
|
|
16
|
+
import std/game/scene/SceneTree
|
|
10
17
|
|
|
11
18
|
# Deterministic games: the game's `Clock` (std/game/input) runs fixed 1/60 s ticks, at
|
|
12
19
|
# most 8 a frame, and hands each tick its input as a value; randomness is a `Random`
|
|
13
20
|
# seeded in the game's state. So one seed and one list of inputs give the same game.
|
|
14
21
|
|
|
15
|
-
#
|
|
22
|
+
# The state of a `Game` for these tests: it counts ticks, adds up and bounds `dt`, counts
|
|
16
|
-
# Space is held, and on each press of Space draws from its `Random`.
|
|
23
|
+
# the ticks Space is held, and on each press of Space draws from its `Random`. Its one
|
|
24
|
+
# actor sends it what each tick saw.
|
|
17
|
-
struct Probe(rng: Random, ticks: Int, time: Float, minDt: Float, maxDt: Float, presses: Int, held: Int, roll: Int) =
|
|
25
|
+
struct Probe(rng: Random, ticks: Int, time: Float, minDt: Float, maxDt: Float, presses: Int, held: Int, roll: Int) is Reducer[Saw] =
|
|
18
26
|
fun seeded(seed: Int) -> Probe =
|
|
19
27
|
Probe(rng: Random.seeded(seed), ticks: 0, time: 0.0, minDt: 1.0, maxDt: 0.0, presses: 0, held: 0, roll: 0)
|
|
20
28
|
|
|
21
|
-
fun update(self,
|
|
29
|
+
fun update(self, saw: Saw) -> Probe =
|
|
22
|
-
pressed :=
|
|
30
|
+
pressed := saw.pressed
|
|
31
|
+
dt := saw.dt
|
|
23
32
|
r := self.rng.nextInt()
|
|
24
33
|
Probe(
|
|
25
34
|
rng: if pressed then r.rng else self.rng,
|
|
@@ -28,15 +37,43 @@ struct Probe(rng: Random, ticks: Int, time: Float, minDt: Float, maxDt: Float, p
|
|
|
28
37
|
minDt: self.minDt.min(dt),
|
|
29
38
|
maxDt: self.maxDt.max(dt),
|
|
30
39
|
presses: if pressed then self.presses + 1 else self.presses,
|
|
31
|
-
held: if
|
|
40
|
+
held: if saw.spaceHeld then self.held + 1 else self.held,
|
|
32
41
|
roll: if pressed then self.roll ^ r.value else self.roll
|
|
33
42
|
)
|
|
34
43
|
|
|
35
44
|
fun same(self, o: Probe) -> Bool =
|
|
36
45
|
self.rng.seed == o.rng.seed && self.ticks == o.ticks && self.time == o.time && self.presses == o.presses && self.held == o.held && self.roll == o.roll
|
|
37
46
|
|
|
47
|
+
|
|
48
|
+
# What a tick saw, sent to the store by the probe's one actor.
|
|
49
|
+
struct Saw(pressed: Bool, spaceHeld: Bool, x: Float, y: Float, dt: Float)
|
|
50
|
+
|
|
51
|
+
# The probe's one actor: it reports each tick's input (`ctx.input`) to the store.
|
|
52
|
+
struct Eye(id: Int) is Actor[Saw] =
|
|
53
|
+
fun key(self) -> Int = self.id
|
|
54
|
+
|
|
55
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
56
|
+
|
|
57
|
+
fun step(self, ctx: Ctx[Saw], dt: Float) -> Eye =
|
|
58
|
+
i := ctx.input
|
|
59
|
+
ctx.send(Saw(pressed: i.isKeyPressed(Key.Space), spaceHeld: i.isKeyDown(Key.Space), x: i.pos.x, y: i.pos.y, dt: dt))
|
|
60
|
+
self
|
|
61
|
+
|
|
62
|
+
# The probe's one screen.
|
|
63
|
+
struct Only(t: SceneTree[Saw]) is Screen[Probe, Saw] =
|
|
64
|
+
fun tree(self) -> SceneTree[Saw] = self.t
|
|
65
|
+
|
|
66
|
+
fun withTree(self, t: SceneTree[Saw]) -> Only = Only(t: t)
|
|
67
|
+
|
|
68
|
+
# The probe's game from `seed`.
|
|
69
|
+
fun probeGame(seed: Int) -> Game[Probe, Saw] = Game.start(Only(t: SceneTree.of(Eye(id: 0))), Probe.seeded(seed))
|
|
70
|
+
|
|
71
|
+
# The screen the tests run on.
|
|
72
|
+
View = Vec2(x: 800.0, y: 600.0)
|
|
73
|
+
|
|
38
|
-
# The
|
|
74
|
+
# The game and its clock, as the entry point the compiler adds to a game holds them.
|
|
39
|
-
struct Run(game: Probe, clock: Clock)
|
|
75
|
+
struct Run(game: Game[Probe, Saw], clock: Clock) =
|
|
76
|
+
fun probe(self) -> Probe = self.game.state()
|
|
40
77
|
|
|
41
78
|
# One host frame `dt` seconds long with the input `frame`: what the generated
|
|
42
79
|
# `gameUpdate` does after polling the host.
|
|
@@ -44,10 +81,10 @@ fun runFrame(io: Io, r: Run, frame: Input, dt: Float) -> Run =
|
|
|
44
81
|
ticks(io, Run(game: r.game, clock: r.clock.accept(frame, dt)))
|
|
45
82
|
|
|
46
83
|
fun ticks(io: Io, r: Run) -> Run =
|
|
47
|
-
if r.clock.due() then ticks(io, Run(game: r.game.
|
|
84
|
+
if r.clock.due() then ticks(io, Run(game: r.game.step(io, r.clock.input(), Clock.Tick, View), clock: r.clock.ticked())) else Run(game: r.game, clock: r.clock.settled())
|
|
48
85
|
|
|
49
86
|
fun start(seed: Int) -> Run =
|
|
50
|
-
Run(game:
|
|
87
|
+
Run(game: probeGame(seed), clock: Clock.create())
|
|
51
88
|
|
|
52
89
|
fun still() -> Input =
|
|
53
90
|
Input.create()
|
|
@@ -80,7 +117,7 @@ fun scriptedRun(io: Io, seed: Int, frames: Int) -> Run =
|
|
|
80
117
|
|
|
81
118
|
# The ticks one frame of `dt` runs from a fresh clock.
|
|
82
119
|
fun ticksOf(io: Io, dt: Float) -> Int =
|
|
83
|
-
runFrame(io, start(1), still(), dt).
|
|
120
|
+
runFrame(io, start(1), still(), dt).probe().ticks
|
|
84
121
|
|
|
85
122
|
test "fixed_timestep: a 50 ms frame runs 3 ticks, a 1 s frame runs 8"
|
|
86
123
|
assert ticksOf(io, 0.05) == 3
|
|
@@ -91,32 +128,32 @@ test "fixed_timestep: a 50 ms frame runs 3 ticks, a 1 s frame runs 8"
|
|
|
91
128
|
|
|
92
129
|
test "a stall's leftover time is dropped, not run later"
|
|
93
130
|
r := runFrame(io, start(1), still(), 10.0)
|
|
94
|
-
assert r.
|
|
131
|
+
assert r.probe().ticks == Clock.MaxTicks
|
|
95
|
-
assert runFrame(io, r, still(), 1.0 / 60.0).
|
|
132
|
+
assert runFrame(io, r, still(), 1.0 / 60.0).probe().ticks == Clock.MaxTicks + 1
|
|
96
133
|
|
|
97
134
|
test "dt is the same constant tick whatever the frame rate"
|
|
98
135
|
rates := [30, 60, 75, 144, 240]
|
|
99
136
|
for k := range rates.length()
|
|
100
137
|
rate := rates.at(k)
|
|
101
138
|
r := 0.until(rate).fold(start(1), |acc, _| runFrame(io, acc, still(), 1.0 / Float(rate)))
|
|
102
|
-
assert r.
|
|
139
|
+
assert r.probe().minDt == Clock.Tick
|
|
103
|
-
assert r.
|
|
140
|
+
assert r.probe().maxDt == Clock.Tick
|
|
104
|
-
assert r.
|
|
141
|
+
assert r.probe().ticks >= 59 && r.probe().ticks <= 60
|
|
105
|
-
assert r.clock.ticks == r.
|
|
142
|
+
assert r.clock.ticks == r.probe().ticks
|
|
106
143
|
|
|
107
144
|
test "same_seed_same_game: one seed and one input list reach the same state"
|
|
108
|
-
a := scriptedRun(io, 77, 40)
|
|
145
|
+
a := scriptedRun(io, 77, 40).probe()
|
|
109
|
-
b := scriptedRun(io, 77, 40)
|
|
146
|
+
b := scriptedRun(io, 77, 40).probe()
|
|
110
|
-
assert a.
|
|
147
|
+
assert a.same(b)
|
|
111
|
-
assert a.
|
|
148
|
+
assert a.presses == 2
|
|
112
|
-
assert a.
|
|
149
|
+
assert a.roll != 0
|
|
113
|
-
assert !a.
|
|
150
|
+
assert !a.same(scriptedRun(io, 78, 40).probe())
|
|
114
|
-
|
|
151
|
+
|
|
115
|
-
test "same_seed_same_game: 120 ticks of
|
|
152
|
+
test "same_seed_same_game: 120 ticks of the game from one seed and one input list match"
|
|
116
153
|
inputs := Slice[Input]()
|
|
117
154
|
for i := range 120
|
|
118
155
|
inputs.push(scripted(i / 3))
|
|
119
|
-
play := |seed: Int| 0.until(120).fold(
|
|
156
|
+
play := |seed: Int| 0.until(120).fold(probeGame(seed), |g, i| g.step(io, inputs.at(i), 1.0 / 60.0, View)).state()
|
|
120
157
|
a := play(5)
|
|
121
158
|
b := play(5)
|
|
122
159
|
assert a.same(b)
|
|
@@ -124,11 +161,11 @@ test "same_seed_same_game: 120 ticks of update from one seed and one input list
|
|
|
124
161
|
|
|
125
162
|
test "a press reaches one tick, even across a frame that ran none"
|
|
126
163
|
r0 := runFrame(io, start(1), space(true), 0.005)
|
|
127
|
-
assert r0.
|
|
164
|
+
assert r0.probe().ticks == 0
|
|
128
165
|
r1 := runFrame(io, r0, space(false), 0.012)
|
|
129
|
-
assert r1.
|
|
166
|
+
assert r1.probe().ticks == 1
|
|
130
|
-
assert r1.
|
|
167
|
+
assert r1.probe().presses == 1
|
|
131
168
|
r2 := runFrame(io, r1, space(false), 2.0 / 60.0)
|
|
132
|
-
assert r2.
|
|
169
|
+
assert r2.probe().ticks == 3
|
|
133
|
-
assert r2.
|
|
170
|
+
assert r2.probe().presses == 1
|
|
134
|
-
assert r2.
|
|
171
|
+
assert r2.probe().held == 3
|
tests/port/game/replay.plum
CHANGED
|
@@ -11,37 +11,74 @@ import std/math
|
|
|
11
11
|
import std/game/Vec2
|
|
12
12
|
import std/game/input
|
|
13
13
|
import std/game/Replay
|
|
14
|
+
import std/game/Affine
|
|
15
|
+
import std/game/Store
|
|
16
|
+
import std/game/Game
|
|
17
|
+
import std/game/scene/Place
|
|
18
|
+
import std/game/scene/Actor
|
|
19
|
+
import std/game/scene/Ctx
|
|
20
|
+
import std/game/scene/SceneTree
|
|
14
21
|
|
|
15
22
|
# Record and replay (std/game/Replay): a run is its seed and one `Input` per tick, as text
|
|
16
23
|
# with exact floats. A game's `Clock` records the ticks of each frame and replays them.
|
|
17
24
|
|
|
18
|
-
#
|
|
25
|
+
# The state of a `Game` for these tests: it counts ticks, follows the pointer, counts the
|
|
19
|
-
# held, and on each press of Space or click draws from its `Random`.
|
|
26
|
+
# ticks Space is held, and on each press of Space or click draws from its `Random`. Its
|
|
27
|
+
# one actor sends it what each tick saw.
|
|
20
|
-
struct Probe(rng: Random, ticks: Int, presses: Int, held: Int, roll: Int, x: Float, y: Float) =
|
|
28
|
+
struct Probe(rng: Random, ticks: Int, presses: Int, held: Int, roll: Int, x: Float, y: Float) is Reducer[Saw] =
|
|
21
29
|
fun seeded(seed: Int) -> Probe =
|
|
22
30
|
Probe(rng: Random.seeded(seed), ticks: 0, presses: 0, held: 0, roll: 0, x: 0.0, y: 0.0)
|
|
23
31
|
|
|
24
|
-
fun update(self,
|
|
32
|
+
fun update(self, saw: Saw) -> Probe =
|
|
25
|
-
pressed :=
|
|
33
|
+
pressed := saw.pressed
|
|
34
|
+
dt := saw.dt
|
|
26
35
|
r := self.rng.nextInt()
|
|
27
36
|
Probe(
|
|
28
37
|
rng: if pressed then r.rng else self.rng,
|
|
29
38
|
ticks: self.ticks + 1,
|
|
30
39
|
presses: if pressed then self.presses + 1 else self.presses,
|
|
31
|
-
held: if
|
|
40
|
+
held: if saw.spaceHeld then self.held + 1 else self.held,
|
|
32
41
|
roll: if pressed then self.roll ^ r.value else self.roll,
|
|
33
|
-
x: self.x +
|
|
42
|
+
x: self.x + saw.x * dt,
|
|
34
|
-
y: self.y +
|
|
43
|
+
y: self.y + saw.y * dt
|
|
35
44
|
)
|
|
36
45
|
|
|
37
46
|
fun same(self, o: Probe) -> Bool =
|
|
38
47
|
self.rng.seed == o.rng.seed && self.ticks == o.ticks && self.presses == o.presses && self.held == o.held && self.roll == o.roll && self.x == o.x && self.y == o.y
|
|
39
48
|
|
|
49
|
+
|
|
50
|
+
# What a tick saw, sent to the store by the probe's one actor.
|
|
51
|
+
struct Saw(pressed: Bool, spaceHeld: Bool, x: Float, y: Float, dt: Float)
|
|
52
|
+
|
|
53
|
+
# The probe's one actor: it reports each tick's input (`ctx.input`) to the store.
|
|
54
|
+
struct Eye(id: Int) is Actor[Saw] =
|
|
55
|
+
fun key(self) -> Int = self.id
|
|
56
|
+
|
|
57
|
+
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
58
|
+
|
|
59
|
+
fun step(self, ctx: Ctx[Saw], dt: Float) -> Eye =
|
|
60
|
+
i := ctx.input
|
|
61
|
+
ctx.send(Saw(pressed: i.isKeyPressed(Key.Space) || i.pointerPressed(), spaceHeld: i.isKeyDown(Key.Space), x: i.pos.x, y: i.pos.y, dt: dt))
|
|
62
|
+
self
|
|
63
|
+
|
|
64
|
+
# The probe's one screen.
|
|
65
|
+
struct Only(t: SceneTree[Saw]) is Screen[Probe, Saw] =
|
|
66
|
+
fun tree(self) -> SceneTree[Saw] = self.t
|
|
67
|
+
|
|
68
|
+
fun withTree(self, t: SceneTree[Saw]) -> Only = Only(t: t)
|
|
69
|
+
|
|
70
|
+
# The probe's game from `seed`.
|
|
71
|
+
fun probeGame(seed: Int) -> Game[Probe, Saw] = Game.start(Only(t: SceneTree.of(Eye(id: 0))), Probe.seeded(seed))
|
|
72
|
+
|
|
73
|
+
# The screen the tests run on.
|
|
74
|
+
View = Vec2(x: 800.0, y: 600.0)
|
|
75
|
+
|
|
40
|
-
# The
|
|
76
|
+
# The game, its clock and the ticks recorded so far, as a recording host holds them.
|
|
41
|
-
struct Run(game: Probe, clock: Clock, log: Slice[Input])
|
|
77
|
+
struct Run(game: Game[Probe, Saw], clock: Clock, log: Slice[Input]) =
|
|
78
|
+
fun probe(self) -> Probe = self.game.state()
|
|
42
79
|
|
|
43
80
|
fun ticks(io: Io, r: Run) -> Run =
|
|
44
|
-
if r.clock.due() then ticks(io, Run(..r, game: r.game.
|
|
81
|
+
if r.clock.due() then ticks(io, Run(..r, game: r.game.step(io, r.clock.input(), Clock.Tick, View), clock: r.clock.ticked())) else Run(..r, clock: r.clock.settled())
|
|
45
82
|
|
|
46
83
|
# One recorded frame: what the generated `gameUpdate` does while the host records, with
|
|
47
84
|
# `frame` as the polled input and the frame's ticks handed to the log.
|
|
@@ -80,11 +117,11 @@ fun jitter(i: Int) -> Float =
|
|
|
80
117
|
0.0166 + Float(i % 3) * 0.004 - 0.004
|
|
81
118
|
|
|
82
119
|
fun recorded(io: Io, seed: Int, frames: Int) -> Run =
|
|
83
|
-
start := Run(game:
|
|
120
|
+
start := Run(game: probeGame(seed), clock: Clock.create(), log: Slice[Input]())
|
|
84
121
|
0.until(frames).fold(start, |r, i| recordFrame(io, r, scripted(i), jitter(i)))
|
|
85
122
|
|
|
86
123
|
fun replayed(io: Io, r: Replay, frames: Int) -> Run =
|
|
87
|
-
start := Run(game:
|
|
124
|
+
start := Run(game: probeGame(r.seed), clock: Clock.playing(r), log: Slice[Input]())
|
|
88
125
|
0.until(frames).fold(start, |run, i| replayFrame(io, run, jitter(i + 1)))
|
|
89
126
|
|
|
90
127
|
test "replay_roundtrip"
|
|
@@ -113,15 +150,15 @@ test "replay_roundtrip"
|
|
|
113
150
|
|
|
114
151
|
test "replay_matches"
|
|
115
152
|
run := recorded(io, 77, 60)
|
|
116
|
-
assert run.
|
|
153
|
+
assert run.probe().presses == 3
|
|
117
154
|
rec := Replay(seed: 77, width: 0, height: 0, ticks: run.log)
|
|
118
|
-
assert rec.length() == run.
|
|
155
|
+
assert rec.length() == run.probe().ticks
|
|
119
156
|
if Ok(back) := Replay.decode(rec.encode())
|
|
120
157
|
assert back.seed == 77
|
|
121
158
|
# More frames than the recording: the ticks stop where it ends.
|
|
122
159
|
again := replayed(io, back, 80)
|
|
123
|
-
assert again.
|
|
160
|
+
assert again.probe().same(run.probe())
|
|
124
|
-
assert again.clock.ticks == run.
|
|
161
|
+
assert again.clock.ticks == run.probe().ticks
|
|
125
162
|
assert !again.clock.due()
|
|
126
163
|
else
|
|
127
164
|
assert false
|
|
@@ -132,8 +169,8 @@ test "a replay with no input ends elsewhere"
|
|
|
132
169
|
for i := range run.log.length()
|
|
133
170
|
idle.push(Input.create())
|
|
134
171
|
still := replayed(io, Replay(seed: 5, width: 0, height: 0, ticks: idle), 80)
|
|
135
|
-
assert still.
|
|
172
|
+
assert still.probe().ticks == run.probe().ticks
|
|
136
|
-
assert !still.
|
|
173
|
+
assert !still.probe().same(run.probe())
|
|
137
174
|
|
|
138
175
|
test "a frame's due ticks are the ones it runs"
|
|
139
176
|
c := Clock.create().accept(scripted(3), 0.05)
|