@pinkaphant/create-kolmo 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +15 -5
  2. package/bin/create-kolmo.mjs +50 -27
  3. package/package.json +2 -1
  4. package/templates/longline/README.md +14 -0
  5. package/templates/longline/index.html +15 -0
  6. package/templates/longline/package.json +38 -0
  7. package/templates/longline/src/App.tsx +48 -0
  8. package/templates/longline/src/components/Boat.tsx +97 -0
  9. package/templates/longline/src/components/CameraRig.tsx +61 -0
  10. package/templates/longline/src/components/Crates.tsx +48 -0
  11. package/templates/longline/src/components/Hud.tsx +197 -0
  12. package/templates/longline/src/components/Longline.tsx +107 -0
  13. package/templates/longline/src/components/Ocean.tsx +27 -0
  14. package/templates/longline/src/components/Radar.tsx +88 -0
  15. package/templates/longline/src/components/Referee.tsx +39 -0
  16. package/templates/longline/src/components/Scene.tsx +56 -0
  17. package/templates/longline/src/components/Sky.tsx +23 -0
  18. package/templates/longline/src/components/ocean-material.ts +169 -0
  19. package/templates/longline/src/components/round-context.ts +26 -0
  20. package/templates/longline/src/game/boat-control.ts +131 -0
  21. package/templates/longline/src/game/constants.ts +98 -0
  22. package/templates/longline/src/game/input.test.ts +83 -0
  23. package/templates/longline/src/game/input.ts +73 -0
  24. package/templates/longline/src/game/logic.test.ts +110 -0
  25. package/templates/longline/src/game/logic.ts +109 -0
  26. package/templates/longline/src/game/physics.test.ts +211 -0
  27. package/templates/longline/src/game/radar.ts +22 -0
  28. package/templates/longline/src/game/registry.ts +53 -0
  29. package/templates/longline/src/game/sea.ts +26 -0
  30. package/templates/longline/src/game/session.ts +6 -0
  31. package/templates/longline/src/game/simulation.test.ts +393 -0
  32. package/templates/longline/src/game/simulation.ts +137 -0
  33. package/templates/longline/src/game/store.test.ts +222 -0
  34. package/templates/longline/src/game/store.ts +195 -0
  35. package/templates/longline/src/game/test-world.ts +128 -0
  36. package/templates/longline/src/main.tsx +8 -0
  37. package/templates/longline/src/sfx.ts +50 -0
  38. package/templates/longline/src/styles.css +374 -0
  39. package/templates/longline/tsconfig.json +18 -0
  40. package/templates/longline/vite.config.ts +28 -0
