plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
84a0463
— Peter John
2026-11-16T15:06:55+05:30
declarative bodies (user: "Yes please do it"): std/game/Body, `struct Body(pos: Vec2, vel = Vec2.Zero, push = Vec2.Zero, drag = 0.0, edge: Walls = Free, angle = 0.0, turn = 0.0, faceAbove: Option<Float> = None)` with `step(dt)` written once (push, drag, move, edges, then faces its motion above `faceAbove` or turns at `turn`) and `place(origin)`; `enum Walls = Free | Halt(box) | Bounce(box) | Wrap(box)` (`Edge` and `Stop` taken; std's `Aabb` is the rect); the `[Steps]` derive steps any field whose type has `step(self, dt: Float) -> Self` (a `List`/`Option` of them by `map`), still a static construction, and joins the fields' steps to an actor's own `step` when that is one spread of `self` (no `step$own`/`step$fields` then); games: the ship's `step` is its clock, `steer(dir: Vec2)` sets `push`, `hurtUntil` with `hurt()` = `clock < hurtUntil`; orbs and mines hold a bouncing `Body` (`Arena.drift`, `Motion` gone), a mine `turn: 2.0`; `Ring(pos: Vec2)`; Balloon Pop's balloon a rising `Body`; clicks' `Ball[Actor, Steps](body: Body)`; checksum 181767343 to 166413027, scripted replay tests on seed 44; orbit update 13.85 to 15.34 ms, paint 143.9 to 149.4 ms (medians of 5); in place all kept (`Motion.spawn`, `Place.rotateTo$unique` gone, `Mine.spawn`, `Body.place` new); tests/std/game/Body.plum, derive diagnostics; docs: game.md, std.md, the review plan
- benchmarks/screen_views/orbit.plum +3 -3
- compiler/checker/tests/checker/diagnostic_tests.rs +8 -3
- compiler/cli/tests/cli/game_in_place_test.rs +10 -2
- compiler/core/src/steps_derive.rs +99 -25
- docs/game.md +16 -10
- docs/plans/2026-11-13-std-game-review.md +1 -0
- docs/std.md +1 -1
- examples/games/balloonpop/actors/Balloon.plum +11 -11
- examples/games/clicks.plum +5 -6
- examples/games/orbitrunner/OrbitRunner.plum +13 -24
- examples/games/orbitrunner/actors/Mine.plum +5 -4
- examples/games/orbitrunner/actors/Orb.plum +5 -4
- examples/games/orbitrunner/actors/Ring.plum +3 -4
- examples/games/orbitrunner/actors/Ship.plum +16 -28
- examples/games/orbitrunner/screens/PlayingScreen.plum +5 -5
- std/game/Body.plum +71 -0
- std/game/View.plum +6 -5
- tests/examples/games/balloonpop/actors/Balloon.plum +3 -2
- tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +7 -6
- tests/examples/games/clicks.plum +2 -1
- tests/examples/games/orbitrunner/actors/Mine.plum +9 -3
- tests/examples/games/orbitrunner/actors/Orb.plum +8 -10
- tests/examples/games/orbitrunner/actors/Ring.plum +2 -1
- tests/examples/games/orbitrunner/actors/Ship.plum +28 -9
- tests/examples/games/orbitrunner/screens/PlayingScreen.plum +54 -54
- tests/std/game/Body.plum +117 -0
benchmarks/screen_views/orbit.plum
CHANGED
|
@@ -47,10 +47,10 @@ primitive OrbitBench[App] =
|
|
|
47
47
|
|
|
48
48
|
# The run's state: the run, the tick count, the ship, each orb and each mine.
|
|
49
49
|
fun state(p: PlayingScreen) -> Int =
|
|
50
|
-
head := [p.score, p.best, p.lives, Timing.flag(p.over), p.ticks, p.ship.
|
|
50
|
+
head := [p.score, p.best, p.lives, Timing.flag(p.over), p.ticks, p.ship.body.pos.x.toBits(), p.ship.body.pos.y.toBits(), p.ship.body.vel.x.toBits(), p.ship.body.vel.y.toBits(), p.orbs.length(), p.mines.length()]
|
|
51
51
|
none: List<Int> := Nil
|
|
52
|
-
orbs := p.orbs.fold(none, |acc, o| Cons(o.
|
|
52
|
+
orbs := p.orbs.fold(none, |acc, o| Cons(o.body.pos.y.toBits(), Cons(o.body.pos.x.toBits(), acc)))
|
|
53
|
-
mines := p.mines.fold(none, |acc, m| Cons(m.
|
|
53
|
+
mines := p.mines.fold(none, |acc, m| Cons(m.body.angle.toBits(), Cons(m.body.pos.x.toBits(), acc)))
|
|
54
54
|
Timing.hash(head.append(orbs.reverse()).append(mines.reverse()))
|
|
55
55
|
|
|
56
56
|
fun tickOnce(io: Io, g: Game, inp: Input, paint: Bool) -> Game =
|
compiler/checker/tests/checker/diagnostic_tests.rs
CHANGED
|
@@ -406,7 +406,7 @@ fn stepsOk(rest: &str) -> bool {
|
|
|
406
406
|
#[test]
|
|
407
407
|
fn stepsIsForAnActorStructHoldingActors() {
|
|
408
408
|
let es = stepsErrors("enum E[Actor, Steps] = A | B\n");
|
|
409
|
-
assert!(es.iter().any(|e| e.message.contains("`E` lists `Steps`, which steps a struct's
|
|
409
|
+
assert!(es.iter().any(|e| e.message.contains("`E` lists `Steps`, which steps a struct's fields, but it is an enum")), "{es:?}");
|
|
410
410
|
let es = stepsErrors("struct P[Steps](w: W)\n");
|
|
411
411
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
412
412
|
assert!(es[0].message.contains("`P` lists `Steps` but is not an `Actor`"), "{es:?}");
|
|
@@ -416,8 +416,13 @@ fn stepsIsForAnActorStructHoldingActors() {
|
|
|
416
416
|
assert!(es[0].message.contains("`P` is a screen and lists `Steps`: a screen's `stepped` is derived without it"), "{es:?}");
|
|
417
417
|
let es = stepsErrors("struct P[Actor, Steps](n: Int, ws: List<Int>) =\n fun step(self, dt: Float) -> P = self\n");
|
|
418
418
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
419
|
-
assert!(es[0].message.contains("`P` lists `Steps` but holds
|
|
419
|
+
assert!(es[0].message.contains("`P` lists `Steps` but holds nothing to step"), "{es:?}");
|
|
420
420
|
assert!(stepsOk("struct P[Screen](n: Int, ws: List<Int>) =\n fun name(self) -> Str = \"p\"\n"), "a screen holding no actors keeps the default `stepped`");
|
|
421
|
+
let body = "struct V(t: Float) =\n fun step(self, dt: Float) -> V = V(t: self.t + dt)\n\n";
|
|
422
|
+
assert!(stepsOk(&format!("{body}struct P[Actor, Steps](v: V)\n")), "a value with its own `step(dt) -> Self` is something to step");
|
|
423
|
+
assert!(stepsOk(&format!("{body}struct P[Screen](on: Bool, @stepsWhen(self.on) v: V) =\n fun name(self) -> Str = \"p\"\n")));
|
|
424
|
+
let es = stepsErrors("struct V(t: Float) =\n fun step(self, dt: Int) -> V = self\n\nstruct P[Actor, Steps](v: V)\n");
|
|
425
|
+
assert!(es.iter().any(|e| e.message.contains("`P` lists `Steps` but holds nothing to step")), "a `step` not of a `Float` is not one: {es:?}");
|
|
421
426
|
}
|
|
422
427
|
|
|
423
428
|
/// `[Show]` derives `toStr` only when each field of a type of the program can be shown.
|
|
@@ -435,7 +440,7 @@ fn showNeedsEachFieldShown() {
|
|
|
435
440
|
fn stepsWhenGoesOnAnActorFieldOfADerivedStepping() {
|
|
436
441
|
let es = stepsErrors("struct P[Screen](on: Bool, @stepsWhen(self.on) n: Int, w: W) =\n fun name(self) -> Str = \"p\"\n");
|
|
437
442
|
assert_eq!(es.len(), 1, "{es:?}");
|
|
438
|
-
assert!(es[0].message.contains("`@stepsWhen` on `P.n`, a `Int`: only a field holding
|
|
443
|
+
assert!(es[0].message.contains("`@stepsWhen` on `P.n`, a `Int`: only a field holding something to step is stepped"), "{es:?}");
|
|
439
444
|
assert_eq!((es[0].line, es[0].column), (12, 39), "{es:?}");
|
|
440
445
|
assert!(stepsOk("struct P[Screen](on: Bool, @stepsWhen(self.on) w: W) =\n fun name(self) -> Str = \"p\"\n"));
|
|
441
446
|
let es = stepsErrors("struct P(on: Bool, @stepsWhen(self.on) w: W)\n");
|
compiler/cli/tests/cli/game_in_place_test.rs
CHANGED
|
@@ -20,6 +20,13 @@
|
|
|
20
20
|
//! the head of the list it is stepped in (`List.head`, which std's read-only walks `all`,
|
|
21
21
|
//! `filter` and `next` hand to closures and results), where it was that copy and then one or
|
|
22
22
|
//! two in-place writes to it: the same allocation a step.
|
|
23
|
+
//!
|
|
24
|
+
//! Since the declarative bodies (2026-11-16) an actor's motion is a std `Body`: `Motion.spawn`
|
|
25
|
+
//! and `Place.rotateTo$unique` went with `Motion` and the ship's hand-written place; `Mine.spawn`
|
|
26
|
+
//! (its drifting body given its turn) and `Body.place` (the place made, then turned) are new; the
|
|
27
|
+
//! actors' own steps are one spread each, their bodies' steps joined to it by the derive.
|
|
28
|
+
//! `PlayingScreen.update`'s `Hit` reads the ship into a local before the spread, as `Caught`
|
|
29
|
+
//! does, so the ring made at its position doesn't read `self` after `ship` is written.
|
|
23
30
|
|
|
24
31
|
use std::collections::BTreeMap;
|
|
25
32
|
use std::process::Command;
|
|
@@ -76,7 +83,8 @@ fn orbitRunnerKeepsItsInPlaceSpreads() {
|
|
|
76
83
|
("PlayingScreen.stepped", 1),
|
|
77
84
|
("PlayingScreen.deal", 1),
|
|
78
85
|
("PlayingScreen.grown", 1),
|
|
79
|
-
("
|
|
86
|
+
("Mine.spawn", 1),
|
|
87
|
+
("Body.place", 1),
|
|
80
88
|
]);
|
|
81
89
|
assertKept("examples/games/orbitrunner/OrbitRunner.plum", &want);
|
|
82
90
|
}
|
|
@@ -84,6 +92,6 @@ fn orbitRunnerKeepsItsInPlaceSpreads() {
|
|
|
84
92
|
#[test]
|
|
85
93
|
fn balloonPopKeepsItsInPlaceSpreads() {
|
|
86
94
|
let mut want = TICK.to_vec();
|
|
87
|
-
want.
|
|
95
|
+
want.extend([("PlaygroundScreen.update", 1), ("Body.place", 1)]);
|
|
88
96
|
assertKept("examples/games/balloonpop/BalloonPop.plum", &want);
|
|
89
97
|
}
|
compiler/core/src/steps_derive.rs
CHANGED
|
@@ -1,34 +1,40 @@
|
|
|
1
|
-
//! The stepping of a struct's
|
|
1
|
+
//! The stepping of a struct's fields, derived: every `Screen`'s `stepped`, and the field
|
|
2
|
-
//!
|
|
2
|
+
//! stepping of an `Actor` that lists `[Steps]` (std/game/View).
|
|
3
3
|
//!
|
|
4
4
|
//! A screen, and an actor that lists `Steps`, gets, as an ordinary method written out here
|
|
5
|
-
//! before the checker sees it, the stepping of each field that holds
|
|
5
|
+
//! before the checker sees it, the stepping of each field that holds something to step: a
|
|
6
|
-
//! type is an `Actor` (a type that implements it, or a trait type that is one),
|
|
6
|
+
//! field whose type is an `Actor` (a type that implements it, or a trait type that is one),
|
|
7
|
+
//! a value whose type has its own `step(self, dt: Float) -> Self` (a std `Body`: found by
|
|
8
|
+
//! its type's name among the program's methods, as written, before checking), a `List` or
|
|
7
|
-
//!
|
|
9
|
+
//! an `Option` of either, or a `List<View>` (each `Actor` in it, through `Views.stepIn`: a
|
|
8
|
-
//!
|
|
10
|
+
//! type test per item, as the list holds views of any kind). Other fields are left as they
|
|
9
|
-
//! are
|
|
11
|
+
//! are. What is made is what a screen would write by hand, one static construction:
|
|
10
|
-
//! construction:
|
|
11
12
|
//!
|
|
12
13
|
//! fun stepped(self, dt: Float) -> PlayingScreen =
|
|
13
14
|
//! PlayingScreen(..self, ship: self.ship.step(dt), mines: Views.stepAll(self.mines, dt))
|
|
14
15
|
//!
|
|
16
|
+
//! (`Views.stepSome` for an `Option` of an actor, `map(|x| x.step(dt))` for a `List` or an
|
|
15
|
-
//!
|
|
17
|
+
//! `Option` of other values), so it costs what the hand-written one did.
|
|
16
18
|
//!
|
|
17
19
|
//! - On a `Screen` it is `stepped(dt)`, which a slice calls in its frame action and a plain
|
|
18
20
|
//! screen's tick is. It needs no `Steps`. A screen that writes its own `stepped` keeps it,
|
|
19
21
|
//! and one holding no actors keeps the default: nothing is derived.
|
|
20
22
|
//! - On an `Actor` that lists `Steps` it is part of `step`: the actor's own `step`, if it
|
|
21
|
-
//! writes one, runs first (it is renamed `step$own`), and then its
|
|
23
|
+
//! writes one, runs first (it is renamed `step$own`), and then its fields are stepped
|
|
22
|
-
//! (`step$fields`), so a container writes only what is special about itself
|
|
24
|
+
//! (`step$fields`), so a container writes only what is special about itself (a ship holding
|
|
23
|
-
//! fields' conditions see the actor after its own
|
|
25
|
+
//! a `Body` writes only its clock), and the fields' conditions see the actor after its own
|
|
26
|
+
//! step. When its own `step(self, dt)` is one spread of `self` that sets none of those
|
|
27
|
+
//! fields and no field has `@stepsWhen`, the fields' steps are added to that spread instead
|
|
28
|
+
//! (`Ship(..self, clock: self.clock + dt, body: self.body.step(dt))`): the same values, one
|
|
29
|
+
//! construction.
|
|
24
30
|
//! - `@stepsWhen(cond) name: T` steps that field only while `cond` (read on `self`) holds:
|
|
25
31
|
//! `if cond then <stepped> else self.name`.
|
|
26
32
|
//!
|
|
27
33
|
//! Errors: `Steps` on a screen (its `stepped` is derived without it), on an enum, on a
|
|
28
|
-
//! struct that is not an `Actor`, or on an actor with no field holding
|
|
34
|
+
//! struct that is not an `Actor`, or on an actor with no field holding something to step;
|
|
29
|
-
//! on a field that holds
|
|
35
|
+
//! `@stepsWhen` on a field that holds nothing to step, on an actor that doesn't list `Steps`
|
|
30
|
-
//! neither a screen nor an actor, or on a screen that writes its own
|
|
36
|
+
//! or a type that is neither a screen nor an actor, or on a screen that writes its own
|
|
31
|
-
//! attribute would do nothing).
|
|
37
|
+
//! `stepped` (the attribute would do nothing).
|
|
32
38
|
|
|
33
39
|
use std::collections::{HashMap, HashSet};
|
|
34
40
|
|
|
@@ -37,7 +43,7 @@ use crate::diag::{DiagKind, Diagnostic};
|
|
|
37
43
|
use crate::forms::mapExprs;
|
|
38
44
|
use crate::main_result::{parseItems, typeText};
|
|
39
45
|
|
|
40
|
-
/// The trait
|
|
46
|
+
/// The trait an actor lists to have its fields stepped.
|
|
41
47
|
pub const STEPS_TRAIT: &str = "Steps";
|
|
42
48
|
const ACTOR: &str = "Actor";
|
|
43
49
|
const SCREEN: &str = "Screen";
|
|
@@ -47,6 +53,8 @@ pub const OWN_STEP: &str = "step$own";
|
|
|
47
53
|
/// The stepping of an actor's fields, called by the derived `step` after `step$own`.
|
|
48
54
|
pub const FIELDS_STEP: &str = "step$fields";
|
|
49
55
|
const COND: &str = "stepsWhenDerived";
|
|
56
|
+
/// What a field holds to be stepped, for the errors.
|
|
57
|
+
const WHAT: &str = "an `Actor`, a value with its own `step(self, dt: Float) -> Self`, a `List` or an `Option` of either, or a `List<View>`";
|
|
50
58
|
|
|
51
59
|
#[derive(Clone, Copy)]
|
|
52
60
|
enum Holds {
|
|
@@ -56,6 +64,9 @@ enum Holds {
|
|
|
56
64
|
/// A `List<View>`: views of any kind, each `Actor` among them stepped
|
|
57
65
|
/// (`Views.stepIn`, a type test per item; a `Group` or an `Overlay` looked inside).
|
|
58
66
|
Views,
|
|
67
|
+
/// A `List` or an `Option` of values with their own `step` that are not actors
|
|
68
|
+
/// (`map`, as `Views.stepAll` wants actors).
|
|
69
|
+
Mapped,
|
|
59
70
|
}
|
|
60
71
|
|
|
61
72
|
/// Writes out each `[Steps]` struct's stepping (see the module doc) and empties every
|
|
@@ -98,13 +109,38 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
98
109
|
|| (supers.contains_key(name) && closure(vec![name.to_string()]).contains(ACTOR))
|
|
99
110
|
|| traitsOf.get(name).is_some_and(|ts| ts.contains(ACTOR))
|
|
100
111
|
};
|
|
112
|
+
// A value with its own `step(self, dt: Float) -> Self` that is not an actor (a `Body`):
|
|
113
|
+
// the derive steps it the same way, by its type's name, at compile time.
|
|
114
|
+
let steppables: HashSet<String> = source
|
|
115
|
+
.items
|
|
116
|
+
.iter()
|
|
117
|
+
.filter_map(|i| match i {
|
|
118
|
+
Item::Fn(f) if f.name == "step" && f.has_self => {
|
|
119
|
+
let ty = f.type_param.as_ref()?;
|
|
120
|
+
let args: Vec<&Param> = f.params.iter().filter(|p| p.name != "self").collect();
|
|
121
|
+
let float = args.len() == 1 && matches!(&args[0].ty, ParamType::Type(t) if t.name == "Float" && t.generics.is_empty());
|
|
122
|
+
let selfish = f.returns.as_ref().is_some_and(|r| r.name == *ty || r.name == "Self");
|
|
123
|
+
(float && selfish).then(|| ty.clone())
|
|
124
|
+
}
|
|
125
|
+
_ => None,
|
|
126
|
+
})
|
|
127
|
+
.collect();
|
|
128
|
+
let steps = |name: &str| !isActor(name) && steppables.contains(name);
|
|
101
129
|
let holds = |t: &Type| -> Option<Holds> {
|
|
130
|
+
let one = t.generics.len() == 1;
|
|
131
|
+
let inner = |h: Holds, g: Holds| {
|
|
102
|
-
|
|
132
|
+
if one && isActor(&t.generics[0].name) {
|
|
133
|
+
Some(h)
|
|
134
|
+
} else if one && steps(&t.generics[0].name) {
|
|
135
|
+
Some(g)
|
|
136
|
+
} else {
|
|
137
|
+
None
|
|
138
|
+
}
|
|
139
|
+
};
|
|
103
140
|
match t.name.as_str() {
|
|
104
|
-
"List" if
|
|
141
|
+
"List" if one && t.generics[0].name == VIEW => Some(Holds::Views),
|
|
105
|
-
"List" => inner(Holds::List),
|
|
106
|
-
"Option" => inner(Holds::Some_),
|
|
142
|
+
"List" | "Option" => inner(if t.name == "List" { Holds::List } else { Holds::Some_ }, Holds::Mapped),
|
|
107
|
-
n if isActor(n) => Some(Holds::One),
|
|
143
|
+
n if isActor(n) || steps(n) => Some(Holds::One),
|
|
108
144
|
_ => None,
|
|
109
145
|
}
|
|
110
146
|
};
|
|
@@ -115,6 +151,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
115
151
|
let mut errors: Vec<Diagnostic> = Vec::new();
|
|
116
152
|
let mut made: Vec<Item> = Vec::new();
|
|
117
153
|
let mut renames: Vec<String> = Vec::new();
|
|
154
|
+
let mut merges: Vec<(String, Vec<FieldArg>)> = Vec::new();
|
|
118
155
|
for item in &source.items {
|
|
119
156
|
let Item::Enum(e) = item else { continue };
|
|
120
157
|
let at = |line: usize, column: usize, msg: String| Diagnostic::new(DiagKind::Type, e.file.clone(), line, column, msg);
|
|
@@ -148,7 +185,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
148
185
|
}
|
|
149
186
|
if !e.isStruct() {
|
|
150
187
|
if steps {
|
|
151
|
-
errors.push(here(format!("`{name}` lists `Steps`, which steps a struct's
|
|
188
|
+
errors.push(here(format!("`{name}` lists `Steps`, which steps a struct's fields, but it is an enum")));
|
|
152
189
|
}
|
|
153
190
|
continue;
|
|
154
191
|
}
|
|
@@ -171,7 +208,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
171
208
|
errors.push(attrAt(
|
|
172
209
|
c,
|
|
173
210
|
format!(
|
|
174
|
-
"`@stepsWhen` on `{name}.{}`, a `{}`: only a field holding
|
|
211
|
+
"`@stepsWhen` on `{name}.{}`, a `{}`: only a field holding something to step is stepped ({WHAT})",
|
|
175
212
|
v.field_names[*i],
|
|
176
213
|
typeText(&v.fields[*i])
|
|
177
214
|
),
|
|
@@ -181,7 +218,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
181
218
|
if fields.is_empty() {
|
|
182
219
|
if steps {
|
|
183
220
|
errors.push(here(format!(
|
|
184
|
-
"`{name}` lists `Steps` but holds
|
|
221
|
+
"`{name}` lists `Steps` but holds nothing to step: no field is {WHAT}"
|
|
185
222
|
)));
|
|
186
223
|
}
|
|
187
224
|
continue;
|
|
@@ -214,6 +251,7 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
214
251
|
Holds::List => format!("Views.stepAll(self.{f}, dt)"),
|
|
215
252
|
Holds::Some_ => format!("Views.stepSome(self.{f}, dt)"),
|
|
216
253
|
Holds::Views => format!("Views.stepIn(self.{f}, dt)"),
|
|
254
|
+
Holds::Mapped => format!("self.{f}.map(|x| x.step(dt))"),
|
|
217
255
|
};
|
|
218
256
|
match c {
|
|
219
257
|
Some(c) => {
|
|
@@ -225,8 +263,20 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
225
263
|
})
|
|
226
264
|
.collect();
|
|
227
265
|
let body = format!("{name}(..self, {})", args.join(", "));
|
|
266
|
+
let ownSpread = conds.is_empty() && ownStepSpread(&source.items, name).is_some_and(|c| !c.fields.iter().any(|a| fields.iter().any(|(f, _, _)| *f == a.name)));
|
|
228
267
|
let text = if !actor {
|
|
229
268
|
format!("struct {ty} =\n fun stepped(self, dt: Float) -> {ty} = {body}\n")
|
|
269
|
+
} else if ownSpread {
|
|
270
|
+
// Its own `step` is one spread of `self` that leaves the stepped fields alone: the
|
|
271
|
+
// fields' steps join it, one construction (`Ship(..self, clock: .., body: self.body.step(dt))`).
|
|
272
|
+
for it in parseItems(&format!("struct {ty} =\n fun step(self, dt: Float) -> {ty} = {body}\n"), &e.file) {
|
|
273
|
+
if let Item::Fn(f) = it {
|
|
274
|
+
if let FnBody::Expr(Expr { kind: ExprKind::ClassCall(c), .. }) = f.body {
|
|
275
|
+
merges.push((name.clone(), c.fields));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
continue;
|
|
230
280
|
} else if hasMethod(&source.items, name, "step") {
|
|
231
281
|
renames.push(name.clone());
|
|
232
282
|
format!(
|
|
@@ -266,6 +316,14 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
266
316
|
Item::Fn(f) if f.name == "step" && f.has_self && f.type_param.as_ref().is_some_and(|t| renames.contains(t)) => {
|
|
267
317
|
f.name = OWN_STEP.to_string();
|
|
268
318
|
}
|
|
319
|
+
Item::Fn(f) if f.name == "step" && f.has_self && f.type_param.as_ref().is_some_and(|t| merges.iter().any(|(m, _)| m == t)) => {
|
|
320
|
+
let t = f.type_param.clone().unwrap_or_default();
|
|
321
|
+
if let FnBody::Expr(Expr { kind: ExprKind::ClassCall(c), .. }) = &mut f.body {
|
|
322
|
+
if let Some((_, more)) = merges.iter().find(|(m, _)| *m == t) {
|
|
323
|
+
c.fields.extend(more.iter().cloned());
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
269
327
|
Item::Enum(e) => {
|
|
270
328
|
for v in &mut e.variants {
|
|
271
329
|
v.field_steps_when.clear();
|
|
@@ -278,6 +336,22 @@ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
|
|
|
278
336
|
errors
|
|
279
337
|
}
|
|
280
338
|
|
|
339
|
+
/// An actor's own `step(self, dt)` when it is one spread of `self`, `T(..self, ..)`: the
|
|
340
|
+
/// construction (the fields' steps it is joined with read `dt`).
|
|
341
|
+
fn ownStepSpread<'a>(items: &'a [Item], name: &str) -> Option<&'a ClassCall> {
|
|
342
|
+
items.iter().find_map(|i| match i {
|
|
343
|
+
Item::Fn(f) if f.name == "step" && f.has_self && f.type_param.as_deref() == Some(name) && f.params.iter().any(|p| p.name == "dt") => match &f.body {
|
|
344
|
+
FnBody::Expr(Expr { kind: ExprKind::ClassCall(c), .. })
|
|
345
|
+
if c.type_name == name && c.spread.as_ref().is_some_and(|s| matches!(&s.kind, ExprKind::Self_) || matches!(&s.kind, ExprKind::Var(v) if v == "self")) =>
|
|
346
|
+
{
|
|
347
|
+
Some(c)
|
|
348
|
+
}
|
|
349
|
+
_ => None,
|
|
350
|
+
},
|
|
351
|
+
_ => None,
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
|
|
281
355
|
/// The generated text spells `step$own` and `step$fields` as identifiers the grammar takes.
|
|
282
356
|
fn fixName(n: &str) -> String {
|
|
283
357
|
match n {
|
docs/game.md
CHANGED
|
@@ -145,16 +145,22 @@ trait Actor[View] = # acts: state that advan
|
|
|
145
145
|
`place` is its `Place` (`std/game/Place`: position, rotation, scale, the origin it turns about and its `alpha`); `view` is what is under it, ready-made items placed in its coordinates; `visible` hides it, with what is under it, from the draw and from presses; `paintSelf` is what it draws itself, before its view, for what no ready-made view draws (an additive glow, a line): it draws with `Gfx` through `m`, its own coordinates to the world's, at `alpha` (Orbit Runner's `Orb`, Balloon Pop's `Balloon`, whose string is a line). Its other fields are plain and public. `step` returns the actor's next version, `dt` seconds on. The ready-made views (`Group`, `Box`, `Circle`, `Sprite`, `Label`, `Overlay`) are stateless and never stepped.
|
|
146
146
|
|
|
147
147
|
```plum
|
|
148
|
-
struct Mine[Actor
|
|
148
|
+
struct Mine[Actor, Round, Steps](body: Body, clock: Float = 0.0, tex: Texture) =
|
|
149
|
-
fun place(self) -> Place =
|
|
149
|
+
fun place(self) -> Place = self.body.place(Sheet.Pivot)
|
|
150
150
|
|
|
151
151
|
fun view(self) -> List<View> =
|
|
152
152
|
[Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
|
|
153
153
|
|
|
154
|
-
fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt
|
|
154
|
+
fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt)
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
-
|
|
157
|
+
Its motion is a `Body` (below), which `Steps` steps for it: its own `step` is its clock.
|
|
158
|
+
|
|
159
|
+
**Bodies.** How a thing moves is declared, not written per axis: a `Body` (`std/game/Body`) is its position `pos` (the point it turns about), `vel`, `push` (an acceleration: a ship's thrust), `drag` (the share of the velocity lost a second), `edge` (what it does at the sides of a box: `Free`, `Halt(box)`, stop there, that axis's velocity gone, `Bounce(box)`, that axis's velocity turned, or `Wrap(box)`, in at the other side), `angle`, which turns at `turn` radians a second, and `faceAbove: Option<Float>`, which turns it to face its motion while it is faster than that (0 is facing up, -y, turning clockwise: a sprite drawn pointing up). Its `step(dt)` is written once, in std: pushed, slowed, moved, held to its edges, turned. `body.place(origin)` is where to draw it: turned by its angle about `origin` (in the drawing's coordinates), which lands on `pos`, so `Place.pivot()` is `pos` and `Round`'s `touches` reads the body's position. Orbit Runner's ship is `Body(pos: .., drag: Ship.Drag, edge: Halt(box: Arena.inside(Ship.Radius)), faceAbove: Some(20.0))` and its steering sets `push`; an orb or a mine drifts with `edge: Bounce(box: Arena.inside(r))` (`Arena.drift(dice, near, gap, speed, r)` deals one away from the ship), a mine with `turn: 2.0`; a balloon rises at its `vel`, and stops where it bursts (its body made again with no velocity).
|
|
160
|
+
|
|
161
|
+
**Timers are moments.** Nothing counts down: a ship hit is hurt until a moment on its own clock, `hurtFor(t)` is `Ship(..self, hurtUntil: self.clock + t)` and `hurt()` is `self.clock < self.hurtUntil`, as a balloon keeps `poppedAt` and Balloon Pop's party `partyAt`.
|
|
162
|
+
|
|
163
|
+
**Stepping.** There is no stepping phase: the frame reaches a slice screen as an action (`OnFrame(|dt| Tick(dt: dt))`), and its `update` steps its actors there with `stepped(dt)`, then runs its rules on what has moved. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen's own fields are stepped. Every screen has its `stepped` derived by the compiler (it lists nothing for it): each field that is an `Actor`, a value whose type has its own `step(self, dt: Float) -> Self` (a `Body`), a `List` of either (of one type, or of a trait type that is an `Actor`), an `Option` of one or a `List<View>` is stepped, and the other fields are as they are. `@stepsWhen(cond)` before a field steps it only while `cond`, read on `self`, holds. Orbit Runner's:
|
|
158
164
|
|
|
159
165
|
```plum
|
|
160
166
|
struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
@@ -174,7 +180,7 @@ fun stepped(self, dt: Float) -> PlayingScreen =
|
|
|
174
180
|
rings: Views.stepAll(self.rings, dt))
|
|
175
181
|
```
|
|
176
182
|
|
|
177
|
-
and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`, `Views.stepIn` for a `List<View>`), not a walk at run time, so it costs what the hand-written one did. A screen that writes its own `stepped` keeps it; one holding no actors keeps the default, the screen as it is. Its frame action calls it:
|
|
183
|
+
and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list of actors, `Views.stepSome` for an `Option` of one, `map(|x| x.step(dt))` for a `List` or an `Option` of other values, `Views.stepIn` for a `List<View>`), not a walk at run time, so it costs what the hand-written one did. A screen that writes its own `stepped` keeps it; one holding no actors keeps the default, the screen as it is. Its frame action calls it:
|
|
178
184
|
|
|
179
185
|
```plum
|
|
180
186
|
fun update(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
@@ -187,18 +193,18 @@ fun update(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
|
187
193
|
|
|
188
194
|
so a screen that doesn't call it steps nothing, and one that pauses (a menu over the play) skips the call. A plain screen (no slice) has no actions: its tick is its `stepped`. An `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick.
|
|
189
195
|
|
|
190
|
-
An actor that lists `Steps` (`std/game/View`) has
|
|
196
|
+
An actor that lists `Steps` (`std/game/View`) has the same fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. When its own `step(self, dt)` is one spread of `self` that sets none of those fields and none has `@stepsWhen`, the fields' steps join that spread instead, one construction: Orbit Runner's ship writes `Ship(..self, clock: self.clock + dt)` and is compiled as `Ship(..self, clock: self.clock + dt, body: self.body.step(dt))`. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds (clicks' `Ball[Actor, Steps](body: Body)`). An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field is stepped with `Views.stepIn`: it holds views of any kind, so each item is tested for being an `Actor` (or a `Group` or an `Overlay`) as it is stepped, the one place the stepping looks at an item's type at run time (`benchmarks/screen_views/scale.plum`'s `CrowdScreen`, 10,000 actors in a `List<View>`). An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not.
|
|
191
197
|
|
|
192
198
|
Once Orbit Runner's run is over its ship, orbs and mines stand still under the game over panel, while the stars, which read the screen's clock, keep twinkling, and the ship is left out of the view; the rings, with no condition, step on, so the ripple of the last hit grows on under the panel.
|
|
193
199
|
|
|
194
|
-
`Steps` is an error on a screen (its `stepped` is derived without it), on an enum, on a struct that is not an `Actor`, and on an actor with no field holding
|
|
200
|
+
`Steps` is an error on a screen (its `stepped` is derived without it), on an enum, on a struct that is not an `Actor`, and on an actor with no field holding something to step; `@stepsWhen` is an error on a field that holds nothing to step, on a struct that is neither a screen nor a `[Steps]` actor, and on a screen that writes its own `stepped` (it would do nothing).
|
|
195
201
|
|
|
196
202
|
What else a view is, it says with a small trait:
|
|
197
203
|
|
|
198
204
|
| Trait | What it says |
|
|
199
205
|
|---|---|
|
|
200
206
|
| `Actor` (`std/game/View`) | `step(self, dt) -> Self`: its next version `dt` seconds on, which the screen's `stepped` keeps |
|
|
201
|
-
| `Steps` (`std/game/View`) | nothing to write: on an actor the compiler steps its
|
|
207
|
+
| `Steps` (`std/game/View`) | nothing to write: on an actor the compiler steps its fields holding actors or bodies after its `step` (above); `@stepsWhen(cond)` on a field. A screen needs none |
|
|
202
208
|
| `Sized` (`std/game/Sized`) | `bounds(self) -> Aabb`, the box it covers in its own coordinates. A view with bounds can be hit; one without cannot. `hit(self, p) -> Bool` is inside the bounds, edges included, unless the view says otherwise for an exact shape (`Circle` is hit inside its circle; a balloon on its body, its knot and its string). Culling goes by the bounds too |
|
|
203
209
|
| `Round` (`std/game/Round`) | `radius(self) -> Float`: it is the circle of that radius about its pivot (`Place.pivot`). `touches(self, other: Round) -> Bool`, given, is whether the two circles overlap (closer than the sum of the radii, centre to centre) |
|
|
204
210
|
| `Touch` (`std/game/Touch`) | `touch(self) -> Touchable`: whether it takes presses. `Enabled`: it is hit where it is (when it is `Sized`) and what is under it is; `Disabled`: neither it nor anything under it is hit; `ChildrenOnly`: what is under it is, it is not. A view that says nothing is `ChildrenOnly` |
|
|
@@ -397,13 +403,13 @@ Several subscriptions may answer one event, each in the order listed. Then the t
|
|
|
397
403
|
```plum
|
|
398
404
|
fun rules(self) -> List<PlayAction> = [
|
|
399
405
|
..self.orbs.filter(|o| self.ship.touches(o)).map(|o| Caught(orb: o.id))
|
|
400
|
-
if self.ship.hurt
|
|
406
|
+
if !self.ship.hurt() && self.mines.any(|m| self.ship.touches(m)) then Hit
|
|
401
407
|
]
|
|
402
408
|
```
|
|
403
409
|
|
|
404
410
|
so two orbs caught in one tick are two `Caught` actions (each scored, and that orb respawned, in `update`), and mines touching the ship are one `Hit`. The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). The game keeps the screen it had (its screens, and the ones a rewind starts from), so the fold starts from a copy of it (`@copy`, one a tick delivered, [language.md](language.md#copies)): the copy is the fold's alone, and each `update` of the tick updates it in place, Orbit Runner's steering, frame, scoring, hits and start over among them (a sound read from the screen is read before the spread: `sounds := self.assets`). A test calls `update` itself: `s.update(Keyed).then`, `s.update(a).state`. An action enum that lists `Show` (std/Str) has its `toStr` derived, so a test can compare the actions sent as text (`"Steer(1.0, -1.0) Tick(0.016) Caught(0)"`). How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
|
|
405
411
|
|
|
406
|
-
Orbit Runner steers with `h.axis`: `Steer(ax: {h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`. What the rules need of geometry is std's: an actor that lists `Round` (`std/game/Round`) declares its `radius()`, and is the circle of that radius about its pivot (`Place.pivot`, the point its place turns about, whatever its rotation and scale), so `a.touches(b)` is whether two round actors overlap, with no positions copied out by hand; `Vec2.near(other, dist)` (closer than `dist`) is the test under it. Orbit Runner's ship, orbs and mines are `Round`. An actor that appears somewhere new makes itself: `Orb.spawn(id, dice, near, tex)` and `Mine.spawn(dice, near, tex)` return the actor, placed away from the ship by the draws of `dice` (an orb keeps its `id`, which its `Caught` names and its respawn reuses).
|
|
412
|
+
Orbit Runner steers with `h.axis`: `Steer(ax: {h.axis(Key.Left, Key.Right) + h.axis(Key.KeyA, Key.KeyD)}.max(-1.0).min(1.0), ..)`. What the rules need of geometry is std's: an actor that lists `Round` (`std/game/Round`) declares its `radius()`, and is the circle of that radius about its pivot (`Place.pivot`, the point its place turns about, whatever its rotation and scale), so `a.touches(b)` is whether two round actors overlap, with no positions copied out by hand; `Vec2.near(other, dist)` (closer than `dist`) is the test under it. Orbit Runner's ship, orbs and mines are `Round`, each the circle about its body's position. An actor that appears somewhere new makes itself: `Orb.spawn(id, dice, near, tex)` and `Mine.spawn(dice, near, tex)` return the actor, its body placed away from the ship by the draws of `dice` (an orb keeps its `id`, which its `Caught` names and its respawn reuses).
|
|
407
413
|
|
|
408
414
|
## Clicks
|
|
409
415
|
|
docs/plans/2026-11-13-std-game-review.md
CHANGED
|
@@ -49,3 +49,4 @@ Objects decide their own collisions (option A): `Meets<Other, A>` with `meets(se
|
|
|
49
49
|
- `Vec2` fields (`vel`, `thrust`) instead of x/y pairs; vector operators.
|
|
50
50
|
- Timers as moments (`hurtUntil`, `hurt()` = `clock < hurtUntil`) instead of countdowns.
|
|
51
51
|
- The `[Steps]` derive steps a `Body` field (any steppable value, not only actors), so `Ship.step` only advances `clock`; Orb/Mine `Motion`/`drifted`/bounce become a `Body` with `bounceAtEdges`; Balloon Pop where it fits.
|
|
52
|
+
- Done on `sl/body`: `struct Body(pos: Vec2, vel = Vec2.Zero, push = Vec2.Zero, drag = 0.0, edge: Walls = Free, angle = 0.0, turn = 0.0, faceAbove: Option<Float> = None)` in std/game/Body with `step(dt)` (push, drag, move, edges, then the angle: faces its motion above `faceAbove`, 0 up and clockwise, else turns at `turn`) and `place(origin)` (pivot on `pos`, rotated by `angle`); `enum Walls = Free | Halt(box: Aabb) | Bounce(box: Aabb) | Wrap(box: Aabb)` (the box is the edge's, so no `bounds` beside it; `Edge` and `Stop` were taken by the screen slide and `Cmd.Stop`; std's `Aabb` is the rect); the derive steps any field whose type has `step(self, dt: Float) -> Self` (found by name before checking, still a static construction; a `List`/`Option` of such values by `map`), and joins a `[Steps]` actor's fields to its own `step` when that is one spread of `self` not setting them and there is no `@stepsWhen` (one construction, no `step$own`/`step$fields`); games: the ship is `Ship[Actor, Round, Steps](tex, body, hurtUntil, clock)`, `step` its clock only, `steer(dir: Vec2)` sets `push`, `hurt()` is `clock < hurtUntil`; orbs and mines hold a bouncing `Body` from `Arena.drift(dice, near, gap, speed, r)` (`Motion` gone; positions are centres, so the arena clamp no longer lets the ship hang 14 px off the right and bottom), a mine `turn: 2.0`; `Ring(pos: Vec2)`; Balloon Pop's balloon a rising `Body` (its x/y/speed gone, popping makes a still body), clicks' `Ball[Actor, Steps](body: Body)` with no `step`. Orbit Runner's checksum 181767343 to 166413027; the scripted runs of the replay tests moved to seed 44 (43 no longer loses a life in 600 ticks, 42 no game over in 900); orbit update 13.85 to 15.34 ms, paint 143.9 to 149.4 ms (medians of 5: two `Vec2`s and a `Place` a body; `Body.landed` not in place as the ship's `@stepsWhen` field is passed on conditionally); in place: all kept, `Motion.spawn` and `Place.rotateTo$unique` gone, `Mine.spawn` and `Body.place` new (`Hit` reads the ship into a local first).
|
docs/std.md
CHANGED
|
@@ -273,7 +273,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
|
|
|
273
273
|
|
|
274
274
|
## Game screens and slices
|
|
275
275
|
|
|
276
|
-
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which a screen steps through its `stepped(dt)`, derived for every screen from its fields holding actors, a `List<View>` among them), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), in the Elm style: its fields are its state, `A` its actions, `update(self, a) -> Next<Self, A>` its one entry point (pure, with no `Io`, so the same actions from the same state give the same state), returning the next screen with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. Its `subscriptions(self) -> List<Sub<A>>` say which of each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) and which frames become its actions: `OnFrame(|dt| ..)`, `OnKeyDown(key:, act:)`, `OnKeyUp`, `OnHeld(|h| ..)`, `OnWheel`, `OnPointerDown`, `OnPointerUp`, `OnPointerMove`, read once a tick; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default. The frame is an action: the screen steps its actors in it. std keeps the screen each `update` returns. An actor that lists `Round` (`std/game/Round`) declares its `radius()` and is that circle about its pivot (`Place.pivot`, the point its place turns about), and `a.touches(b)` is whether two round actors overlap; under it, `Vec2.near(other, dist)` (`std/math/Vec2`) is the overlap test of two circles (`a.near(b, ra + rb)`). A run records as a `Replay` (`std/game/Replay`: the seed and a `List<Input>`, one a tick). All of it is in [the game engine](game.md).
|
|
276
|
+
A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which a screen steps through its `stepped(dt)`, derived for every screen from its fields holding actors, a `List<View>` among them), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), in the Elm style: its fields are its state, `A` its actions, `update(self, a) -> Next<Self, A>` its one entry point (pure, with no `Io`, so the same actions from the same state give the same state), returning the next screen with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. Its `subscriptions(self) -> List<Sub<A>>` say which of each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) and which frames become its actions: `OnFrame(|dt| ..)`, `OnKeyDown(key:, act:)`, `OnKeyUp`, `OnHeld(|h| ..)`, `OnWheel`, `OnPointerDown`, `OnPointerUp`, `OnPointerMove`, read once a tick; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default. The frame is an action: the screen steps its actors in it. std keeps the screen each `update` returns. An actor's motion is a `Body` (`std/game/Body`): `pos`, `vel`, `push`, `drag`, `edge` (`Free`, `Halt(box)`, `Bounce(box)`, `Wrap(box)`, a `Walls`), `angle`, `turn` and `faceAbove`, declared, with `step(dt)` written once in std and `place(origin)` where to draw it; a field holding one is stepped by the screen's derived `stepped` or an actor's `Steps` (any field whose type has `step(self, dt: Float) -> Self`). An actor that lists `Round` (`std/game/Round`) declares its `radius()` and is that circle about its pivot (`Place.pivot`, the point its place turns about), and `a.touches(b)` is whether two round actors overlap; under it, `Vec2.near(other, dist)` (`std/math/Vec2`) is the overlap test of two circles (`a.near(b, ra + rb)`). A run records as a `Replay` (`std/game/Replay`: the seed and a `List<Input>`, one a tick). All of it is in [the game engine](game.md).
|
|
277
277
|
|
|
278
278
|
```plum
|
|
279
279
|
import std/Int
|
examples/games/balloonpop/actors/Balloon.plum
CHANGED
|
@@ -14,6 +14,7 @@ import std/math/Math
|
|
|
14
14
|
import std/game/Color
|
|
15
15
|
import std/game/Gfx
|
|
16
16
|
import std/game/Place
|
|
17
|
+
import std/game/Body
|
|
17
18
|
import std/game/View
|
|
18
19
|
import std/game/Circle
|
|
19
20
|
import std/game/Label
|
|
@@ -23,8 +24,8 @@ import std/game/Button
|
|
|
23
24
|
import BalloonPop
|
|
24
25
|
import screens/PlaygroundScreen
|
|
25
26
|
|
|
26
|
-
struct Balloon[Actor, Sized, Touch, Presses<PopAction>](
|
|
27
|
+
struct Balloon[Actor, Sized, Touch, Presses<PopAction>, Steps](
|
|
27
|
-
id: Int,
|
|
28
|
+
id: Int, body: Body, hue: Int = 0, phase: Float = 0.0, clock: Float = 0.0, poppedAt: Float = -1.0) =
|
|
28
29
|
const Radius = 40.0
|
|
29
30
|
const MinSpeed = 35.0
|
|
30
31
|
const MaxSpeed = 70.0
|
|
@@ -32,23 +33,22 @@ struct Balloon[Actor, Sized, Touch, Presses<PopAction>](
|
|
|
32
33
|
const FirstId = 100
|
|
33
34
|
|
|
34
35
|
fun spawn(id: Int, dice: Random, depth: Float, clock: Float) -> Balloon =
|
|
36
|
+
speed := Balloon.MinSpeed + dice.floatAt(1) * {Balloon.MaxSpeed - Balloon.MinSpeed}
|
|
35
37
|
Balloon(
|
|
36
|
-
id: id, x: 60.0 + dice.floatAt(0) * {Arena.W - 120.0}, y: Arena.H + Balloon.Radius + depth,
|
|
38
|
+
id: id, body: Body(pos: Vec2(x: 60.0 + dice.floatAt(0) * {Arena.W - 120.0}, y: Arena.H + Balloon.Radius + depth), vel: Vec2(x: 0.0, y: 0.0 - speed)),
|
|
37
|
-
speed: Balloon.MinSpeed + dice.floatAt(1) * {Balloon.MaxSpeed - Balloon.MinSpeed}, hue: dice.intBelowAt(2, Hue.All.length()),
|
|
38
|
-
phase: dice.floatAt(0) * Float.Tau, clock: clock)
|
|
39
|
+
hue: dice.intBelowAt(2, Hue.All.length()), phase: dice.floatAt(0) * Float.Tau, clock: clock)
|
|
39
40
|
|
|
40
|
-
fun place(self) -> Place = Place.at(self.drawnX(), self.y)
|
|
41
|
+
fun place(self) -> Place = Place.at(self.drawnX(), self.body.pos.y)
|
|
41
42
|
|
|
42
|
-
fun pop(self) -> Balloon = Balloon(..self, x: self.drawnX(), poppedAt: self.clock)
|
|
43
|
+
fun pop(self) -> Balloon = Balloon(..self, body: Body(pos: Vec2(x: self.drawnX(), y: self.body.pos.y)), poppedAt: self.clock)
|
|
43
44
|
|
|
44
45
|
fun popped(self) -> Bool = self.poppedAt >= 0.0
|
|
45
46
|
|
|
46
|
-
fun drawnX(self) -> Float = if self.popped() then self.x else self.x + 14.0 * Math.sin(self.clock * 1.3 + self.phase)
|
|
47
|
+
fun drawnX(self) -> Float = if self.popped() then self.body.pos.x else self.body.pos.x + 14.0 * Math.sin(self.clock * 1.3 + self.phase)
|
|
47
48
|
|
|
48
|
-
fun step(self, dt: Float) -> Balloon =
|
|
49
|
+
fun step(self, dt: Float) -> Balloon = Balloon(..self, clock: self.clock + dt)
|
|
49
|
-
Balloon(..self, clock: self.clock + dt, y: if self.popped() then self.y else self.y - self.speed * dt)
|
|
50
50
|
|
|
51
|
-
fun done(self) -> Bool = self.y < 0.0 - Balloon.Radius * 3.0 || {self.popped() && self.clock - self.poppedAt > Balloon.PopTime}
|
|
51
|
+
fun done(self) -> Bool = self.body.pos.y < 0.0 - Balloon.Radius * 3.0 || {self.popped() && self.clock - self.poppedAt > Balloon.PopTime}
|
|
52
52
|
|
|
53
53
|
fun stringX(self) -> Float = 6.0 * Math.sin(self.clock * 3.0 + self.phase)
|
|
54
54
|
|
examples/games/clicks.plum
CHANGED
|
@@ -9,6 +9,7 @@ import std/math/Vec2
|
|
|
9
9
|
import std/game/Color
|
|
10
10
|
import std/game/Input
|
|
11
11
|
import std/game/Place
|
|
12
|
+
import std/game/Body
|
|
12
13
|
import std/game/View
|
|
13
14
|
import std/game/Box
|
|
14
15
|
import std/game/Button
|
|
@@ -23,18 +24,16 @@ import std/App
|
|
|
23
24
|
|
|
24
25
|
enum TapAction = Tapped | Push(dx: Float) | Tick(dt: Float) | Quit
|
|
25
26
|
|
|
26
|
-
struct Ball[Actor](
|
|
27
|
+
struct Ball[Actor, Steps](body: Body) =
|
|
27
|
-
fun place(self) -> Place = Place.at(self.x, self.y)
|
|
28
|
+
fun place(self) -> Place = Place.at(self.body.pos.x, self.body.pos.y)
|
|
28
29
|
|
|
29
30
|
fun view(self) -> List<View> = [Circle(r: 10.0, color: Color.Yellow)]
|
|
30
31
|
|
|
31
|
-
fun push(self, vx: Float) -> Ball = Ball(..self,
|
|
32
|
+
fun push(self, vx: Float) -> Ball = Ball(body: Body(..self.body, vel: Vec2(x: vx, y: 0.0)))
|
|
32
|
-
|
|
33
|
-
fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
|
|
34
33
|
|
|
35
34
|
struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
36
35
|
fun start() -> TapScreen =
|
|
37
|
-
TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0
|
|
36
|
+
TapScreen(taps: 0, ball: Ball(body: Body(pos: Vec2(x: 20.0, y: 150.0))))
|
|
38
37
|
|
|
39
38
|
fun name(self) -> Str = "tap"
|
|
40
39
|
|
examples/games/orbitrunner/OrbitRunner.plum
CHANGED
|
@@ -9,6 +9,8 @@ import std/collections/List
|
|
|
9
9
|
import std/math/Random
|
|
10
10
|
import std/math/Math
|
|
11
11
|
import std/math/Vec2
|
|
12
|
+
import std/math/Aabb
|
|
13
|
+
import std/game/Body
|
|
12
14
|
import std/game/Gfx
|
|
13
15
|
import std/game/Audio
|
|
14
16
|
import std/game/Screen
|
|
@@ -20,35 +22,22 @@ primitive Arena =
|
|
|
20
22
|
const W = 800.0
|
|
21
23
|
const H = 600.0
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
fun inside(r: Float) -> Aabb = Aabb(min: Vec2(x: r, y: r), max: Vec2(x: Arena.W - r, y: Arena.H - r))
|
|
24
|
-
const Cell = 16.0
|
|
25
|
-
const Size = 48.0
|
|
26
26
|
|
|
27
|
-
struct Motion(x: Float, y: Float, vx: Float, vy: Float) =
|
|
28
|
-
fun
|
|
27
|
+
fun drift(dice: Random, near: Vec2, gap: Float, speed: Float, r: Float) -> Body =
|
|
29
28
|
heading := dice.floatAt(0) * Float.Tau
|
|
30
29
|
pace := speed * {0.4 + 0.6 * dice.floatAt(1)}
|
|
31
|
-
|
|
30
|
+
Body(pos: Arena.spot(dice, near, gap, 0), vel: Vec2(x: Math.cos(heading), y: Math.sin(heading)) * pace, edge: Bounce(box: Arena.inside(r)))
|
|
32
31
|
|
|
33
|
-
fun spot(dice: Random, near: Vec2, gap: Float, n: Int) ->
|
|
32
|
+
fun spot(dice: Random, near: Vec2, gap: Float, n: Int) -> Vec2 =
|
|
34
|
-
margin :=
|
|
33
|
+
margin := 54.0
|
|
35
|
-
|
|
34
|
+
p := Vec2(x: margin + dice.floatAt(2 + 2 * n) * {Arena.W - 2.0 * margin}, y: margin + dice.floatAt(3 + 2 * n) * {Arena.H - 2.0 * margin})
|
|
36
|
-
y := margin + dice.floatAt(3 + 2 * n) * {Arena.H - 2.0 * margin}
|
|
37
|
-
if n >= 19 || !
|
|
35
|
+
if n >= 19 || !p.near(near, gap) then p else Arena.spot(dice, near, gap, n + 1)
|
|
38
|
-
Motion(x: x, y: y, vx: 0.0, vy: 0.0)
|
|
39
|
-
else
|
|
40
|
-
Motion.spot(dice, near, gap, n + 1)
|
|
41
36
|
|
|
42
|
-
|
|
37
|
+
primitive Sheet =
|
|
43
|
-
|
|
38
|
+
const Cell = 16.0
|
|
44
|
-
|
|
39
|
+
const Size = 48.0
|
|
45
|
-
|
|
40
|
+
const Pivot = Vec2(x: 24.0, y: 24.0)
|
|
46
|
-
bounceY := y0 < r || y0 > Arena.H - r
|
|
47
|
-
Motion(
|
|
48
|
-
x: if bounceX then x0.max(r).min(Arena.W - r) else x0,
|
|
49
|
-
y: if bounceY then y0.max(r).min(Arena.H - r) else y0,
|
|
50
|
-
vx: if bounceX then 0.0 - self.vx else self.vx,
|
|
51
|
-
vy: if bounceY then 0.0 - self.vy else self.vy)
|
|
52
41
|
|
|
53
42
|
struct Assets(sheet: Texture, pickup: Sound, hit: Sound, over: Sound, music: Sound) =
|
|
54
43
|
const MusicVolume = 0.3
|
examples/games/orbitrunner/actors/Mine.plum
CHANGED
|
@@ -6,24 +6,25 @@ import std/collections/List
|
|
|
6
6
|
import std/math/Math
|
|
7
7
|
import std/math/Random
|
|
8
8
|
import std/game/Place
|
|
9
|
+
import std/game/Body
|
|
9
10
|
import std/game/View
|
|
10
11
|
import std/game/Sprite
|
|
11
12
|
import std/game/Round
|
|
12
13
|
import OrbitRunner
|
|
13
14
|
import actors/Ship
|
|
14
15
|
|
|
15
|
-
struct Mine[Actor, Round](
|
|
16
|
+
struct Mine[Actor, Round, Steps](body: Body, clock: Float = 0.0, tex: Texture) =
|
|
16
17
|
const Radius = 11.0
|
|
17
18
|
|
|
18
|
-
fun spawn(dice: Random, near: Ship, tex: Texture) -> Mine = Mine(
|
|
19
|
+
fun spawn(dice: Random, near: Ship, tex: Texture) -> Mine = Mine(body: Body(..Arena.drift(dice, near.body.pos, 220.0, 90.0, Mine.Radius), turn: 2.0), tex: tex)
|
|
19
20
|
|
|
20
21
|
fun radius(self) -> Float = Mine.Radius
|
|
21
22
|
|
|
22
23
|
fun countFor(score: Int) -> Int = {3 + score / 50}.min(8)
|
|
23
24
|
|
|
24
|
-
fun place(self) -> Place =
|
|
25
|
+
fun place(self) -> Place = self.body.place(Sheet.Pivot)
|
|
25
26
|
|
|
26
27
|
fun view(self) -> List<View> =
|
|
27
28
|
[Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
|
|
28
29
|
|
|
29
|
-
fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt
|
|
30
|
+
fun step(self, dt: Float) -> Mine = Mine(..self, clock: self.clock + dt)
|
examples/games/orbitrunner/actors/Orb.plum
CHANGED
|
@@ -11,26 +11,27 @@ import std/math/Random
|
|
|
11
11
|
import std/game/Color
|
|
12
12
|
import std/game/Gfx
|
|
13
13
|
import std/game/Place
|
|
14
|
+
import std/game/Body
|
|
14
15
|
import std/game/View
|
|
15
16
|
import std/game/Sprite
|
|
16
17
|
import std/game/Round
|
|
17
18
|
import OrbitRunner
|
|
18
19
|
import actors/Ship
|
|
19
20
|
|
|
20
|
-
struct Orb[Actor, Round](id: Int,
|
|
21
|
+
struct Orb[Actor, Round, Steps](id: Int, body: Body, clock: Float = 0.0, tex: Texture) =
|
|
21
22
|
const Radius = 10.0
|
|
22
23
|
const Points = 10
|
|
23
24
|
|
|
24
|
-
fun spawn(id: Int, dice: Random, near: Ship, tex: Texture) -> Orb = Orb(id: id,
|
|
25
|
+
fun spawn(id: Int, dice: Random, near: Ship, tex: Texture) -> Orb = Orb(id: id, body: Arena.drift(dice, near.body.pos, 120.0, 40.0, Orb.Radius), tex: tex)
|
|
25
26
|
|
|
26
27
|
fun radius(self) -> Float = Orb.Radius
|
|
27
28
|
|
|
28
|
-
fun place(self) -> Place =
|
|
29
|
+
fun place(self) -> Place = self.body.place(Sheet.Pivot)
|
|
29
30
|
|
|
30
31
|
fun view(self) -> List<View> =
|
|
31
32
|
[Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock + Float(self.id) * 0.1, 8.0, 4))]
|
|
32
33
|
|
|
33
|
-
fun step(self, dt: Float) -> Orb = Orb(..self, clock: self.clock + dt
|
|
34
|
+
fun step(self, dt: Float) -> Orb = Orb(..self, clock: self.clock + dt)
|
|
34
35
|
|
|
35
36
|
fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
|
|
36
37
|
c := m.apply(Vec2(x: Sheet.Size / 2.0, y: Sheet.Size / 2.0))
|
examples/games/orbitrunner/actors/Ring.plum
CHANGED
|
@@ -4,18 +4,17 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/collections/List
|
|
7
|
+
import std/math/Vec2
|
|
7
8
|
import std/game/Color
|
|
8
9
|
import std/game/Place
|
|
9
10
|
import std/game/View
|
|
10
11
|
import std/game/Circle
|
|
11
12
|
|
|
12
|
-
struct Ring[Actor](
|
|
13
|
+
struct Ring[Actor](pos: Vec2, age: Float = 0.0) =
|
|
13
14
|
const Reach = 40.0
|
|
14
15
|
const Secs = 0.4
|
|
15
16
|
|
|
16
|
-
fun at(x: Float, y: Float) -> Ring = Ring(x: x, y: y, age: 0.0)
|
|
17
|
-
|
|
18
|
-
fun place(self) -> Place = Place.at(self.x, self.y)
|
|
17
|
+
fun place(self) -> Place = Place.at(self.pos.x, self.pos.y)
|
|
19
18
|
|
|
20
19
|
fun view(self) -> List<View> =
|
|
21
20
|
k := self.age / Ring.Secs
|
examples/games/orbitrunner/actors/Ship.plum
CHANGED
|
@@ -4,7 +4,9 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/collections/List
|
|
7
|
+
import std/Option
|
|
7
|
-
import std/math/
|
|
8
|
+
import std/math/Vec2
|
|
9
|
+
import std/game/Body
|
|
8
10
|
import std/game/Color
|
|
9
11
|
import std/game/Place
|
|
10
12
|
import std/game/View
|
|
@@ -13,18 +15,16 @@ import std/game/Sprite
|
|
|
13
15
|
import std/game/Round
|
|
14
16
|
import OrbitRunner
|
|
15
17
|
|
|
16
|
-
struct Ship[Actor, Round](tex: Texture,
|
|
18
|
+
struct Ship[Actor, Round, Steps](tex: Texture, body: Body, hurtUntil: Float = 0.0, clock: Float = 0.0) =
|
|
17
19
|
const Radius = 10.0
|
|
18
20
|
const Thrust = 900.0
|
|
19
21
|
const Drag = 2.2
|
|
20
22
|
const HurtTime = 1.5
|
|
21
23
|
|
|
22
|
-
fun create(tex: Texture) -> Ship =
|
|
24
|
+
fun create(tex: Texture) -> Ship =
|
|
25
|
+
Ship(tex: tex, body: Body(pos: Vec2(x: Arena.W / 2.0, y: Arena.H / 2.0), drag: Ship.Drag, edge: Halt(box: Arena.inside(Ship.Radius)), faceAbove: Some(20.0)))
|
|
23
26
|
|
|
24
|
-
fun startAt(tex: Texture, x: Float, y: Float) -> Ship =
|
|
25
|
-
Ship(tex: tex, at: Place.pivoted(x, y, Sheet.Size / 2.0, Sheet.Size / 2.0), vx: 0.0, vy: 0.0, ax: 0.0, ay: 0.0, hurt: 0.0, clock: 0.0)
|
|
26
|
-
|
|
27
|
-
fun place(self) -> Place = self.
|
|
27
|
+
fun place(self) -> Place = self.body.place(Sheet.Pivot)
|
|
28
28
|
|
|
29
29
|
fun radius(self) -> Float = Ship.Radius
|
|
30
30
|
|
|
@@ -35,24 +35,12 @@ struct Ship[Actor, Round](tex: Texture, at: Place, vx: Float, vy: Float, ax: Flo
|
|
|
35
35
|
Sprite(tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 0.0, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 14.0, 4))
|
|
36
36
|
]
|
|
37
37
|
|
|
38
|
-
fun steer(self,
|
|
38
|
+
fun steer(self, dir: Vec2) -> Ship = Ship(..self, body: Body(..self.body, push: dir * Ship.Thrust))
|
|
39
|
-
|
|
39
|
+
|
|
40
|
-
fun hurtFor(self, t: Float) -> Ship = Ship(..self,
|
|
40
|
+
fun hurtFor(self, t: Float) -> Ship = Ship(..self, hurtUntil: self.clock + t)
|
|
41
|
+
|
|
41
|
-
|
|
42
|
+
fun hurt(self) -> Bool = self.clock < self.hurtUntil
|
|
43
|
+
|
|
42
|
-
fun step(self, dt: Float) -> Ship =
|
|
44
|
+
fun step(self, dt: Float) -> Ship = Ship(..self, clock: self.clock + dt)
|
|
43
|
-
|
|
45
|
+
|
|
44
|
-
vx0 := {self.vx + self.ax * Ship.Thrust * dt} * keep
|
|
45
|
-
vy0 := {self.vy + self.ay * Ship.Thrust * dt} * keep
|
|
46
|
-
x0 := self.at.x + vx0 * dt
|
|
47
|
-
y0 := self.at.y + vy0 * dt
|
|
48
|
-
r := Ship.Radius
|
|
49
|
-
x := x0.max(r).min(Arena.W - r)
|
|
50
|
-
y := y0.max(r).min(Arena.H - r)
|
|
51
|
-
vx := if x != x0 then 0.0 else vx0
|
|
52
|
-
vy := if y != y0 then 0.0 else vy0
|
|
53
|
-
moved := self.at.moveTo(x, y)
|
|
54
|
-
Ship(
|
|
55
|
-
..self, clock: self.clock + dt, hurt: {self.hurt - dt}.max(0.0), vx: vx, vy: vy,
|
|
56
|
-
at: if vx * vx + vy * vy > 400.0 then moved.rotateTo(Math.atan2(vx, 0.0 - vy)) else moved)
|
|
57
|
-
|
|
58
|
-
fun lit(self) -> Bool = !{self.hurt
|
|
46
|
+
fun lit(self) -> Bool = !{self.hurt() && Sprite.frameAt(self.clock, 10.0, 2) == 0}
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -85,7 +85,7 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
85
85
|
Steer(ax: ax.max(-1.0).min(1.0), ay: ay.max(-1.0).min(1.0))
|
|
86
86
|
|
|
87
87
|
fun update(self, a: PlayAction) -> Next<PlayingScreen, PlayAction> = match a
|
|
88
|
-
Steer(ax, ay) => Next(state: PlayingScreen(..self, ship: self.ship.steer(ax, ay)))
|
|
88
|
+
Steer(ax, ay) => Next(state: PlayingScreen(..self, ship: self.ship.steer(Vec2(x: ax, y: ay))))
|
|
89
89
|
Tick(dt) =>
|
|
90
90
|
stepped := self.stepped(dt)
|
|
91
91
|
moved := PlayingScreen(..stepped, ticks: stepped.ticks + 1, clock: stepped.clock + dt, rings: stepped.rings.filter(|r| !r.done()))
|
|
@@ -99,13 +99,13 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
99
99
|
Hit =>
|
|
100
100
|
sounds := self.assets
|
|
101
101
|
lives := self.lives - 1
|
|
102
|
-
|
|
102
|
+
ship := self.ship
|
|
103
|
-
ring := Ring
|
|
103
|
+
ring := Ring(pos: ship.body.pos)
|
|
104
104
|
over := self.over || lives <= 0
|
|
105
105
|
Next(
|
|
106
106
|
state: PlayingScreen(
|
|
107
107
|
..self, best: if over then self.best.max(self.score) else self.best, lives: lives, over: over,
|
|
108
|
-
ship:
|
|
108
|
+
ship: ship.hurtFor(Ship.HurtTime), rings: self.rings.append([ring])),
|
|
109
109
|
cmds: if over then [Stop(sound: sounds.music), Play(sound: sounds.over, volume: 1.0)] else [Play(sound: sounds.hit, volume: 1.0)])
|
|
110
110
|
StartOver =>
|
|
111
111
|
sounds := self.assets
|
|
@@ -116,7 +116,7 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
116
116
|
|
|
117
117
|
fun rules(self) -> List<PlayAction> = [
|
|
118
118
|
..self.orbs.filter(|o| self.ship.touches(o)).map(|o| Caught(orb: o.id))
|
|
119
|
-
if self.ship.hurt
|
|
119
|
+
if !self.ship.hurt() && self.mines.any(|m| self.ship.touches(m)) then Hit
|
|
120
120
|
]
|
|
121
121
|
|
|
122
122
|
fun dice(self, salt: Int) -> Random = Random.at(self.seed, self.ticks, salt)
|
std/game/Body.plum
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Bool
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Option
|
|
6
|
+
import std/math/Math
|
|
7
|
+
import std/math/Vec2
|
|
8
|
+
import std/math/Aabb
|
|
9
|
+
import std/game/Place
|
|
10
|
+
|
|
11
|
+
# What a body does at the sides of a box its position stays in: nothing (`Free`), stop
|
|
12
|
+
# there (`Halt`: that axis's velocity goes), bounce back (`Bounce`: that axis's velocity
|
|
13
|
+
# turns), or come in at the other side (`Wrap`).
|
|
14
|
+
enum Walls =
|
|
15
|
+
| Free
|
|
16
|
+
| Halt(box: Aabb)
|
|
17
|
+
| Bounce(box: Aabb)
|
|
18
|
+
| Wrap(box: Aabb)
|
|
19
|
+
|
|
20
|
+
# A moving thing's physics, declared: its position (`pos`, the point it turns about), its
|
|
21
|
+
# velocity, the acceleration pushing it (`push`), the share of its velocity lost per second
|
|
22
|
+
# (`drag`), what it does at the edges, and its `angle`, which turns at `turn` radians per
|
|
23
|
+
# second, or faces the way it moves while its speed is above `faceAbove` (0 facing up, -y,
|
|
24
|
+
# turning clockwise: a sprite drawn pointing up). An actor holding one in a field lists
|
|
25
|
+
# `Steps` and the field is stepped for it (std/game/View); `place(origin)` is where to draw it.
|
|
26
|
+
#
|
|
27
|
+
# struct Ship[Actor, Steps](body: Body, ..) =
|
|
28
|
+
# fun create() -> Ship = Ship(body: Body(pos: Vec2(x: 400.0, y: 300.0), drag: 2.2, edge: Halt(box: arena), faceAbove: Some(20.0)))
|
|
29
|
+
# fun place(self) -> Place = self.body.place(Vec2(x: 24.0, y: 24.0))
|
|
30
|
+
struct Body(
|
|
31
|
+
pos: Vec2, vel: Vec2 = Vec2.Zero, push: Vec2 = Vec2.Zero, drag: Float = 0.0, edge: Walls = Free,
|
|
32
|
+
angle: Float = 0.0, turn: Float = 0.0, faceAbove: Option<Float> = None) =
|
|
33
|
+
|
|
34
|
+
# `dt` seconds later: pushed, slowed by the drag, moved, held to its edges, then turned.
|
|
35
|
+
fun step(self, dt: Float) -> Body =
|
|
36
|
+
keep := {1.0 - self.drag * dt}.max(0.0)
|
|
37
|
+
vx := {self.vel.x + self.push.x * dt} * keep
|
|
38
|
+
vy := {self.vel.y + self.push.y * dt} * keep
|
|
39
|
+
x := self.pos.x + vx * dt
|
|
40
|
+
y := self.pos.y + vy * dt
|
|
41
|
+
match self.edge
|
|
42
|
+
Free => self.landed(x, y, vx, vy, dt)
|
|
43
|
+
Halt(box) =>
|
|
44
|
+
hx := x.max(box.min.x).min(box.max.x)
|
|
45
|
+
hy := y.max(box.min.y).min(box.max.y)
|
|
46
|
+
self.landed(hx, hy, if hx != x then 0.0 else vx, if hy != y then 0.0 else vy, dt)
|
|
47
|
+
Bounce(box) =>
|
|
48
|
+
outX := x < box.min.x || x > box.max.x
|
|
49
|
+
outY := y < box.min.y || y > box.max.y
|
|
50
|
+
self.landed(
|
|
51
|
+
if outX then x.max(box.min.x).min(box.max.x) else x, if outY then y.max(box.min.y).min(box.max.y) else y,
|
|
52
|
+
if outX then 0.0 - vx else vx, if outY then 0.0 - vy else vy, dt)
|
|
53
|
+
Wrap(box) => self.landed(Body.wrap(x, box.min.x, box.max.x), Body.wrap(y, box.min.y, box.max.y), vx, vy, dt)
|
|
54
|
+
|
|
55
|
+
# At (x, y) moving at (vx, vy), its angle turned for `dt`: the way it moves when it faces
|
|
56
|
+
# its motion and is fast enough, else turned by `turn`.
|
|
57
|
+
fun landed(self, x: Float, y: Float, vx: Float, vy: Float, dt: Float) -> Body =
|
|
58
|
+
fast := match self.faceAbove
|
|
59
|
+
Some(s) => vx * vx + vy * vy > s * s
|
|
60
|
+
None => false
|
|
61
|
+
Body(..self, pos: Vec2(x: x, y: y), vel: Vec2(x: vx, y: vy), angle: if fast then Math.atan2(vx, 0.0 - vy) else self.angle + self.turn * dt)
|
|
62
|
+
|
|
63
|
+
# Where to draw it: turned by its angle about `origin` (in the drawing's own
|
|
64
|
+
# coordinates), which lands on `pos`.
|
|
65
|
+
fun place(self, origin: Vec2) -> Place =
|
|
66
|
+
Place(..Place.pivoted(self.pos.x - origin.x, self.pos.y - origin.y, origin.x, origin.y), rotation: self.angle)
|
|
67
|
+
|
|
68
|
+
# `v` brought into `[lo, hi)` by whole spans.
|
|
69
|
+
fun wrap(v: Float, lo: Float, hi: Float) -> Float =
|
|
70
|
+
span := hi - lo
|
|
71
|
+
if v >= lo && v < hi then v else v - span * {{v - lo} / span}.floor()
|
std/game/View.plum
CHANGED
|
@@ -100,11 +100,12 @@ trait View =
|
|
|
100
100
|
trait Actor[View] =
|
|
101
101
|
fun step(self, dt: Float) -> Self
|
|
102
102
|
|
|
103
|
-
# An actor whose fields
|
|
103
|
+
# An actor whose fields the compiler steps after its own `step`: each field that is an
|
|
104
|
+
# `Actor`, a value whose type has its own `step(self, dt: Float) -> Self` (a `Body`,
|
|
104
|
-
#
|
|
105
|
+
# std/game/Body), a `List` or an `Option` of either, or a `List<View>` (`Views.stepIn`,
|
|
105
|
-
#
|
|
106
|
+
# each item's type tested as it is stepped), the others as they are, at compile time (the
|
|
106
|
-
#
|
|
107
|
+
# same static construction a hand-written step is), so its own `step` holds only what is
|
|
107
|
-
#
|
|
108
|
+
# special about it (`Ship(..self, clock: self.clock + dt)`, its body stepped with it). A screen needs no `Steps`: its `stepped` is derived
|
|
108
109
|
# from the same fields (std/game/Screen). `@stepsWhen(cond)` before a field, on a screen or
|
|
109
110
|
# a `[Steps]` actor, steps it only while `cond` holds, read on `self`:
|
|
110
111
|
#
|
tests/examples/games/balloonpop/actors/Balloon.plum
CHANGED
|
@@ -12,6 +12,7 @@ import std/math/Math
|
|
|
12
12
|
import std/game/Color
|
|
13
13
|
import std/game/Gfx
|
|
14
14
|
import std/game/Place
|
|
15
|
+
import std/game/Body
|
|
15
16
|
import std/game/View
|
|
16
17
|
import std/game/Circle
|
|
17
18
|
import std/game/Label
|
|
@@ -24,7 +25,7 @@ import std/Test
|
|
|
24
25
|
primitive BalloonTest[UnitTest] =
|
|
25
26
|
# a whole balloon is hit on its body, its knot and its string, and a burst one nowhere
|
|
26
27
|
fun aWholeBalloonIsHitOnItsBody() =
|
|
27
|
-
b := Balloon(id: 1, x: 100.0, y: 100.0)
|
|
28
|
+
b := Balloon(id: 1, body: Body(pos: Vec2(x: 100.0, y: 100.0)))
|
|
28
29
|
r := Balloon.Radius
|
|
29
30
|
assert b.hit(Vec2(x: 0.0, y: 0.0))
|
|
30
31
|
assert b.hit(Vec2(x: 0.0, y: r + 6.0))
|
|
@@ -35,7 +36,7 @@ primitive BalloonTest[UnitTest] =
|
|
|
35
36
|
|
|
36
37
|
# a balloon rises and sways as the clock runs, and stays where it burst
|
|
37
38
|
fun aBalloonRisesAndSwaysAsTheClock() =
|
|
38
|
-
b := Balloon(id: 1, x: 100.0, y: 500.0,
|
|
39
|
+
b := Balloon(id: 1, body: Body(pos: Vec2(x: 100.0, y: 500.0), vel: Vec2(x: 0.0, y: -50.0))).step(1.0)
|
|
39
40
|
assert b.place().y == 450.0
|
|
40
41
|
assert b.place().x != 100.0
|
|
41
42
|
x := b.place().x
|
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -11,6 +11,7 @@ import std/math/Vec2
|
|
|
11
11
|
import std/math/Math
|
|
12
12
|
import std/game/Color
|
|
13
13
|
import std/game/Input
|
|
14
|
+
import std/game/Body
|
|
14
15
|
import std/game/Replay
|
|
15
16
|
import std/game/View
|
|
16
17
|
import std/game/Box
|
|
@@ -33,7 +34,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
33
34
|
p := t.screen
|
|
34
35
|
assert p.balloons.length() == PlaygroundScreen.Count
|
|
35
36
|
assert p.pops == 0
|
|
36
|
-
assert p.balloons.all(|b| b.y > Arena.H * 0.4)
|
|
37
|
+
assert p.balloons.all(|b| b.body.pos.y > Arena.H * 0.4)
|
|
37
38
|
assert t.count<Balloon>() == PlaygroundScreen.Count
|
|
38
39
|
assert @sameRef(t.find<Balloon>().at(5), t.screen.balloons.at(5))
|
|
39
40
|
assert t.text(t.first<Label>()) == "0"
|
|
@@ -41,7 +42,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
41
42
|
fun balloonsRiseAsTheTicksGoBy() =
|
|
42
43
|
t := PlaygroundScreenHelpers.field(io, 3)
|
|
43
44
|
u := t.tick(1.0)
|
|
44
|
-
assert u.screen.balloons.at(0).y < t.screen.balloons.at(0).y
|
|
45
|
+
assert u.screen.balloons.at(0).body.pos.y < t.screen.balloons.at(0).body.pos.y
|
|
45
46
|
assert u.screen.clock == 1.0
|
|
46
47
|
|
|
47
48
|
# a press on a balloon is a Pop of it, which bursts it and is followed by Popped, which plays the pop; a burst one takes no press
|
|
@@ -68,7 +69,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
68
69
|
assert PlaygroundScreenHelpers.lines(t) == "Blue!, 1"
|
|
69
70
|
u := t.tick(Balloon.PopTime + 0.1)
|
|
70
71
|
assert !u.screen.balloons.at(0).popped()
|
|
71
|
-
assert u.screen.balloons.at(0).y > Arena.H
|
|
72
|
+
assert u.screen.balloons.at(0).body.pos.y > Arena.H
|
|
72
73
|
|
|
73
74
|
fun everyTenthPopStartsAPartyThatEnds() =
|
|
74
75
|
t := Range.until(0, 9).fold(PlaygroundScreenHelpers.field(io, 3), |r, i| r.dispatch(Popped(at: -50.0)))
|
|
@@ -104,7 +105,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
104
105
|
fun theSameSeedGivesTheSameBalloons() =
|
|
105
106
|
a := PlaygroundScreenHelpers.field(io, 9).screen
|
|
106
107
|
b := PlaygroundScreenHelpers.field(io, 9).screen
|
|
107
|
-
assert a.balloons.at(0).
|
|
108
|
+
assert a.balloons.at(0).body.pos == b.balloons.at(0).body.pos
|
|
108
109
|
assert a.balloons.at(0).hue == b.balloons.at(0).hue
|
|
109
110
|
|
|
110
111
|
fun thePartyTitleGrowsThenPulses() =
|
|
@@ -187,7 +188,7 @@ primitive PlaygroundScreenHelpers =
|
|
|
187
188
|
|
|
188
189
|
fun stillAt(t: TestRig<PlaygroundScreen>, i: Int, x: Float, y: Float) -> TestRig<PlaygroundScreen> =
|
|
189
190
|
s := t.screen
|
|
190
|
-
poked(t, PlaygroundScreen(..s, balloons: s.balloons.map(|b| if b.id == Balloon.FirstId + i then Balloon(..b, x: x, y: y,
|
|
191
|
+
poked(t, PlaygroundScreen(..s, balloons: s.balloons.map(|b| if b.id == Balloon.FirstId + i then Balloon(..b, body: Body(pos: Vec2(x: x, y: y)), phase: 0.0) else b)))
|
|
191
192
|
|
|
192
193
|
fun centred(t: TestRig<PlaygroundScreen>) -> TestRig<PlaygroundScreen> = stillAt(t, 0, 400.0, 300.0)
|
|
193
194
|
|
|
@@ -207,7 +208,7 @@ primitive PlaygroundScreenHelpers =
|
|
|
207
208
|
&& Range.until(0, a.balloons.length()).all(|i|
|
|
208
209
|
p := a.balloons.at(i)
|
|
209
210
|
q := b.balloons.at(i)
|
|
210
|
-
p.
|
|
211
|
+
p.body.pos == q.body.pos && p.hue == q.hue && p.poppedAt == q.poppedAt)
|
|
211
212
|
|
|
212
213
|
fun framesFrom(t: TestRig<PlaygroundScreen>, from: Int, n: Int) -> TestRig<PlaygroundScreen> =
|
|
213
214
|
Range.until(0, n).fold(t, |r, f| r.frame(runInput(from + f), Ticker.Tick))
|
tests/examples/games/clicks.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/math/Vec2
|
|
|
8
8
|
import std/game/Color
|
|
9
9
|
import std/game/Input
|
|
10
10
|
import std/game/Place
|
|
11
|
+
import std/game/Body
|
|
11
12
|
import std/game/View
|
|
12
13
|
import std/game/Box
|
|
13
14
|
import std/game/Button
|
|
@@ -34,5 +35,5 @@ primitive ClicksTest[UnitTest] =
|
|
|
34
35
|
assert u.screen.taps == 1
|
|
35
36
|
assert u.text(u.first<Label>()) == "Taps: 1"
|
|
36
37
|
v := u.hold(Key.Right).ticks(60)
|
|
37
|
-
assert v.screen.ball.x > 110.0
|
|
38
|
+
assert v.screen.ball.body.pos.x > 110.0
|
|
38
39
|
assert v.press(Key.Escape).tick().exited()
|
tests/examples/games/orbitrunner/actors/Mine.plum
CHANGED
|
@@ -5,15 +5,21 @@ import std/math/Math
|
|
|
5
5
|
import std/game/Place
|
|
6
6
|
import std/game/View
|
|
7
7
|
import std/game/Sprite
|
|
8
|
+
import std/game/Body
|
|
9
|
+
import std/math/Vec2
|
|
10
|
+
import std/math/Random
|
|
8
11
|
import examples/games/orbitrunner/OrbitRunner
|
|
9
12
|
import examples/games/orbitrunner/actors/Mine
|
|
13
|
+
import examples/games/orbitrunner/actors/Ship
|
|
10
14
|
import std/Test
|
|
11
15
|
|
|
12
16
|
primitive MineTest[UnitTest] =
|
|
13
17
|
fun aMineSpinsAsItDrifts() =
|
|
14
|
-
mine := Mine(at
|
|
18
|
+
mine := Mine.spawn(Random.at(3, 0, 4), Ship.create(Texture.none()), Texture.none())
|
|
19
|
+
later := mine.step(0.5)
|
|
15
|
-
assert Math.near(
|
|
20
|
+
assert Math.near(later.place().rotation, 1.0, 0.01)
|
|
21
|
+
assert later.body.pos == mine.body.pos + mine.body.vel * 0.5
|
|
16
|
-
assert
|
|
22
|
+
assert later.clock == 0.5
|
|
17
23
|
|
|
18
24
|
fun moreMinesAreOutAsTheScoreGrows() =
|
|
19
25
|
assert Mine.countFor(0) == 3
|
tests/examples/games/orbitrunner/actors/Orb.plum
CHANGED
|
@@ -12,6 +12,7 @@ import std/game/Gfx
|
|
|
12
12
|
import std/game/Place
|
|
13
13
|
import std/game/View
|
|
14
14
|
import std/game/Sprite
|
|
15
|
+
import std/game/Body
|
|
15
16
|
import examples/games/orbitrunner/OrbitRunner
|
|
16
17
|
import examples/games/orbitrunner/actors/Orb
|
|
17
18
|
import examples/games/orbitrunner/actors/Ship
|
|
@@ -20,21 +21,18 @@ import std/Test
|
|
|
20
21
|
|
|
21
22
|
primitive OrbTest[UnitTest] =
|
|
22
23
|
fun anOrbDriftsAndBouncesOffTheWalls() =
|
|
23
|
-
orb := Orb(id: 0,
|
|
24
|
+
orb := Orb(id: 0, body: Body(pos: Vec2(x: 785.0, y: 300.0), vel: Vec2(x: 100.0, y: 0.0), edge: Bounce(box: Arena.inside(Orb.Radius))), tex: Texture.none()).step(0.1)
|
|
24
|
-
assert orb.
|
|
25
|
+
assert orb.body.vel.x == -100.0
|
|
25
|
-
assert orb.
|
|
26
|
+
assert orb.body.pos.x == Arena.W - Orb.Radius
|
|
26
27
|
assert orb.clock == 0.1
|
|
27
28
|
|
|
28
29
|
# an orb and a mine spawn themselves away from the ship, each a pure draw of its key
|
|
29
30
|
fun orbsAndMinesSpawnAwayFromTheShip() =
|
|
30
31
|
ship := Ship.create(Texture.none())
|
|
31
32
|
seeds := Range.until(0, 200)
|
|
32
|
-
assert seeds.all(|k|
|
|
33
|
+
assert seeds.all(|k| Orb.spawn(1, Random.at(k, 3, 1), ship, Texture.none()).body.pos.distance(ship.body.pos) >= 120.0)
|
|
33
|
-
assert seeds.all(|k|
|
|
34
|
+
assert seeds.all(|k| Mine.spawn(Random.at(k, 3, 4), ship, Texture.none()).body.pos.distance(ship.body.pos) >= 220.0)
|
|
34
35
|
o := Orb.spawn(2, Random.at(7, 0, 2), ship, Texture.none())
|
|
35
36
|
assert o.id == 2 && o.clock == 0.0
|
|
36
|
-
assert Orb.spawn(2, Random.at(7, 0, 2), ship, Texture.none()).
|
|
37
|
+
assert Orb.spawn(2, Random.at(7, 0, 2), ship, Texture.none()).body.pos == o.body.pos
|
|
37
|
-
assert Orb.spawn(2, Random.at(7, 1, 2), ship, Texture.none()).
|
|
38
|
+
assert Orb.spawn(2, Random.at(7, 1, 2), ship, Texture.none()).body.pos != o.body.pos
|
|
38
|
-
|
|
39
|
-
primitive OrbHelpers =
|
|
40
|
-
fun away(m: Motion, ship: Ship) -> Float = Math.hypot(m.x - ship.at.x, m.y - ship.at.y)
|
tests/examples/games/orbitrunner/actors/Ring.plum
CHANGED
|
@@ -2,6 +2,7 @@ import std/Int
|
|
|
2
2
|
import std/Float
|
|
3
3
|
import std/Bool
|
|
4
4
|
import std/collections/List
|
|
5
|
+
import std/math/Vec2
|
|
5
6
|
import std/game/Color
|
|
6
7
|
import std/game/Place
|
|
7
8
|
import std/game/View
|
|
@@ -12,7 +13,7 @@ import std/Test
|
|
|
12
13
|
primitive RingTest[UnitTest] =
|
|
13
14
|
# a ring grows and fades over its time, then is done
|
|
14
15
|
fun aRingGrowsAndFadesOverItsTime() =
|
|
15
|
-
ring := Ring
|
|
16
|
+
ring := Ring(pos: Vec2(x: 10.0, y: 20.0)).step(0.2)
|
|
16
17
|
assert !ring.done()
|
|
17
18
|
c := match ring.view().at(0)
|
|
18
19
|
Circle as c => c
|
tests/examples/games/orbitrunner/actors/Ship.plum
CHANGED
|
@@ -8,23 +8,42 @@ import std/game/Place
|
|
|
8
8
|
import std/game/View
|
|
9
9
|
import std/game/Circle
|
|
10
10
|
import std/game/Sprite
|
|
11
|
+
import std/game/Body
|
|
12
|
+
import std/math/Vec2
|
|
11
13
|
import examples/games/orbitrunner/OrbitRunner
|
|
12
14
|
import examples/games/orbitrunner/actors/Ship
|
|
13
15
|
import std/Test
|
|
14
16
|
|
|
15
17
|
primitive ShipTest[UnitTest] =
|
|
16
18
|
fun steeringAcceleratesAndDragSlowsTheShip() =
|
|
17
|
-
ship := Ship.
|
|
19
|
+
ship := Ship.create(Texture.none()).steer(Vec2(x: 1.0, y: 0.0)).step(0.1)
|
|
18
|
-
assert ship.
|
|
20
|
+
assert ship.body.vel.x > 0.0
|
|
21
|
+
assert ship.body.pos.x > Arena.W / 2.0
|
|
19
|
-
assert ship.
|
|
22
|
+
assert ship.clock == 0.1
|
|
20
|
-
slow := Range.until(0, 30).fold(ship.steer(
|
|
23
|
+
slow := Range.until(0, 30).fold(ship.steer(Vec2.Zero), |s, i| s.step(0.1))
|
|
21
|
-
assert slow.
|
|
24
|
+
assert slow.body.vel.x < ship.body.vel.x / 4.0
|
|
22
25
|
|
|
23
26
|
fun theShipStopsAtTheArenaWalls() =
|
|
27
|
+
start := Ship.create(Texture.none())
|
|
24
|
-
ship := Range.until(0, 20).fold(Ship
|
|
28
|
+
ship := Range.until(0, 20).fold(Ship(..start, body: Body(..start.body, pos: Vec2(x: 20.0, y: 20.0))).steer(Vec2(x: -1.0, y: -1.0)), |s, i| s.step(0.1))
|
|
29
|
+
assert ship.body.pos == Vec2(x: Ship.Radius, y: Ship.Radius)
|
|
25
|
-
assert ship.
|
|
30
|
+
assert ship.body.vel == Vec2.Zero
|
|
31
|
+
|
|
32
|
+
# it turns to face the way it moves once it is fast enough, and keeps its heading when it slows
|
|
33
|
+
fun itFacesTheWayItMoves() =
|
|
34
|
+
right := Ship.create(Texture.none()).steer(Vec2(x: 1.0, y: 0.0)).step(0.1)
|
|
35
|
+
assert Math.near(right.place().rotation, Float.Pi / 2.0, 0.000001)
|
|
36
|
+
still := Ship.create(Texture.none()).step(0.1)
|
|
37
|
+
assert still.place().rotation == 0.0
|
|
38
|
+
assert right.place().pivot().distance(right.body.pos) < 0.000001
|
|
39
|
+
|
|
40
|
+
# it is hurt until a moment on its clock, nothing counting down
|
|
41
|
+
fun itIsHurtUntilAMoment() =
|
|
42
|
+
ship := Ship.create(Texture.none()).step(1.0).hurtFor(Ship.HurtTime)
|
|
26
|
-
assert ship.
|
|
43
|
+
assert ship.hurtUntil == 1.0 + Ship.HurtTime
|
|
27
|
-
assert ship.
|
|
44
|
+
assert ship.hurt()
|
|
45
|
+
assert ship.step(1.4).hurt()
|
|
46
|
+
assert !ship.step(1.6).hurt()
|
|
28
47
|
|
|
29
48
|
# its view is a glow and a sprite at the frame of its clock, and it is hidden on the blink's off beats
|
|
30
49
|
fun itsViewIsAGlowAndASprite() =
|
tests/examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -11,6 +11,7 @@ import std/math/Random
|
|
|
11
11
|
import std/math/Math
|
|
12
12
|
import std/game/Color
|
|
13
13
|
import std/game/Input
|
|
14
|
+
import std/game/Body
|
|
14
15
|
import std/game/Replay
|
|
15
16
|
import std/game/View
|
|
16
17
|
import std/game/Box
|
|
@@ -61,8 +62,8 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
61
62
|
assert t.screen.score == Orb.Points
|
|
62
63
|
orb := t.screen.orbs.at(0)
|
|
63
64
|
ship := t.screen.ship
|
|
64
|
-
assert
|
|
65
|
+
assert orb.body.pos.distance(ship.body.pos) >= 120.0
|
|
65
|
-
assert orb.
|
|
66
|
+
assert orb.body.pos.x < 5000.0
|
|
66
67
|
assert orb.id == 0
|
|
67
68
|
assert t.screen.orbs.map(|o| o.id) == [0, 1, 2]
|
|
68
69
|
assert t.count<Orb>() == PlayingScreen.OrbCount
|
|
@@ -76,13 +77,13 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
76
77
|
assert t.screen.score == 2 * Orb.Points
|
|
77
78
|
a := t.screen.orbs.at(0)
|
|
78
79
|
b := t.screen.orbs.at(1)
|
|
79
|
-
assert a.
|
|
80
|
+
assert a.body.pos.x < 5000.0 && b.body.pos.x < 5000.0 && a.body.pos.x != b.body.pos.x
|
|
80
81
|
|
|
81
82
|
# two mines on the ship are one Hit
|
|
82
83
|
fun twoMinesOnTheShipAreOneHit() =
|
|
83
84
|
s := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives).screen
|
|
84
85
|
on := PlayingScreenHelpers.onShip(s.ship)
|
|
85
|
-
p := PlayingScreen(..s, mines: s.mines.map(|m| Mine(..m,
|
|
86
|
+
p := PlayingScreen(..s, mines: s.mines.map(|m| Mine(..m, body: on)))
|
|
86
87
|
assert PlayingScreenHelpers.names(p.rules()) == "Hit"
|
|
87
88
|
assert p.update(Hit).state.lives == PlayingScreen.StartLives - 1
|
|
88
89
|
|
|
@@ -90,12 +91,12 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
90
91
|
fun theRulesCatchOrbsAndHitTheShip() =
|
|
91
92
|
s := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives).screen
|
|
92
93
|
ship := s.ship
|
|
93
|
-
orb := Orb(..s.orbs.at(2),
|
|
94
|
+
orb := Orb(..s.orbs.at(2), body: PlayingScreenHelpers.onShip(ship))
|
|
94
95
|
withOrb := |o: Orb| PlayingScreenHelpers.names(PlayingScreen(..s, orbs: [o]).rules())
|
|
95
96
|
assert withOrb(orb) == "Caught(2)"
|
|
96
|
-
assert withOrb(Orb(..orb,
|
|
97
|
+
assert withOrb(Orb(..orb, body: Body(pos: ship.body.pos + Vec2(x: 19.0, y: 0.0)))) == "Caught(2)"
|
|
97
|
-
assert withOrb(Orb(..orb,
|
|
98
|
+
assert withOrb(Orb(..orb, body: Body(pos: ship.body.pos + Vec2(x: 20.0, y: 0.0)))) == ""
|
|
98
|
-
mined := PlayingScreen(..s, mines: [Mine(..s.mines.at(0),
|
|
99
|
+
mined := PlayingScreen(..s, mines: [Mine(..s.mines.at(0), body: PlayingScreenHelpers.onShip(ship))])
|
|
99
100
|
assert PlayingScreenHelpers.names(mined.rules()) == "Hit"
|
|
100
101
|
assert PlayingScreenHelpers.names(PlayingScreen(..mined, ship: ship.hurtFor(1.0)).rules()) == ""
|
|
101
102
|
assert PlayingScreenHelpers.names(s.rules()) == ""
|
|
@@ -107,14 +108,14 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
107
108
|
assert Cmd.names(t.cmds) == "play(-1, 1.0)"
|
|
108
109
|
assert t.screen.lives == PlayingScreen.StartLives - 1
|
|
109
110
|
assert PlayingScreenHelpers.icons(t) == PlayingScreen.StartLives - 1
|
|
110
|
-
assert t.screen.ship.hurt
|
|
111
|
+
assert t.screen.ship.hurt()
|
|
111
112
|
safe := PlayingScreenHelpers.mineAway(t)
|
|
112
113
|
blinks := Range.until(0, 100).fold(Run(rig: safe, overs: 0, restarts: 0), |r, i|
|
|
113
114
|
next := r.rig.tick(0.016)
|
|
114
115
|
Run(rig: next, overs: if next.screen.ship.lit() then r.overs else r.overs + 1, restarts: if next.screen.ship.lit() then r.restarts + 1 else r.restarts))
|
|
115
116
|
assert blinks.overs > 0
|
|
116
117
|
assert blinks.restarts > 0
|
|
117
|
-
assert blinks.rig.screen.ship.hurt
|
|
118
|
+
assert !blinks.rig.screen.ship.hurt()
|
|
118
119
|
assert blinks.rig.screen.ship.lit()
|
|
119
120
|
assert blinks.rig.screen.lives == PlayingScreen.StartLives - 1
|
|
120
121
|
|
|
@@ -128,7 +129,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
128
129
|
assert @sameRef(u.find<Mine>().at(3), late)
|
|
129
130
|
assert late.clock == 0.0
|
|
130
131
|
v := u.tick(0.1).screen.mines.at(3)
|
|
131
|
-
assert v.
|
|
132
|
+
assert v.body.pos.x != late.body.pos.x
|
|
132
133
|
assert v.clock == 0.1
|
|
133
134
|
|
|
134
135
|
# a hit adds a ring where the ship is, which the view draws until it has faded
|
|
@@ -137,7 +138,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
137
138
|
assert t.count<Ring>() == 0
|
|
138
139
|
u := t.tick(0.016)
|
|
139
140
|
assert u.count<Ring>() == 1
|
|
140
|
-
assert u.first<Ring>().
|
|
141
|
+
assert u.first<Ring>().pos == u.screen.ship.body.pos
|
|
141
142
|
assert u.first<Ring>().age == 0.0
|
|
142
143
|
v := u.ticks(30)
|
|
143
144
|
assert v.count<Ring>() == 0
|
|
@@ -150,20 +151,20 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
150
151
|
|
|
151
152
|
fun theKeysHeldSteerTheShip() =
|
|
152
153
|
t := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives).hold(Key.Right).hold(Key.KeyW).tick(0.1)
|
|
153
|
-
assert t.screen.ship.
|
|
154
|
+
assert t.screen.ship.body.vel.x > 0.0
|
|
154
|
-
assert t.screen.ship.
|
|
155
|
+
assert t.screen.ship.body.vel.y < 0.0
|
|
155
156
|
u := t.release(Key.KeyW).hold(Key.Left).tick(0.1)
|
|
156
|
-
assert u.screen.ship.
|
|
157
|
+
assert u.screen.ship.body.push.x == 0.0
|
|
157
158
|
|
|
158
159
|
# update alone plays the slice: Steer sets the thrust and Tick steps the ship; the view draws what it left
|
|
159
160
|
fun updateAlonePlaysTheSliceSteerSets() =
|
|
160
161
|
t := PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)
|
|
161
162
|
steered := t.screen.update(Steer(ax: 1.0, ay: 0.0)).state
|
|
162
|
-
assert steered.ship.
|
|
163
|
+
assert steered.ship.body.push.x == Ship.Thrust
|
|
163
|
-
assert steered.ship.
|
|
164
|
+
assert steered.ship.body.pos.x == Arena.W / 2.0
|
|
164
165
|
p := steered.update(Tick(dt: 0.1)).state
|
|
165
|
-
assert p.ship.
|
|
166
|
+
assert p.ship.body.pos.x > Arena.W / 2.0
|
|
166
|
-
assert p.ship.
|
|
167
|
+
assert p.ship.body.pos.x == t.hold(Key.Right).tick(0.1).screen.ship.body.pos.x
|
|
167
168
|
q := p.update(Caught(orb: 1)).state.update(Caught(orb: 2)).state
|
|
168
169
|
assert q.score == 20
|
|
169
170
|
assert PlayingScreenHelpers.hud(PlayingScreenHelpers.poked(t, q)) == "Score 20, Best 20"
|
|
@@ -177,16 +178,16 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
177
178
|
assert t.screen.lives == 0
|
|
178
179
|
assert t.screen.best == 40
|
|
179
180
|
assert !t.shown(t.screen.ship)
|
|
180
|
-
x := t.screen.ship.
|
|
181
|
+
x := t.screen.ship.body.pos.x
|
|
181
182
|
u := t.hold(Key.Right).tick(0.5)
|
|
182
183
|
assert PlayingScreenHelpers.ruledLast(u).isEmpty()
|
|
183
|
-
assert u.screen.ship.
|
|
184
|
+
assert u.screen.ship.body.pos.x == x
|
|
184
185
|
|
|
185
186
|
# after game over the field stands still, the stars keep twinkling and the ring of the last hit grows on
|
|
186
187
|
fun afterGameOverTheFieldStandsStillThe() =
|
|
187
188
|
t := PlayingScreenHelpers.emptied(io, 0, 1)
|
|
188
189
|
s := t.screen
|
|
189
|
-
started := PlayingScreenHelpers.poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0),
|
|
190
|
+
started := PlayingScreenHelpers.poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), body: Body(pos: s.ship.body.pos, vel: Vec2(x: 10.0, y: 0.0), turn: 2.0)), PlayingScreenHelpers.rest(s.mines)))).tick(0.016)
|
|
190
191
|
p := started.screen
|
|
191
192
|
assert p.over
|
|
192
193
|
mine := p.mines.at(0)
|
|
@@ -194,9 +195,9 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
194
195
|
assert grown.screen.rings.at(0).age > 0.09
|
|
195
196
|
later := Range.until(0, 10).fold(grown.hold(Key.Right), |r, i| r.tick(0.1))
|
|
196
197
|
q := later.screen
|
|
197
|
-
assert q.mines.at(0).
|
|
198
|
+
assert q.mines.at(0).body.pos.x == mine.body.pos.x
|
|
198
|
-
assert q.mines.at(0).
|
|
199
|
+
assert q.mines.at(0).body.angle == mine.body.angle
|
|
199
|
-
assert q.ship.
|
|
200
|
+
assert q.ship.body.pos.x == Arena.W / 2.0
|
|
200
201
|
assert q.mines.at(0).clock == mine.clock
|
|
201
202
|
assert q.orbs.at(0).clock == p.orbs.at(0).clock
|
|
202
203
|
assert q.clock > p.clock + 0.9
|
|
@@ -220,8 +221,8 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
220
221
|
a := PlayingScreenHelpers.mounted(io, 11, 0, PlayingScreen.StartLives).hold(Key.Right).hold(Key.Up).ticks(120)
|
|
221
222
|
b := PlayingScreenHelpers.mounted(io, 11, 0, PlayingScreen.StartLives).hold(Key.Right).hold(Key.Up).ticks(120)
|
|
222
223
|
assert PlayingScreenHelpers.sameRun(a.screen, b.screen)
|
|
223
|
-
assert a.screen.ship.
|
|
224
|
+
assert a.screen.ship.body.pos.x != Arena.W / 2.0
|
|
224
|
-
assert PlayingScreenHelpers.mounted(io, 12, 0, 3).screen.orbs.at(0).
|
|
225
|
+
assert PlayingScreenHelpers.mounted(io, 12, 0, 3).screen.orbs.at(0).body.pos.x != PlayingScreenHelpers.mounted(io, 11, 0, 3).screen.orbs.at(0).body.pos.x
|
|
225
226
|
|
|
226
227
|
fun theArenaIsFittedIntoTheViewCentred() =
|
|
227
228
|
t := PlayingScreenHelpers.mounted(io, 7, 0, 3).resize(1600.0, 600.0)
|
|
@@ -342,30 +343,30 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
342
343
|
assert p.best == 100
|
|
343
344
|
assert p.lives == PlayingScreen.StartLives
|
|
344
345
|
assert u.shown(p.ship)
|
|
345
|
-
assert p.ship.
|
|
346
|
+
assert p.ship.body.pos.x == Arena.W / 2.0
|
|
346
347
|
assert p.mines.length() == Mine.countFor(0)
|
|
347
348
|
assert u.count<Mine>() == Mine.countFor(0)
|
|
348
349
|
assert PlayingScreenHelpers.hud(u) == "Score 0, Best 100"
|
|
349
|
-
assert p.orbs.at(0).
|
|
350
|
+
assert p.orbs.at(0).body.pos.x != PlayingScreenHelpers.mounted(io, 42, 0, 3).screen.orbs.at(0).body.pos.x
|
|
350
351
|
|
|
351
352
|
# a recorded run of 600 ticks replays to the same score and positions
|
|
352
353
|
fun aRecordedRunOf600TicksReplaysTo() =
|
|
353
|
-
a := PlayingScreenHelpers.framesUntil(PlayingScreenHelpers.mounted(io,
|
|
354
|
+
a := PlayingScreenHelpers.framesUntil(PlayingScreenHelpers.mounted(io, 44, 0, PlayingScreen.StartLives).record(44), 0, 600)
|
|
354
355
|
r := a.recorded()
|
|
355
356
|
assert r.length() == a.game.ticks
|
|
356
357
|
assert a.screen.score > 0
|
|
357
358
|
assert a.screen.lives < PlayingScreen.StartLives
|
|
358
359
|
back := Replay.decode(r.encode()).unwrap()
|
|
359
|
-
assert back.seed ==
|
|
360
|
+
assert back.seed == 44
|
|
360
361
|
b := PlayingScreenHelpers.mounted(io, back.seed, 0, PlayingScreen.StartLives).replay(back)
|
|
361
362
|
assert PlayingScreenHelpers.sameRun(b.screen, a.screen)
|
|
362
363
|
assert b.screen.score == a.screen.score
|
|
363
|
-
c := PlayingScreenHelpers.mounted(io,
|
|
364
|
+
c := PlayingScreenHelpers.mounted(io, 45, 0, PlayingScreen.StartLives).replay(back)
|
|
364
365
|
assert !PlayingScreenHelpers.sameRun(c.screen, a.screen)
|
|
365
366
|
|
|
366
367
|
# a recorded run through game over and a restart replays to the same state
|
|
367
368
|
fun aRecordedRunThroughGameOverAndA() =
|
|
368
|
-
run := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io,
|
|
369
|
+
run := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 44, 0, 1).record(44), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
369
370
|
a := run.rig
|
|
370
371
|
assert run.overs > 0
|
|
371
372
|
assert run.restarts > 0
|
|
@@ -376,11 +377,11 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
376
377
|
|
|
377
378
|
# a run through game over and a restart, rewound to its middle and played on again, reaches the same end
|
|
378
379
|
fun aRunThroughGameOverAndARestart() =
|
|
379
|
-
a := PlayingScreenHelpers.counted(Run(rig: TestRig.mountWith(io, PlayingScreen.at(
|
|
380
|
+
a := PlayingScreenHelpers.counted(Run(rig: TestRig.mountWith(io, PlayingScreen.at(44, Assets.none(), 0, 1)), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
380
|
-
b := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io,
|
|
381
|
+
b := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 44, 0, 1), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
381
382
|
assert a.restarts > 0
|
|
382
383
|
assert PlayingScreenHelpers.sameRun(a.rig.screen, b.rig.screen)
|
|
383
|
-
mid := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io,
|
|
384
|
+
mid := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 44, 0, 1), overs: 0, restarts: 0), 0, 450, Ticker.Tick)
|
|
384
385
|
back := a.rig.rewindTo(450)
|
|
385
386
|
assert back.moved()
|
|
386
387
|
assert back.game.rewound == 450
|
|
@@ -394,9 +395,9 @@ primitive PlayingScreenHelpers =
|
|
|
394
395
|
Nil => Nil
|
|
395
396
|
Cons(_, t) => t
|
|
396
397
|
|
|
397
|
-
fun away() ->
|
|
398
|
+
fun away() -> Body = Body(pos: Vec2(x: 5000.0, y: 0.0))
|
|
398
399
|
|
|
399
|
-
fun onShip(ship: Ship) ->
|
|
400
|
+
fun onShip(ship: Ship) -> Body = Body(pos: ship.body.pos)
|
|
400
401
|
|
|
401
402
|
fun ruled(out: List<PlayAction>) -> List<PlayAction> = out.filter(|a| match a
|
|
402
403
|
Steer(_, _) => false
|
|
@@ -408,7 +409,7 @@ primitive PlayingScreenHelpers =
|
|
|
408
409
|
fun mounted(io: Io, seed: Int, score: Int, lives: Int) -> TestRig<PlayingScreen> =
|
|
409
410
|
TestRig.mount(io, PlayingScreen.at(seed, Assets.none(), score, lives))
|
|
410
411
|
|
|
411
|
-
fun cleared(s: PlayingScreen) -> PlayingScreen = PlayingScreen(..s, orbs: s.orbs.map(|o| Orb(..o,
|
|
412
|
+
fun cleared(s: PlayingScreen) -> PlayingScreen = PlayingScreen(..s, orbs: s.orbs.map(|o| Orb(..o, body: away())), mines: s.mines.map(|m| Mine(..m, body: away())))
|
|
412
413
|
|
|
413
414
|
fun emptied(io: Io, score: Int, lives: Int) -> TestRig<PlayingScreen> =
|
|
414
415
|
TestRig.mount(io, cleared(PlayingScreen.at(7, Assets.none(), score, lives)))
|
|
@@ -419,19 +420,19 @@ primitive PlayingScreenHelpers =
|
|
|
419
420
|
|
|
420
421
|
fun orbOnShip(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
|
|
421
422
|
s := t.screen
|
|
422
|
-
poked(t, PlayingScreen(..s, orbs: Cons(Orb(..s.orbs.at(0),
|
|
423
|
+
poked(t, PlayingScreen(..s, orbs: Cons(Orb(..s.orbs.at(0), body: onShip(s.ship)), rest(s.orbs))))
|
|
423
424
|
|
|
424
425
|
fun orbsOnShip(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
|
|
425
426
|
s := t.screen
|
|
426
|
-
poked(t, PlayingScreen(..s, orbs: s.orbs.map(|o| if o.id < 2 then Orb(..o,
|
|
427
|
+
poked(t, PlayingScreen(..s, orbs: s.orbs.map(|o| if o.id < 2 then Orb(..o, body: onShip(s.ship)) else o)))
|
|
427
428
|
|
|
428
429
|
fun mineOnShip(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
|
|
429
430
|
s := t.screen
|
|
430
|
-
poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0),
|
|
431
|
+
poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), body: onShip(s.ship)), rest(s.mines))))
|
|
431
432
|
|
|
432
433
|
fun mineAway(t: TestRig<PlayingScreen>) -> TestRig<PlayingScreen> =
|
|
433
434
|
s := t.screen
|
|
434
|
-
poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0),
|
|
435
|
+
poked(t, PlayingScreen(..s, mines: Cons(Mine(..s.mines.at(0), body: away()), rest(s.mines))))
|
|
435
436
|
|
|
436
437
|
fun lastLife(io: Io) -> TestRig<PlayingScreen> = mineOnShip(emptied(io, 30, 1))
|
|
437
438
|
|
|
@@ -449,21 +450,20 @@ primitive PlayingScreenHelpers =
|
|
|
449
450
|
|
|
450
451
|
fun sameRun(a: PlayingScreen, b: PlayingScreen) -> Bool =
|
|
451
452
|
a.score == b.score && a.best == b.best && a.lives == b.lives && a.over == b.over && a.ticks == b.ticks
|
|
452
|
-
&& a.ship.
|
|
453
|
+
&& a.ship.body.pos == b.ship.body.pos && a.ship.body.vel == b.ship.body.vel
|
|
453
|
-
&& a.ship.
|
|
454
|
+
&& a.ship.hurtUntil == b.ship.hurtUntil && a.ship.clock == b.ship.clock
|
|
454
455
|
&& a.orbs.length() == b.orbs.length() && a.mines.length() == b.mines.length()
|
|
455
|
-
&& Range.until(0, a.orbs.length()).all(|i| a.orbs.at(i).
|
|
456
|
+
&& Range.until(0, a.orbs.length()).all(|i| a.orbs.at(i).body.pos == b.orbs.at(i).body.pos)
|
|
456
|
-
&& Range.until(0, a.mines.length()).all(|i| a.mines.at(i).
|
|
457
|
+
&& Range.until(0, a.mines.length()).all(|i| a.mines.at(i).body.pos == b.mines.at(i).body.pos)
|
|
457
458
|
|
|
458
459
|
fun runInput(i: Int, p: PlayingScreen) -> Input =
|
|
459
|
-
s := p.ship.
|
|
460
|
+
s := p.ship.body.pos
|
|
460
|
-
target := p.orbs.fold(p.orbs.at(0), |best, o|
|
|
461
|
-
|
|
461
|
+
target := p.orbs.fold(p.orbs.at(0), |best, o| if o.body.pos.distance(s) < best.body.pos.distance(s) then o else best).body.pos
|
|
462
462
|
keys := [
|
|
463
|
-
if target.
|
|
463
|
+
if target.x > s.x + 4.0 then Key.Right
|
|
464
|
-
if target.
|
|
464
|
+
if target.x < s.x - 4.0 then Key.KeyA
|
|
465
|
-
if target.
|
|
465
|
+
if target.y > s.y + 4.0 then Key.Down
|
|
466
|
-
if target.
|
|
466
|
+
if target.y < s.y - 4.0 then Key.KeyW
|
|
467
467
|
]
|
|
468
468
|
pos := Vec2(x: Float(i) * 0.37, y: 300.0 - Float(i) * 0.11)
|
|
469
469
|
Input(events: [if i % 150 == 149 then KeyDown(key: Key.Enter), PointerMove(x: pos.x, y: pos.y)], held: Held(keys: keys, pointer: pos))
|
tests/std/game/Body.plum
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Bool
|
|
3
|
+
import std/Float
|
|
4
|
+
import std/Option
|
|
5
|
+
import std/collections/List
|
|
6
|
+
import std/math/Math
|
|
7
|
+
import std/math/Vec2
|
|
8
|
+
import std/math/Aabb
|
|
9
|
+
import std/game/Place
|
|
10
|
+
import std/game/View
|
|
11
|
+
import std/game/Body
|
|
12
|
+
import std/Test
|
|
13
|
+
|
|
14
|
+
struct Puck[Actor, Steps](body: Body, trail: List<Body>, spare: Option<Body>, clock: Float = 0.0) =
|
|
15
|
+
fun place(self) -> Place = self.body.place(Vec2.Zero)
|
|
16
|
+
|
|
17
|
+
fun step(self, dt: Float) -> Puck = Puck(..self, clock: self.clock + dt)
|
|
18
|
+
|
|
19
|
+
struct Drifter[Actor, Steps](body: Body) =
|
|
20
|
+
fun place(self) -> Place = self.body.place(Vec2.Zero)
|
|
21
|
+
|
|
22
|
+
primitive BodyTest[UnitTest] =
|
|
23
|
+
# it moves by its velocity, and its push adds to the velocity first
|
|
24
|
+
fun itMovesByItsVelocityPushedFirst() =
|
|
25
|
+
b := Body(pos: Vec2(x: 1.0, y: 2.0), vel: Vec2(x: 10.0, y: -4.0)).step(0.5)
|
|
26
|
+
assert b.pos == Vec2(x: 6.0, y: 0.0)
|
|
27
|
+
assert b.vel == Vec2(x: 10.0, y: -4.0)
|
|
28
|
+
p := Body(pos: Vec2.Zero, push: Vec2(x: 4.0, y: 0.0)).step(0.5)
|
|
29
|
+
assert p.vel == Vec2(x: 2.0, y: 0.0)
|
|
30
|
+
assert p.pos == Vec2(x: 1.0, y: 0.0)
|
|
31
|
+
assert Body(pos: Vec2(x: 3.0, y: 4.0)).step(1.0).pos == Vec2(x: 3.0, y: 4.0)
|
|
32
|
+
|
|
33
|
+
# drag takes its share of the velocity each second, and never turns it round
|
|
34
|
+
fun dragTakesItsShareOfTheVelocity() =
|
|
35
|
+
b := Body(pos: Vec2.Zero, vel: Vec2(x: 100.0, y: 0.0), drag: 2.0).step(0.25)
|
|
36
|
+
assert b.vel == Vec2(x: 50.0, y: 0.0)
|
|
37
|
+
assert b.pos == Vec2(x: 12.5, y: 0.0)
|
|
38
|
+
assert Body(pos: Vec2.Zero, vel: Vec2(x: 100.0, y: 0.0), drag: 10.0).step(0.5).vel == Vec2.Zero
|
|
39
|
+
|
|
40
|
+
# free, it goes anywhere
|
|
41
|
+
fun freeItGoesAnywhere() =
|
|
42
|
+
b := Body(pos: Vec2(x: 5.0, y: 5.0), vel: Vec2(x: -100.0, y: 0.0)).step(1.0)
|
|
43
|
+
assert b.pos == Vec2(x: -95.0, y: 5.0)
|
|
44
|
+
|
|
45
|
+
# halted, it stops at the sides: that axis's velocity goes, the other keeps
|
|
46
|
+
fun haltedItStopsAtTheSides() =
|
|
47
|
+
box := Aabb.of(0.0, 0.0, 100.0, 100.0)
|
|
48
|
+
b := Body(pos: Vec2(x: 95.0, y: 50.0), vel: Vec2(x: 20.0, y: 10.0), edge: Halt(box: box)).step(0.5)
|
|
49
|
+
assert b.pos == Vec2(x: 100.0, y: 55.0)
|
|
50
|
+
assert b.vel == Vec2(x: 0.0, y: 10.0)
|
|
51
|
+
c := Body(pos: Vec2(x: 5.0, y: 5.0), vel: Vec2(x: -20.0, y: -20.0), edge: Halt(box: box)).step(1.0)
|
|
52
|
+
assert c.pos == Vec2.Zero
|
|
53
|
+
assert c.vel == Vec2.Zero
|
|
54
|
+
|
|
55
|
+
# bouncing, it is held at the side and that axis's velocity turns
|
|
56
|
+
fun bouncingItTurnsAtTheSides() =
|
|
57
|
+
box := Aabb.of(10.0, 10.0, 80.0, 80.0)
|
|
58
|
+
b := Body(pos: Vec2(x: 85.0, y: 50.0), vel: Vec2(x: 20.0, y: -10.0), edge: Bounce(box: box)).step(0.5)
|
|
59
|
+
assert b.pos == Vec2(x: 90.0, y: 45.0)
|
|
60
|
+
assert b.vel == Vec2(x: -20.0, y: -10.0)
|
|
61
|
+
back := b.step(0.5)
|
|
62
|
+
assert back.pos == Vec2(x: 80.0, y: 40.0)
|
|
63
|
+
top := Body(pos: Vec2(x: 50.0, y: 12.0), vel: Vec2(x: 0.0, y: -10.0), edge: Bounce(box: box)).step(1.0)
|
|
64
|
+
assert top.pos == Vec2(x: 50.0, y: 10.0)
|
|
65
|
+
assert top.vel == Vec2(x: 0.0, y: 10.0)
|
|
66
|
+
|
|
67
|
+
# wrapping, it comes in at the other side with its velocity
|
|
68
|
+
fun wrappingItComesInAtTheOtherSide() =
|
|
69
|
+
box := Aabb.of(0.0, 0.0, 100.0, 50.0)
|
|
70
|
+
b := Body(pos: Vec2(x: 95.0, y: 5.0), vel: Vec2(x: 10.0, y: -20.0), edge: Wrap(box: box)).step(1.0)
|
|
71
|
+
assert b.pos == Vec2(x: 5.0, y: 35.0)
|
|
72
|
+
assert b.vel == Vec2(x: 10.0, y: -20.0)
|
|
73
|
+
far := Body(pos: Vec2(x: 10.0, y: 10.0), vel: Vec2(x: -250.0, y: 0.0), edge: Wrap(box: box)).step(1.0)
|
|
74
|
+
assert far.pos == Vec2(x: 60.0, y: 10.0)
|
|
75
|
+
assert Body.wrap(100.0, 0.0, 100.0) == 0.0
|
|
76
|
+
|
|
77
|
+
# facing its motion, it turns to its heading (0 up, clockwise) above the speed, and keeps it below
|
|
78
|
+
fun facingItTurnsToItsHeading() =
|
|
79
|
+
face := |v: Vec2| Body(pos: Vec2.Zero, vel: v, faceAbove: Some(5.0)).step(0.0).angle
|
|
80
|
+
assert face(Vec2(x: 0.0, y: -10.0)) == 0.0
|
|
81
|
+
assert Math.near(face(Vec2(x: 10.0, y: 0.0)), Float.Pi / 2.0, 0.000001)
|
|
82
|
+
assert Math.near(face(Vec2(x: 0.0, y: 10.0)), Float.Pi, 0.000001)
|
|
83
|
+
assert Math.near(face(Vec2(x: -10.0, y: 0.0)), 0.0 - Float.Pi / 2.0, 0.000001)
|
|
84
|
+
slow := Body(pos: Vec2.Zero, vel: Vec2(x: 3.0, y: 0.0), angle: 1.0, faceAbove: Some(5.0)).step(0.1)
|
|
85
|
+
assert slow.angle == 1.0
|
|
86
|
+
assert Body(pos: Vec2.Zero, vel: Vec2(x: 10.0, y: 0.0)).step(0.1).angle == 0.0
|
|
87
|
+
|
|
88
|
+
# its angle turns at its rate when it doesn't face its motion
|
|
89
|
+
fun itsAngleTurnsAtItsRate() =
|
|
90
|
+
b := Body(pos: Vec2.Zero, turn: 2.0).step(0.25).step(0.25)
|
|
91
|
+
assert b.angle == 1.0
|
|
92
|
+
|
|
93
|
+
# its place turns about the origin, which lands on its position
|
|
94
|
+
fun itsPlaceTurnsAboutTheOrigin() =
|
|
95
|
+
b := Body(pos: Vec2(x: 100.0, y: 50.0), angle: 0.5)
|
|
96
|
+
p := b.place(Vec2(x: 24.0, y: 24.0))
|
|
97
|
+
assert p.pivot() == b.pos
|
|
98
|
+
assert p.rotation == 0.5
|
|
99
|
+
assert p.x == 76.0 && p.y == 26.0
|
|
100
|
+
|
|
101
|
+
# the same body stepped the same way is the same body
|
|
102
|
+
fun theSameStepsGiveTheSameBody() =
|
|
103
|
+
run := |n: Int| Range.until(0, n).fold(Body(pos: Vec2(x: 50.0, y: 50.0), vel: Vec2(x: 37.0, y: -91.0), push: Vec2(x: 3.0, y: 7.0), drag: 0.3, edge: Bounce(box: Aabb.of(0.0, 0.0, 100.0, 100.0)), faceAbove: Some(1.0)), |b, i| b.step(0.016 + Float(i % 3) * 0.004))
|
|
104
|
+
a := run(500)
|
|
105
|
+
b := run(500)
|
|
106
|
+
assert a.pos == b.pos && a.vel == b.vel && a.angle == b.angle
|
|
107
|
+
assert a.pos.x >= 0.0 && a.pos.x <= 100.0 && a.pos.y >= 0.0 && a.pos.y <= 100.0
|
|
108
|
+
|
|
109
|
+
# an actor listing Steps steps the bodies it holds, alone, in a list and in an option, after its own step
|
|
110
|
+
fun anActorStepsTheBodiesItHolds() =
|
|
111
|
+
moving := Body(pos: Vec2.Zero, vel: Vec2(x: 1.0, y: 2.0))
|
|
112
|
+
p := Puck(body: moving, trail: [moving, moving], spare: Some(moving)).step(2.0)
|
|
113
|
+
assert p.clock == 2.0
|
|
114
|
+
assert p.body.pos == Vec2(x: 2.0, y: 4.0)
|
|
115
|
+
assert p.trail.all(|b| b.pos == Vec2(x: 2.0, y: 4.0))
|
|
116
|
+
assert p.spare.map(|b| b.pos.x) == Some(2.0)
|
|
117
|
+
assert Drifter(body: moving).step(1.0).body.pos == Vec2(x: 1.0, y: 2.0)
|