@@ -0,0 +1,393 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { planeHeading, type DriveInput, type Quat, type Vec3 } from "./boat-control.js";
4
+ import { ARENA, BOAT, CRATE, FIXED_DT, LINE, ROUND, SEA_STATE_IDS, type SeaStateId } from "./constants.js";
5
+ import { LOSS_MARGIN } from "./logic.js";
6
+ import { createSea } from "./sea.js";
7
+ import { Simulation, type BoatBody, type CrateBody, type Fleet } from "./simulation.js";
8
+ import { Game } from "./store.js";
9
+ import { createTestWorld, initRapier, planarSpeed, type TestWorld } from "./test-world.js";
10
+
11
+ await initRapier();
12
+
13
+ const FULL: DriveInput = { throttle: 1, steer: 0 };
14
+ const IDLE: DriveInput = { throttle: 0, steer: 0 };
15
+ const ZERO: Vec3 = { x: 0, y: 0, z: 0 };
16
+ const IDENTITY: Quat = { x: 0, y: 0, z: 0, w: 1 };
17
+
18
+ // ---------------------------------------------------------------------------------------------------------------------
19
+ // The rules on their own, against bodies that only remember what they were asked. No physics, so every number is exact.
20
+ // ---------------------------------------------------------------------------------------------------------------------
21
+
22
+ class Fake implements BoatBody, CrateBody {
23
+ rot: Quat = { ...IDENTITY };
24
+ vel: Vec3 = { ...ZERO };
25
+ spin: Vec3 = { ...ZERO };
26
+ readonly impulses: Vec3[] = [];
27
+ readonly torques: Vec3[] = [];
28
+
29
+ constructor(public pos: Vec3) {}
30
+
31
+ translation(): Vec3 {
32
+ return this.pos;
33
+ }
34
+ rotation(): Quat {
35
+ return this.rot;
36
+ }
37
+ linvel(): Vec3 {
38
+ return this.vel;
39
+ }
40
+ angvel(): Vec3 {
41
+ return this.spin;
42
+ }
43
+ mass(): number {
44
+ return 1440;
45
+ }
46
+ principalInertia(): Vec3 {
47
+ return { x: 1585, y: 1862, z: 337 };
48
+ }
49
+ applyImpulse(impulse: Vec3): void {
50
+ this.impulses.push({ ...impulse });
51
+ }
52
+ applyTorqueImpulse(torque: Vec3): void {
53
+ this.torques.push({ ...torque });
54
+ }
55
+ setTranslation(v: Vec3): void {
56
+ this.pos = { ...v };
57
+ }
58
+ setRotation(q: Quat): void {
59
+ this.rot = { ...q };
60
+ }
61
+ setLinvel(v: Vec3): void {
62
+ this.vel = { ...v };
63
+ }
64
+ setAngvel(v: Vec3): void {
65
+ this.spin = { ...v };
66
+ }
67
+ }
68
+
69
+ const total = (list: readonly Vec3[]): Vec3 => list.reduce((a, v) => ({ x: a.x + v.x, y: a.y + v.y, z: a.z + v.z }), { ...ZERO });
70
+ const size = (v: Vec3): number => Math.abs(v.x) + Math.abs(v.y) + Math.abs(v.z);
71
+
72
+ function near(actual: Vec3, expected: Vec3, eps = 1e-9): void {
73
+ assert.ok(
74
+ Math.abs(actual.x - expected.x) < eps && Math.abs(actual.y - expected.y) < eps && Math.abs(actual.z - expected.z) < eps,
75
+ `${JSON.stringify(actual)} is not ${JSON.stringify(expected)}`,
76
+ );
77
+ }
78
+
79
+ /** A boat at the origin with its line streamed out astern, and the crates waiting out on the water clear of the line. */
80
+ function rules(playing = true) {
81
+ const sea = createSea("calm");
82
+ const game = new Game(null);
83
+ if (playing) game.start("calm");
84
+ const simulation = new Simulation(game, sea.field, 5);
85
+ const boat = new Fake({ x: 0, y: 0, z: 0 });
86
+ const floats = Array.from({ length: LINE.floats }, (_, i) => new Fake({ x: 0, y: 0, z: BOAT.tow[2] + (i + 1) * LINE.spacing }));
87
+ const crates = Array.from({ length: CRATE.count }, (_, i) => new Fake({ x: -60 + i * 3, y: 0, z: -55 }));
88
+ const fleet: Fleet = { boat, floats, crates };
89
+ return { sea, game, simulation, boat, floats, crates, fleet };
90
+ }
91
+
92
+ test("a crate on the line is hauled for 100 and replaced upstream, afloat and at rest", () => {
93
+ const r = rules();
94
+ const crate = r.crates[0]!;
95
+ crate.setTranslation({ x: 0.5, y: 0.3, z: 6 });
96
+ crate.vel = { x: 1, y: 2, z: 3 };
97
+ crate.spin = { x: 1, y: 2, z: 3 };
98
+ crate.rot = { x: 0.5, y: 0.5, z: 0.5, w: 0.5 };
99
+ r.simulation.afterStep(r.fleet, 2.5, FIXED_DT);
100
+ const s = r.game.getSnapshot();
101
+ assert.deepEqual([s.score, s.hauled, s.combo, s.lost], [100, 1, 1, 0]);
102
+ const p = crate.translation();
103
+ const d = Math.hypot(p.x, p.z);
104
+ assert.ok(p.x < 0, `upstream is -X, but the crate is at x ${p.x}`);
105
+ assert.ok(d > ARENA.radius - 3 - ARENA.spawnBand - 1e-9 && d <= ARENA.radius - 3 + 1e-9, `${d} m from the middle`);
106
+ assert.equal(p.y, r.sea.field.heightAt(p.x, p.z, 2.5), "on the water as it is at that moment");
107
+ assert.deepEqual(crate.vel, ZERO);
108
+ assert.deepEqual(crate.spin, ZERO);
109
+ assert.deepEqual(crate.rot, IDENTITY);
110
+ // it moved off the line, so the next step does not haul it again
111
+ r.simulation.afterStep(r.fleet, 2.5, FIXED_DT);
112
+ assert.equal(r.game.getSnapshot().score, 100);
113
+ });
114
+
115
+ test("crates hauled in one step are worth 100, 200 and 300 in turn", () => {
116
+ const r = rules();
117
+ [5, 8, 11].forEach((z, i) => r.crates[i]!.setTranslation({ x: 0.2, y: 0, z }));
118
+ r.simulation.afterStep(r.fleet, 0, FIXED_DT);
119
+ const s = r.game.getSnapshot();
120
+ assert.deepEqual([s.score, s.hauled, s.combo, s.lost], [600, 3, 3, 0]);
121
+ assert.equal(s.lastHaul?.points, 300);
122
+ });
123
+
124
+ test("the line catches within the catch radius of any of its segments, and the hull's own middle does not count", () => {
125
+ const r = rules();
126
+ const R = CRATE.catchRadius;
127
+ r.crates[0]!.setTranslation({ x: R - 0.01, y: 0, z: 6 }); // just inside, beside a rope
128
+ r.crates[1]!.setTranslation({ x: R + 0.01, y: 0, z: 9 }); // just outside
129
+ r.crates[2]!.setTranslation({ x: 0, y: 0, z: 0 }); // under the middle of the hull: 1.85 m from the tow point
130
+ r.crates[3]!.setTranslation({ x: 0, y: 0, z: BOAT.tow[2] - R + 0.01 }); // just inside, on the hull side of the tow point
131
+ const stay = [r.crates[1]!, r.crates[2]!].map((c) => ({ ...c.translation() }));
132
+ r.simulation.afterStep(r.fleet, 0, FIXED_DT);
133
+ assert.equal(r.game.getSnapshot().hauled, 2, "the two inside the radius and no more");
134
+ assert.deepEqual(r.crates[1]!.translation(), stay[0]);
135
+ assert.deepEqual(r.crates[2]!.translation(), stay[1]);
136
+ });
137
+
138
+ test("a crate carried past the edge and the margin is lost and replaced; one still inside the margin stays", () => {
139
+ const r = rules();
140
+ const gone = r.crates[0]!;
141
+ const held = r.crates[1]!;
142
+ gone.setTranslation({ x: ARENA.radius + LOSS_MARGIN + 0.5, y: 0, z: 0 });
143
+ held.setTranslation({ x: ARENA.radius + LOSS_MARGIN - 0.5, y: 0, z: 0 });
144
+ r.simulation.afterStep(r.fleet, 0, FIXED_DT);
145
+ const s = r.game.getSnapshot();
146
+ assert.deepEqual([s.lost, s.score, s.hauled], [1, 0, 0]);
147
+ const p = gone.translation();
148
+ assert.ok(p.x < 0 && Math.hypot(p.x, p.z) < ARENA.radius, `the replacement is at ${p.x}, ${p.z}`);
149
+ assert.equal(held.translation().x, ARENA.radius + LOSS_MARGIN - 0.5);
150
+ });
151
+
152
+ test("nothing is scored, moved or steered outside a round", () => {
153
+ const r = rules(false); // the title screen
154
+ r.crates[0]!.setTranslation({ x: 0.2, y: 0, z: 6 }); // on the line
155
+ r.crates[1]!.setTranslation({ x: ARENA.radius + 20, y: 0, z: 0 }); // far out
156
+ const before = r.crates.map((c) => ({ ...c.translation() }));
157
+ r.simulation.afterStep(r.fleet, 0, FIXED_DT);
158
+ assert.deepEqual(
159
+ r.crates.map((c) => c.translation()),
160
+ before,
161
+ );
162
+ const quiet = r.game.getSnapshot();
163
+ assert.deepEqual([quiet.score, quiet.hauled, quiet.lost], [0, 0, 0]);
164
+
165
+ // the helm answers no one
166
+ r.simulation.beforeStep(r.fleet, { throttle: 1, steer: 1 }, 1, FIXED_DT);
167
+ assert.equal(size(total([...r.boat.impulses, ...r.boat.torques])), 0);
168
+
169
+ // and the very same call, once the round is on, pushes the bow ahead (-Z) with the thrust of one step
170
+ r.game.start("calm");
171
+ r.boat.impulses.length = 0;
172
+ r.simulation.beforeStep(r.fleet, FULL, 1, FIXED_DT);
173
+ near(total(r.boat.impulses), { x: 0, y: 0, z: -BOAT.thrust * FIXED_DT });
174
+ });
175
+
176
+ test("the round is ninety seconds of physics steps, and the helm is dead once it is over", () => {
177
+ const r = rules();
178
+ let steps = 0;
179
+ while (r.game.phase === "playing" && steps < 10_000) {
180
+ r.simulation.afterStep(r.fleet, steps * FIXED_DT, FIXED_DT);
181
+ steps++;
182
+ }
183
+ assert.equal(r.game.phase, "over");
184
+ assert.ok(Math.abs(steps - ROUND.seconds / FIXED_DT) <= 2, `${steps} steps for ${ROUND.seconds} s`);
185
+ r.simulation.beforeStep(r.fleet, FULL, 1, FIXED_DT);
186
+ assert.equal(size(total(r.boat.impulses)), 0);
187
+ });
188
+
189
+ test("the edge of the arena pushes a boat back toward the middle, harder the further out it is", () => {
190
+ const r = rules(false); // no helm in the way: only the edge acts
191
+ const pushOn = (x: number, z: number): Vec3 => {
192
+ const boat = new Fake({ x, y: 0, z });
193
+ r.simulation.beforeStep({ ...r.fleet, boat }, FULL, 1, FIXED_DT);
194
+ return total(boat.impulses);
195
+ };
196
+ assert.equal(size(pushOn(ARENA.radius - 0.1, 0)), 0, "nothing inside the edge");
197
+ near(pushOn(ARENA.radius + 10, 0), { x: -ARENA.push * 10 * 1440 * FIXED_DT, y: 0, z: 0 });
198
+ near(pushOn(0, -(ARENA.radius + 15)), { x: 0, y: 0, z: ARENA.push * 15 * 1440 * FIXED_DT });
199
+ // diagonally out: the same push, still aimed at the middle
200
+ const d = (ARENA.radius + 10) * Math.SQRT1_2;
201
+ const diagonal = pushOn(d, d);
202
+ assert.ok(diagonal.x < 0 && Math.abs(diagonal.x - diagonal.z) < 1e-9);
203
+ assert.ok(Math.abs(Math.hypot(diagonal.x, diagonal.z) - ARENA.push * 10 * 1440 * FIXED_DT) < 1e-9);
204
+ });
205
+
206
+ test("the line is made fast at the hull's tow point, wherever the hull points", () => {
207
+ const r = rules(false);
208
+ const [tx, ty, tz] = BOAT.tow;
209
+ const boat = new Fake({ x: 10, y: 2, z: -5 });
210
+ near(r.simulation.towPoint(boat, { ...ZERO }), { x: 10 + tx, y: 2 + ty, z: -5 + tz });
211
+ // a quarter turn about +Y (counter-clockwise from above) swings the stern, which was at +Z, round to +X
212
+ const s = Math.SQRT1_2;
213
+ boat.rot = { x: 0, y: s, z: 0, w: s };
214
+ near(r.simulation.towPoint(boat, { ...ZERO }), { x: 10 + tz, y: 2 + ty, z: -5 - tx });
215
+ });
216
+
217
+ test("the crates start spread out inside the arena, and the same seed gives the same layout", () => {
218
+ const field = createSea("calm").field;
219
+ const make = (seed: number) => new Simulation(new Game(null), field, seed).initialCrates;
220
+ assert.deepEqual(make(1001), make(1001));
221
+ assert.notDeepEqual(make(1001), make(1002));
222
+ for (let seed = 1001; seed < 1041; seed++) {
223
+ const crates = make(seed);
224
+ assert.equal(crates.length, CRATE.count);
225
+ crates.forEach((p, i) => {
226
+ const d = Math.hypot(p.x, p.z);
227
+ assert.ok(d >= 14 - 1e-9 && d <= ARENA.radius * 0.7 + 1e-9, `seed ${seed}: crate ${i} starts ${d} m out`);
228
+ for (const q of crates.slice(i + 1)) {
229
+ assert.ok(Math.hypot(p.x - q.x, p.z - q.z) >= 12 - 1e-9, `seed ${seed}: two crates start too close`);
230
+ }
231
+ });
232
+ }
233
+ });
234
+
235
+ // ---------------------------------------------------------------------------------------------------------------------
236
+ // The same rules in a real Rapier world: the boat, the line and the crates float, and the helm is the real one.
237
+ // ---------------------------------------------------------------------------------------------------------------------
238
+
239
+ const heading = { fx: 0, fz: -1, rx: 1, rz: 0 };
240
+
241
+ /** A spot `metres` ahead of the boat along its heading, on the water plane. */
242
+ function ahead(w: TestWorld, metres: number): Vec3 {
243
+ const b = w.boat.translation();
244
+ planeHeading(w.boat.rotation(), heading);
245
+ return { x: b.x + heading.fx * metres, y: 0, z: b.z + heading.fz * metres };
246
+ }
247
+
248
+ /** Parks every crate but the ones named upstream and well off to one side, where the boat has no reason to go. */
249
+ function park(w: TestWorld, keep: readonly number[] = []): void {
250
+ w.crates.forEach((c, i) => {
251
+ if (!keep.includes(i)) c.setTranslation({ x: -50 + i * 4, y: 0, z: 50 }, true);
252
+ });
253
+ }
254
+
255
+ function round(id: SeaStateId, seed: number) {
256
+ const game = new Game(null);
257
+ game.start(id);
258
+ const sea = createSea(id);
259
+ const simulation = new Simulation(game, sea.field, seed);
260
+ const w = createTestWorld({ sea, simulation, game, withLine: true, withCrates: true });
261
+ return { game, sea, simulation, w };
262
+ }
263
+
264
+ /**
265
+ * A pilot for the tests: steers for the crate that is cheapest to reach, and closes the throttle to turn tighter when
266
+ * the crate is well off the bow, the way a person would. A boat at 7 m/s turns in about 11 m; at a crawl, in three.
267
+ */
268
+ function pilot(w: TestWorld): DriveInput {
269
+ const b = w.boat.translation();
270
+ planeHeading(w.boat.rotation(), heading);
271
+ let cost = Infinity;
272
+ let error = 0;
273
+ for (const c of w.crates) {
274
+ const p = c.translation();
275
+ const dx = p.x - b.x;
276
+ const dz = p.z - b.z;
277
+ const d = Math.hypot(dx, dz) || 1e-9;
278
+ // the angle from the bow to the crate, positive to starboard
279
+ const e = Math.atan2((dx * heading.rx + dz * heading.rz) / d, (dx * heading.fx + dz * heading.fz) / d);
280
+ if (d + 8 * Math.abs(e) < cost) {
281
+ cost = d + 8 * Math.abs(e);
282
+ error = e;
283
+ }
284
+ }
285
+ const off = Math.abs(error);
286
+ return { throttle: off > 1.2 ? 0.25 : off > 0.6 ? 0.6 : 1, steer: Math.max(-1, Math.min(1, error * 3)) };
287
+ }
288
+
289
+ test("sweeping the line over a crate scores it, and a replacement floats in upstream", () => {
290
+ const { game, w } = round("calm", 42);
291
+ park(w, [0]);
292
+ w.run(4, FULL);
293
+ assert.equal(game.getSnapshot().hauled, 0, "the line has nothing to catch yet");
294
+ w.crates[0]!.setTranslation(ahead(w, 12), true);
295
+ w.run(3, FULL);
296
+ const s = game.getSnapshot();
297
+ assert.deepEqual([s.score, s.hauled, s.combo, s.lost], [100, 1, 1, 0]);
298
+ const p = w.crates[0]!.translation();
299
+ assert.ok(p.x < -20 && Math.hypot(p.x, p.z) < ARENA.radius, `the replacement is at ${p.x}, ${p.z}`);
300
+ });
301
+
302
+ test("crates swept one after another build the combo: 100, 200, 300", () => {
303
+ const { game, w } = round("calm", 42);
304
+ park(w, [0, 1, 2]);
305
+ w.run(4, FULL);
306
+ for (let k = 0; k < 3; k++) {
307
+ w.crates[k]!.setTranslation(ahead(w, 12), true);
308
+ for (let i = 0; i < 5 * 60 && game.getSnapshot().hauled === k; i++) w.step(FULL);
309
+ assert.equal(game.getSnapshot().hauled, k + 1, `crate ${k} was not hauled`);
310
+ }
311
+ const s = game.getSnapshot();
312
+ assert.deepEqual([s.score, s.combo, s.lost], [600, 3, 0]);
313
+ });
314
+
315
+ test("a crate the current carries out of the arena is lost and replaced, and does not score", () => {
316
+ const { game, w } = round("choppy", 42);
317
+ park(w, [0]);
318
+ w.crates[0]!.setTranslation({ x: ARENA.radius + 5, y: 0, z: 0 }, true);
319
+ w.run(8, IDLE);
320
+ const s = game.getSnapshot();
321
+ assert.deepEqual([s.lost, s.score, s.hauled], [1, 0, 0]);
322
+ const p = w.crates[0]!.translation();
323
+ assert.ok(p.x < 0 && Math.hypot(p.x, p.z) < ARENA.radius, `the replacement is at ${p.x}, ${p.z}`);
324
+ });
325
+
326
+ test("the helm does nothing before the round starts", () => {
327
+ const sea = createSea("calm");
328
+ const game = new Game(null); // still on the title screen
329
+ const simulation = new Simulation(game, sea.field, 42);
330
+ const w = createTestWorld({ sea, simulation, game, withLine: true, withCrates: true });
331
+ w.run(3, FULL);
332
+ const p = w.boat.translation();
333
+ assert.ok(Math.abs(p.z) < 1, `the boat made way: z ${p.z}`);
334
+ assert.ok(planarSpeed(w.boat) < 1, `speed ${planarSpeed(w.boat)}`);
335
+ });
336
+
337
+ test("a boat driven flat out at the edge of the arena is stopped a few metres past it and held there", () => {
338
+ const sea = createSea("choppy");
339
+ const game = new Game(null);
340
+ game.start("choppy");
341
+ const simulation = new Simulation(game, sea.field, 42);
342
+ const w = createTestWorld({ sea, simulation, game, withLine: false });
343
+ w.boat.setTranslation({ x: 0, y: 0, z: -60 }, true);
344
+ let farthest = 0;
345
+ for (let i = 0; i < 40 * 60; i++) {
346
+ w.step(FULL);
347
+ const p = w.boat.translation();
348
+ farthest = Math.max(farthest, Math.hypot(p.x, p.z));
349
+ }
350
+ const p = w.boat.translation();
351
+ const r = Math.hypot(p.x, p.z);
352
+ assert.ok(farthest < ARENA.radius + 13, `overshot to ${farthest} m`);
353
+ assert.ok(r > ARENA.radius && r < ARENA.radius + 10, `held ${r} m from the middle`);
354
+ assert.ok(planarSpeed(w.boat) < 2, `still making ${planarSpeed(w.boat)} m/s`);
355
+ });
356
+
357
+ for (const id of SEA_STATE_IDS) {
358
+ test(`${id} sea: a pilot who closes the throttle to turn can win it, and the round ends on time`, () => {
359
+ const { game, w } = round(id, 1001);
360
+ let steps = 0;
361
+ let farthest = 0;
362
+ while (game.phase === "playing" && steps < 6000) {
363
+ w.step(pilot(w));
364
+ steps++;
365
+ const p = w.boat.translation();
366
+ assert.ok(Number.isFinite(p.x + p.y + p.z), `the boat went to NaN at step ${steps}`);
367
+ farthest = Math.max(farthest, Math.hypot(p.x, p.z));
368
+ }
369
+ const s = game.getSnapshot();
370
+ assert.equal(s.phase, "over");
371
+ assert.equal(s.secondsLeft, 0);
372
+ assert.ok(Math.abs(steps - ROUND.seconds / FIXED_DT) <= 2, `${steps} steps for ${ROUND.seconds} s`);
373
+ assert.ok(s.hauled >= 6, `only ${s.hauled} crates hauled in ${ROUND.seconds} s`);
374
+ assert.ok(
375
+ s.score >= CRATE.points * s.hauled && s.score <= CRATE.points * ROUND.maxCombo * s.hauled,
376
+ `a score of ${s.score} for ${s.hauled} crates`,
377
+ );
378
+ assert.equal(s.newBest, true, "the first score in a sea is the best so far");
379
+ assert.ok(farthest < ARENA.radius + 15, `strayed ${farthest} m from the middle`);
380
+ });
381
+ }
382
+
383
+ test("the same seed and the same helm give the same round, to the last bit", () => {
384
+ const play = (): number[] => {
385
+ const { game, w } = round("choppy", 1001);
386
+ for (let i = 0; i < 20 * 60; i++) w.step({ throttle: 1, steer: Math.sin(i / 60) });
387
+ const p = w.boat.translation();
388
+ const q = w.floats[LINE.floats - 1]!.translation();
389
+ const c = w.crates[0]!.translation();
390
+ return [p.x, p.y, p.z, q.x, q.y, q.z, c.x, c.y, c.z, game.getSnapshot().score];
391
+ };
392
+ assert.deepEqual(play(), play());
393
+ });
@@ -0,0 +1,137 @@
1
+ import type { WaveField } from "@pinkaphant/kolmo/water";
2
+ import { driveBoat, rotateByQuat, wetGrip, type DrivableBody, type DriveInput, type Quat, type Vec3 } from "./boat-control.js";
3
+ import { ARENA, BOAT, CRATE, LINE } from "./constants.js";
4
+ import { boundaryAcceleration, cratesOnLine, isLost, mulberry32, scatter, upstreamSpawn } from "./logic.js";
5
+ import type { Game } from "./store.js";
6
+
7
+ /** A body the game only reads the position of: a float on the line. */
8
+ export interface PointBody {
9
+ translation(): Vec3;
10
+ }
11
+
12
+ /** A crate: read where it is, put it somewhere else. */
13
+ export interface CrateBody extends PointBody {
14
+ setTranslation(v: Vec3, wakeUp: boolean): void;
15
+ setRotation(q: Quat, wakeUp: boolean): void;
16
+ setLinvel(v: Vec3, wakeUp: boolean): void;
17
+ setAngvel(v: Vec3, wakeUp: boolean): void;
18
+ }
19
+
20
+ export interface BoatBody extends DrivableBody, PointBody {}
21
+
22
+ /** The bodies the rules look at. Rapier's `RigidBody` satisfies every one of these. */
23
+ export interface Fleet {
24
+ boat: BoatBody;
25
+ floats: readonly PointBody[];
26
+ crates: readonly CrateBody[];
27
+ }
28
+
29
+ const IDENTITY: Quat = { x: 0, y: 0, z: 0, w: 1 };
30
+ const ZERO: Vec3 = { x: 0, y: 0, z: 0 };
31
+
32
+ /**
33
+ * The rules of the round, one step at a time. `beforeStep` is the helm and the arena's edge; `afterStep` looks at where
34
+ * everything ended up: it hauls the crates the line passed over, replaces the ones the current carried out of the
35
+ * arena and counts the clock. It touches bodies only through the small interfaces above, so the tests run it against
36
+ * a real Rapier world with no React.
37
+ */
38
+ export class Simulation {
39
+ /** Where the crates start: spread over the arena, away from the boat. */
40
+ readonly initialCrates: ReadonlyArray<{ x: number; z: number }>;
41
+
42
+ private readonly rand: () => number;
43
+ private readonly line = new Float64Array((LINE.floats + 1) * 2);
44
+ /** The crates' positions on the water plane as of the last step, (x, z) pairs. */
45
+ readonly crateXZ = new Float64Array(CRATE.count * 2);
46
+ private readonly hits: number[] = [];
47
+ private readonly push = { x: 0, z: 0 };
48
+ private readonly tow: Vec3 = { x: 0, y: 0, z: 0 };
49
+ private readonly spawn = { x: 0, z: 0 };
50
+ private readonly local: Vec3 = { x: BOAT.tow[0], y: BOAT.tow[1], z: BOAT.tow[2] };
51
+
52
+ constructor(
53
+ private readonly game: Game,
54
+ private readonly field: WaveField,
55
+ seed: number,
56
+ ) {
57
+ this.rand = mulberry32(seed);
58
+ this.initialCrates = scatter(this.rand, CRATE.count, 14, ARENA.radius * 0.7, 12);
59
+ }
60
+
61
+ /** Where the line is made fast, in the world: the hull's tow point. */
62
+ towPoint(boat: BoatBody, out: Vec3 = this.tow): Vec3 {
63
+ rotateByQuat(boat.rotation(), this.local, false, out);
64
+ const p = boat.translation();
65
+ out.x += p.x;
66
+ out.y += p.y;
67
+ out.z += p.z;
68
+ return out;
69
+ }
70
+
71
+ /** Call right before the world steps: the helm and the arena's edge. */
72
+ beforeStep(fleet: Fleet, input: DriveInput, submergedFraction: number, dt: number): void {
73
+ const boat = fleet.boat;
74
+ // the helm only answers during the round
75
+ const asked = this.game.phase === "playing" ? input : { throttle: 0, steer: 0 };
76
+ driveBoat(boat, asked, wetGrip(submergedFraction), dt);
77
+ const p = boat.translation();
78
+ boundaryAcceleration(p.x, p.z, ARENA.radius, ARENA.push, this.push);
79
+ if (this.push.x !== 0 || this.push.z !== 0) {
80
+ const m = boat.mass();
81
+ boat.applyImpulse({ x: this.push.x * m * dt, y: 0, z: this.push.z * m * dt }, true);
82
+ }
83
+ }
84
+
85
+ /** Call right after the world has stepped, with the water time at the end of the step. */
86
+ afterStep(fleet: Fleet, time: number, dt: number): void {
87
+ this.game.tick(dt);
88
+ if (this.game.phase !== "playing") return;
89
+
90
+ // the line: the tow point, then every float
91
+ const tow = this.towPoint(fleet.boat);
92
+ this.line[0] = tow.x;
93
+ this.line[1] = tow.z;
94
+ const n = fleet.floats.length;
95
+ for (let i = 0; i < n; i++) {
96
+ const p = fleet.floats[i]!.translation();
97
+ this.line[(i + 1) * 2] = p.x;
98
+ this.line[(i + 1) * 2 + 1] = p.z;
99
+ }
100
+ for (let c = 0; c < fleet.crates.length; c++) this.readCrate(fleet, c);
101
+
102
+ const hauled = cratesOnLine(this.line, n + 1, this.crateXZ, fleet.crates.length, CRATE.catchRadius, this.hits);
103
+ if (hauled > 0) {
104
+ this.game.haul(hauled);
105
+ for (let i = 0; i < hauled; i++) {
106
+ const c = this.hits[i]!;
107
+ this.respawn(fleet.crates[c]!, time);
108
+ this.readCrate(fleet, c);
109
+ }
110
+ }
111
+
112
+ let lost = 0;
113
+ for (let c = 0; c < fleet.crates.length; c++) {
114
+ if (isLost(this.crateXZ[c * 2]!, this.crateXZ[c * 2 + 1]!, ARENA.radius)) {
115
+ lost++;
116
+ this.respawn(fleet.crates[c]!, time);
117
+ }
118
+ }
119
+ if (lost > 0) this.game.lose(lost);
120
+ }
121
+
122
+ private readCrate(fleet: Fleet, c: number): void {
123
+ const p = fleet.crates[c]!.translation();
124
+ this.crateXZ[c * 2] = p.x;
125
+ this.crateXZ[c * 2 + 1] = p.z;
126
+ }
127
+
128
+ /** Puts a crate back in at the upstream edge, afloat and at rest. */
129
+ respawn(crate: CrateBody, time: number): void {
130
+ upstreamSpawn(this.rand, ARENA.radius, ARENA.spawnBand, this.spawn);
131
+ const y = this.field.heightAt(this.spawn.x, this.spawn.z, time);
132
+ crate.setTranslation({ x: this.spawn.x, y, z: this.spawn.z }, true);
133
+ crate.setRotation(IDENTITY, true);
134
+ crate.setLinvel(ZERO, true);
135
+ crate.setAngvel(ZERO, true);
136
+ }
137
+ }