From 2d6c7078ae6490e69376984285b6779ff55a888b Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Mon, 2 Nov 2026 12:00:13 -0800 Subject: [PATCH] Add the new Activities games (bounce, bumper, fuse, drive, Ghoul Rush stages and more) with their suites and design notes AI Assisted --- scripts/play.mjs | 24 + ...est-web-console-activities-bounce-cars.mjs | 425 ++ ...est-web-console-activities-bounce-game.mjs | 688 +++ .../test-web-console-activities-bounce.mjs | 1329 +++++ ...test-web-console-activities-ghoul-arms.mjs | 1605 ++++++ ...est-web-console-activities-ghoul-bones.mjs | 458 ++ ...-web-console-activities-ghoul-carnival.mjs | 2015 +++++++ ...test-web-console-activities-ghoul-cart.mjs | 1301 +++++ ...st-web-console-activities-ghoul-chapel.mjs | 1109 ++++ ...test-web-console-activities-ghoul-dice.mjs | 482 ++ ...st-web-console-activities-ghoul-frozen.mjs | 1635 ++++++ ...-web-console-activities-ghoul-gameover.mjs | 90 + ...web-console-activities-ghoul-graveyard.mjs | 445 ++ ...t-web-console-activities-ghoul-grounds.mjs | 921 ++++ ...test-web-console-activities-ghoul-mine.mjs | 1569 ++++++ ...est-web-console-activities-ghoul-retry.mjs | 318 ++ ...test-web-console-activities-ghoul-ride.mjs | 935 ++++ ...eb-console-activities-ghoul-sanatorium.mjs | 1341 +++++ ...test-web-console-activities-ghoul-sled.mjs | 933 ++++ ...t-web-console-activities-ghoul-village.mjs | 1091 ++++ scripts/test-web-console-activities-ghoul.mjs | 3077 +++++++++++ .../test-web-console-activities-rapids.mjs | 1422 +++++ scripts/test-web-console-activities.mjs | 4624 ++++++++++++++++- scripts/test-web-console-page-activities.mjs | 1518 +++++- src/web-console/public/activities.js | 65 +- .../public/activities/bounce-cars.js | 947 ++++ .../public/activities/bounce-draw.js | 554 ++ .../public/activities/bounce-rivals.js | 509 ++ .../public/activities/bounce-road.js | 726 +++ .../public/activities/bounce-roads.js | 293 ++ .../public/activities/bounce-scenery.js | 919 ++++ .../public/activities/bounce-sfx.js | 118 + src/web-console/public/activities/bounce.js | 1886 +++++++ src/web-console/public/activities/bugs-sfx.js | 192 + src/web-console/public/activities/bugs.js | 1729 ++++++ .../public/activities/bumper-draw.js | 915 ++++ .../public/activities/bumper-sfx.js | 133 + src/web-console/public/activities/bumper.js | 1725 ++++++ .../public/activities/drive-sfx.js | 490 ++ src/web-console/public/activities/drive.js | 2170 ++++++++ .../public/activities/fuse-draw.js | 1070 ++++ src/web-console/public/activities/fuse-sfx.js | 170 + src/web-console/public/activities/fuse.js | 1911 +++++++ .../public/activities/ghoul-arms-draw.js | 763 +++ .../public/activities/ghoul-arms.js | 760 +++ .../public/activities/ghoul-bones-draw.js | 265 + .../public/activities/ghoul-bones.js | 282 + .../public/activities/ghoul-bonus-draw.js | 117 + .../public/activities/ghoul-bonus.js | 112 + .../public/activities/ghoul-carnival-draw.js | 1769 +++++++ .../public/activities/ghoul-carnival-world.js | 1225 +++++ .../public/activities/ghoul-carnival.js | 870 ++++ .../public/activities/ghoul-cart-draw.js | 2006 +++++++ .../public/activities/ghoul-cart.js | 576 ++ .../public/activities/ghoul-chapel-draw.js | 2498 +++++++++ .../public/activities/ghoul-chapel.js | 555 ++ .../public/activities/ghoul-dice-draw.js | 225 + .../public/activities/ghoul-dice.js | 180 + .../public/activities/ghoul-draw.js | 2487 +++++++++ .../public/activities/ghoul-flare.js | 84 + .../public/activities/ghoul-frozen-draw.js | 1452 ++++++ .../public/activities/ghoul-frozen-world.js | 880 ++++ .../public/activities/ghoul-frozen.js | 991 ++++ .../public/activities/ghoul-gameover-draw.js | 54 + .../public/activities/ghoul-graveyard-draw.js | 840 +++ .../public/activities/ghoul-graveyard.js | 400 ++ .../public/activities/ghoul-grounds-draw.js | 2111 ++++++++ .../public/activities/ghoul-grounds.js | 442 ++ .../public/activities/ghoul-mine-draw.js | 1256 +++++ .../public/activities/ghoul-mine-tommy.js | 635 +++ .../public/activities/ghoul-mine-world.js | 1638 ++++++ .../public/activities/ghoul-mine.js | 677 +++ .../public/activities/ghoul-monsters-draw.js | 607 +++ .../public/activities/ghoul-pans.js | 123 + .../public/activities/ghoul-picker-draw.js | 871 ++++ .../public/activities/ghoul-powers.js | 305 ++ .../public/activities/ghoul-ride-core.js | 76 + .../public/activities/ghoul-ride-draw-hud.js | 227 + .../activities/ghoul-ride-draw-kinds.js | 560 ++ .../public/activities/ghoul-ride-draw-sets.js | 260 + .../public/activities/ghoul-ride-draw.js | 254 + .../public/activities/ghoul-ride-gfx.js | 131 + .../public/activities/ghoul-ride-scenes.js | 166 + .../public/activities/ghoul-ride-voices.js | 75 + .../public/activities/ghoul-ride.js | 1058 ++++ .../public/activities/ghoul-rockets-draw.js | 201 + .../public/activities/ghoul-rockets.js | 308 ++ .../public/activities/ghoul-rooms.js | 995 ++++ .../public/activities/ghoul-run.js | 429 ++ .../activities/ghoul-sanatorium-draw.js | 2550 +++++++++ .../public/activities/ghoul-sanatorium.js | 576 ++ .../public/activities/ghoul-sfx-arms.js | 118 + .../public/activities/ghoul-sfx-carnival.js | 1112 ++++ .../public/activities/ghoul-sfx-chapel.js | 825 +++ .../public/activities/ghoul-sfx-frozen.js | 1062 ++++ .../public/activities/ghoul-sfx-graveyard.js | 752 +++ .../public/activities/ghoul-sfx-grounds.js | 725 +++ .../public/activities/ghoul-sfx-mine.js | 1046 ++++ .../public/activities/ghoul-sfx-ride.js | 1253 +++++ .../public/activities/ghoul-sfx-sanatorium.js | 735 +++ .../public/activities/ghoul-sfx-sled.js | 283 + .../public/activities/ghoul-sfx-village.js | 849 +++ .../public/activities/ghoul-sfx.js | 1993 +++++++ .../public/activities/ghoul-sled-draw.js | 1346 +++++ .../public/activities/ghoul-sled.js | 514 ++ .../public/activities/ghoul-village-draw.js | 1305 +++++ .../public/activities/ghoul-village-wolf.js | 336 ++ .../public/activities/ghoul-village-world.js | 1702 ++++++ .../public/activities/ghoul-village.js | 621 +++ src/web-console/public/activities/ghoul.js | 2909 +++++++++++ .../public/activities/golf-course-candy.js | 368 ++ .../public/activities/golf-course-cave.js | 399 ++ .../public/activities/golf-course-dino.js | 401 ++ .../public/activities/golf-course-frost.js | 355 ++ .../public/activities/golf-course-pirate.js | 368 ++ .../public/activities/golf-course-space.js | 362 ++ .../public/activities/golf-decor.js | 382 +- .../public/activities/golf-draw.js | 232 +- .../public/activities/golf-holes.js | 458 +- src/web-console/public/activities/golf-kit.js | 113 + .../public/activities/golf-look-candy.js | 805 +++ .../public/activities/golf-look-dino.js | 978 ++++ .../public/activities/golf-look-frost.js | 903 ++++ .../public/activities/golf-look-space.js | 913 ++++ .../public/activities/golf-looks.js | 49 + .../public/activities/golf-paint.js | 100 + src/web-console/public/activities/golf-sfx.js | 248 + src/web-console/public/activities/golf.js | 508 +- src/web-console/public/activities/hop-draw.js | 1324 +++++ src/web-console/public/activities/hop-sfx.js | 126 + src/web-console/public/activities/hop.js | 2028 ++++++++ src/web-console/public/activities/pills.js | 118 + .../public/activities/rapids-draw.js | 1175 +++++ .../public/activities/rapids-sfx.js | 138 + src/web-console/public/activities/rapids.js | 1687 ++++++ .../public/activities/snake-sfx.js | 219 + src/web-console/public/activities/snake.js | 339 +- .../public/activities/stack-sfx.js | 136 + src/web-console/public/activities/stack.js | 1135 ++++ .../public/activities/trails-sfx.js | 187 + src/web-console/public/activities/trails.js | 1626 ++++++ src/web-console/public/music.js | 411 ++ src/web-console/public/screens/activities.js | 1023 +++- src/web-console/public/styles/activities.css | 228 +- 144 files changed, 120156 insertions(+), 971 deletions(-) create mode 100644 scripts/play.mjs create mode 100644 scripts/test-web-console-activities-bounce-cars.mjs create mode 100644 scripts/test-web-console-activities-bounce-game.mjs create mode 100644 scripts/test-web-console-activities-bounce.mjs create mode 100644 scripts/test-web-console-activities-ghoul-arms.mjs create mode 100644 scripts/test-web-console-activities-ghoul-bones.mjs create mode 100644 scripts/test-web-console-activities-ghoul-carnival.mjs create mode 100644 scripts/test-web-console-activities-ghoul-cart.mjs create mode 100644 scripts/test-web-console-activities-ghoul-chapel.mjs create mode 100644 scripts/test-web-console-activities-ghoul-dice.mjs create mode 100644 scripts/test-web-console-activities-ghoul-frozen.mjs create mode 100644 scripts/test-web-console-activities-ghoul-gameover.mjs create mode 100644 scripts/test-web-console-activities-ghoul-graveyard.mjs create mode 100644 scripts/test-web-console-activities-ghoul-grounds.mjs create mode 100644 scripts/test-web-console-activities-ghoul-mine.mjs create mode 100644 scripts/test-web-console-activities-ghoul-retry.mjs create mode 100644 scripts/test-web-console-activities-ghoul-ride.mjs create mode 100644 scripts/test-web-console-activities-ghoul-sanatorium.mjs create mode 100644 scripts/test-web-console-activities-ghoul-sled.mjs create mode 100644 scripts/test-web-console-activities-ghoul-village.mjs create mode 100644 scripts/test-web-console-activities-ghoul.mjs create mode 100644 scripts/test-web-console-activities-rapids.mjs create mode 100644 src/web-console/public/activities/bounce-cars.js create mode 100644 src/web-console/public/activities/bounce-draw.js create mode 100644 src/web-console/public/activities/bounce-rivals.js create mode 100644 src/web-console/public/activities/bounce-road.js create mode 100644 src/web-console/public/activities/bounce-roads.js create mode 100644 src/web-console/public/activities/bounce-scenery.js create mode 100644 src/web-console/public/activities/bounce-sfx.js create mode 100644 src/web-console/public/activities/bounce.js create mode 100644 src/web-console/public/activities/bugs-sfx.js create mode 100644 src/web-console/public/activities/bugs.js create mode 100644 src/web-console/public/activities/bumper-draw.js create mode 100644 src/web-console/public/activities/bumper-sfx.js create mode 100644 src/web-console/public/activities/bumper.js create mode 100644 src/web-console/public/activities/drive-sfx.js create mode 100644 src/web-console/public/activities/drive.js create mode 100644 src/web-console/public/activities/fuse-draw.js create mode 100644 src/web-console/public/activities/fuse-sfx.js create mode 100644 src/web-console/public/activities/fuse.js create mode 100644 src/web-console/public/activities/ghoul-arms-draw.js create mode 100644 src/web-console/public/activities/ghoul-arms.js create mode 100644 src/web-console/public/activities/ghoul-bones-draw.js create mode 100644 src/web-console/public/activities/ghoul-bones.js create mode 100644 src/web-console/public/activities/ghoul-bonus-draw.js create mode 100644 src/web-console/public/activities/ghoul-bonus.js create mode 100644 src/web-console/public/activities/ghoul-carnival-draw.js create mode 100644 src/web-console/public/activities/ghoul-carnival-world.js create mode 100644 src/web-console/public/activities/ghoul-carnival.js create mode 100644 src/web-console/public/activities/ghoul-cart-draw.js create mode 100644 src/web-console/public/activities/ghoul-cart.js create mode 100644 src/web-console/public/activities/ghoul-chapel-draw.js create mode 100644 src/web-console/public/activities/ghoul-chapel.js create mode 100644 src/web-console/public/activities/ghoul-dice-draw.js create mode 100644 src/web-console/public/activities/ghoul-dice.js create mode 100644 src/web-console/public/activities/ghoul-draw.js create mode 100644 src/web-console/public/activities/ghoul-flare.js create mode 100644 src/web-console/public/activities/ghoul-frozen-draw.js create mode 100644 src/web-console/public/activities/ghoul-frozen-world.js create mode 100644 src/web-console/public/activities/ghoul-frozen.js create mode 100644 src/web-console/public/activities/ghoul-gameover-draw.js create mode 100644 src/web-console/public/activities/ghoul-graveyard-draw.js create mode 100644 src/web-console/public/activities/ghoul-graveyard.js create mode 100644 src/web-console/public/activities/ghoul-grounds-draw.js create mode 100644 src/web-console/public/activities/ghoul-grounds.js create mode 100644 src/web-console/public/activities/ghoul-mine-draw.js create mode 100644 src/web-console/public/activities/ghoul-mine-tommy.js create mode 100644 src/web-console/public/activities/ghoul-mine-world.js create mode 100644 src/web-console/public/activities/ghoul-mine.js create mode 100644 src/web-console/public/activities/ghoul-monsters-draw.js create mode 100644 src/web-console/public/activities/ghoul-pans.js create mode 100644 src/web-console/public/activities/ghoul-picker-draw.js create mode 100644 src/web-console/public/activities/ghoul-powers.js create mode 100644 src/web-console/public/activities/ghoul-ride-core.js create mode 100644 src/web-console/public/activities/ghoul-ride-draw-hud.js create mode 100644 src/web-console/public/activities/ghoul-ride-draw-kinds.js create mode 100644 src/web-console/public/activities/ghoul-ride-draw-sets.js create mode 100644 src/web-console/public/activities/ghoul-ride-draw.js create mode 100644 src/web-console/public/activities/ghoul-ride-gfx.js create mode 100644 src/web-console/public/activities/ghoul-ride-scenes.js create mode 100644 src/web-console/public/activities/ghoul-ride-voices.js create mode 100644 src/web-console/public/activities/ghoul-ride.js create mode 100644 src/web-console/public/activities/ghoul-rockets-draw.js create mode 100644 src/web-console/public/activities/ghoul-rockets.js create mode 100644 src/web-console/public/activities/ghoul-rooms.js create mode 100644 src/web-console/public/activities/ghoul-run.js create mode 100644 src/web-console/public/activities/ghoul-sanatorium-draw.js create mode 100644 src/web-console/public/activities/ghoul-sanatorium.js create mode 100644 src/web-console/public/activities/ghoul-sfx-arms.js create mode 100644 src/web-console/public/activities/ghoul-sfx-carnival.js create mode 100644 src/web-console/public/activities/ghoul-sfx-chapel.js create mode 100644 src/web-console/public/activities/ghoul-sfx-frozen.js create mode 100644 src/web-console/public/activities/ghoul-sfx-graveyard.js create mode 100644 src/web-console/public/activities/ghoul-sfx-grounds.js create mode 100644 src/web-console/public/activities/ghoul-sfx-mine.js create mode 100644 src/web-console/public/activities/ghoul-sfx-ride.js create mode 100644 src/web-console/public/activities/ghoul-sfx-sanatorium.js create mode 100644 src/web-console/public/activities/ghoul-sfx-sled.js create mode 100644 src/web-console/public/activities/ghoul-sfx-village.js create mode 100644 src/web-console/public/activities/ghoul-sfx.js create mode 100644 src/web-console/public/activities/ghoul-sled-draw.js create mode 100644 src/web-console/public/activities/ghoul-sled.js create mode 100644 src/web-console/public/activities/ghoul-village-draw.js create mode 100644 src/web-console/public/activities/ghoul-village-wolf.js create mode 100644 src/web-console/public/activities/ghoul-village-world.js create mode 100644 src/web-console/public/activities/ghoul-village.js create mode 100644 src/web-console/public/activities/ghoul.js create mode 100644 src/web-console/public/activities/golf-course-candy.js create mode 100644 src/web-console/public/activities/golf-course-cave.js create mode 100644 src/web-console/public/activities/golf-course-dino.js create mode 100644 src/web-console/public/activities/golf-course-frost.js create mode 100644 src/web-console/public/activities/golf-course-pirate.js create mode 100644 src/web-console/public/activities/golf-course-space.js create mode 100644 src/web-console/public/activities/golf-kit.js create mode 100644 src/web-console/public/activities/golf-look-candy.js create mode 100644 src/web-console/public/activities/golf-look-dino.js create mode 100644 src/web-console/public/activities/golf-look-frost.js create mode 100644 src/web-console/public/activities/golf-look-space.js create mode 100644 src/web-console/public/activities/golf-looks.js create mode 100644 src/web-console/public/activities/golf-paint.js create mode 100644 src/web-console/public/activities/golf-sfx.js create mode 100644 src/web-console/public/activities/hop-draw.js create mode 100644 src/web-console/public/activities/hop-sfx.js create mode 100644 src/web-console/public/activities/hop.js create mode 100644 src/web-console/public/activities/pills.js create mode 100644 src/web-console/public/activities/rapids-draw.js create mode 100644 src/web-console/public/activities/rapids-sfx.js create mode 100644 src/web-console/public/activities/rapids.js create mode 100644 src/web-console/public/activities/snake-sfx.js create mode 100644 src/web-console/public/activities/stack-sfx.js create mode 100644 src/web-console/public/activities/stack.js create mode 100644 src/web-console/public/activities/trails-sfx.js create mode 100644 src/web-console/public/activities/trails.js create mode 100644 src/web-console/public/music.js diff --git a/scripts/play.mjs b/scripts/play.mjs new file mode 100644 index 0000000..22815af --- /dev/null +++ b/scripts/play.mjs @@ -0,0 +1,24 @@ +#!/usr/bin/env node +// Open a console from src/ to try the Activities games while working on them. +// The server reads every page file fresh, so saving a game and reloading the +// page is the whole cycle: no build:skills, no reinstall. Open the die in the +// top bar to pick a game. The server stops itself 30 minutes after the page closes. + +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const cli = path.join(root, "src", "web-console", "console.mjs"); +const env = { ...process.env, PLAN2CODE_CONSOLE_DEV: "1" }; +const run = spawnSync(process.execPath, [cli, "open"], { cwd: root, env, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }); +// `open` answers the agent in JSON; a person only needs the link. +let url; +try { + url = JSON.parse(run.stdout).url; +} catch { + process.stdout.write(run.stdout || ""); +} +if (url) console.log(`Games from src/ at ${url} +Open the die in the top bar. Save a game file, then reload the page to see it.`); +process.exit(run.status ?? 1); diff --git a/scripts/test-web-console-activities-bounce-cars.mjs b/scripts/test-web-console-activities-bounce-cars.mjs new file mode 100644 index 0000000..8c5d1ee --- /dev/null +++ b/scripts/test-web-console-activities-bounce-cars.mjs @@ -0,0 +1,425 @@ +// Web console tests, Bounce Road's cars: every style draws with finite numbers under every option, inside the reach carReach() gives (the w by h box with no options), with balanced save and restore, Planny's star in the color given, an unknown style as a sedan, and colors in any spelling. +// Run with: node --test scripts/test-web-console-activities-bounce-cars.mjs +// +// No browser: a stub 2D context follows the transform the drawing sets up +// and records every point it draws through, as in +// scripts/test-web-console-activities-rapids.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { CAR_STYLES, MARGINS, STYLE_NAMES, carLength, carReach, drawCarBody, drawCarShadow, rgbOf, shade, styleOf } from "../src/web-console/public/activities/bounce-cars.js"; + +/* ------------------------------------------------------------- helpers */ + +// A 2D context that keeps the current transform (translate, scale, rotate, +// save and restore), records each point drawn through it in the caller's +// space, each fill's color, each filled shape's color and bounds (`shapes`), +// every call's arguments and every property set, and flags any number that +// is not finite. +function recorder() { + const log = { points: [], fills: [], shapes: [], calls: [], bad: [], saves: 0, restores: 0, depth: 0, minDepth: 0 }; + let path = []; + const bounds = (pts) => ({ x0: Math.min(...pts.map((p) => p[0])), x1: Math.max(...pts.map((p) => p[0])), y0: Math.min(...pts.map((p) => p[1])), y1: Math.max(...pts.map((p) => p[1])) }); + let m = [1, 0, 0, 1, 0, 0]; + const stack = []; + const state = { fillStyle: "#000000", strokeStyle: "#000000", lineWidth: 1, globalAlpha: 1 }; + const at = (x, y) => { + const p = [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]; + log.points.push(p); + path.push(p); + }; + const box = (x, y, w, h) => { + at(x, y); + at(x + w, y); + at(x, y + h); + at(x + w, y + h); + }; + const check = (name, args) => { + for (const a of args) if (typeof a === "number" && !Number.isFinite(a)) log.bad.push(`${name}(${args.join(", ")})`); + }; + const methods = { + save() { + stack.push({ m: [...m], ...state }); + log.saves += 1; + log.depth += 1; + }, + restore() { + const s = stack.pop(); + if (s) { + m = s.m; + Object.assign(state, { fillStyle: s.fillStyle, strokeStyle: s.strokeStyle, lineWidth: s.lineWidth, globalAlpha: s.globalAlpha }); + } + log.restores += 1; + log.depth -= 1; + log.minDepth = Math.min(log.minDepth, log.depth); + }, + translate(x, y) { + m = [m[0], m[1], m[2], m[3], m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]; + }, + scale(x, y) { + m = [m[0] * x, m[1] * x, m[2] * y, m[3] * y, m[4], m[5]]; + }, + rotate(a) { + const c = Math.cos(a); + const s = Math.sin(a); + m = [m[0] * c + m[2] * s, m[1] * c + m[3] * s, m[2] * c - m[0] * s, m[3] * c - m[1] * s, m[4], m[5]]; + }, + beginPath() { + path = []; + }, + moveTo: at, + lineTo: at, + quadraticCurveTo(cx, cy, x, y) { + at(cx, cy); + at(x, y); + }, + bezierCurveTo(ax, ay, bx, by, x, y) { + at(ax, ay); + at(bx, by); + at(x, y); + }, + rect: box, + roundRect: box, + fillRect(x, y, w, h) { + const keep = path; + path = []; + box(x, y, w, h); + log.fills.push(state.fillStyle); + log.shapes.push({ style: state.fillStyle, points: path.length, ...bounds(path) }); + path = keep; + }, + strokeRect: box, + arc(x, y, r) { + box(x - r, y - r, r * 2, r * 2); + }, + ellipse(x, y, rx, ry) { + box(x - rx, y - ry, rx * 2, ry * 2); + }, + fillText(text, x, y) { + at(x, y); + }, + fill() { + log.fills.push(state.fillStyle); + if (path.length) log.shapes.push({ style: state.fillStyle, points: path.length, ...bounds(path) }); + }, + }; + const ctx = new Proxy(state, { + get: (t, name) => { + if (name in methods) { + return (...args) => { + check(name, args); + log.calls.push([name, ...args]); + return methods[name](...args); + }; + } + if (name in t) return t[name]; + return (...args) => { + check(name, args); + log.calls.push([name, ...args]); + }; + }, + set: (t, name, value) => { + if (typeof value === "number" && !Number.isFinite(value)) log.bad.push(`${String(name)} = ${value}`); + if (typeof value === "string" && /NaN|undefined|Infinity/.test(value)) log.bad.push(`${String(name)} = ${value}`); + log.calls.push(["set", name, value]); + t[name] = value; + return true; + }, + }); + return { ctx, log }; +} + +const draw = (style, opts) => { + const { ctx, log } = recorder(); + drawCarBody(ctx, style, opts); + return log; +}; + +// Every combination of the options worth telling apart. +// The points drawCarShadow() draws for the same options. +function recordShadow(style, opts) { + const { ctx, log } = recorder(); + drawCarShadow(ctx, style, opts); + assert.equal(log.saves, log.restores); + return log.points; +} + +function* combos() { + for (const squash of [0, 0.5, 1]) { + for (const tilt of [-1, 0, 1]) { + for (const air of [0, 0.6, 1]) { + for (const flags of [0, 1, 2, 3]) { + yield { + arms: ["wheel", "up", "down", undefined][(flags + Math.round(squash * 2)) % 4], + squash, + tilt, + air, + lights: flags === 1 || flags === 3, + boost: flags >= 2, + brake: flags === 2, + siren: flags === 3 ? 480 : undefined, + damage: [0, 0.4, 0.7, 1][(flags + Math.round(tilt + 1)) % 4], + clock: 1234 + flags * 77, + }; + } + } + } + } +} + +const EPS = 1e-6; + +/* --------------------------------------------------------------- tests */ + +test("the styles: at least the thirteen asked for, frozen, each with a natural length", () => { + for (const name of ["planny", "hatch", "sedan", "coupe", "muscle", "pickup", "van", "truck", "police", "racer", "taxi", "jeep", "monster"]) { + assert.ok(STYLE_NAMES.includes(name), name); + } + assert.deepEqual(STYLE_NAMES, Object.keys(CAR_STYLES)); + assert.ok(Object.isFrozen(CAR_STYLES) && Object.isFrozen(STYLE_NAMES)); + for (const name of STYLE_NAMES) { + const s = CAR_STYLES[name]; + assert.ok(Object.isFrozen(s) && Object.isFrozen(s.body) && Object.isFrozen(s.wheels.at), name); + assert.ok(s.aspect > 1 && s.aspect < 3, name); + assert.equal(carLength(name), s.aspect); + assert.equal(carLength(name, 4), 4 * s.aspect); + } +}); + +test("every style under every option draws only finite numbers, with balanced save and restore", () => { + for (const name of STYLE_NAMES) { + for (const opts of combos()) { + for (const [w, h] of [ + [4.2, 7], + [6, 12], + [0.5, 0.8], + ]) { + const log = draw(name, { ...opts, w, h, color: "#3a7", accent: "#ffd84a", star: "#ff4fa3" }); + assert.deepEqual(log.bad, [], `${name} ${JSON.stringify(opts)}`); + assert.ok(log.saves > 0, name); + assert.equal(log.saves, log.restores, `${name} ${JSON.stringify(opts)}`); + assert.equal(log.minDepth, 0, `${name} restores past its own save`); + assert.ok(log.points.length > 20, name); + } + } + } +}); + +test("with no options a car stays inside its w by h box", () => { + for (const name of STYLE_NAMES) { + for (const [w, h] of [ + [4.2, 7], + [6, 12], + [3, 3], + ]) { + // No shadow allowance here: the shadow is the one thing that leaves + // the box at rest, so leave it out by checking everything after it. + const log = draw(name, { w, h }); + const r = carReach(name, { w, h }); + assert.equal(r.left, w / 2); + assert.equal(r.top, h / 2); + // The resting shadow is offset a little down and right, so it alone + // reaches past the right and bottom edges, by the documented amount. + assert.ok(Math.abs(r.right - (w / 2 + w * 0.04)) < EPS, name); + assert.ok(Math.abs(r.bottom - (h / 2 + h * 0.05)) < EPS, name); + // The first four points are the shadow's; everything after is the car. + for (const [x, y] of log.points.slice(4)) { + assert.ok(Math.abs(x) <= w / 2 + EPS, `${name} ${w}x${h}: x ${x}`); + assert.ok(Math.abs(y) <= h / 2 + EPS, `${name} ${w}x${h}: y ${y}`); + } + } + } +}); + +test("every option keeps a car inside the reach carReach() gives, at natural and odd sizes, and the reach inside the documented margins", () => { + for (const name of STYLE_NAMES) { + for (const [w, h] of [ + [4.2, carLength(name, 4.2)], + [4, 4], + [3, 12], + [8, 5], + ]) { + for (const opts of combos()) { + for (const shadow of [true, false]) { + const all = { ...opts, w, h, shadow }; + const r = carReach(name, all); + if (shadow) for (const [x, y] of recordShadow(name, all)) assert.ok(x <= r.right + EPS && y <= r.bottom + EPS, `${name} shadow`); + for (const [x, y] of draw(name, all).points) { + assert.ok(x >= -r.left - EPS && x <= r.right + EPS, `${name} ${JSON.stringify(all)}: x ${x} outside ${-r.left}..${r.right}`); + assert.ok(y >= -r.top - EPS && y <= r.bottom + EPS, `${name} ${JSON.stringify(all)}: y ${y} outside ${-r.top}..${r.bottom}`); + } + // The header's numbers: at most a lift of 0.35, a squash of 0.2 + // wide, beams 1.3 h ahead and 0.35 w aside, a flame 0.45 h behind, + // a shadow 0.44 w right and 0.4 h down. + const k = 1 + MARGINS.lift; + const sx = 1 + MARGINS.squashW; + assert.ok(r.left <= (w / 2 + w * 0.35) * sx * k + EPS); + assert.ok(r.top <= (h / 2 + h * 1.3) * k + EPS); + assert.ok(r.bottom <= Math.max((h / 2 + h * 0.45) * k, h * 0.4 + (h / 2) * sx) + EPS); + assert.ok(r.right <= Math.max(r.left, w * 0.44 + (w / 2) * sx) + EPS); + } + } + } + } +}); + +test("a car in the air is bigger and its shadow further down and right", () => { + const low = carReach("sedan", { w: 4, h: 8 }); + const high = carReach("sedan", { w: 4, h: 8, air: 1 }); + assert.ok(Math.abs(high.left - 2 * 1.35) < EPS); + assert.ok(Math.abs(high.top - 4 * 1.35) < EPS); + assert.ok(high.right > low.right && high.bottom > low.bottom); + // The shadow is the first shape drawn: its middle sits down and right. + const log = draw("sedan", { w: 4, h: 8, air: 1 }); + const [[x0, y0], , , [x1, y1]] = log.points; + assert.ok(Math.abs((x0 + x1) / 2 - 4 * 0.44) < EPS); + assert.ok(Math.abs((y0 + y1) / 2 - 8 * 0.4) < EPS); +}); + +test("Planny's car fills his ten point star eye in the star color, and other cars do not use it", () => { + // Neither the default star blue nor the paint, so only the star can match. + const star = "#e0457b"; + const eyes = (log, color) => log.shapes.filter((s) => s.points === 10 && s.style === color); + for (const arms of ["wheel", "up", "down"]) { + for (const squash of [0, 1]) { + const log = draw("planny", { star, arms, squash, color: "#206cc3" }); + assert.equal(eyes(log, star).length, 1, `${arms} ${squash}`); + // Nothing but the star is filled in its color. + assert.equal(log.shapes.filter((s) => s.style === star).length, 1, `${arms} ${squash}`); + } + } + for (const name of STYLE_NAMES.filter((n) => n !== "planny")) assert.ok(!draw(name, { star }).fills.includes(star), name); + // With no star given, the eye is still a ten point star, in the default blue. + assert.equal(eyes(draw("planny", { color: "#c0392b" }), "#206cc3").length, 1); +}); + +test("an unknown style draws as a sedan, and a style object is used as given", () => { + const sedan = draw("sedan", { w: 4, h: 8, color: "#123456" }).calls; + for (const style of ["nope", undefined, null, 7, { body: 1 }]) assert.deepEqual(draw(style, { w: 4, h: 8, color: "#123456" }).calls, sedan, String(style)); + assert.equal(styleOf("nope"), CAR_STYLES.sedan); + assert.equal(styleOf(CAR_STYLES.van), CAR_STYLES.van); + assert.deepEqual(draw(CAR_STYLES.taxi, { w: 4, h: 8 }).calls, draw("taxi", { w: 4, h: 8 }).calls); + assert.equal(carLength("nope"), CAR_STYLES.sedan.aspect); +}); + +test("colors in #abc, #aabbcc, rgb() or nonsense all draw, alike when they name one color", () => { + assert.deepEqual(rgbOf("#abc"), [0xaa, 0xbb, 0xcc]); + assert.deepEqual(rgbOf("#AABBCC"), [0xaa, 0xbb, 0xcc]); + assert.deepEqual(rgbOf("rgb(170, 187, 204)"), [0xaa, 0xbb, 0xcc]); + assert.equal(rgbOf("banana"), null); + assert.equal(rgbOf(undefined), null); + assert.equal(rgbOf(""), null); + assert.equal(rgbOf("red"), null); + assert.deepEqual(rgbOf("#aabbcc80"), [0xaa, 0xbb, 0xcc]); + assert.deepEqual(rgbOf("rgba(170, 187, 204, 0.5)"), [0xaa, 0xbb, 0xcc]); + assert.ok(Object.isFrozen(rgbOf("#abc"))); + assert.equal(shade("#abc"), "#aabbcc"); + assert.equal(shade("#abc", NaN), "#aabbcc"); + assert.equal(shade("#abc", "x"), "#aabbcc"); + assert.equal(shade("#abc", 0), "#aabbcc"); + assert.equal(shade("#000000", 0.5), "#808080"); + assert.equal(shade("#ffffff", -1), "#000000"); + for (const name of STYLE_NAMES) { + const short = draw(name, { color: "#abc", accent: "#f00", star: "#0f0" }).calls; + assert.deepEqual(draw(name, { color: "#aabbcc", accent: "#ff0000", star: "#00ff00" }).calls, short, name); + assert.deepEqual(draw(name, { color: "rgb(170, 187, 204)", accent: "rgba(255, 0, 0, 1)", star: "rgb(0,255,0)" }).calls, short, name); + assert.deepEqual(draw(name, { color: "#aabbccff", accent: "#ff0000ff", star: "rgba(0, 255, 0, 0.9)" }).calls, short, name); + for (const color of ["", "red"]) assert.deepEqual(draw(name, { color, accent: color, star: color }).calls, draw(name, {}).calls, `${name} ${color}`); + // A color it cannot read falls back to the style's own paint. + const odd = draw(name, { color: "banana", accent: 12, star: null }); + assert.deepEqual(odd.bad, [], name); + assert.deepEqual(odd.calls, draw(name, {}).calls, name); + for (const c of odd.fills) assert.match(String(c), /^(#[0-9a-f]{6}|rgba?\([\d., ]+\))$/, `${name}: ${c}`); + } +}); + +test("nonsense numbers are clamped or ignored, never drawn", () => { + for (const name of STYLE_NAMES) { + const log = draw(name, { w: NaN, h: -3, squash: Infinity, tilt: "left", air: -1, damage: 5, siren: NaN, clock: Infinity, number: NaN }); + assert.deepEqual(log.bad, [], name); + assert.equal(log.saves, log.restores); + // No options at all, or null, is the default car. + assert.deepEqual(draw(name, null).calls, draw(name, {}).calls, name); + assert.deepEqual(draw(name, undefined).calls, draw(name, {}).calls, name); + assert.deepEqual(carReach(name, null), carReach(name, {}), name); + assert.deepEqual(recordShadow(name, null), recordShadow(name, {}), name); + // A size of 0 or below is missing, not a speck. + for (const bad of [0, -2]) { + assert.deepEqual(draw(name, { w: bad, h: bad }).calls, draw(name, {}).calls, `${name} ${bad}`); + assert.deepEqual(carReach(name, { w: bad }), carReach(name, {}), `${name} ${bad}`); + } + } +}); + +test("the racer's number stays a number of at most two digits", () => { + const text = (opts) => draw("racer", opts).calls.find((c) => c[0] === "fillText"); + assert.equal(text({})[1], "7"); + assert.equal(text({ number: 123 })[1], "99"); + assert.equal(text({ number: -4 })[1], "0"); + assert.equal(text({ number: 41.6 })[1], "42"); + // And a width it is squeezed to, so even two wide digits stay on the roundel. + assert.ok(text({ number: 88 })[4] > 0); +}); + +test("drawCarShadow draws just the shadow drawCarBody draws, and shadow: false leaves it out", () => { + for (const name of STYLE_NAMES) { + for (const opts of [{}, { air: 1 }, { squash: 1, w: 6, h: 9 }]) { + const alone = recordShadow(name, opts); + assert.equal(alone.length, 4); + assert.deepEqual(draw(name, opts).points.slice(0, 4), alone, name); + const bare = draw(name, { ...opts, shadow: false }); + assert.deepEqual(bare.points, draw(name, opts).points.slice(4), name); + assert.equal(bare.saves, bare.restores); + } + // Without its shadow a resting car stays inside its box exactly. + assert.deepEqual(carReach(name, { w: 4, h: 7, shadow: false }), { left: 2, right: 2, top: 3.5, bottom: 3.5 }); + } +}); + +test("nothing is drawn over a lit brake lamp", () => { + const overlap = (a, b) => a.x0 < b.x1 - EPS && b.x0 < a.x1 - EPS && a.y0 < b.y1 - EPS && b.y0 < a.y1 - EPS; + for (const name of STYLE_NAMES) { + for (const opts of [{ brake: true }, { brake: true, siren: 300 }, { brake: true, boost: true, tilt: 1 }]) { + const { shapes } = draw(name, opts); + const lit = shapes.map((s, i) => [s, i]).filter(([s]) => s.style === "#ff3a2a"); + assert.ok(lit.length > 0, name); + for (const [lamp, i] of lit) { + for (const later of shapes.slice(i + 1)) assert.ok(!overlap(lamp, later), `${name} ${JSON.stringify(opts)}: ${later.style} over the brake lamp`); + } + } + } +}); + +test("a siren puts a light bar on every style, open cars included", () => { + for (const name of STYLE_NAMES) { + assert.ok(draw(name, { siren: 0 }).fills.includes("#ff2d2d"), name); + if (name !== "police") assert.ok(!draw(name, {}).fills.includes("#ff2d2d"), name); + } +}); + +test("the siren alternates its lit side on the clock, and a car with no clock stays still", () => { + const a = draw("police", { siren: 0 }).fills; + const b = draw("police", { siren: 200 }).fills; + assert.notDeepEqual(a, b); + assert.deepEqual(draw("police", { siren: 0 }).fills, a); + // The same moment draws the same frame: nothing random. + for (const name of STYLE_NAMES) assert.deepEqual(draw(name, { boost: true, damage: 1, squash: 1, clock: 500 }).calls, draw(name, { boost: true, damage: 1, squash: 1, clock: 500 }).calls, name); +}); + +test("braking lights the taillights and a boost draws a flame behind the tail", () => { + for (const name of STYLE_NAMES) { + assert.ok(draw(name, { brake: true }).fills.includes("#ff3a2a"), name); + assert.ok(!draw(name, {}).fills.includes("#ff3a2a"), name); + const h = carLength(name, 4.2); + const behind = (log) => Math.max(...log.points.slice(4).map(([, y]) => y)); + assert.ok(behind(draw(name, { boost: true, w: 4.2, h })) > h / 2 + h * 0.2, name); + } +}); + +test("the source keeps to the house rules: no em dash, no shadowBlur, no Math.random, no imports", async () => { + const fs = await import("node:fs"); + const src = fs.readFileSync(new URL("../src/web-console/public/activities/bounce-cars.js", import.meta.url), "utf8"); + assert.ok(!src.includes(String.fromCharCode(0x2014))); + const code = src.split(String.fromCharCode(10)).filter((line) => !line.trim().startsWith("//")); + assert.ok(!code.some((line) => /shadowBlur|Math[.]random|^import /.test(line))); +}); diff --git a/scripts/test-web-console-activities-bounce-game.mjs b/scripts/test-web-console-activities-bounce-game.mjs new file mode 100644 index 0000000..74cb002 --- /dev/null +++ b/scripts/test-web-console-activities-bounce-game.mjs @@ -0,0 +1,688 @@ +// Web console tests, Bounce Road through the game contract: the pills and their contrast, held keys, jumps and pauses, the start and end screens and the memo, the tones every event plays and the held hums, Planny in every state, the engine, the landing ring, the road drawn in slanting bands and in chunks kept off screen, the opening banner and the dark of Night Lights. +// Run with: node --test scripts/test-web-console-activities-bounce-game.mjs +// +// The rules have their own suite, scripts/test-web-console-activities-bounce.mjs. +// No browser and no server: the game draws only through the canvas it is +// handed, so a stub canvas stands in for the page, as in +// scripts/test-web-console-activities.mjs, whose helpers this file copies. + +import test from "node:test"; +import assert from "node:assert/strict"; +import * as bounce from "../src/web-console/public/activities/bounce.js"; +import { LOOKS } from "../src/web-console/public/activities/bounce-draw.js"; +import { ACCENTS } from "../src/web-console/public/palette.js"; +import { humNames, toneNames } from "../src/web-console/public/tones.js"; + +const game = bounce.default; + +/* ------------------------------------------------------------- helpers */ + +// A 2D context whose every method is a no-op that counts itself. +function stubCanvas() { + const calls = { count: 0 }; + const ctx = new Proxy({}, { + get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }), + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls }; +} + +// A 2D context that records where each strip in a banner's shade is filled +// (its top and height), and does nothing else. +function bannerCanvas(shade) { + const shades = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillRect" ? (x, y, w, h) => t.fillStyle === shade && shades.push([y, h]) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, shades }; +} + +// The page's tokens in light and dark, for readColors() through a stubbed +// getComputedStyle. +const THEME_TOKENS = Object.freeze({ + light: Object.freeze({ "--panel": "#ffffff", "--panel-2": "#fbf9f6", "--rule": "#e4ddd1", "--accent": "#206cc3", "--ink": "#1d1a17" }), + dark: Object.freeze({ "--panel": "#201d1a", "--panel-2": "#262220", "--rule": "#332e29", "--accent": "#619fe5", "--ink": "#f0ece5" }), +}); + +// "#rrggbb" or "rgb(a)(...)" as [r, g, b, a], and the WCAG contrast of two. +function rgbaOf(color) { + const hex = /^#([0-9a-f]{6})$/i.exec(color); + if (hex) return [0, 2, 4].map((k) => parseInt(hex[1].slice(k, k + 2), 16)).concat(1); + const [r, g, b, a = 1] = /rgba?\(([^)]*)\)/.exec(color)[1].split(",").map(Number); + return [r, g, b, a]; +} +const toHex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`; +const overColor = (top, alpha, base) => top.slice(0, 3).map((v, i) => v * alpha + base[i] * (1 - alpha)); +function wcag(a, b) { + const lum = (c) => { + const [r, g, bl] = rgbaOf(c).slice(0, 3).map((v) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4)); + return 0.2126 * r + 0.7152 * g + 0.0722 * bl; + }; + const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); + return (x + 0.05) / (y + 0.05); +} + +// A 2D context that keeps, for each pill it draws (a rounded fill, perhaps +// a timer's rounded tint, then the text with no dark edge), the text's +// color, the backing composited over `board` and each tint over that. +function pillCanvas(board) { + const drawn = []; + let since = []; + const target = { globalAlpha: 1, getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), measureText: () => ({ width: 50 }) }; + const ctx = new Proxy(target, { + get: (t, name) => { + if (name in t) return t[name]; + if (name === "roundRect") return () => since.push({ k: "round" }); + if (name === "fill") return () => since.push({ k: "fill", style: t.fillStyle, alpha: t.globalAlpha }); + if (name === "fillText") return (text) => { drawn.push({ text: String(text), ink: t.fillStyle, since }); since = []; }; + if (name === "strokeText" || name === "fillRect" || name === "stroke") return () => since.push({ k: name }); + return () => {}; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 900, height: 900, getContext: () => ctx }; + ctx.canvas = canvas; + const pills = () => drawn.flatMap(({ text, ink, since: seq }) => { + if (seq.some((e) => e.k === "strokeText") || seq.at(-1)?.k !== "fill") return []; + const fills = seq.filter((e, i) => e.k === "fill" && seq[i - 1]?.k === "round"); + const back = fills.find((e) => e.alpha === 1); + if (!back) return []; + const b = rgbaOf(back.style); + const backing = toHex(overColor(b, b[3], rgbaOf(board))); + const tints = fills.slice(fills.indexOf(back) + 1).map((e) => { + const c = rgbaOf(e.style); + return toHex(overColor(c, e.alpha * c[3], rgbaOf(backing))); + }); + return [{ text, ink, backing, tints }]; + }); + return { canvas, pills, reset: () => { drawn.length = 0; since = []; } }; +} + +// Plays the game a few frames in light and dark under every highlight, runs +// `setup(round)`, draws one more frame and checks every pill's text reads +// at 4.5:1 on its backing and each tint, and that each of `expect` showed +// (a "~" before one: drawn with a timer's tint). +function checkPills({ setup = () => {}, expect = [] } = {}) { + const saved = globalThis.getComputedStyle; + try { + for (const [theme, tokens] of Object.entries(THEME_TOKENS)) { + for (const [id, accent] of Object.entries(ACCENTS)) { + const values = { ...tokens, "--accent": accent[theme][0] }; + globalThis.getComputedStyle = () => ({ getPropertyValue: (name) => values[name] || "" }); + const { canvas, pills, reset } = pillCanvas(values["--panel"]); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + setup(g.round); + reset(); + g.tick(16); + const seen = pills(); + assert.ok(seen.length > 0, `${theme}/${id}: pills drawn`); + for (const p of seen) { + for (const under of [p.backing, ...p.tints]) { + const k = wcag(p.ink, under); + assert.ok(k >= 4.5, `${theme}/${id}: "${p.text}" in ${p.ink} on ${under} reads ${k.toFixed(2)}:1`); + } + } + for (const want of expect) { + const tinted = want.startsWith("~"); + const text = tinted ? want.slice(1) : want; + assert.ok(seen.some((p) => p.text.includes(text) && (!tinted || p.tints.length)), `${theme}/${id}: "${text}" drawn${tinted ? " with its tint" : ""} (${seen.map((p) => p.text)})`); + } + } + } + } finally { + if (saved === undefined) delete globalThis.getComputedStyle; + else globalThis.getComputedStyle = saved; + } +} + +// Starts the game the way the window's key does and checks its opening +// banner: painted on the start's own frame, inside the field (0 to +// `field`), and in the same place on the first tick. +function openingBanner(g, shades, field) { + shades.length = 0; + g.key("action"); + assert.equal(shades.length, 1, "the start paints its banner"); + const [[top, h]] = shades; + assert.ok(top >= 0 && top + h <= field, `inside the field, not at its top edge (${top})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [[top, h]], "in the same place once play begins"); +} + +// A 2D context that keeps every method name it was called with, and answers +// the few calls the road's chunks need. +function recordingCanvas() { + const names = []; + const target = { + getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), + measureText: () => ({ width: 50 }), + }; + const ctx = new Proxy(target, { + get: (t, name) => (name in t ? t[name] : (...args) => { names.push(name); }), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 800, height: 600, getContext: () => ctx }; + ctx.canvas = canvas; + return { canvas, names }; +} + +// A 2D context that keeps the style each fill and stroke used, and counts +// every other call. +function styleCanvas() { + const fills = []; + const strokes = []; + const ctx = new Proxy({}, { + get: (target, name) => { + if (name === "fill" || name === "fillRect") return () => fills.push(target.fillStyle); + if (name === "stroke" || name === "strokeRect") return () => strokes.push(target.strokeStyle); + return name in target ? target[name] : () => {}; + }, + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, fills, strokes }; +} + +// A random source that always says the same, so no rival guesses. +const steady = () => 0.5; +const eventsOf = (round, type) => round.events.filter((e) => e.type === type); + +// A rival of `kind` put at (x, d), still and on the ground, going nowhere on +// its own. +function bounceRival(round, kind, x, d, over = {}) { + const car = bounce.spawnRival(round, kind, steady, round.cars[0].d + 300); + assert.ok(car, `a ${kind} spawns`); + Object.assign(car, { x, d, v: 0, tv: 0, vx: 0, kx: 0, air: 0, tx: x, lane: x, hopIn: 1e9, dropIn: 1e9, mode: "calm", ...over }); + return car; +} + +// A spot on plain road: the middle of the first row at or after `d` with +// nothing to catch you out for `clear` units either side (no hole, water, +// flowerbed, timed part, rails, pad, barrier or hazard). +function plainSpot(road, d = 40, clear = 20) { + bounce.ensureRoad(road, d + 400); + const busy = (lo, hi) => [road.pads, road.blocks, road.hazards, road.items, road.stars].some((list) => list.some((e) => e.d > lo - 12 && (e.d1 ?? e.d) > lo - 12 && e.d < hi + 12)); + for (let i = Math.floor(d / bounce.ROW); i < road.rows; i++) { + let ok = true; + for (let j = i - clear / bounce.ROW; ok && j <= i + clear / bounce.ROW; j++) ok = bounce.plainRow(road, j); + if (ok && !busy(i * bounce.ROW - clear, i * bounce.ROW + clear)) return { x: (road.L[i] + road.R[i]) / 2, d: i * bounce.ROW + 1, i }; + } + throw new Error("no plain road"); +} + +/* ------------------------------------------------------- the game */ + +// Starts a Bounce Road game, the rivals cleared away and none coming. +function bounceGame(opts = {}) { + const { canvas, calls } = stubCanvas(); + const g = game.create({ canvas, ...opts }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + return { g, calls }; +} + +test("Bounce Road: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives, a burning Nitro, Mega wheels, the power-ups, the chain and the combo included, in light and dark under every highlight", () => { + checkPills({ + setup: (r) => { + const you = r.cars[0]; + you.spring = true; + you.bubble = true; + you.nitroMs = bounce.NITRO_MS / 2; + you.megaMs = bounce.MEGA_MS / 2; + r.chain = 3; + r.streak = bounce.COMBO_STEP; + r.streakMs = bounce.STREAK_MS / 2; + }, + expect: ["STAGE 1", "♥", "SPRING", "BUBBLE", "~NITRO", "~MEGA", "CHAIN x3", "~COMBO x2"], + }); +}); + +test("Bounce Road game: held arrows drive and steer until let go; space jumps once a press, never on its key repeat, never with the press that plays on; a pause lets go of every key, drops an early press and holds a jump mid-air; and the board refuses a tiny window", () => { + const { canvas } = stubCanvas(); + const t = game.create({ canvas }); + assert.equal(t.resize(bounce.W * bounce.MIN_CELL - 1, 2000), false, "too narrow to play"); + assert.equal(t.resize(bounce.W * bounce.MIN_CELL, bounce.H * bounce.MIN_CELL), true, "just big enough"); + const { g } = bounceGame(); + const you = g.round.cars[0]; + g.key("up", true); + for (let i = 0; i < 40; i++) g.tick(16); + assert.ok(you.v > 30, "up held through the countdown (its repeats) drives"); + g.release("up"); + assert.equal(g.round.input.up, false, "let go, it stops driving"); + g.key("up"); + g.key("action", true); + g.tick(16); + assert.equal(you.air, 0, "a repeat of space never jumps"); + g.key("action"); + g.tick(16); + assert.ok(you.air > 0, "a press jumps"); + for (let i = 0; i < 80 && you.air > 0; i++) { + g.key("action", true); + g.tick(16); + } + assert.equal(you.air, 0, "down again"); + for (let i = 0; i < 10; i++) { + g.key("action", true); + g.tick(16); + } + assert.equal(you.air, 0, "and only once: holding it never jumps again"); + g.key("left"); + g.key("action"); + g.pause(); + assert.deepEqual(Object.values(g.round.input), [false, false, false, false, 0], "a pause holds nothing, the early press dropped"); + g.key("action"); + assert.equal(g.state, "paused", "space never plays on by itself: the window resumes through resume()"); + g.resume(); + assert.equal(g.state, "running", "resume() plays on"); + g.tick(16); + assert.equal(you.air, 0, "and the press that played on never jumps"); + const clock = g.round.clock; + g.pause(); + g.tick(1000); + assert.equal(g.round.clock, clock, "a paused game holds still"); + g.resume(); + g.tick(16); + g.key("action"); + g.tick(16); + const air = you.air; + assert.ok(air > 0); + g.pause(); + g.tick(500); + assert.equal(you.air, air, "a pause mid-air holds the jump"); + g.resume(); + g.tick(16); + assert.ok(you.air < air && you.air > 0, "and it carries on from there"); +}); + +test("Bounce Road game: the start screen names the furthest stage, the memo only grows, and the round's end calls onScore once with its score big on the end screen", () => { + const texts = []; + let font = ""; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text), font]) : name in target ? target[name] : () => {}), + set: (target, name, value) => { if (name === "font") font = value; target[name] = value; return true; }, + }); + let saved = 3; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo, onScore: (n) => scores.push(n) }); + g.resize(900, 900); + assert.ok(texts.some(([t]) => t.includes(`Furthest: ${bounce.STAGES[2].title} (stage 3)`)), "the start screen names the furthest stage"); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + const you = g.round.cars[0]; + const cross = (n) => { + you.d = g.round.road.stageAt[n] - 0.1; + const i = Math.floor(you.d / bounce.ROW); + you.x = (g.round.road.L[i] + g.round.road.R[i]) / 2; + g.round.far = you.d; + g.tick(16); + }; + cross(1); + cross(2); + assert.equal(g.round.stage, 3); + assert.equal(saved, 3, "a stage already reached changes nothing"); + cross(3); + assert.equal(saved, 4, "a new furthest stage is saved"); + g.round.lives = 1; + const hole = g.round.road.holes.find((h) => h.d0 > you.d && h.kind === "crack"); + you.d = hole.d0 + 2; + you.air = 0; + you.x = (g.round.road.L[bounce.rowOf(you.d)] + g.round.road.R[bounce.rowOf(you.d)]) / 2; + for (let ms = 0; ms < bounce.CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + assert.ok(g.score > 0); + texts.length = 0; + g.resize(900, 900); + assert.ok(texts.some(([t, f]) => t === String(g.score) && /\b7px/.test(f)), "the score, big"); + assert.ok(texts.some(([t]) => t.includes(`Reached ${bounce.STAGES[3].title} (stage 4). New furthest!`))); + g.tick(1000); + assert.equal(scores.length, 1, "once"); +}); + +test("Bounce Road game: a jump springs, a crush squashes higher up the chain, passing the best plays the fanfare once, and every stage and lap draws", () => { + const tones = []; + const { g, calls } = bounceGame({ tone: (name, level, pitch) => tones.push([name, pitch || 1]), best: () => 5000 }); + const you = g.round.cars[0]; + g.key("up"); + for (let i = 0; i < 30; i++) g.tick(16); + assert.ok(tones.some(([n]) => n === "engine"), "the engine hums"); + tones.length = 0; + g.key("action"); + g.tick(16); + assert.ok(tones.some(([n]) => n === "spring"), "a jump springs"); + tones.length = 0; + for (let i = 0; i < 10; i++) g.tick(16); + assert.ok(you.air > 0); + assert.equal(tones.filter(([n]) => n === "engine").length, 0, "quiet in the air"); + const squash = () => { + const car = bounceRival(g.round, "zigzag", you.x, you.d); + for (let i = 0; i < 120 && !tones.some(([n]) => n === "squash"); i++) { + if (car.out === 0) Object.assign(car, { x: you.x, d: you.d, v: 0 }); + g.tick(8); + } + const hit = tones.filter(([n]) => n === "squash"); + tones.length = 0; + return hit.length ? hit[0][1] : 0; + }; + const first = squash(); + const second = squash(); + assert.ok(first > 0 && second > first, `the second crush squashes higher (${first} then ${second})`); + g.round.score = 60000; + g.tick(16); + g.tick(16); + assert.equal(tones.filter(([n]) => n === "best").length, 1); + for (let n = 1; n <= 12; n++) { + while (g.round.road.built < n + 1) bounce.buildStage(g.round.road, g.round.road.built + 1); + g.round.stage = n; + you.d = g.round.road.stageAt[n - 1] + 400; + you.air = 500; + g.round.lives = 99; + const drawn = calls.count; + for (let k = 0; k < 6; k++) g.tick(50); + assert.ok(calls.count > drawn, `stage ${n} draws`); + } +}); + +test("Bounce Road game: every event plays a tone that tones.js has (its blips, its shared kit or bounce-sfx.js), so no stunt or hazard is silent", () => { + const known = new Set(toneNames()); + assert.ok(known.size > 40, "tones.js read"); + const tones = []; + const { g } = bounceGame({ tone: (name) => tones.push(name) }); + const you = g.round.cars[0]; + const at = { x: you.x, d: you.d + 10 }; + const events = [ + { type: "boost", ...at, points: 10 }, { type: "ramp", id: 0, ...at, v: 50 }, { type: "slick", ...at }, { type: "star", ...at, run: 3, points: 10 }, + { type: "cone", ...at, kind: "cone", mine: true }, { type: "bonk", id: 0, ...at }, { type: "spray", ...at }, { type: "trainWarn", ...at }, { type: "train", ...at }, + { type: "dropWarn", ...at, what: "pot" }, { type: "dropLand", ...at, what: "pot" }, { type: "gust", dir: 1, ...at }, { type: "crumble", ...at }, { type: "litter", id: 3, ...at }, + { type: "brake", id: 3, ...at }, { type: "near", ...at, kind: "zigzag", points: 30 }, { type: "stomp", ...at, id: 3, hp: 2, chain: 1, points: 250 }, { type: "boss", ...at, points: 2000, life: true }, + { type: "quake", ...at, near: true }, { type: "bossHop", id: 3, ...at }, { type: "escape", ...at }, { type: "spawn", id: 3, kind: "cop", ...at }, { type: "spawn", id: 4, kind: "racer", ...at }, + { type: "spawn", id: 5, kind: "monster", ...at }, { type: "power", kind: "mega", ...at }, { type: "crush", ...at, kind: "cop", id: 3, chain: 2, points: 500 }, + { type: "copGone", id: 3, ...at }, { type: "bubble", ...at, cause: "crash" }, { type: "bump", a: 0, b: 3, ...at, speed: 30, kind: "zigzag" }, + { type: "bumped", ...at, id: 3, kind: "zigzag", how: "splash", points: 50 }, { type: "haul", ...at, kind: "truck", id: 3, chain: 1, points: 50 }, + ]; + for (const e of events) { + tones.length = 0; + g.round.events.push(e); + g.tick(16); + const played = tones.filter((n) => n !== "engine" && n !== "beat"); + assert.ok(played.length > 0, `${e.type}${e.kind ? ` (${e.kind})` : ""} plays a tone`); + for (const n of played) assert.ok(known.has(n), `${n} is in tones.js`); + } +}); + +test("Bounce Road game: Planny keeps his star eye in your highlight driving, in the air, crashed, squashed, sinking, cheering a stage line and at the end", () => { + const frame = (setup) => { + const { canvas, fills } = styleCanvas(); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + setup(g, g.round.cars[0]); + fills.length = 0; + g.resize(900, 900); + return fills; + }; + // His car's paint and his star: fills in your highlight. + const mine = (fills) => fills.filter((f) => f === "#206cc3").length; + const states = { + driving: () => {}, + "in the air": (g, you) => Object.assign(you, { v: 40, air: 300, airMax: 600 }), + crashed: (g) => bounce.lose(g.round, "crash"), + squashed: (g) => bounce.lose(g.round, "squash"), + sinking: (g) => bounce.lose(g.round, "splash"), + "cheering a stage line": (g, you) => { + you.d = g.round.road.stageAt[1] - 0.1; + const i = Math.floor(you.d / bounce.ROW); + you.x = (g.round.road.L[i] + g.round.road.R[i]) / 2; + g.round.far = you.d; + g.tick(16); + assert.equal(g.round.stage, 2); + for (let k = 0; k < 20; k++) g.tick(16); + }, + "at the end": (g, you) => { + g.round.lives = 1; + const hole = g.round.road.holes.find((h) => h.kind === "crack"); + you.d = hole.d0 - 6; + g.round.far = you.d; + for (let ms = 0; ms < bounce.CRASH_MS + 2000 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + }, + }; + const counts = Object.fromEntries(Object.entries(states).map(([name, setup]) => [name, mine(frame(setup))])); + for (const [name, n] of Object.entries(counts)) assert.ok(n >= 2, `${name} (${n})`); +}); + +test("Bounce Road game: the engine hums while you pick up speed and through a Nitro, and is quiet once you cruise at the top speed or coast", () => { + const tones = []; + const { g } = bounceGame({ tone: (name) => tones.push(name) }); + const you = g.round.cars[0]; + const at = plainSpot(g.round.road, 40, 20); + const hums = (ticks) => { + tones.length = 0; + for (let i = 0; i < ticks; i++) { + Object.assign(you, { d: at.d, x: at.x }); + g.round.far = 1e9; + g.tick(16); + } + return tones.filter((n) => n === "engine").length; + }; + g.key("up"); + assert.ok(hums(40) > 3, "it hums as you speed up"); + hums(200); + assert.ok(Math.abs(you.v - bounce.TOP_SPEED) < 1e-6, "at the top speed"); + assert.equal(hums(120), 0, "cruising, quiet"); + g.release("up"); + assert.equal(hums(120), 0, "coasting, quiet"); + bounce.applyPower(g.round, "nitro"); + g.key("up"); + assert.ok(hums(60) > 3, "a Nitro hums"); +}); + +test("Bounce Road game: the motor hums all the way up the road and climbs with your speed; the tires squeal on hard steering, the Monster truck rumbles near, and a pause goes quiet", () => { + const hums = []; + const tones = []; + const { g } = bounceGame({ hum: (id, name, level, pitch) => hums.push({ id, name, level, pitch }), tone: (name) => tones.push(name) }); + const known = new Set(humNames()); + const you = g.round.cars[0]; + const at = plainSpot(g.round.road, 40, 20); + const run = (ticks, each = () => {}) => { + hums.length = 0; + for (let i = 0; i < ticks; i++) { + Object.assign(you, { d: at.d, x: at.x }); + g.round.far = 1e9; + each(); + g.tick(16); + } + return hums; + }; + g.key("up"); + const slow = run(4).filter((h) => h.id === "bounce:you"); + run(200); + const fast = run(4).filter((h) => h.id === "bounce:you"); + assert.ok(slow.length && fast.length, "the motor hums"); + assert.ok(fast.at(-1).pitch > slow[0].pitch, `it climbs with your speed (${slow[0].pitch} then ${fast.at(-1).pitch})`); + assert.ok(run(30).some((h) => h.id === "bounce:you"), "cruising, it still hums (a toy car never stops)"); + assert.ok(!run(30).some((h) => h.id === "bounce:squeal"), "straight ahead, no squeal"); + const squeal = run(30, () => (you.vx = bounce.STEER_SPEED)).filter((h) => h.id === "bounce:squeal"); + assert.ok(squeal.length > 0 && squeal.every((h) => h.level > 0), "steering hard at speed squeals"); + const monster = bounceRival(g.round, "monster", at.x, at.d + 40); + assert.ok(run(4).some((h) => h.id === "bounce:monster"), "the Monster truck rumbles near"); + monster.d = at.d + 1000; + assert.ok(!run(4).some((h) => h.id === "bounce:monster"), "and not from far off"); + for (const h of hums) assert.ok(known.has(h.name), `${h.name} is a hum tones.js has`); + g.pause(); + hums.length = 0; + g.tick(16); + assert.equal(hums.length, 0, "paused, nothing is held, so it all fades"); +}); + +test("Bounce Road game: a landing thuds louder the further it fell", () => { + const tones = []; + const { g } = bounceGame({ tone: (name, level) => tones.push([name, level]) }); + const you = g.round.cars[0]; + const thud = (airMax) => { + tones.length = 0; + you.airMax = airMax; + g.round.events.push({ type: "land", x: you.x, d: you.d, chain: 0, holes: 0, overs: [], big: false, points: 0 }); + g.tick(16); + return tones.find(([n]) => n === "bounceLand")[1]; + }; + assert.ok(thud(1500) > thud(450), "a big fall lands harder"); +}); + +test("Bounce Road game: a ring in your highlight shows where your jump comes down, only while you are in the air", () => { + const strokesFor = (setup) => { + const { canvas, strokes } = styleCanvas(); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + setup(g.round.cars[0]); + strokes.length = 0; + g.resize(900, 900); + return strokes.filter((c) => c === "#206cc3").length; + }; + const base = strokesFor(() => {}); + assert.equal(strokesFor((you) => Object.assign(you, { v: 30, air: 300, airMax: 600 })), base + 1, "in the air, one more"); +}); + +test("Bounce Road game: the road's surface and edge lines are drawn slanting from each row's edges to the next's, never in stair steps", () => { + const paths = []; + let path = []; + const ctx = new Proxy({}, { + get: (t, name) => { + if (name === "beginPath") return () => (path = []); + if (name === "moveTo" || name === "lineTo") return (x, y) => path.push([x, y]); + if (name === "fill") return () => paths.push({ color: t.fillStyle, pts: path }); + if (name === "fillRect") return () => paths.push({ color: t.fillStyle, rect: true }); + return name in t ? t[name] : () => {}; + }, + set: (t, n, v) => { t[n] = v; return true; }, + }); + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.road = bounce.newRoad(3); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + const r = g.round.road; + let at = 60; + while (!(r.deck[at] === 1 && r.stageOf[at] === 1 && Math.abs(r.L[at] - r.L[at - 1]) > 0.3)) at++; + const you = g.round.cars[0]; + for (let k = 0; k < 40; k++) { + Object.assign(you, { d: at * bounce.ROW, x: (r.L[at] + r.R[at]) / 2, air: 0 }); + g.round.far = 1e9; + g.tick(16); + } + paths.length = 0; + g.resize(900, 900); + const road = paths.filter((p) => p.color === LOOKS.chalk.road); + assert.ok(road.length > 20, `the road drawn row by row (${road.length})`); + assert.ok(road.every((p) => !p.rect && p.pts.length === 4), "as bands, never boxes"); + assert.ok(road.some((p) => Math.abs(p.pts[0][0] - p.pts[3][0]) > 0.05), "some slanting"); + const edges = paths.filter((p) => p.color === LOOKS.chalk.edge && !p.rect); + assert.ok(edges.length > 20, "the edge lines too"); +}); + +test("Bounce Road game: the opening banner sits in the field from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.32)"); + const g = game.create({ canvas }); + g.resize(900, 900); + openingBanner(g, shades, bounce.FIELD_H); +}); + +test("Bounce Road game: the road is drawn off screen a chunk at a time, once per chunk, and the frames copy the chunks", () => { + const saved = globalThis.OffscreenCanvas; + const layers = []; + globalThis.OffscreenCanvas = class { + constructor(w, h) { + this.width = w; + this.height = h; + this.names = []; + layers.push(this); + const names = this.names; + this.ctx = new Proxy({}, { + get: (t, name) => (name in t ? t[name] : () => { + names.push(name); + }), + set: (t, n, v) => { t[n] = v; return true; }, + }); + } + getContext() { return this.ctx; } + }; + try { + const { canvas, names } = recordingCanvas(); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + const you = g.round.cars[0]; + const road = g.round.road; + you.d = 48 * 4 + 10 + bounce.BEHIND; + you.x = (road.L[Math.floor(you.d / bounce.ROW)] + road.R[Math.floor(you.d / bounce.ROW)]) / 2; + g.round.far = you.d; + for (let k = 0; k < 30; k++) g.tick(16); + you.v = 0; + layers.length = 0; + names.length = 0; + g.tick(16); + g.tick(16); + assert.equal(layers.length, 0, "kept from frame to frame, never drawn again"); + assert.ok(names.filter((n) => n === "drawImage").length >= 4, "copied every frame"); + const rects = names.filter((n) => n === "fillRect").length; + assert.ok(rects < 400, `with no row drawn by hand (${rects})`); + // On to plain road a few chunks on, in its middle: never over a crack + // or water, where a crash would hold the view still. + const next = plainSpot(road, you.d + 48 * 4, 10); + Object.assign(you, { d: next.d, x: next.x, v: 0, air: 0 }); + g.round.far = you.d; + for (let k = 0; k < 20; k++) g.tick(16); + assert.ok(layers.length >= 2, `new road, new chunks (${layers.length})`); + assert.ok(layers.every((l) => l.names.length > 50), "the road drawn on them"); + } finally { + if (saved === undefined) delete globalThis.OffscreenCanvas; + else globalThis.OffscreenCanvas = saved; + } +}); + +test("Bounce Road game: Night Lights is dark but for your headlights' reach", () => { + const fills = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fill" ? (rule) => fills.push(rule || "") : name in t ? t[name] : () => {}), + set: (t, n, v) => { t[n] = v; return true; }, + }); + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + g.round.cars.length = 1; + g.round.spawnMs = 1e12; + fills.length = 0; + g.tick(16); + assert.ok(!fills.includes("evenodd"), "by day, no dark"); + bounce.ensureRoad(g.round.road, 30000); + const night = bounce.STAGES.findIndex((s) => s.id === "night") + 1; + g.round.stage = night; + const you = g.round.cars[0]; + you.d = g.round.road.stageAt[night - 1] + 30; + g.round.far = 1e9; + fills.length = 0; + g.tick(16); + assert.ok(fills.includes("evenodd"), "at night, the dark with the headlights cut out of it"); +}); diff --git a/scripts/test-web-console-activities-bounce.mjs b/scripts/test-web-console-activities-bounce.mjs new file mode 100644 index 0000000..436b107 --- /dev/null +++ b/scripts/test-web-console-activities-bounce.mjs @@ -0,0 +1,1329 @@ +// Web console tests, Bounce Road's rules: driving, jumps, landings and bumps, the bounce chain and the combo, the road and its fairness (every hole jumpable, a run-up before each), the timed parts (drawbridges, swaying bridges, crumbling road), the hazards (boost strips, ramps, slicks, barriers, trains, balls, sprinklers, falling things, gusts), every rival's ways and the Monster truck, the stages and laps, the banner's strip, the colors and the pill layout, and bots that show every stage is passable and that a careless run ends quickly. The game contract, the pills' contrast, the tones and the drawing are in scripts/test-web-console-activities-bounce-game.mjs. +// Run with: node --test scripts/test-web-console-activities-bounce.mjs +// +// No browser and no server: the game draws only through the canvas it is +// handed, so a stub canvas stands in for the page, as in +// scripts/test-web-console-activities.mjs, whose helpers this file copies. + +import test from "node:test"; +import assert from "node:assert/strict"; +import * as bounce from "../src/web-console/public/activities/bounce.js"; +import { hudLayout, labelSpot, LOOKS, limbInk, contrast, inkOn } from "../src/web-console/public/activities/bounce-draw.js"; +import { CAR_STYLES } from "../src/web-console/public/activities/bounce-cars.js"; +import { ACCENTS } from "../src/web-console/public/palette.js"; + + +/* ------------------------------------------------------------- helpers */ + +// A random source that always says the same, so no rival guesses. +const steady = () => 0.5; +const eventsOf = (round, type) => round.events.filter((e) => e.type === type); + +// A round on the road from `seed`, with only you on it unless `rivals`. +function bounceRound(seed = 7, rivals = false) { + const round = bounce.newRound(seed, steady); + if (!rivals) round.cars.length = 1; + round.spawnMs = 1e12; + return round; +} + +// A rival of `kind` put at (x, d), still and on the ground, going nowhere on +// its own. +function bounceRival(round, kind, x, d, over = {}) { + const car = bounce.spawnRival(round, kind, steady, round.cars[0].d + 300); + assert.ok(car, `a ${kind} spawns`); + Object.assign(car, { x, d, v: 0, tv: 0, vx: 0, kx: 0, air: 0, tx: x, lane: x, hopIn: 1e9, dropIn: 1e9, mode: "calm", ...over }); + return car; +} + +// A spot on plain road: the middle of the first row at or after `d` with +// nothing to catch you out for `clear` units either side (no hole, water, +// flowerbed, timed part, rails, pad, barrier or hazard). +function plainSpot(road, d = 40, clear = 20) { + bounce.ensureRoad(road, d + 400); + const busy = (lo, hi) => [road.pads, road.blocks, road.hazards, road.items, road.stars].some((list) => list.some((e) => e.d > lo - 12 && (e.d1 ?? e.d) > lo - 12 && e.d < hi + 12)); + for (let i = Math.floor(d / bounce.ROW); i < road.rows; i++) { + let ok = true; + for (let j = i - clear / bounce.ROW; ok && j <= i + clear / bounce.ROW; j++) ok = bounce.plainRow(road, j); + if (ok && !busy(i * bounce.ROW - clear, i * bounce.ROW + clear)) return { x: (road.L[i] + road.R[i]) / 2, d: i * bounce.ROW + 1, i }; + } + throw new Error("no plain road"); +} + +// The first stage whose road holds an entry of `list` matching `pick`, with +// you put a little before it on the stage and the round set to that stage. +function onto(round, list, pick, before = 30) { + const road = round.road; + bounce.ensureRoad(road, 40000); + const e = road[list].find(pick); + assert.ok(e, `a ${list} entry on the road`); + const d0 = e.d ?? e.d0; + while (road.stageAt[round.stage] <= d0) round.stage++; + const you = round.cars[0]; + const d = d0 - before; + const i = bounce.rowOf(d); + Object.assign(you, { d, x: (road.L[i] + road.R[i]) / 2, v: 40, air: 0, pnose: d + you.l / 2 }); + round.far = 1e9; + return e; +} + +// A careful bot: full throttle, the middle of the narrowest road just ahead +// (its side of a flowerbed, the band a swaying bridge always covers), round +// the nearest barrier, falling thing or car in the way, and a jump at every +// hole, ball, train that is coming and barrier it cannot get round. +function carefulBot(round) { + const you = round.cars[0]; + const road = round.road; + const inp = round.input; + inp.up = true; + inp.down = false; + let lo = -1e9; + let hi = 1e9; + let side = 0; + for (let d = you.d; d < you.d + 40; d += bounce.ROW) { + const i = Math.max(0, Math.min(road.rows - 1, Math.floor(d / bounce.ROW))); + let L = road.L[i]; + let R = road.R[i]; + if (road.deck[i] === 2) { + const s = road.dyn[road.dynOf[i] - 1]; + L += s.amp; + R -= s.amp; + } + if (road.ML[i] < road.MR[i]) { + side ||= you.x < (road.ML[i] + road.MR[i]) / 2 ? -1 : 1; + if (side < 0) R = road.ML[i]; + else L = road.MR[i]; + } + lo = Math.max(lo, L); + hi = Math.min(hi, R); + } + let tx = (lo + hi) / 2; + const things = []; + for (const list of [road.blocks, round.drops]) for (const o of list) if (!o.hit && o.d - you.d > -2 && o.d - you.d < 40) things.push(o); + for (const h of road.hazards) if (h.kind === "drop" && h.at && !h.landed && h.d - you.d > -4 && h.d - you.d < 70) things.push(h); + for (const c of round.cars) if (c.id !== 0 && c.out === 0 && c.d - you.d > 0 && c.d - you.d < 24) things.push(c); + things.sort((p, q) => p.d - q.d); + const o = things[0]; + if (o && Math.abs(tx - o.x) < (o.w + you.w) / 2 + 1.6) { + const l = o.x - (o.w + you.w) / 2 - 1.6; + const r = o.x + (o.w + you.w) / 2 + 1.6; + tx = l - lo > hi - r ? l : r; + } + tx = Math.min(hi - you.w / 2 - 0.8, Math.max(lo + you.w / 2 + 0.8, tx)); + inp.left = tx < you.x - 0.5; + inp.right = tx > you.x + 0.5; + const soon = (d) => d > you.d && d - you.d < 3 + you.v * 0.02 + you.l / 2; + for (let k = bounce.firstAt(road.holes, "d0", you.d); k < road.holes.length && road.holes[k].d0 < you.d + 20; k++) if (soon(road.holes[k].d0)) inp.jump = bounce.JUMP_BUFFER_MS; + for (const h of road.hazards) { + if (h.kind === "ball" && soon(h.d - h.r - 1)) inp.jump = bounce.JUMP_BUFFER_MS; + if (h.kind === "train" && soon(h.d - h.half - 1) && bounce.trainAt(h, round.clock + 150).warn) inp.jump = bounce.JUMP_BUFFER_MS; + } + for (const b of things) if (b.l && b.kind && b.id === undefined && soon(b.d - b.l / 2) && Math.abs(b.x - you.x) < (b.w + you.w) / 2) inp.jump = bounce.JUMP_BUFFER_MS; +} + +// Plays `round` with `bot` until `stage` or the end, `ms` at most, a rival's +// random seeded; returns the seconds each stage took and the lives lost. +function play(round, bot, { stage = 11, ms = 900000, rivals = false, seed = 1 } = {}) { + const random = rivals ? bounce.seeded(seed * 13) : steady; + const secs = []; + const lost = []; + let t = 0; + let at = 0; + while (round.stage < stage && t < ms && !round.over) { + if (!rivals) round.cars.length = 1; + bot(round); + bounce.advance(round, 16, random); + t += 16; + for (const e of round.events) { + if (e.type === "stage") { + secs.push((t - at) / 1000); + at = t; + } + if (e.type === "lose") lost.push(`${e.cause} at stage ${round.stage}`); + } + round.events.length = 0; + } + return { secs, lost, ms: t }; +} + +/* ------------------------------------------------------- driving */ + +test("Bounce Road: full throttle reaches TOP_SPEED and holds it, the verge holds it to VERGE_TOP of that, and the brake slows a toy car only to ROLL_SPEED", () => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 40, 20); + round.input.up = true; + let fastest = 0; + for (let ms = 0; ms < 3000; ms += 4) { + bounce.move(round, you, 4); + fastest = Math.max(fastest, you.v); + Object.assign(you, { d: at.d, x: at.x }); + } + assert.ok(Math.abs(you.v - bounce.TOP_SPEED) < 1e-6, `at top speed (${you.v})`); + assert.ok(fastest <= bounce.TOP_SPEED + 1e-6, "and never past it"); + for (let ms = 0; ms < 2000; ms += 4) { + you.x = round.road.L[at.i] - 3; + you.d = at.d; + bounce.move(round, you, 4); + } + assert.ok(Math.abs(you.v - bounce.TOP_SPEED * bounce.VERGE_TOP) < 0.5, `the verge slows it (${you.v})`); + round.input.up = false; + round.input.down = true; + for (let ms = 0; ms < 3000; ms += 4) bounce.move(round, you, 4); + assert.equal(you.v, bounce.ROLL_SPEED, "the brake leaves it rolling"); +}); + +test("Bounce Road: a jump needs JUMP_MIN, lasts airMs(v), longer the faster, holds its speed in the air, steers only AIR_STEER as much, and a Spring lengthens it", () => { + const round = bounceRound(); + const you = round.cars[0]; + you.v = bounce.JUMP_MIN - 1; + assert.equal(bounce.jump(round, you), false, "too slow to jump"); + assert.ok(bounce.airMs(40) > bounce.airMs(20) && bounce.reach(60) > bounce.reach(40) * 1.5, "faster goes higher and further"); + you.v = 40; + assert.equal(bounce.jump(round, you), true); + assert.equal(you.air, bounce.airMs(40)); + assert.equal(you.jumps, 1, "each jump counted, so a rival decides once a jump whether to dodge it"); + assert.equal(bounce.jump(round, you), false, "never twice in the air"); + round.input.up = true; + round.input.right = true; + const x0 = you.x; + for (let ms = 0; ms < 300; ms += 4) bounce.move(round, you, 4); + assert.equal(you.v, 40, "the throttle does nothing in the air"); + const airMove = you.x - x0; + const ground = bounceRound(); + const g = ground.cars[0]; + ground.input.right = true; + for (let ms = 0; ms < 300; ms += 4) bounce.move(ground, g, 4); + assert.ok(airMove > 0 && airMove < (g.x - x0) * (bounce.AIR_STEER + 0.15), `only a nudge in the air (${airMove.toFixed(2)} against ${(g.x - x0).toFixed(2)})`); + const s = bounceRound().cars[0]; + s.v = 40; + bounce.jump(round, s, bounce.SPRING_AIR); + assert.equal(s.air, bounce.airMs(40) * bounce.SPRING_AIR); +}); + +test("Bounce Road: landing on a rival flattens it for its own points and rebounds, a second landing before the road steps the chain, and the road ends it", () => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 30); + Object.assign(you, { x: at.x, d: at.d, v: 40, air: 4, airMax: 600, jumpFrom: at.d - 20 }); + round.far = 1e9; + const a = bounceRival(round, "zigzag", at.x, at.d + 1); + const b = bounceRival(round, "brick", at.x, at.d + 60); + bounce.advance(round, 4, steady); + assert.ok(a.out > 0 && a.outKind === "flat", "the first is flattened"); + assert.equal(round.chain, 1); + assert.equal(round.score, bounce.RIVALS.zigzag.points, "a crush scores the rival's points"); + assert.equal(you.air, bounce.REBOUND_MS, "and you bounce up again"); + for (let ms = 0; ms < bounce.REBOUND_MS + 8 && round.chain < 2; ms += 4) { + Object.assign(b, { x: you.x, d: you.d, v: 0 }); + bounce.advance(round, 4, steady); + } + assert.equal(round.chain, 2, "a second landing steps the chain"); + assert.equal(round.score, bounce.RIVALS.zigzag.points + bounce.RIVALS.brick.points * 2, "and scores twice its points"); + for (let ms = 0; ms < bounce.REBOUND_MS + 8; ms += 4) bounce.advance(round, 4, steady); + assert.equal(you.air, 0); + assert.equal(round.chain, 0, "the road ends it"); + assert.equal(round.bestChain, 2); + assert.ok(bounce.MAX_CHAIN >= 8, "a long chain to chase"); +}); + +test("Bounce Road: the Hauler cannot be bumped and its back is a crash, but its roof is a rebound that steps the chain and leaves it rolling", () => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 30); + Object.assign(you, { x: at.x - 5, d: at.d, vx: 34 }); + const hauler = bounceRival(round, "hauler", at.x, at.d); + bounce.collide(round, you, hauler); + assert.ok(Math.abs(hauler.kx) < Math.abs(you.kx) / 5, `a side bump barely moves it (${hauler.kx.toFixed(1)} against ${you.kx.toFixed(1)})`); + Object.assign(you, { x: at.x, d: at.d - 9, v: 50, kx: 0, vx: 0 }); + hauler.v = 20; + bounce.collide(round, you, hauler); + assert.equal(round.phase, "crash", "into its back is a crash"); + assert.equal(round.lives, bounce.START_LIVES - 1); + const r2 = bounceRound(); + const y2 = r2.cars[0]; + const at2 = plainSpot(r2.road, 60, 30); + Object.assign(y2, { x: at2.x, d: at2.d, v: 40, air: 4, airMax: 600 }); + r2.far = 1e9; + const h2 = bounceRival(r2, "hauler", at2.x, at2.d + 2); + bounce.advance(r2, 4, steady); + assert.equal(h2.out, 0, "it rolls on"); + assert.equal(y2.air, bounce.REBOUND_MS); + assert.equal(r2.chain, 1); + assert.equal(r2.score, bounce.HAUL_POINTS, "its roof scores HAUL_POINTS"); +}); + +test("Bounce Road: a rival bumped past the road's edge is out, and yours for BUMP_POINTS within CREDIT_MS; one that goes off later scores nothing", () => { + const off = (wait) => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 30); + const edge = round.road.R[at.i]; + const rival = bounceRival(round, "zigzag", edge - 3, at.d + 0.5); + Object.assign(you, { x: edge - 3 - 4, d: at.d, vx: 34 }); + bounce.collide(round, you, rival); + assert.ok(rival.kx > 20, `knocked hard toward the edge (${rival.kx.toFixed(1)})`); + rival.kx = 0; + you.x -= 10; + for (let ms = 0; ms < wait; ms += 4) { + you.vx = 0; + Object.assign(rival, { x: edge - 3, tv: 0, v: 0 }); + bounce.advance(round, 4, steady); + } + round.far = 1e9; + const before = round.score; + rival.x = edge + 2; + bounce.advance(round, 4, steady); + return { round, rival, got: round.score - before }; + }; + const quick = off(400); + assert.ok(quick.rival.out > 0 && quick.rival.outKind === "tip", "off the road it tips over"); + assert.equal(quick.round.stats.bumped, 1); + assert.equal(quick.got, bounce.BUMP_POINTS, "and scores"); + const late = off(bounce.CREDIT_MS + 100); + assert.ok(late.rival.out > 0); + assert.equal(late.round.stats.bumped, 0, "too late to be yours"); + assert.equal(late.got, 0); +}); + +test("Bounce Road: water or a hole under your wheels costs a life, flying over it does not, and a Bubble throws you clear instead", () => { + const round = bounceRound(); + const you = round.cars[0]; + const hole = round.road.holes.find((h) => h.kind === "crack"); + Object.assign(you, { d: hole.d0 + 2, v: 40, air: 300, airMax: 600 }); + bounce.advance(round, 100, steady); + assert.equal(round.phase, "drive", "in the air over it, nothing"); + you.air = 0; + you.d = hole.d0 + 2; + bounce.advance(round, 4, steady); + assert.equal(round.phase, "crash"); + assert.equal(round.lives, bounce.START_LIVES - 1, "wheels down over the hole: a life"); + for (let ms = 0; ms < bounce.CRASH_MS + 40; ms += 4) bounce.advance(round, 4, steady); + assert.equal(round.phase, "ready"); + assert.ok(you.d < hole.d0 - bounce.RESPAWN_BACK / 2, `back before the hole (${you.d.toFixed(0)} < ${hole.d0})`); + assert.equal(bounce.groundAt(round.road, you.x, you.d), bounce.GROUND.road, "on the road"); + const saved = bounceRound(); + const s = saved.cars[0]; + s.bubble = true; + Object.assign(s, { d: hole.d0 + 2, v: 40 }); + bounce.advance(saved, 4, steady); + assert.equal(saved.phase, "drive"); + assert.equal(saved.lives, bounce.START_LIVES, "the Bubble pops instead"); + assert.equal(s.bubble, false); + assert.ok(s.air > 0, "and throws you up"); + for (let ms = 0; ms < 3000 && s.air > 0; ms += 4) bounce.advance(saved, 4, steady); + assert.ok(s.d > hole.d1, "clear over the hole"); + for (let ms = 0; ms < 200; ms += 4) bounce.advance(saved, 4, steady); + assert.equal(saved.lives, bounce.START_LIVES, "onto the road"); +}); + +test("Bounce Road: a broken span the Bubble's throw carries you over is the Bubble's, never a jump of yours that scores", () => { + const round = bounceRound(1); + const road = round.road; + bounce.ensureRoad(road, 20000); + const span = road.holes.find((h) => h.kind === "span"); + assert.ok(span, "a broken span on the road"); + const river = road.rivers.find((r) => r.d0 <= span.d0 && r.d1 >= span.d1); + const you = round.cars[0]; + while (road.stageAt[round.stage] <= river.d0) round.stage++; + const d = river.d0 + 4; + Object.assign(you, { d, x: road.L[bounce.rowOf(d)] - 3, v: 40, air: 0, bubble: true }); + Object.assign(round, { far: d, score: 0 }); + bounce.advance(round, 4, steady); + assert.ok(you.air > 0 && you.bubble === false, "the Bubble pops and throws you"); + for (let ms = 0; ms < 3000 && you.air > 0; ms += 4) bounce.advance(round, 4, steady); + assert.ok(you.d > span.d1, "clear over the break"); + const land = round.events.find((e) => e.type === "land"); + assert.equal(land.holes, 0, "no hole counted as jumped"); + assert.equal(round.stats.holes, 0); + assert.equal(round.lives, bounce.START_LIVES); +}); + +/* ---------------------------------------------------- the road is fair */ + +test("Bounce Road: every hole of the first twenty stages, on many roads, is jumpable at JUMP_FAIR of the top speed (a drawbridge's lifted span included), with a run-up of road and a sign before it, and even the longest jump off the first of two breaks lands on the bridge between", () => { + const fair = bounce.reach(bounce.JUMP_FAIR * bounce.TOP_SPEED); + let twins = 0; + let draws = 0; + assert.ok(bounce.MIN_HOLE / 2 > (bounce.MAX_SPEED * bounce.SLICE_MS) / 1000, "no slice moves a car half the shortest hole"); + assert.ok(bounce.MAX_HOLE + bounce.CAR_L <= fair, "the longest hole any stage may cut is jumpable"); + for (let seed = 1; seed <= 8; seed++) { + const road = bounce.newRoad(seed); + while (road.built < 20) bounce.buildStage(road, road.built + 1); + assert.ok(road.holes.length > 30, `seed ${seed} cuts holes`); + const solid = (from, to) => { + for (let i = Math.floor(from / bounce.ROW); i < Math.floor(to / bounce.ROW); i++) if (!road.deck[i] || road.dynOf[i]) return false; + return true; + }; + const riverOf = (x) => road.rivers.find((r) => r.d0 <= x.d0 && r.d1 >= x.d1); + for (let k = 0; k < road.holes.length; k++) { + const h = road.holes[k]; + const len = h.d1 - h.d0; + if (h.kind === "draw") draws++; + assert.ok(len >= bounce.MIN_HOLE && len <= bounce.MAX_HOLE, `seed ${seed}: a hole ${len} long`); + assert.ok(len + bounce.CAR_L <= fair, `seed ${seed}: a ${len} hole is jumpable at ${bounce.JUMP_FAIR * bounce.TOP_SPEED} (${fair.toFixed(1)})`); + const prev = k ? road.holes[k - 1] : null; + if (prev && h.kind === "span" && prev.kind === "span" && riverOf(prev) === riverOf(h)) { + twins++; + assert.ok(prev.d0 + bounce.LONGEST_JUMP < h.d0 - 1, `seed ${seed}: the longest jump from the first brink (${bounce.LONGEST_JUMP.toFixed(1)}) lands before the second break (${h.d0 - prev.d0} on)`); + assert.ok(bounce.LONGEST_JUMP >= bounce.reach(bounce.MAX_SPEED) * bounce.RAMP_AIR, "a ramp goes no further"); + assert.ok(h.d0 - prev.d1 >= 24 && solid(prev.d1, h.d0), "on a bridge long enough to jump again"); + } else { + assert.ok(!prev || h.d0 - prev.d1 >= bounce.RUNUP - 10, `seed ${seed}: only two breaks on one bridge sit close`); + const runup = h.kind === "crack" ? bounce.RUNUP : bounce.RUNUP - 34; + for (let i = Math.floor((h.d0 - runup) / bounce.ROW); i < Math.floor(h.d0 / bounce.ROW); i++) assert.ok(road.deck[i] === 1 && !road.dynOf[i], `seed ${seed}: a run-up of road before the hole at ${h.d0}`); + assert.ok(road.signs.some((s) => s.d < h.d0 && s.d > h.d0 - bounce.RUNUP - 60), `seed ${seed}: a sign before the hole at ${h.d0}`); + } + } + } + assert.ok(twins > 12, `bridges with two breaks were checked (${twins})`); + assert.ok(draws > 8, `drawbridges were checked (${draws})`); +}); + +test("Bounce Road: with a Spring held and a Nitro burning, a jump off the first of two breaks at full speed comes down on the bridge between, never in the second break", () => { + const round = bounceRound(1); + const road = round.road; + bounce.ensureRoad(road, 40000); + const riverOf = (h) => road.rivers.find((r) => r.d0 <= h.d0 && r.d1 >= h.d1); + const k = road.holes.findIndex((h, j) => j && h.kind === "span" && road.holes[j - 1].kind === "span" && riverOf(h) === riverOf(road.holes[j - 1])); + assert.ok(k > 0, "a bridge with two breaks"); + const [first, second] = [road.holes[k - 1], road.holes[k]]; + while (road.stageAt[round.stage] <= first.d0) round.stage++; + const you = round.cars[0]; + const i = bounce.rowOf(first.d0 - 1); + Object.assign(you, { d: first.d0 - 0.5, x: (road.L[i] + road.R[i]) / 2, v: bounce.TOP_SPEED * bounce.NITRO_TOP, nitroMs: bounce.NITRO_MS, spring: true }); + round.far = 1e9; + round.input.up = true; + round.input.jump = bounce.JUMP_BUFFER_MS; + bounce.advance(round, 4, steady); + assert.ok(you.air > bounce.airMs(bounce.TOP_SPEED), "a long, sprung jump"); + for (let ms = 0; ms < 3000 && you.air > 0; ms += 4) bounce.advance(round, 4, steady); + assert.equal(round.phase, "drive", "no splash"); + assert.ok(!round.events.some((e) => e.type === "lose" || e.type === "bubble"), "no life lost"); + assert.ok(you.d > first.d1 && you.d < second.d0, `down on the bridge between (${you.d.toFixed(1)}, between ${first.d1} and ${second.d0})`); +}); + +test("Bounce Road: a life lost puts you back with RESPAWN_RUN of plain road ahead, room to reach JUMP_FAIR of the top speed from a roll before the next hole, river or crumbling road", () => { + const need = (bounce.JUMP_FAIR * bounce.TOP_SPEED) ** 2 - bounce.ROLL_SPEED ** 2; + assert.ok(bounce.RESPAWN_RUN > need / (2 * bounce.ACCEL) + 0.5 * bounce.ROLL_SPEED, "a run-up long enough, with half a second to react"); + for (let seed = 1; seed <= 4; seed++) { + const road = bounce.newRoad(seed); + while (road.built < 11) bounce.buildStage(road, road.built + 1); + const danger = [...road.holes.map((h) => h.d0), ...road.rivers.map((r) => r.d0), ...road.dyn.map((s) => s.d0)].sort((a, b) => a - b); + for (let d = 60; d < road.stageAt[10]; d += 9) { + const at = bounce.safeSpot(road, d); + const next = danger.find((x) => x > at); + assert.ok(next - at >= bounce.RESPAWN_RUN, `seed ${seed}: back at ${at.toFixed(0)} after a crash at ${d}, ${(next - at).toFixed(0)} before the next hole`); + assert.ok(d - at < 450, `seed ${seed}: never far back (${(d - at).toFixed(0)})`); + } + } +}); + +test("Bounce Road: the road's edges slant from row to row the way they are drawn, never a stair step: the ground under a car eases from one row's edge to the next", () => { + const road = bounce.newRoad(3); + while (road.built < 4) bounce.buildStage(road, road.built + 1); + let checked = 0; + for (let i = 1; i < road.rows; i++) { + if (road.deck[i] !== 1 || road.dynOf[i] || road.ML[i] < road.MR[i] || Math.abs(road.L[i] - road.L[i - 1]) < 1) continue; + const x = (road.L[i] + road.L[i - 1]) / 2; + const near = bounce.groundAt(road, x, i * bounce.ROW + 0.1); + const far = bounce.groundAt(road, x, i * bounce.ROW + bounce.ROW - 0.1); + assert.notEqual(near, far, `row ${i}: halfway between its edges, the ground changes along the row`); + const mid = road.L[i - 1] + (road.L[i] - road.L[i - 1]) * 0.5; + assert.equal(bounce.groundAt(road, mid + 0.05, i * bounce.ROW + 1), bounce.GROUND.road, "just inside the eased edge, road"); + assert.notEqual(bounce.groundAt(road, mid - 0.05, i * bounce.ROW + 1), bounce.GROUND.road, "just outside it, not"); + checked++; + } + assert.ok(checked > 20, `slanted rows checked (${checked})`); +}); + +test("Bounce Road: a long run's lists are read from where the view is, not from the start: firstAt finds the same entries a full scan does, and holesIn too, and every list is laid in order along the road", () => { + const road = bounce.newRoad(4); + bounce.ensureRoad(road, 30000); + for (const [list, key] of [[road.holes, "d0"], [road.signs, "d"], [road.items, "d"], [road.stars, "d"], [road.pads, "d"], [road.blocks, "d"], [road.hazards, "d"], [road.dyn, "d0"]]) { + for (let k = 1; k < list.length; k++) assert.ok(list[k][key] >= list[k - 1][key], `${key} in order`); + } + for (const d of [-5, 0, 333, 5000, 12345, 19999, 1e9]) { + for (const [list, key] of [[road.holes, "d0"], [road.signs, "d"], [road.items, "d"], [road.hazards, "d"]]) { + const k = bounce.firstAt(list, key, d); + assert.ok(list.slice(0, k).every((e) => e[key] < d) && list.slice(k).every((e) => e[key] >= d), `${key} at ${d}`); + } + for (const len of [10, 80, 400]) assert.deepEqual(bounce.holesIn(road, d, d + len), road.holes.filter((h) => h.d0 > d && h.d1 <= d + len)); + } +}); + +test("Bounce Road: the rivals' list is kept in place from slice to slice, with the ones far behind dropped", () => { + const round = bounceRound(5, true); + const cars = round.cars; + assert.ok(cars.length >= 2); + const far = cars[1]; + far.d = round.cars[0].d - 500; + bounce.advance(round, 40, steady); + assert.equal(round.cars, cars, "the same list"); + assert.ok(!cars.includes(far), "the one far behind is gone"); + assert.equal(cars[0].id, 0, "you first"); +}); + +test("Bounce Road: the same seed builds the same road, a different one another, every stage keeps the road on the field and a flowerbed with room either side, and past the tenth the road goes round again, quicker and meaner", () => { + const a = bounce.newRoad(42); + const b = bounce.newRoad(42); + const c = bounce.newRoad(43); + for (const r of [a, b, c]) while (r.built < 12) bounce.buildStage(r, r.built + 1); + assert.deepEqual([a.L, a.R, a.ML, a.deck, a.under, a.dynOf, a.stageAt, a.hazards.map((h) => h.kind)], [b.L, b.R, b.ML, b.deck, b.under, b.dynOf, b.stageAt, b.hazards.map((h) => h.kind)]); + assert.notDeepEqual(a.L, c.L); + for (let i = 0; i < a.rows; i++) { + assert.ok(a.L[i] >= 1 && a.R[i] <= bounce.FIELD_W - 1, `row ${i} on the field`); + if (a.ML[i] < a.MR[i]) assert.ok(a.ML[i] - a.L[i] >= 15 && a.R[i] - a.MR[i] >= 15, `row ${i}: room round the flowerbed`); + } + assert.equal(bounce.STAGES.length, 10, "ten stages"); + assert.equal(new Set(bounce.STAGES.map((s) => s.id)).size, 10, "each with its own look"); + for (const s of bounce.STAGES) assert.ok(LOOKS[s.id], `${s.id} has a look`); + for (let n = 1; n <= 10; n++) { + const len = a.stageAt[n] - a.stageAt[n - 1]; + assert.ok(len >= bounce.STAGES[n - 1].len && len < bounce.STAGES[n - 1].len + 350, `stage ${n} is ${len} long`); + } + assert.equal(bounce.stageFor(11), bounce.stageFor(11), "built once"); + assert.equal(bounce.stageFor(11).name, `${bounce.STAGES[bounce.LAP_FROM - 1].title} 2`); + assert.equal(bounce.stageFor(18).name, "Monster Mash 2"); + assert.ok(bounce.stageFor(18).boss, "the Monster is back each lap"); + assert.ok(bounce.stageFor(11).pace > bounce.stageFor(bounce.LAP_FROM).pace && bounce.stageFor(40).rivals <= bounce.MAX_RIVALS && bounce.stageFor(40).crack[1] <= bounce.MAX_HOLE); +}); + +test("Bounce Road: each stage brings something new: its own pieces, hazards or rivals, and later stages bring more at once", () => { + const seen = new Set(); + let before = 0; + for (const s of bounce.STAGES) { + const things = [...Object.keys(s.weights).filter((k) => k !== "straight" && s.weights[k] > 0), ...s.kinds]; + const fresh = things.filter((t) => !seen.has(t)); + if (s.n !== 1) assert.ok(fresh.length > 0 || s.boss || s.id === "night", `${s.title} brings something new (Night Lights brings the dark)`); + for (const t of things) seen.add(t); + assert.ok(things.length >= before - 7, `${s.title} keeps up the mix (${things.length})`); + before = Math.max(before, things.length); + } + for (const piece of bounce.PIECE_NAMES) if (piece !== "straight") assert.ok(seen.has(piece), `the ${piece} turns up`); + for (const kind of bounce.RIVAL_KINDS) if (kind !== "monster") assert.ok(seen.has(kind), `the ${kind} turns up`); + const kinds = new Set(); + for (const seed of [2, 9]) { + const road = bounce.newRoad(seed); + while (road.built < 10) bounce.buildStage(road, road.built + 1); + for (const e of [...road.hazards, ...road.pads, ...road.blocks, ...road.dyn]) kinds.add(e.kind); + } + for (const k of ["train", "ball", "sprinkler", "drop", "wind", "boost", "ramp", "slick", "cone", "block", "draw", "sway", "crumble"]) assert.ok(kinds.has(k), `a ${k} on the road`); +}); + +/* ------------------------------------------------------------ bots */ + +test("Bounce Road: a careful bot crosses all ten stages with no rivals and no life lost, each stage taking 20 to 50 seconds", () => { + for (const seed of [3, 21]) { + const round = bounceRound(seed); + const { secs, lost } = play(round, carefulBot, { stage: 11 }); + assert.equal(round.stage, 11, `seed ${seed} reaches stage 11 (${round.stage}, lost ${lost})`); + assert.deepEqual(lost, [], `seed ${seed}: no life lost`); + for (const [n, s] of secs.entries()) assert.ok(s > 20 && s < 50, `seed ${seed}: stage ${n + 1} took ${s.toFixed(0)} s`); + } +}); + +test("Bounce Road: with the rivals out, the careful bot still gets far, but they cost it lives on the way", () => { + let lostAll = 0; + for (const seed of [11, 42]) { + const round = bounce.newRound(seed, bounce.seeded(seed)); + const { lost } = play(round, carefulBot, { stage: 11, rivals: true, seed }); + assert.ok(round.stage >= 6, `seed ${seed}: reached stage ${round.stage}`); + lostAll += lost.length; + assert.ok(round.stats.crushed + round.stats.bumped + round.stats.near > 5, "and it met them"); + } + assert.ok(lostAll >= 4, `the rivals cost lives (${lostAll})`); +}); + +test("Bounce Road: a sloppy bot that drives the middle and never jumps loses every life within the first two stages, in under a minute", () => { + for (const seed of [3, 11, 21]) { + const round = bounce.newRound(seed, steady); + const { ms } = play(round, (r) => { + const you = r.cars[0]; + const i = Math.floor(you.d / bounce.ROW); + const tx = (r.road.L[i] + r.road.R[i]) / 2; + Object.assign(r.input, { up: true, left: tx < you.x - 0.5, right: tx > you.x + 0.5 }); + }, { rivals: true, seed }); + assert.ok(round.over, `seed ${seed}: the run is over`); + assert.ok(round.stage <= 2 && ms < 60000, `seed ${seed}: at stage ${round.stage} after ${(ms / 1000).toFixed(0)} s`); + } +}); + +test("Bounce Road: with you out of the way the rivals keep driving, never under RIVAL_MIN_SPEED and never stuck, hop the holes, and hardly ever tip off the road on their own", () => { + let tipped = 0; + let hops = 0; + let seen = 0; + for (const seed of [2, 5]) { + const round = bounce.newRound(seed, steady); + const you = round.cars[0]; + const last = new Map(); + for (let ms = 0; ms < 160000; ms += 16) { + const i = Math.floor(you.d / bounce.ROW); + Object.assign(you, { ghostMs: 1e9, air: 1000, airMax: 1000, v: 46, x: round.road.ML[i] < round.road.MR[i] ? round.road.L[i] + 3 : (round.road.L[i] + round.road.R[i]) / 2 }); + bounce.advance(round, 16, steady); + for (const e of round.events) { + if (e.type === "wreck" && e.how === "tip") tipped++; + if (e.type === "hop") hops++; + } + round.events.length = 0; + for (const c of round.cars) { + if (c.id === 0 || c.out > 0) continue; + assert.ok(c.v >= bounce.RIVAL_MIN_SPEED - 1e-9, `${c.kind} keeps moving`); + if (ms % 2000 === 0) { + if (last.has(c)) assert.ok(c.d - last.get(c) > 20, `${c.kind} makes headway`); + last.set(c, c.d); + seen++; + } + } + } + assert.ok(round.stage >= 5, `you got as far as stage ${round.stage}`); + } + assert.ok(seen > 200 && hops > 40, `rivals seen ${seen}, hops ${hops}`); + assert.ok(tipped <= 12, `rivals tipped off the road on their own: ${tipped}`); +}); + +/* ------------------------------------------------------- the rivals */ + +test("Bounce Road: a jump pressed in the slice a Frog lands on you leaves the ground first, and two landing on each other in one slice is your crush", () => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 30); + Object.assign(you, { x: at.x, d: at.d, v: 40 }); + const frog = bounceRival(round, "frog", at.x, at.d, { air: 3, airMax: 640, v: 0 }); + round.input.jump = bounce.JUMP_BUFFER_MS; + bounce.advance(round, 4, steady); + assert.equal(round.phase, "drive", "no squash"); + assert.ok(you.air > 0, "you are up"); + assert.equal(frog.out, 0); + const r2 = bounceRound(); + const y2 = r2.cars[0]; + Object.assign(y2, { x: at.x, d: at.d, v: 40, air: 3, airMax: 600 }); + const f2 = bounceRival(r2, "frog", at.x, at.d + 0.5, { air: 3, airMax: 640, v: 0 }); + bounce.advance(r2, 4, steady); + assert.equal(r2.phase, "drive", "a dead heat is never your squash"); + assert.equal(f2.outKind, "flat", "it is the Frog's"); + assert.equal(r2.chain, 1); + const r3 = bounceRound(); + const y3 = r3.cars[0]; + Object.assign(y3, { x: at.x, d: at.d, v: 40 }); + bounceRival(r3, "frog", at.x, at.d, { air: 3, airMax: 640, v: 0 }); + bounce.advance(r3, 4, steady); + assert.equal(r3.phase, "crash", "a Frog landing on you with your wheels down squashes you"); +}); + +test("Bounce Road: the Brick holds the lane in front of you, the Nudge comes alongside and swipes into you up to 1 + 2 * sharp times, and the Zigzag weaves", () => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 60); + Object.assign(you, { x: at.x - 6, d: at.d, v: 40 }); + const brick = bounceRival(round, "brick", at.x + 6, at.d + 20, { v: 34 }); + for (let ms = 0; ms < 2000; ms += 4) { + bounce.think(round, brick, 4, steady); + bounce.move(round, brick, 4); + brick.d = at.d + 20; + } + assert.ok(Math.abs(brick.x - you.x) < 2, `the Brick slid over in front of you (${brick.x.toFixed(1)} against ${you.x.toFixed(1)})`); + const r2 = bounceRound(); + const y2 = r2.cars[0]; + Object.assign(y2, { x: at.x, d: at.d, v: 40 }); + const nudge = bounceRival(r2, "nudge", at.x + 6, at.d - 20, { v: 40, mode: "chase", chaseMs: 0 }); + const limit = 1 + Math.round(2 * bounce.stageFor(1).sharp); + for (let ms = 0; ms < 8000 && nudge.mode === "chase"; ms += 4) { + bounce.think(r2, nudge, 4, steady); + bounce.move(r2, nudge, 4); + y2.d += 0.16; + y2.x = at.x; + y2.kx = 0; + bounce.collide(r2, nudge, y2); + } + assert.equal(nudge.swipes, limit, `it swiped ${limit} times`); + assert.equal(nudge.mode, "calm", "then settled"); + const r3 = bounceRound(); + const zig = bounceRival(r3, "zigzag", at.x, at.d + 30, { v: 40 }); + let lo = 1e9; + let hi = -1e9; + for (let ms = 0; ms < 6000; ms += 4) { + bounce.think(r3, zig, 4, steady); + bounce.move(r3, zig, 4); + r3.clock += 4; + zig.d = at.d + 30; + lo = Math.min(lo, zig.x); + hi = Math.max(hi, zig.x); + } + assert.ok(hi - lo > 10, `the Zigzag weaves (${(hi - lo).toFixed(1)} across)`); +}); + +test("Bounce Road: a sharp Brick brake-checks you from in front, and a rival far behind you speeds up to keep the pack close", () => { + const round = bounceRound(); + round.stage = 10; + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 40); + Object.assign(you, { x: at.x, d: at.d, v: 50 }); + const brick = bounceRival(round, "brick", at.x, at.d + 13, { v: 50, mode: "" }); + bounce.think(round, brick, 4, () => 0); + assert.equal(brick.mode, "brake", "it brakes"); + assert.ok(brick.tv <= you.v * 0.5 + 1e-9, `hard (${brick.tv.toFixed(1)})`); + assert.equal(eventsOf(round, "brake").length, 1); + const zig = bounceRival(round, "zigzag", at.x, at.d - 35, { v: 40 }); + const ahead = bounceRival(round, "zigzag", at.x - 8, at.d + 60, { v: 40 }); + bounce.think(round, zig, 4, steady); + bounce.think(round, ahead, 4, steady); + assert.ok(zig.tv > ahead.tv * 1.05, `the one behind hurries (${zig.tv.toFixed(1)} against ${ahead.tv.toFixed(1)})`); +}); + +test("Bounce Road: the Cop comes up from behind, sits on your roomier side and leans in to push you toward the near edge, then gives up after COP_MS", () => { + const round = bounceRound(); + round.stage = 7; + const you = round.cars[0]; + const at = plainSpot(round.road, 200, 60); + const span = bounce.spanAt(round.road, at.x, at.d); + const lo = span.lo; + Object.assign(you, { x: lo + 8, d: at.d, v: 40 }); + const cop = bounceRival(round, "cop", you.x + 3, at.d - 25, { v: 40, mode: "chase", chaseMs: 0, modeMs: 0 }); + let pushed = 0; + for (let ms = 0; ms < 4000 && !pushed; ms += 4) { + bounce.think(round, cop, 4, steady); + bounce.move(round, cop, 4); + you.d += 0.16; + you.x = lo + 8; + if (bounce.collide(round, cop, you) === "side" && you.kx < 0) pushed = you.kx; + you.kx = 0; + } + assert.equal(cop.offside, 1, "on your right, where the road is wider"); + assert.ok(pushed < 0, "it shoved you toward the near (left) edge"); + cop.chaseMs = bounce.COP_MS + 1; + bounce.think(round, cop, 4, steady); + assert.equal(cop.mode, "calm", "and gives up in the end"); +}); + +test("Bounce Road: the Bruiser swerves into you when you come alongside, the Sneak drops cones behind it while you follow, and the Racer comes past and flees", () => { + const round = bounceRound(); + round.stage = 8; + const you = round.cars[0]; + const at = plainSpot(round.road, 200, 80); + Object.assign(you, { x: at.x - 6, d: at.d, v: 45 }); + const bruiser = bounceRival(round, "bruiser", at.x + 6, at.d + 4, { v: 45, mode: "" }); + bounce.think(round, bruiser, 4, steady); + assert.ok(bruiser.tx < at.x + 6 - 3, `it heads for you (${bruiser.tx.toFixed(1)})`); + const sneak = bounceRival(round, "sneak", at.x, at.d + 40, { v: 45, dropIn: 0, mode: "" }); + for (let ms = 0; ms < 12000; ms += 16) { + bounce.think(round, sneak, 16, steady); + sneak.d = at.d + 40; + } + assert.equal(sneak.drops, bounce.SNEAK_DROPS, `it dropped its ${bounce.SNEAK_DROPS} cones`); + assert.equal(round.drops.filter((b) => b.kind === "cone").length, bounce.SNEAK_DROPS); + assert.ok(round.drops.every((b) => b.d < sneak.d), "behind it"); + const racer = bounce.spawnRival(round, "racer", steady); + assert.ok(racer && racer.d < you.d, "the Racer comes from behind"); + assert.ok(racer.v > you.v, "faster than you"); + for (let ms = 0; ms < 10000 && racer.mode === "chase"; ms += 4) { + bounce.think(round, racer, 4, steady); + bounce.move(round, racer, 4); + you.d += 0.18; + } + assert.equal(racer.mode, "flee", "past you, it flees"); + bounce.think(round, racer, 4, steady); + assert.ok(racer.tv > bounce.TOP_SPEED, "faster than you can go without a boost"); + assert.ok(bounce.RIVALS.racer.points >= 2 * bounce.RIVALS.zigzag.points, "worth catching"); +}); + +test("Bounce Road: a sharp rival under your landing swerves out from under it, a dull one does not, and each decides once a jump", () => { + const swerve = (roll) => { + const round = bounceRound(); + round.stage = 10; + const you = round.cars[0]; + const at = plainSpot(round.road, 200, 60); + Object.assign(you, { x: at.x, d: at.d - 20, v: 40, air: 500, airMax: 800, jumps: 1 }); + const zig = bounceRival(round, "zigzag", at.x, at.d, { v: 0, mode: "" }); + bounce.think(round, zig, 4, () => roll); + return { zig, at }; + }; + const sharp = swerve(0.05); + assert.notEqual(sharp.zig.dodge, 0, "it swerves"); + assert.ok(Math.abs(sharp.zig.tx - sharp.at.x) > 5, `away from where you land (${sharp.zig.tx.toFixed(1)})`); + const dull = swerve(0.99); + assert.equal(dull.zig.dodge, 0, "a poor roll stays put"); + assert.equal(dull.zig.dodgeFor, 1, "decided for this jump"); +}); + +test("Bounce Road: the Monster truck comes in Monster Mash, five landings on its roof beat it for BOSS_POINTS and a life, its back is a wall, and it gets away at the stage line", () => { + const round = bounceRound(4); + const road = round.road; + bounce.ensureRoad(road, 30000); + round.stage = 10; + const you = round.cars[0]; + const from = road.stageAt[9]; + const at = plainSpot(road, from + bounce.stageFor(10).len * 0.2, 30); + Object.assign(you, { x: at.x, d: at.d, v: 40 }); + round.far = 1e9; + bounce.advance(round, 16, steady); + const m = round.cars.find((c) => c.kind === "monster"); + assert.ok(m, "the Monster is out"); + assert.equal(m.hp, bounce.BOSS_HP); + assert.ok(eventsOf(round, "spawn").some((e) => e.kind === "monster")); + round.lives = 2; + for (let n = 0; n < bounce.BOSS_HP; n++) { + Object.assign(m, { x: you.x, d: you.d + 1, air: 0, hopIn: 1e9, dropIn: 1e9, v: you.v }); + Object.assign(you, { air: 4, airMax: 600 }); + bounce.advance(round, 4, steady); + you.air = 0; + m.d = you.d + 40; + } + assert.equal(m.hp, 0); + assert.equal(m.outKind, "flat", "flattened at last"); + assert.equal(eventsOf(round, "boss").length, 1); + assert.equal(round.lives, 3, "a life back"); + assert.equal(round.stats.bosses, 1); + const r2 = bounceRound(4); + r2.stage = 10; + bounce.ensureRoad(r2.road, 30000); + const y2 = r2.cars[0]; + Object.assign(y2, { x: at.x, d: at.d, v: 50 }); + const m2 = bounceRival(r2, "monster", at.x, at.d + 9.5, { v: 20, hp: bounce.BOSS_HP }); + bounce.collide(r2, y2, m2); + assert.equal(r2.phase, "crash", "its back is a wall"); + const r3 = bounceRound(4); + r3.stage = 10; + bounce.ensureRoad(r3.road, 30000); + const m3 = bounceRival(r3, "monster", 30, r3.road.stageAt[10] + 30, { hp: 3 }); + r3.bossFor = 10; + const y3 = r3.cars[0]; + y3.d = r3.road.stageAt[10] - 0.5; + y3.x = (r3.road.L[bounce.rowOf(y3.d)] + r3.road.R[bounce.rowOf(y3.d)]) / 2; + r3.far = 1e9; + bounce.advance(r3, 60, steady); + assert.equal(r3.stage, 11); + assert.equal(m3.outKind, "gone", "it got away"); + assert.equal(eventsOf(r3, "escape").length, 1); +}); + +/* ------------------------------------------------------- the hazards */ + +test("Bounce Road: a boost strip pushes you past the top speed even off the throttle, and scores", () => { + const round = bounceRound(2); + const pad = onto(round, "pads", (p) => p.kind === "boost", 0); + const you = round.cars[0]; + Object.assign(you, { x: pad.x, d: pad.d, v: bounce.TOP_SPEED }); + bounce.advance(round, 4, steady); + assert.ok(you.boostMs > 0, "boosting"); + assert.ok(round.score >= bounce.BOOST_POINTS, "and it scores"); + let top = 0; + for (let ms = 0; ms < 800; ms += 4) { + bounce.move(round, you, 4); + top = Math.max(top, you.v); + } + assert.ok(top > bounce.TOP_SPEED * 1.15, `faster than the top speed (${top.toFixed(1)})`); + assert.ok(top <= bounce.MAX_SPEED); +}); + +test("Bounce Road: a slick takes your grip: the steering answers slowly and a knock lasts longer", () => { + const steerAfter = (slick) => { + const round = bounceRound(); + const you = round.cars[0]; + you.slickMs = slick ? 5000 : 0; + you.kx = 10; + round.input.right = true; + for (let ms = 0; ms < 200; ms += 4) bounce.move(round, you, 4); + return { vx: you.vx, kx: you.kx }; + }; + const dry = steerAfter(false); + const wet = steerAfter(true); + assert.ok(wet.vx < dry.vx * 0.6, `slower to steer (${wet.vx.toFixed(1)} against ${dry.vx.toFixed(1)})`); + assert.ok(wet.kx > dry.kx * 1.2, "the knock lingers"); + const round = bounceRound(3); + const pad = onto(round, "pads", (p) => p.kind === "slick", 0); + const you = round.cars[0]; + Object.assign(you, { x: pad.x, d: pad.d }); + bounce.advance(round, 4, steady); + assert.ok(you.slickMs > 0, "driving onto one"); +}); + +test("Bounce Road: a ramp launches whoever crosses its lip RAMP_AIR the usual jump, clear over its crack, for big-air points on landing", () => { + const round = bounceRound(5); + const ramp = onto(round, "pads", (p) => p.kind === "ramp", 0); + const you = round.cars[0]; + const lip = ramp.d + ramp.l / 2; + Object.assign(you, { x: ramp.x, d: lip - 0.5, v: 50, pnose: lip - 0.5 + you.l / 2 }); + round.input.up = true; + for (let ms = 0; ms < 40 && you.air <= 0; ms += 4) bounce.advance(round, 4, steady); + assert.ok(you.air > 0, "launched"); + assert.ok(Math.abs(you.airMax - bounce.airMs(you.v) * bounce.RAMP_AIR) < 1, "a ramp's jump"); + for (let ms = 0; ms < 3000 && you.air > 0; ms += 4) bounce.advance(round, 4, steady); + assert.equal(round.lives, bounce.START_LIVES, "clear over the crack"); + const land = round.events.find((e) => e.type === "land"); + assert.ok(land && land.big && land.holes === 1, "big air, and the hole jumped"); + const rv = bounceRound(5); + const r2 = onto(rv, "pads", (p) => p.kind === "ramp", 60); + const zig = bounceRival(rv, "zigzag", r2.x, r2.d + r2.l / 2 - 0.3, { v: 45, tv: 45, mode: "" }); + bounce.advance(rv, 16, steady); + assert.ok(zig.air > bounce.airMs(40), "a rival flies off it too"); +}); + +test("Bounce Road: a chicane's cones knock flying and slow you, a block nose first is a crash and from the side a push back out, and one jumped scores", () => { + const round = bounceRound(1); + const cone = onto(round, "blocks", (b) => b.kind === "cone", 0); + const you = round.cars[0]; + Object.assign(you, { x: cone.x, d: cone.d - 4.6, v: 50 }); + round.input.up = true; + for (let ms = 0; ms < 200 && !cone.hit; ms += 4) bounce.advance(round, 4, steady); + assert.ok(cone.hit, "knocked flying"); + assert.ok(you.v < 40, `it slows you (${you.v.toFixed(1)})`); + assert.equal(round.lives, bounce.START_LIVES, "no life"); + const r2 = bounceRound(1); + const block = onto(r2, "blocks", (b) => b.kind === "block", 0); + const y2 = r2.cars[0]; + Object.assign(y2, { x: block.x, d: block.d - 5.2, v: 40, pnose: block.d - 5.2 + 3.5 }); + for (let ms = 0; ms < 200 && r2.phase === "drive"; ms += 4) bounce.advance(r2, 4, steady); + assert.equal(r2.phase, "crash", "nose first into a block"); + const r3 = bounceRound(1); + const b3 = onto(r3, "blocks", (b) => b.kind === "block", 0); + const y3 = r3.cars[0]; + const inner = b3.side < 0 ? b3.x + b3.w / 2 : b3.x - b3.w / 2; + Object.assign(y3, { x: inner + (b3.side < 0 ? 1.5 : -1.5), d: b3.d, v: 40, pnose: b3.d + 3.5 }); + bounce.advance(r3, 4, steady); + assert.equal(r3.phase, "drive", "from the side, no crash"); + assert.ok(Math.abs(y3.x - b3.x) >= (b3.w + y3.w) / 2 - 1e-6, "pushed out"); + const r4 = bounceRound(1); + const b4 = onto(r4, "blocks", (b) => b.kind === "block", 0); + const y4 = r4.cars[0]; + Object.assign(y4, { x: b4.x, d: b4.d - 8, v: 50, air: 500, airMax: 600, jumpFrom: b4.d - 8 }); + for (let ms = 0; ms < 1000 && y4.air > 0; ms += 4) { + bounce.advance(r4, 4, steady); + y4.x = b4.x; + } + const land = r4.events.find((e) => e.type === "land"); + assert.ok(land && land.overs.includes("block"), "over the block"); + assert.ok(land.points >= bounce.OVER_POINTS); +}); + +test("Bounce Road: crumbling road falls away behind you once you reach it: at a fair speed you outrun it, at a roll it takes you, and a life lost makes it whole again", () => { + const run = (speed) => { + const round = bounceRound(6); + const s = onto(round, "dyn", (x) => x.kind === "crumble", 4); + const you = round.cars[0]; + you.v = speed; + for (let ms = 0; ms < 20000 && you.d < s.d1 + 10 && round.phase === "drive"; ms += 16) { + const i = bounce.rowOf(you.d); + you.x = (round.road.L[i] + round.road.R[i]) / 2; + round.input.up = speed > bounce.ROLL_SPEED; + round.input.down = speed <= bounce.ROLL_SPEED; + bounce.advance(round, 16, steady); + } + return { round, s }; + }; + assert.ok(bounce.CRUMBLE_SPEED < bounce.JUMP_FAIR * bounce.TOP_SPEED, "slower than a fair speed"); + const fast = run(bounce.JUMP_FAIR * bounce.TOP_SPEED); + assert.ok(fast.s.start !== null, "it started"); + assert.equal(fast.round.lives, bounce.START_LIVES, "outrun"); + const slow = run(bounce.ROLL_SPEED); + assert.equal(slow.round.phase, "crash", "at a roll it falls away under you"); + for (let ms = 0; ms < bounce.CRASH_MS + 40; ms += 4) bounce.advance(slow.round, 4, steady); + assert.equal(slow.s.start, null, "made whole for another go"); +}); + +test("Bounce Road: a drawbridge's span is water while it lifts and road while it is down, and a swaying bridge always carries its middle line while its edge goes over the water", () => { + const road = bounce.newRoad(2); + bounce.ensureRoad(road, 40000); + const draw = road.dyn.find((s) => s.kind === "draw"); + assert.ok(draw, "a drawbridge"); + const mid = (draw.d0 + draw.d1) / 2; + const i = bounce.rowOf(mid); + const x = (road.L[i] + road.R[i]) / 2; + let open = 0; + let shut = 0; + for (let t = 0; t < 8000; t += 50) { + const g = bounce.groundAt(road, x, mid, t); + if (bounce.drawLift(draw, t) > 0.05) { + assert.equal(g, bounce.GROUND.water); + open++; + } else { + assert.equal(g, bounce.GROUND.road); + shut++; + } + } + assert.ok(open > 10 && shut > 10, `it lifts and lowers (${open} open, ${shut} shut)`); + const sway = road.dyn.find((s) => s.kind === "sway"); + assert.ok(sway, "a swaying bridge"); + const sm = (sway.d0 + sway.d1) / 2; + let wet = 0; + for (let t = 0; t < 8000; t += 40) { + assert.equal(bounce.groundAt(road, sway.c, sm, t), bounce.GROUND.road, "the middle line always on it"); + if (bounce.groundAt(road, sway.c + sway.bw / 2 - 0.5, sm, t) !== bounce.GROUND.road) wet++; + } + assert.ok(wet > 10, `its edge sways over the water (${wet})`); + assert.ok(sway.amp >= 3, `it really sways (${sway.amp.toFixed(1)})`); +}); + +test("Bounce Road: a toy train flashes before it crosses, hits a car on the track, never one in the air (that scores on landing), and a rival hops the track when it comes", () => { + const round = bounceRound(3); + const h = onto(round, "hazards", (x) => x.kind === "train", 6); + const you = round.cars[0]; + let t = 0; + const covers = (tt) => { + const tr = bounce.trainAt(h, tt); + return tr.on && tr.x0 < you.x - 5 && tr.x1 > you.x + 5; + }; + while (!covers(t)) t += 10; + let warnAt = t; + while (bounce.trainAt(h, warnAt).warn) warnAt -= 10; + assert.ok(t - warnAt >= bounce.TRAIN_WARN_MS - 20, "its lights flash first"); + round.clock = t; + Object.assign(you, { d: h.d, v: 30 }); + bounce.advance(round, 4, steady); + assert.equal(round.phase, "crash", "on the track as it passes: a life"); + assert.equal(eventsOf(round, "lose")[0].cause, "train"); + const r2 = bounceRound(3); + const h2 = onto(r2, "hazards", (x) => x.kind === "train", 6); + const y2 = r2.cars[0]; + r2.clock = t; + Object.assign(y2, { d: h2.d - 6, v: 40, air: 500, airMax: 700, jumpFrom: h2.d - 30 }); + for (let ms = 0; ms < 1000 && y2.air > 0; ms += 4) bounce.advance(r2, 4, steady); + assert.equal(r2.phase, "drive", "over it in the air"); + const land = r2.events.find((e) => e.type === "land"); + assert.ok(land.overs.includes("train"), "jumped the train"); + const r3 = bounceRound(3); + const h3 = onto(r3, "hazards", (x) => x.kind === "train", 60); + r3.clock = t - 200; + const zig = bounceRival(r3, "zigzag", r3.cars[0].x, h3.d - h3.half - 6, { v: 40, tv: 40, mode: "" }); + bounce.think(r3, zig, 4, steady); + assert.ok(zig.air > 0, "the rival hops the coming train"); +}); + +test("Bounce Road: a rolling ball bonks a car sideways and slows you without a life, a sprinkler's jet pushes you off its side, and a gust blows you its way only while it blows", () => { + const round = bounceRound(2); + const ball = onto(round, "hazards", (x) => x.kind === "ball", 0); + const you = round.cars[0]; + const bx = bounce.ballX(ball, round.clock + 4); + Object.assign(you, { x: bx + 2, d: ball.d, v: 50, kx: 0 }); + bounce.advance(round, 4, steady); + assert.ok(you.kx > 20, `knocked away (${you.kx.toFixed(1)})`); + assert.ok(you.v < 40, "slowed"); + assert.equal(round.lives, bounce.START_LIVES, "no life"); + assert.equal(eventsOf(round, "bonk").length, 1); + const r2 = bounceRound(2); + const sp = onto(r2, "hazards", (x) => x.kind === "sprinkler", 0); + const y2 = r2.cars[0]; + const s = bounce.sprayAt(sp, r2.clock); + Object.assign(y2, { x: (s.x0 + s.x1) / 2, d: (s.d0 + s.d1) / 2, v: 0.001, kx: 0 }); + bounce.advance(r2, 40, steady); + assert.ok(y2.kx * -sp.side > 1, `pushed away from the sprinkler's side (${y2.kx.toFixed(2)})`); + const r3 = bounceRound(4); + const w = onto(r3, "hazards", (x) => x.kind === "wind", -20); + const y3 = r3.cars[0]; + let t = 0; + while (bounce.gustAt(w, t) < 1) t += 10; + r3.clock = t; + Object.assign(y3, { kx: 0, v: 0.001 }); + bounce.advance(r3, 200, steady); + assert.ok(y3.kx * w.dir > 5, `blown its way (${y3.kx.toFixed(1)})`); + while (bounce.gustAt(w, t) > 0) t += 10; + t += 10; + r3.clock = t; + Object.assign(y3, { kx: 0, d: w.d + 10 }); + bounce.advance(r3, 100, steady); + assert.ok(Math.abs(y3.kx) < 0.01, "calm between gusts"); +}); + +test("Bounce Road: something falls where you are heading, its shadow growing for DROP_FALL_MS: under it you are squashed, and then it lies on the road as a block", () => { + const round = bounceRound(1); + const h = onto(round, "hazards", (x) => x.kind === "drop", bounce.DROP_TRIGGER - 1); + const you = round.cars[0]; + you.v = 0.001; + bounce.advance(round, 4, steady); + assert.ok(h.at > 0, "it falls"); + assert.ok(Math.abs(h.x - you.x) < 3, "aimed at your line"); + assert.equal(eventsOf(round, "dropWarn").length, 1); + for (let ms = 0; ms < bounce.DROP_FALL_MS + 20 && round.phase === "drive"; ms += 4) { + Object.assign(you, { d: h.d, x: h.x }); + bounce.advance(round, 4, steady); + } + assert.equal(round.phase, "crash", "squashed under it"); + assert.equal(eventsOf(round, "lose")[0].cause, "squash"); + assert.ok(round.drops.some((b) => b.d === h.d && Math.abs(b.x - h.x) < 1e-9), "and there it lies"); +}); + +/* -------------------------------------------------------- scoring */ + +test("Bounce Road: stunts in quick succession step the combo, every COMBO_STEP of them multiplies the points one more up to MAX_COMBO, and it runs out after STREAK_MS or with a life lost", () => { + const round = bounceRound(); + assert.equal(bounce.comboOf(0), 1); + const got = []; + for (let k = 0; k < 16; k++) got.push(bounce.stunt(round, 10)); + assert.deepEqual(got.slice(0, 4), [10, 10, 10, 20], "the fourth in a row is doubled"); + assert.equal(Math.max(...got), 10 * bounce.MAX_COMBO, "never past MAX_COMBO"); + assert.equal(round.bestCombo, bounce.MAX_COMBO); + bounce.advance(round, bounce.STREAK_MS + 40, steady); + assert.equal(round.streak, 0, "it runs out"); + for (let k = 0; k < 5; k++) bounce.stunt(round, 10); + bounce.lose(round, "crash"); + assert.equal(round.streak, 0, "a life lost ends it"); +}); + +test("Bounce Road: passing a rival with a hair between you scores a close shave once, and never after touching it", () => { + const pass = (gap, touch = false) => { + const round = bounceRound(); + const you = round.cars[0]; + const at = plainSpot(round.road, 100, 60); + const zig = bounceRival(round, "zigzag", at.x, at.d + 12, { v: 20, tv: 20, mode: "" }); + const x = at.x - (you.w + zig.w) / 2 - gap; + Object.assign(you, { x, d: at.d, v: 50 }); + if (touch) zig.nearDone = true; + round.far = 1e9; + for (let ms = 0; ms < 1500; ms += 4) { + Object.assign(you, { x, v: 50, kx: 0, vx: 0 }); + Object.assign(zig, { x: at.x, v: 20, tv: 20, tx: at.x, lane: at.x, kx: 0 }); + bounce.advance(round, 4, steady); + } + return round.stats.near; + }; + assert.equal(pass(0.8), 1, "a close shave"); + assert.equal(pass(5), 0, "not close"); + assert.equal(pass(0.8, true), 0, "not after a touch"); +}); + +test("Bounce Road: stars over a hole are taken in the air and score, times the combo", () => { + const round = bounceRound(1); + const road = round.road; + bounce.ensureRoad(road, 20000); + const s = road.stars.find((x) => road.holes.some((h) => x.d > h.d0 && x.d < h.d1)); + assert.ok(s, "a star over a hole"); + const you = round.cars[0]; + while (road.stageAt[round.stage] <= s.d) round.stage++; + Object.assign(you, { x: s.x, d: s.d - 0.5, v: 40, air: 300, airMax: 600 }); + round.far = 1e9; + round.streak = bounce.COMBO_STEP; + round.streakMs = bounce.STREAK_MS; + bounce.advance(round, 8, steady); + assert.ok(s.taken, "taken in the air"); + assert.ok(round.stats.stars >= 1); + assert.equal(eventsOf(round, "star")[0].points, bounce.STAR_POINTS * 2); +}); + +test("Bounce Road: crossing a stage line scores STAGE_POINTS times the stage, a time bonus under par and, with no life lost, a flawless bonus and a life back up to MAX_LIVES", () => { + const round = bounceRound(); + const you = round.cars[0]; + const cross = (n) => { + you.d = round.road.stageAt[n] - 0.5; + const i = Math.floor(you.d / bounce.ROW); + you.x = (round.road.L[i] + round.road.R[i]) / 2; + round.far = 1e9; + round.events.length = 0; + bounce.advance(round, 40, steady); + return eventsOf(round, "stage")[0]; + }; + round.lives = 2; + const one = cross(1); + assert.equal(one.bonus, Math.round((bounce.stageFor(1).par - one.secs) * bounce.TIME_POINTS)); + assert.equal(one.points, bounce.STAGE_POINTS + one.bonus + bounce.FLAWLESS_POINTS); + assert.equal(round.stage, 2); + assert.equal(round.lives, 3, "flawless: a life back"); + round.stageLost = true; + round.stageClock = round.clock - 1e6; + const two = cross(2); + assert.equal(two.bonus, 0, "slow: no time bonus"); + assert.equal(two.points, bounce.STAGE_POINTS * 2); + assert.equal(round.lives, 3, "a life lost on the way: none back"); + round.lives = bounce.MAX_LIVES; + cross(3); + assert.equal(round.lives, bounce.MAX_LIVES, "never past MAX_LIVES"); +}); + +test("Bounce Road: power-ups lie on the road from Hose Creek and driving over one takes it; a Nitro passes the top speed, and Mega wheels make you bigger and flatten a rival you touch", () => { + const road = bounce.newRoad(9); + while (road.built < 4) bounce.buildStage(road, road.built + 1); + assert.ok(road.items.length >= 3, `power-ups on the road (${road.items.length})`); + assert.ok(road.items.every((it) => it.d >= road.stageAt[1]), "none on Chalk Lane"); + assert.ok(road.items.every((it) => bounce.groundAt(road, it.x, it.d) === bounce.GROUND.road), "all on the road"); + const round = bounceRound(9); + const you = round.cars[0]; + bounce.ensureRoad(round.road, 6000); + const it = round.road.items[0]; + Object.assign(you, { x: it.x, d: it.d - 1 }); + round.far = 1e9; + round.stage = 2; + bounce.advance(round, 4, steady); + assert.ok(it.taken, "taken"); + assert.equal(eventsOf(round, "power").length, 1); + bounce.applyPower(round, "nitro"); + round.input.up = true; + you.v = bounce.TOP_SPEED; + for (let ms = 0; ms < 1500; ms += 4) { + bounce.move(round, you, 4); + you.d = it.d; + } + assert.ok(you.v > bounce.TOP_SPEED * 1.15, `a Nitro passes the top speed (${you.v.toFixed(1)})`); + const r2 = bounceRound(); + const y2 = r2.cars[0]; + bounce.applyPower(r2, "mega"); + assert.ok(y2.w > bounce.CAR_W * 1.2 && y2.l > bounce.CAR_L * 1.2, "bigger"); + const at = plainSpot(r2.road, 60, 30); + Object.assign(y2, { x: at.x, d: at.d }); + const zig = bounceRival(r2, "zigzag", at.x + 4, at.d + 1); + assert.equal(bounce.collide(r2, y2, zig), "mega"); + assert.equal(zig.outKind, "flat", "flattened by a touch"); + for (let ms = 0; ms < bounce.MEGA_MS + 40; ms += 4) bounce.move(r2, y2, 4); + assert.equal(y2.w, bounce.CAR_W, "back to size"); +}); + +test("Bounce Road: a banner's strip counts a rival, a train on its way, a ball and a thing still falling, and nothing else", () => { + const round = bounceRound(3); + const you = round.cars[0]; + const cam = you.d - bounce.BEHIND; + const y = bounce.BANNER_Y; + const dAt = cam + bounce.FIELD_H - y; + round.road.hazards.length = 0; + assert.equal(bounce.underBanner(round, y, cam), false, "an empty strip"); + const zig = bounceRival(round, "zigzag", 30, dAt); + assert.equal(bounce.underBanner(round, y, cam), true, "a rival in it"); + zig.d = dAt + 60; + assert.equal(bounce.underBanner(round, y, cam), false, "a rival out of it"); + round.road.hazards.push({ kind: "ball", d: dAt, c: 30, amp: 10, r: 3, period: 3000, phase: 0 }); + assert.equal(bounce.underBanner(round, y, cam), true, "a ball"); + round.road.hazards[0] = { kind: "drop", d: dAt, at: round.clock + 500, landed: false, x: 30, w: 5, l: 5 }; + assert.equal(bounce.underBanner(round, y, cam), true, "a thing falling"); + round.road.hazards[0].landed = true; + assert.equal(bounce.underBanner(round, y, cam), false, "landed, it is a block like any other"); +}); + +/* ------------------------------------------------------- the look */ + +test("Bounce Road: a rival color too near your highlight gives way to a spare, so no highlight leaves a rival beside you, and every rival color stands out from every road", () => { + assert.deepEqual(bounce.rivalColors("#206cc3"), [...bounce.RIVAL_COLORS]); + assert.deepEqual(bounce.rivalColors("not a color"), [...bounce.RIVAL_COLORS]); + assert.equal(bounce.RIVAL_COLORS.length, bounce.RIVAL_KINDS.length, "a color per kind"); + const rgb = (h) => [1, 3, 5].map((k) => parseInt(h.slice(k, k + 2), 16)); + const roads = Object.values(LOOKS).map((l) => l.road); + for (const [id, accent] of Object.entries(ACCENTS)) { + for (const you of [accent.light[0], accent.dark[0]]) { + const colors = bounce.rivalColors(you); + assert.equal(new Set(colors).size, colors.length, `${id}: no two rivals alike`); + for (const c of colors) { + const [a, b] = [rgb(c), rgb(you)]; + assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) >= bounce.NEAR_COLOR, `${id} ${you} beside ${c}`); + for (const road of roads) assert.ok(contrast(c, road) >= 1.8, `${id}: a ${c} rival on a ${road} road (${contrast(c, road).toFixed(2)})`); + } + } + } +}); + +test("Bounce Road: every rival kind is drawn as one of the car art's styles, no two alike, and Planny as his own", () => { + for (const kind of bounce.RIVAL_KINDS) assert.ok(CAR_STYLES[bounce.RIVALS[kind].style], `${kind} drawn as ${bounce.RIVALS[kind].style}`); + assert.ok(CAR_STYLES.planny); + assert.equal(new Set(bounce.RIVAL_KINDS.map((k) => bounce.RIVALS[k].style)).size, bounce.RIVAL_KINDS.length, "no two kinds look alike"); +}); + +test("Bounce Road: the pills never overlap, leave the board or spill out of their strip, even on the smallest board with every pill wanted; every word stays on the field; edges stand out on every road and bridge, and on your car", () => { + const box = (p, h) => [p.x, p.y, p.x + p.w, p.y + h]; + for (const h of [Math.max(12 / bounce.MIN_CELL, 2.4), 2.4]) { + for (const chain of [0, bounce.MAX_CHAIN]) { + for (const effects of [[], ["SPRING", "BUBBLE", "NITRO", "MEGA"]]) { + for (const combo of [null, { mult: bounce.MAX_COMBO, fill: 0.5 }]) { + const hud = { stage: "STAGE 18", effects: effects.map((text) => ({ text, color: "#ffffff", fill: 0.5 })), chain, combo }; + const pills = hudLayout(h, bounce.W, bounce.MAX_LIVES, hud, bounce.HUD_H).map((p) => box(p, p.h)); + for (const [x0, y0, x1, y1] of pills) { + assert.ok(x0 >= 0 && x1 <= bounce.W, `on the board (h ${h})`); + assert.ok(y0 >= 0 && y1 <= bounce.HUD_H, `in the strip (h ${h}, ${y0}..${y1})`); + } + for (let i = 0; i < pills.length; i++) { + for (let j = i + 1; j < pills.length; j++) { + const [p, q] = [pills[i], pills[j]]; + assert.ok(p[2] <= q[0] || q[2] <= p[0] || p[3] <= q[1] || q[3] <= p[1], `pills ${i} and ${j} apart (h ${h})`); + } + } + } + } + } + } + for (const text of ["Bumped off! +60", "+800 chain x8", "It's crumbling! Floor it!", "A line much too long to fit across the field at all, however small"]) { + for (let x = -10; x <= bounce.FIELD_W + 10; x += 13) { + for (let y = -10; y <= bounce.FIELD_H + 10; y += 11) { + const at = labelSpot(text, x, y, 2.8, bounce.FIELD_W, bounce.FIELD_H); + assert.ok(at.x - at.max / 2 >= 0 && at.x + at.max / 2 <= bounce.FIELD_W); + assert.ok(at.y - 1.4 >= 0 && at.y + 1.4 <= bounce.FIELD_H); + } + } + } + for (const [look, t] of Object.entries(LOOKS)) { + const ink = limbInk(look); + for (const tone of [t.road, t.plank]) assert.ok(contrast(ink, tone) >= 3, `${look}: ${ink} on ${tone} (${contrast(ink, tone).toFixed(2)})`); + assert.ok(contrast(t.road, t.ground) >= 1.4, `${look}: the road stands out from the yard (${contrast(t.road, t.ground).toFixed(2)})`); + } + for (const [id, accent] of Object.entries(ACCENTS)) { + for (const you of [accent.light[0], accent.dark[0]]) assert.ok(contrast(inkOn(you), you) >= 2.5, `${id}: ink on a ${you} car`); + } +}); + +/* ------------------------------------------------- fair play near danger */ + +test("Bounce Road: the Bruiser and the Cop never shove you on a bridge or by the water, but do on plain road", () => { + const round = bounceRound(2); + const road = round.road; + bounce.ensureRoad(road, 20000); + const river = road.rivers[0]; + while (road.stageAt[round.stage] <= river.d0) round.stage++; + const you = round.cars[0]; + const onBridge = river.d0 + 12; + const i = bounce.rowOf(onBridge); + const mid = (road.L[i] + road.R[i]) / 2; + Object.assign(you, { d: onBridge, x: mid, v: 45 }); + assert.ok(bounce.nearWater(road, you.d, you.l), "you are on the bridge"); + const bruiser = bounceRival(round, "bruiser", mid + 5, onBridge + 2, { v: 45, mode: "" }); + bounce.think(round, bruiser, 4, steady); + assert.ok(Math.abs(bruiser.tx - you.x) > 3, `the Bruiser holds off on the bridge (${bruiser.tx.toFixed(1)} against ${you.x.toFixed(1)})`); + const cop = bounceRival(round, "cop", mid - 5, onBridge - 1, { v: 45, mode: "chase", chaseMs: 0, modeMs: 1e9, offside: -1 }); + bounce.think(round, cop, 4, steady); + assert.ok(Math.abs(cop.tx - you.x) >= (you.w + cop.w) / 2, `the Cop sits beside you there, never into you (${cop.tx.toFixed(1)})`); + const r2 = bounceRound(2); + const at = plainSpot(r2.road, 200, 60); + const y2 = r2.cars[0]; + Object.assign(y2, { d: at.d, x: at.x, v: 45 }); + assert.ok(!bounce.nearWater(r2.road, y2.d, y2.l + 4)); + const b2 = bounceRival(r2, "bruiser", at.x + 5, at.d + 2, { v: 45, mode: "" }); + bounce.think(r2, b2, 4, steady); + assert.ok(Math.abs(b2.tx - y2.x) < 1e-6, "on plain road the Bruiser comes for you"); +}); + +test("Bounce Road: a Brick brake-checks at most once every BRAKE_REST_MS or so, however sharp it is", () => { + const round = bounceRound(); + round.stage = 10; + const you = round.cars[0]; + const at = plainSpot(round.road, 60, 40); + Object.assign(you, { x: at.x, d: at.d, v: 50 }); + const brick = bounceRival(round, "brick", at.x, at.d + 13, { v: 50, mode: "" }); + const times = []; + for (let ms = 0; ms < 6000; ms += 4) { + round.events.length = 0; + bounce.think(round, brick, 4, () => 0); + if (eventsOf(round, "brake").length) times.push(ms); + brick.d = at.d + 13; + } + assert.ok(times.length >= 2 && times.length <= 3, `brake checks in 6 s: ${times.length}`); + for (let k = 1; k < times.length; k++) assert.ok(times[k] - times[k - 1] >= bounce.BRAKE_REST_MS, `apart (${times[k] - times[k - 1]} ms)`); +}); + +test("Bounce Road: the brake beats a boost strip, so a strip before a train or a drawbridge never forces you on", () => { + const round = bounceRound(2); + const pad = onto(round, "pads", (p) => p.kind === "boost", 0); + const you = round.cars[0]; + Object.assign(you, { x: pad.x, d: pad.d, v: bounce.TOP_SPEED }); + round.input.down = true; + for (let ms = 0; ms < 400; ms += 4) bounce.move(round, you, 4); + you.d = pad.d; + bounce.advance(round, 4, steady); + for (let ms = 0; ms < 400; ms += 4) bounce.move(round, you, 4); + assert.equal(you.boostMs, 0, "braking cuts the boost"); + assert.ok(you.v < bounce.TOP_SPEED * 0.6, `and slows you (${you.v.toFixed(1)})`); +}); + +test("Bounce Road: a stunned Monster's back is never a wall, so running into it right after a stomp is safe", () => { + const round = bounceRound(4); + round.stage = 10; + bounce.ensureRoad(round.road, 30000); + const at = plainSpot(round.road, round.road.stageAt[9] + 300, 30); + const you = round.cars[0]; + Object.assign(you, { x: at.x, d: at.d, v: 60 }); + const m = bounceRival(round, "monster", at.x, at.d + 9.5, { v: 20, hp: 3, stunMs: 800 }); + bounce.collide(round, you, m); + assert.equal(round.phase, "drive", "no crash"); + assert.ok(you.v < 60, "you just bump it"); +}); diff --git a/scripts/test-web-console-activities-ghoul-arms.mjs b/scripts/test-web-console-activities-ghoul-arms.mjs new file mode 100644 index 0000000..448c838 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-arms.mjs @@ -0,0 +1,1605 @@ +// Web console tests, Ghoul Rush's secondary weapons: the double tap that uses one (hammering spends one at most, a hold carries on as bolts), the bag and its HUD pill, what each weapon does, what they may do to a boss, where they are placed and how they drop, and that all of it draws and sounds. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as arm from "../src/web-console/public/activities/ghoul-arms.js"; +import { rocketArt } from "../src/web-console/public/activities/ghoul-rockets-draw.js"; +import * as pans from "../src/web-console/public/activities/ghoul-pans.js"; +import { ARM_DROP, ARM_DROP_OWN, STAGE_ARMS, armDrop, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import { ARMS_SFX } from "../src/web-console/public/activities/ghoul-sfx-arms.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { hudLayout, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); +const COMMON = ["dyn", "stake", "rocket"]; +const ALL = Object.keys(ghoul.POWERS).filter((k) => ghoul.POWERS[k].arm); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the stage `stage`'s room `id`, reached the way play reaches it, +// nothing woken: every spawner spent, the horde held back, nothing to pick up. +function roomOf(stage, id) { + const round = ghoul.newRound(5); + round.dice = 0; + if (stage) { + through(round); + round.offer = [stage]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + } + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.bonus = 1e9; + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x)) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf: -1, coyote: 0, drop: -1, out: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, random = steady) { + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); +} + +const tapTap = (round) => { + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + ghoul.releaseFire(round); +}; +const give = (round, kind, n = 1) => { + round.arms = [{ kind, n }]; +}; +// A boss's fight under way, depth `depth` stages into a run. +function fightOf(stage, id, depth = 0) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.cleared = Array.from({ length: depth }, (_, i) => `x${i}`); + round.offer = [stage]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + round.items.fill(true); + round.timeMs = 1e9; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.you.safeMs = 1e9; + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +// The game itself, on a canvas that draws nothing. +function game() { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const round = g.round; + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.you.safeMs = 1e9; + return { g, round }; +} + +/* ----------------------------------------------------------- the double tap */ + +test("Ghoul Rush's double tap through the keys: the first press fires a bolt at once, the second uses the weapon, and held on, the bolts carry on after a short gap", () => { + const { g, round } = game(); + give(round, "stake", 3); + g.key("action"); + g.tick(16); + const bolts = () => round.shots.filter((s) => !s.arm).length; + assert.equal(bolts(), 1, "a bolt from the first press, with no wait"); + g.release("action"); + g.tick(16); + g.key("action"); + assert.equal(round.arms[0].n, 2, "the second press uses it"); + assert.equal(round.shots.filter((s) => s.arm === "stake").length, 1); + round.shots.length = 0; + g.tick(16); + assert.equal(bolts(), 0, "no bolt with the throw"); + for (let i = 0; i < arm.ARM_GAP_MS / 16 + 2; i++) g.tick(16); + assert.ok(bolts() >= 1, "held on, the blaster carries on"); + g.release("action"); +}); + +test("Ghoul Rush's double tap: a key repeat, a long first press, a slow second press and a plain hold never use a weapon", () => { + // A key repeat is no press. + const { g, round } = game(); + give(round, "stake", 3); + g.key("action"); + g.tick(16); + g.key("action", true); + g.key("action", true); + assert.equal(round.arms[0].n, 3, "repeats"); + g.release("action"); + // Too long a first press was the blaster's. + const long = roomOf(null, "hall"); + standAt(long, 40); + give(long, "stake", 3); + ghoul.pressFire(long); + run(long, arm.TAP_HOLD_MS + 20); + ghoul.releaseFire(long); + run(long, 20); + ghoul.pressFire(long); + assert.equal(long.arms[0].n, 3, "feathering is safe"); + // Too slow a second press starts again, and then counts as the first of a new pair. + const slow = roomOf(null, "hall"); + standAt(slow, 40); + give(slow, "stake", 3); + ghoul.pressFire(slow); + ghoul.releaseFire(slow); + run(slow, arm.DOUBLE_TAP_MS + 8); + ghoul.pressFire(slow); + assert.equal(slow.arms[0].n, 3); + ghoul.releaseFire(slow); + ghoul.pressFire(slow); + assert.equal(slow.arms[0].n, 2, "and that one's pair uses it"); + // Inside the window it is well within reach of a hand. + const quick = roomOf(null, "hall"); + standAt(quick, 40); + give(quick, "stake", 3); + ghoul.pressFire(quick); + run(quick, arm.TAP_HOLD_MS - 20); + ghoul.releaseFire(quick); + run(quick, arm.DOUBLE_TAP_MS - 20); + ghoul.pressFire(quick); + assert.equal(quick.arms[0].n, 2); +}); + +test("Ghoul Rush's double tap: hammering fire spends one at most, till the button has gone quiet", () => { + const round = roomOf(null, "hall"); + standAt(round, 40); + give(round, "dyn", 6); + for (let i = 0; i < 30; i++) { + ghoul.pressFire(round); + run(round, 60); + ghoul.releaseFire(round); + run(round, 60); + } + assert.equal(round.arms[0].n, 5, "thirty taps, one stick"); + run(round, arm.DOUBLE_TAP_MS + 8); + round.armCool = 0; + tapTap(round); + assert.equal(round.arms[0].n, 4, "quiet, it counts again"); +}); + +test("Ghoul Rush's secondary weapon comes out only when Planny can act, and with an empty bag a double tap is two bolts", () => { + const cases = [ + ["a toll's freeze", (r) => (r.stunMs = 500)], + ["an orderly's hold", (r) => (r.you.heldMs = 500)], + ["a throw", (r) => (r.you.flingMs = 500)], + ["down", (r) => (r.you.out = 500)], + ["the cooldown", (r) => (r.armCool = 100)], + ]; + for (const [name, set] of cases) { + const round = roomOf(null, "hall"); + standAt(round, 40); + give(round, "stake", 2); + set(round); + tapTap(round); + assert.equal(round.arms[0].n, 2, name); + assert.equal(events(round, "armUse").length, 0, name); + } + const phase = roomOf(null, "hall"); + give(phase, "stake", 2); + phase.phase = "ready"; + tapTap(phase); + assert.equal(phase.arms[0].n, 2, "before the round is back on"); + const empty = roomOf(null, "hall"); + standAt(empty, 40); + assert.equal(arm.useArm(empty, {}), false); + tapTap(empty); + assert.equal(empty.shots.filter((s) => s.arm).length, 0); +}); + +test("Ghoul Rush's weapon uses cost no heat and count as no shot fired", () => { + const round = roomOf(null, "hall"); + standAt(round, 40); + give(round, "stake", 3); + round.heat = 7; + const shots = round.stats.shots; + tapTap(round); + assert.equal(round.heat, 7); + assert.equal(round.stats.shots, shots); + assert.equal(round.armUsed, true); + assert.ok(round.fireMs >= arm.ARM_GAP_MS); +}); + +/* ------------------------------------------------------------------ the bag */ + +test("Ghoul Rush's bag: the latest picked up comes out first, then the one under it; bundles stop at their cap, then pay points", () => { + const round = roomOf(null, "hall"); + standAt(round, 40); + ghoul.applyPower(round, "dyn"); + assert.deepEqual(round.arms, [{ kind: "dyn", n: 2 }], "2 sticks outside the Mine"); + ghoul.applyPower(round, "stake"); + assert.deepEqual(round.arms, [{ kind: "stake", n: 3 }, { kind: "dyn", n: 2 }]); + ghoul.applyPower(round, "dyn"); + assert.deepEqual(round.arms, [{ kind: "dyn", n: 4 }, { kind: "stake", n: 3 }], "picked up again, it comes back to the top"); + round.arms = [{ kind: "stake", n: 1 }, { kind: "dyn", n: 1 }]; + tapTap(round); + assert.deepEqual(round.arms, [{ kind: "dyn", n: 1 }], "a kind used up gives way to the next"); + // Past the cap: points, and the count stays. + round.arms = [{ kind: "stake", n: ghoul.POWERS.stake.max }]; + const score = round.score; + ghoul.applyPower(round, "stake"); + assert.equal(round.arms[0].n, ghoul.POWERS.stake.max); + assert.ok(round.score > score); + // Each kind's bundle and cap are sane. + for (const kind of ALL) { + const def = ghoul.POWERS[kind]; + assert.ok(def.sticks >= 2 && def.max > def.sticks && def.max <= 6, kind); + assert.ok(!def.ms, `${kind} has no timer`); + assert.equal(def.weight, 0, `${kind}: never from pickPower`); + assert.ok(def.name && def.blurb && def.color, kind); + } +}); + +test("Ghoul Rush's bag stays with you through a new room and a life lost, and is gone only with the round", () => { + const round = roomOf("manor", "foyer"); + round.arms = [{ kind: "ball", n: 2 }]; + through(round); + assert.deepEqual(round.arms, [{ kind: "ball", n: 2 }], "carried"); + round.you.safeMs = 0; + ghoul.lose(round, "zombie"); + run(round, ghoul.CRASH_MS + ghoul.READY_MS + 40); + assert.deepEqual(round.arms, [{ kind: "ball", n: 2 }], "kept through a life lost"); + assert.deepEqual(ghoul.newRound(5).arms, []); +}); + +test("Ghoul Rush's HUD shows the weapon that comes next as its badge and count, against the gauge, and tells you how till the first one is used", () => { + const { g, round } = game(); + assert.equal(g.hud.arm, null); + round.arms = [{ kind: "dyn", n: 3 }]; + g.tick(1); + assert.equal(g.hud.arm.kind, "dyn"); + assert.equal(g.hud.arm.text, "x3 TAP TAP"); + assert.equal(g.hud.arm.fresh, true); + round.armUsed = true; + round.arms = [{ kind: "dyn", n: 3 }, { kind: "stake", n: 1 }]; + g.tick(1); + assert.equal(g.hud.arm.text, "x3 +1"); + assert.equal(g.hud.arm.fresh, false); + assert.ok(!g.hud.effects.some((e) => /DYN/.test(e.text)), "no pill of words as well"); + // Never over another pill, whatever else is showing. + const hud = { room: "THE GRAND OPERA HOUSE", stage: "STAGE 20 OF 21", time: 80, timeLow: false, bonus: 1500, chain: 10, chainFill: 0.5, key: true, effects: [{ text: "SPREAD", color: "#fff", fill: 1 }, { text: "RAPID", color: "#fff", fill: 1 }], gauge: { fill: 0, free: 0.6, rapid: null }, arm: { kind: "dyn", n: 6, text: "x6 +2", color: "#d9382c" } }; + for (const h of [4, 2.4]) { + const laid = hudLayout(h, ghoul.W, 9, hud, ghoul.HUD_H); + const pill = laid.find((p) => p.arm); + const gauge = laid.find((p) => p.gauge); + assert.ok(pill && gauge); + assert.ok(pill.x + pill.w <= gauge.x, "beside the gauge"); + for (let i = 0; i < laid.length; i++) { + for (let j = i + 1; j < laid.length; j++) { + const [p, q] = [laid[i], laid[j]]; + assert.ok(p.x + p.w <= q.x + 1e-6 || q.x + q.w <= p.x + 1e-6 || p.y + p.h <= q.y + 1e-6 || q.y + q.h <= p.y + 1e-6, `pills ${i} and ${j} apart`); + } + } + } +}); + +test("Ghoul Rush's weapon icons pop when the bag changes, on a pickup and on a use, and settle again", () => { + const { g, round } = game(); + g.tick(1); + assert.equal(g.hud.arm, null); + ghoul.applyPower(round, "dyn"); + g.tick(1); + assert.ok(g.hud.arm.pop > 0.9, "a pickup pops"); + for (let i = 0; i < 40; i++) g.tick(16); + assert.equal(g.hud.arm.pop, 0, "and settles"); + round.armCool = 0; + g.key("action"); + g.release("action"); + g.key("action"); + g.release("action"); + g.tick(1); + assert.ok(g.hud.arm.pop > 0.9, "a use pops"); + assert.equal(g.hud.arm.n, 1); +}); + +test("Ghoul Rush's first weapons say how to use them, and a pickup past that gives its own blurb", () => { + const round = roomOf(null, "hall"); + standAt(round, 62); + round.spec.items.forEach((_, i) => (round.items[i] = round.spec.items[i][0] !== "dyn")); + standAt(round, round.spec.items.find((i) => i[0] === "dyn")[1]); + ghoul.advance(round, 8, steady); + const e = events(round, "power").find((p) => p.kind === "dyn"); + assert.equal(e?.teach, true); + const later = roomOf(null, "hall"); + later.armUsed = true; + later.spec.items.forEach((_, i) => (later.items[i] = later.spec.items[i][0] !== "dyn")); + standAt(later, later.spec.items.find((i) => i[0] === "dyn")[1]); + ghoul.advance(later, 8, steady); + assert.equal(events(later, "power").find((p) => p.kind === "dyn")?.teach, false); +}); + +/* -------------------------------------------------------------- each weapon */ + +test("Ghoul Rush's Dynamite does 20 to whatever the blast reaches and breaks stone; the Iron Stake goes through a whole line and glances off stone", () => { + const round = roomOf("chapel", "tower"); + standAt(round, 120); + const stone = put(round, "gargoyle", 126, { y: 6, act: "perch" }); + round.hazards.push({ kind: "stick", x: 124, y: 6, vx: 0, vy: 0, fuse: 8, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(round, 20); + assert.ok(stone.dead, "stone broken"); + // A line of three: the first two hit, four each, hp 3 down at once. + const line = roomOf(null, "hall"); + standAt(line, 30); + const a = put(line, "zombie", 42); + const b = put(line, "zombie", 46); + give(line, "stake", 1); + tapTap(line); + run(line, 200); + assert.ok(a.dead && b.dead, "both on the one stake"); + const glance = roomOf("chapel", "tower"); + standAt(glance, 120); + put(glance, "gargoyle", 130, { y: glance.you.y + 0.5, act: "perch" }); + give(glance, "stake", 1); + tapTap(glance); + run(glance, 200); + assert.ok(events(glance, "glance").length >= 1, "it shows"); +}); + +test("Ghoul Rush's Hedge Sickle flies out, turns and comes back, hits a monster on each pass, and Planny catches it", () => { + const round = roomOf("grounds", "topiary"); + const start = 120; + standAt(round, start); + const m = put(round, "zombie", start + 14, { hp: arm.SICKLE_DMG + 1, speed: 0 }); + m.stunMs = 1e9; + give(round, "sickle", 1); + tapTap(round); + run(round, 300); + assert.equal(m.hp, 1, "hit going out"); + const s = round.shots.find((q) => q.arm === "sickle"); + assert.ok(s); + run(round, 1200); + assert.ok(m.dead, "and again coming back"); + assert.ok(events(round, "armTurn").length === 1); + assert.ok(!round.shots.some((q) => q.arm === "sickle"), "caught"); +}); + +test("Ghoul Rush's Billiard Ball rolls along the floor hurting low things most, down ledges, bounces off a wall once, and a pit takes it", () => { + const round = roomOf(null, "hall"); + standAt(round, 40); + const low = put(round, "crawler", 52, { hp: arm.BALL_LOW_DMG }); + const tall = put(round, "zombie", 56, { hp: arm.BALL_DMG + 1 }); + low.stunMs = tall.stunMs = 1e9; + give(round, "ball", 1); + tapTap(round); + run(round, 600); + assert.ok(low.dead, "low things take the most"); + assert.equal(tall.hp, 1, "a tall one takes less, and only once"); + const ball = round.hazards.find((h) => h.kind === "armBall"); + assert.ok(ball && ball.y === 6, "on the floor"); + // A wall: the hall's rise at 300? No: the Crypt's has none, so take the Foyer's stair, which steps up. Use the kitchen's wall at 70. + const wall = roomOf("wing", "kitchen"); + standAt(wall, 60); + wall.hazards.push({ kind: "armBall", x: 66, y: 6, vx: arm.BALL_V, vy: 0, life: arm.BALL_MS, bounced: false, roll: 0, hit: [], hitBoss: false, w: 1.4, h: 1.4, live: 0, cause: "" }); + run(wall, 200); + const b = wall.hazards.find((h) => h.kind === "armBall"); + assert.ok(b.bounced && b.vx < 0, "back off the wall"); + assert.ok(events(wall, "armBounce").length === 1); + // A pit: the gallery's at 100-110. + const pit = roomOf("manor", "gallery"); + standAt(pit, 90); + pit.hazards.push({ kind: "armBall", x: 96, y: 6, vx: arm.BALL_V, vy: 0, life: arm.BALL_MS, bounced: false, roll: 0, hit: [], hitBoss: false, w: 1.4, h: 1.4, live: 0, cause: "" }); + run(pit, 1500); + assert.ok(!pit.hazards.some((h) => h.kind === "armBall"), "gone"); +}); + +test("Ghoul Rush's Tuning Fork spreads a ring through shelves that hurts once each, ghosts double, and cracks stone", () => { + const round = roomOf("chapel", "tower"); + standAt(round, 120); + const near = put(round, "zombie", 126, { hp: arm.RING_DMG + 1 }); + const ghost = put(round, "chorister", 116, { y: 8, hp: arm.RING_DMG * 2 + 1 }); + const stone = put(round, "gargoyle", 123, { y: 12, act: "perch" }); + const far = put(round, "zombie", 120 + arm.RING_R + 8); + near.stunMs = ghost.stunMs = far.stunMs = 1e9; + stone.stunMs = 1e9; + const farHp = far.hp; + give(round, "fork", 1); + tapTap(round); + run(round, arm.RING_MS + 20); + assert.equal(near.hp, 1); + assert.equal(ghost.hp, 1, "double to a ghost"); + assert.ok(stone.dead, "stone cracked"); + assert.equal(far.hp, farHp); + assert.ok(!round.hazards.some((h) => h.kind === "armRing")); +}); + +test("Ghoul Rush's Grave Salt lands and burns the floor for 4 s, even a hand still buried, and nothing out of its line", () => { + const round = roomOf("graveyard", "graves"); + standAt(round, 170); + const hands = put(round, "hands", 187, { act: "wait" }); + hands.stunMs = 1e9; + const hp = hands.hp; + const out = put(round, "zombie", 210); + out.stunMs = 1e9; + const outHp = out.hp; + give(round, "salt", 1); + tapTap(round); + run(round, 900); + const salt = round.hazards.find((h) => h.kind === "armSalt"); + assert.ok(salt, "it landed"); + assert.ok(Math.abs(salt.x - 170 - 1.8) < 28); + hands.x = salt.x; + run(round, arm.SALT_TICK_MS * 2 + 20); + assert.ok(hands.dead || hands.hp < hp, "the buried burn"); + assert.equal(out.hp, outHp); + run(round, arm.SALT_MS); + assert.ok(!round.hazards.some((h) => h.kind === "armSalt"), "gone in 4 s"); +}); + +test("Ghoul Rush's Flash Powder dazes what is near, still deadly to touch, and shows a flicker for a while", () => { + const round = roomOf("sanatorium", "baths"); + round.spec.flicker && (round.twist = { next: 1e12, stage: "calm", left: 0 }); + standAt(round, 60); + const z = put(round, "zombie", 70); + const f = put(round, "flicker", 72); + const far = put(round, "zombie", 150); + ghoul.advance(round, 4, steady); + assert.ok(f.unseen, "unseen till then"); + give(round, "flash", 1); + tapTap(round); + run(round, 600); + assert.ok(events(round, "armFlash").length === 1); + assert.ok(z.stunMs > 0, "dazed"); + assert.ok(!f.unseen, "shown"); + const zx = z.x; + run(round, 400); + assert.equal(z.x, zx, "it stands"); + assert.ok(!(far.stunMs > 0), "too far"); + run(round, arm.FLASH_STUN_MS); + assert.ok(!(z.stunMs > 0), "and comes round"); +}); + +test("Ghoul Rush's Silver Bear Trap sets at his feet, snaps on the first thing to step in it and holds what lives; flyers go over; five a use, ten at most", () => { + const round = roomOf("village", "inn"); + standAt(round, 40); + give(round, "trap", 3); + tapTap(round); + const trap = round.hazards.find((h) => h.kind === "armTrap"); + assert.ok(trap && trap.x === 40 - 2 * arm.TRAP_GAP); + assert.deepEqual(round.hazards.filter((h) => h.kind === "armTrap").map((h) => h.x).sort((a, b) => a - b), [-2, -1, 0, 1, 2].map((i) => 40 + i * arm.TRAP_GAP), "five, evenly spaced, two behind, one at his feet, two ahead"); + const zombie = put(round, "zombie", 40 + arm.TRAP_GAP + 1, { hp: arm.TRAP_DMG + 1 }); + zombie.stunMs = arm.TRAP_ARM_MS + 400; + const bat = put(round, "bat", 40 + 2 * arm.TRAP_GAP, { y: 14 }); + bat.stunMs = 1e9; + run(round, arm.TRAP_ARM_MS + 40); + assert.ok(events(round, "armSnap").length === 1, "snapped"); + assert.equal(zombie.hp, 1); + assert.ok(zombie.stunMs > 0, "held"); + assert.ok(!bat.dead); + // Two at once is the most: a third takes the oldest's place, so the bag never jams. + const two = roomOf("village", "inn"); + standAt(two, 40); + give(two, "trap", 3); + tapTap(two); + two.armCool = 0; + run(two, arm.DOUBLE_TAP_MS + 8); + tapTap(two); + two.armCool = 0; + run(two, arm.DOUBLE_TAP_MS + 8); + assert.equal(two.arms[0].n, 1); + const oldest = two.hazards.find((h) => h.kind === "armTrap"); + tapTap(two); + assert.deepEqual(two.arms, [], "the third is spent"); + const set = two.hazards.filter((h) => h.kind === "armTrap"); + assert.equal(set.length, arm.TRAP_MAX); + assert.ok(!set.includes(oldest), "in the oldest's place"); + // Left unsprung it goes in the end. + run(two, arm.TRAP_LIFE_MS + 40); + assert.equal(two.hazards.filter((h) => h.kind === "armTrap").length, 0, "gone in time"); +}); + +test("Ghoul Rush's ride rooms keep what needs a floor in the bag, use the next kind down, and a stick or a flash goes off in the air rather than being lost", () => { + const room = ghoul.ROOMS.find((r) => r.ride); + if (!room) return; + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["mine"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== room.id) through(round); + round.phase = "play"; + round.you.safeMs = 1e9; + round.arms = [{ kind: "trap", n: 2 }, { kind: "dyn", n: 1 }]; + round.events.length = 0; + tapTap(round); + assert.deepEqual(round.arms, [{ kind: "trap", n: 2 }], "the stick came out instead"); + assert.equal(round.hazards.filter((h) => h.kind === "armTrap").length, 0); + run(round, arm.DYN_FUSE_MS + 20); + assert.ok(events(round, "dynBlast").length === 1, "it blew in the air"); + round.armCool = 0; + round.tap = null; + tapTap(round); + assert.deepEqual(round.arms, [{ kind: "trap", n: 2 }], "only what needs a floor left: nothing comes out"); +}); + +/* ------------------------------------------------------------ the skillet */ + +const pansOf = (round) => round.hazards.find((h) => h.kind === "armPans"); +const alive = (round) => (pansOf(round) ? pansOf(round).pans.filter((p) => p.alive).length : 0); +const polar = (h, p) => ({ r: Math.hypot(p.x - h.x, p.y - h.y), a: Math.atan2(p.y - h.y, p.x - h.x) }); +const noRandom = () => { + throw new Error("a pan drew a random number"); +}; + +test("Ghoul Rush's Cast-Iron Skillet sends three pans evenly spaced round his chest, each a tight ring first and then a steady spiral outward", () => { + assert.equal(pans.PAN_COUNT, 3); + assert.ok(pans.PAN_R0 >= 4 && pans.PAN_R0 <= 5); + assert.ok(pans.PAN_TURNS >= 1.5 && pans.PAN_TURNS <= 2); + assert.ok(pans.PAN_GROW >= 14 && pans.PAN_GROW <= 18); + assert.ok(pans.PAN_ORBIT_MS >= 800 && pans.PAN_ORBIT_MS <= 1200); + assert.ok(pans.PAN_LIFE_MS >= 2500 && pans.PAN_LIFE_MS <= 3200); + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + give(round, "skillet", 2); + tapTap(round); + assert.equal(round.arms[0].n, 1); + // The cool-down holds a second use back. + tapTap(round); + assert.equal(round.arms[0].n, 1); + assert.equal(round.hazards.filter((q) => q.kind === "armPans").length, 1); + const h = pansOf(round); + assert.equal(h.pans.length, 3); + const at = h.pans.map((p) => polar(h, p)); + for (let i = 0; i < 3; i++) { + const turn = (((at[(i + 1) % 3].a - at[i].a) % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2); + assert.ok(Math.abs(turn - (Math.PI * 2) / 3) < 1e-6, "120 degrees apart"); + } + // Round his chest, and following him as he runs. + assert.equal(h.x, round.you.x); + assert.equal(h.y, round.you.y + pans.PAN_LIFT); + run(round, pans.PAN_ORBIT_MS - 40); + for (const p of pansOf(round).pans) assert.ok(Math.abs(polar(pansOf(round), p).r - pans.PAN_R0) < 1e-6, "a tight ring for the first second"); + round.you.x += 7; + run(round, 4); + assert.equal(pansOf(round).x, round.you.x, "the ring follows him"); + // Then the radius is a straight line of time. + const radii = []; + for (let i = 0; i < 4; i++) { + run(round, 400); + if (!pansOf(round)) break; + radii.push([pansOf(round).t, polar(pansOf(round), pansOf(round).pans[0]).r]); + } + assert.ok(radii.length >= 3); + for (const [t, r] of radii) assert.ok(Math.abs(r - (pans.PAN_R0 + ((t - pans.PAN_ORBIT_MS) / 1000) * pans.PAN_GROW)) < 1e-6, "an Archimedean spiral"); + assert.ok(radii[radii.length - 1][1] > pans.PAN_R0 + 15, "it widens a long way"); +}); + +test("Ghoul Rush's pans leave the view or end at their lifetime, and draw no random number", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + give(round, "skillet", 2); + tapTap(round); + // Nothing in the room, so nothing else draws: advance the whole way on a random that throws. + for (let t = 0; t < pans.PAN_LIFE_MS + 100 && pansOf(round); t += 4) ghoul.advance(round, 4, noRandom); + assert.ok(!pansOf(round), "gone by the lifetime cap"); + // Out at the edge of a room, a pan that flies off the side is let go before the cap. + const edge = roomOf("wing", "kitchen"); + standAt(edge, 6); + edge.camX = 0; + give(edge, "skillet", 1); + tapTap(edge); + let left = 3; + for (let t = 0; t < pans.PAN_LIFE_MS - 100; t += 4) { + ghoul.advance(edge, 4, steady); + if (pansOf(edge)) left = alive(edge); + } + assert.ok(left < 3, "a pan off the side is gone for good"); +}); + +test("Ghoul Rush's pans one-shot whatever they touch and break on it, so one use kills three things at most", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + // Six sturdy zombies standing in the ring's way, none able to hurt him. + const crowd = [4.5, -4.5, 3.5, -3.5, 4.5, -4.5].map((dx, i) => put(round, "zombie", 40 + dx, { hp: 99 + i })); + for (const m of crowd) m.stunMs = 1e9; + const score = round.score; + give(round, "skillet", 1); + tapTap(round); + const bursts = new Set(); + for (let t = 0; t < 1000; t += 4) { + ghoul.advance(round, 4, steady); + for (const h of round.hazards) if (h.kind === "armPanBurst") bursts.add(h); + } + assert.equal(crowd.filter((m) => !round.monsters.includes(m)).length, 3, "exactly three kills"); + assert.equal(round.stats.kills, 3); + assert.ok(!pansOf(round), "all three pans broke on them"); + assert.ok(round.score > score); + assert.ok(events(round, "kill").every((e) => e.how === "arm")); + assert.equal(round.drops.length, 0, "no drops from an area weapon"); + assert.equal(events(round, "armUse").length, 1); + assert.ok(events(round, "armClang").length >= 1 && events(round, "armClang").length <= 3); + assert.equal(bursts.size, 3, "a burst for each pan"); + // Any hp goes in one hit. + const tough = roomOf("wing", "kitchen"); + standAt(tough, 40); + const big = put(tough, "zombie", 44.5, { hp: 5000 }); + big.stunMs = 1e9; + give(tough, "skillet", 1); + tapTap(tough); + run(tough, 800); + assert.ok(!tough.monsters.includes(big), "any hp"); +}); + +test("Ghoul Rush's three pans that meet three monsters at once clang once, and each kill is one", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + give(round, "skillet", 1); + tapTap(round); + const crowd = pansOf(round).pans.map((p) => { + const m = put(round, "zombie", p.x, { y: p.y - 1 }); + m.stunMs = 1e9; + return m; + }); + round.events.length = 0; + run(round, 8); + assert.ok(crowd.every((m) => !round.monsters.includes(m))); + assert.equal(events(round, "kill").length, 3); + assert.equal(events(round, "armClang").length, 1, "rate limited"); +}); + +test("Ghoul Rush's pans never hurt Planny, who stands in the middle of them, and skip what cannot be hit or only carries him", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + round.you.safeMs = 0; + const lives = round.lives; + give(round, "skillet", 1); + tapTap(round); + for (const h of round.hazards) assert.equal(h.live, 0); + run(round, pans.PAN_LIFE_MS + 100); + assert.equal(round.lives, lives); + assert.equal(round.phase, "play"); + assert.equal(round.you.out, 0); + // A cage he stands on, a canary and an imp (harmless) and a zombie not yet up, all untouched. + const mine = roomOf("mine", ghoul.STAGES.find((s) => s.id === "mine").rooms[0]); + standAt(mine, 40); + const cage = put(mine, "cage", 44.5); + const canary = put(mine, "canary", 35.5); + const imp = put(mine, "imp", 44.5, { y: 4 }); + const rising = put(mine, "zombie", 40, { rise: 5000 }); + give(mine, "skillet", 1); + tapTap(mine); + run(mine, 1400); + for (const m of [cage, canary, imp, rising]) assert.ok(mine.monsters.includes(m) && !m.dead, m.kind); + assert.equal(mine.stats.kills, 0); + assert.ok(pansOf(mine) && alive(mine) === 3, "the pans flew on"); +}); + +test("Ghoul Rush's pans never one-shot a boss: each does a weapon's boss damage through armBossDamage and breaks, a guard blocks and a hidden boss is missed", () => { + const fight = fightOf("manor", "ballroom"); + const b = fight.boss; + b.stunMs = 1e9; + standAt(fight, b.x - 4); + const hp = b.hp; + give(fight, "skillet", 1); + tapTap(fight); + run(fight, 1200); + assert.equal(b.state, "fight", "not killed"); + assert.ok(b.hp < hp); + assert.ok(hp - b.hp <= 3 * pans.PAN_BOSS, "at most three weapon hits"); + assert.equal(fight.armBossDmg, hp - b.hp, "counted by armBossDamage"); + assert.ok(!pansOf(fight), "the pans broke on him"); + // Deep in a run the same pan takes the same share of a tougher boss, as a stick does. + const deep = fightOf("manor", "ballroom", 7); + deep.boss.stunMs = 1e9; + standAt(deep, deep.boss.x - 4); + const before = deep.boss.hp; + give(deep, "skillet", 1); + tapTap(deep); + run(deep, 1200); + assert.ok(before - deep.boss.hp > hp - b.hp, "more off a tougher boss"); + // Mother Mourning weeping: guarded, the iron rings off and breaks. + const mourn = fightOf("graveyard", "angel"); + const m = mourn.boss; + m.act = "weep"; + m.stunMs = 1e9; + const mh = m.hp; + standAt(mourn, m.x - 4); + give(mourn, "skillet", 1); + tapTap(mourn); + run(mourn, 1200); + assert.equal(m.hp, mh, "guarded"); + assert.ok(events(mourn, "bossBlock").length >= 1); + // The Tommyknocker, hidden: not hit, and the pans fly on. + const tommy = fightOf("mine", "seam"); + tommy.boss.hidden = true; + tommy.boss.stunMs = 1e9; + standAt(tommy, tommy.boss.x - 4); + const th = tommy.boss.hp; + give(tommy, "skillet", 1); + tapTap(tommy); + run(tommy, 1200); + assert.equal(tommy.boss.hp, th); + assert.equal(alive(tommy), 3); +}); + +test("Ghoul Rush's skillets carry between rooms in the bag, and the pans are cleared by a room change and a life lost", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + give(round, "skillet", 3); + tapTap(round); + assert.ok(pansOf(round)); + assert.equal(round.arms[0].n, 2); + through(round); + assert.ok(!pansOf(round), "a room change clears them"); + assert.equal(round.arms[0].kind, "skillet"); + assert.equal(round.arms[0].n, 2, "and the bag stays"); + // A life lost puts the room back as it was. + const dead = roomOf("wing", "kitchen"); + standAt(dead, 40); + give(dead, "skillet", 3); + tapTap(dead); + dead.you.safeMs = 0; + ghoul.lose(dead, "bone"); + for (let i = 0; i < 600 && dead.phase !== "play"; i++) ghoul.advance(dead, 16, steady); + run(dead, 40); + assert.ok(!pansOf(dead), "a respawn clears them"); + assert.equal(dead.arms[0].n, 2); + // Endless lives change nothing about them. + const infinite = roomOf("wing", "kitchen"); + infinite.infinite = true; + standAt(infinite, 40); + give(infinite, "skillet", 1); + tapTap(infinite); + assert.ok(pansOf(infinite)); +}); + +test("Ghoul Rush's pans freeze while the game is paused", () => { + const { g, round } = game(); + standAt(round, 40); + give(round, "skillet", 2); + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + assert.ok(pansOf(round)); + g.tick(100); + const t = pansOf(round).t; + assert.ok(t > 0); + g.pause(); + g.tick(500); + assert.equal(pansOf(round).t, t, "paused"); + g.resume(); + g.tick(100); + assert.ok(pansOf(round).t > t); +}); + +test("Ghoul Rush's pans draw in a dark room and a lit one, with a burst", () => { + for (const dark of [false, true]) { + const { g, round } = game(); + round.dark = dark; + standAt(round, 40); + const z = put(round, "zombie", 44.5); + z.stunMs = 1e9; + give(round, "skillet", 2); + g.key("action"); + g.tick(8); + g.release("action"); + g.tick(8); + g.key("action"); + g.tick(16); + g.release("action"); + let burst = false; + for (let i = 0; i < 12; i++) { + g.tick(32); + burst ||= round.hazards.some((h) => h.kind === "armPanBurst"); + } + assert.ok(pansOf(round), "in flight"); + assert.ok(burst, `a burst, dark ${dark}`); + for (let i = 0; i < 100; i++) g.tick(32); + assert.ok(!pansOf(round), `done, dark ${dark}`); + } +}); + +/* ------------------------------------------------------------ Bottle Rocket */ + +const rocketsOf = (round) => round.hazards.filter((h) => h.kind === "armRocket"); +const boomsOf = (round) => round.hazards.filter((h) => h.kind === "armRocketBoom"); +const launch = (round, n = 1) => { + give(round, "rocket", n); + tapTap(round); +}; +const sparkTotal = (round) => round.hazards.reduce((n, h) => n + (h.sparks ? h.sparks.length : 0), 0); +const rocketStuff = (round) => round.hazards.filter((h) => /^armRocket|^armMuzzle/.test(h.kind)).length; +// A level, open stretch of floor with room to fly: the hall. +const open = () => { + const round = roomOf(null, "hall"); + standAt(round, 60); + return round; +}; + +test("Ghoul Rush's Bottle Rocket fires three at once, ahead, up and behind, for one use from the bag, with a flash at the muzzle", () => { + assert.equal(arm.ROCKET_COUNT, 3); + for (const face of [1, -1]) { + const round = open(); + standAt(round, 60, face); + launch(round, 3); + assert.equal(round.arms[0].n, 2, "one use from the bag, not three"); + assert.equal(events(round, "armUse").length, 1, "one use event, so one launch sound"); + assert.equal(events(round, "armUse")[0].kind, "rocket"); + const rs = rocketsOf(round); + assert.deepEqual(rs.map((h) => h.dir), ["fwd", "up", "back"]); + const [fwd, up, back] = rs; + const chest = round.you.y + ghoul.SHOT_Y; + assert.equal(fwd.vx, face * arm.ROCKET_SPEED, "ahead, the way he faces, fast"); + assert.equal(fwd.vy, 0, "level"); + assert.equal(fwd.y, chest, "with his chest"); + assert.equal(up.vx, 0); + assert.equal(up.vy, arm.ROCKET_UP_SPEED, "straight up"); + assert.equal(back.vx, -face * arm.ROCKET_BACK_SPEED, "behind, opposite his facing"); + assert.equal(back.vy, 0); + assert.ok((fwd.x - round.you.x) * face > 0 && (back.x - round.you.x) * face < 0); + assert.equal(round.hazards.filter((h) => h.kind === "armMuzzle").length, 1, "a muzzle flash"); + assert.equal(round.armCool, arm.ARM_COOL_MS); + } + assert.ok(arm.ROCKET_SPEED > 72, "faster than the old one"); +}); + +test("Ghoul Rush's Bottle Rocket flies ahead and behind in straight lines, the ahead one level with his chest", () => { + const round = open(); + launch(round); + const [fwd, , back] = rocketsOf(round); + const y = fwd.y; + const x0 = fwd.x; + const bx0 = back.x; + run(round, 400); + assert.equal(fwd.y, y); + assert.equal(back.y, y); + assert.ok(Math.abs(fwd.x - x0 - arm.ROCKET_SPEED * 0.4) < 0.7, "ahead at ROCKET_SPEED"); + assert.ok(Math.abs(bx0 - back.x - arm.ROCKET_BACK_SPEED * 0.4) < 0.7, "behind at ROCKET_BACK_SPEED"); +}); + +test("Ghoul Rush's ahead and behind rockets bend toward a monster above or below their line on their side, and stay straight with none", () => { + for (const [name, y, dir, x] of [["above ahead", 22, "fwd", 96], ["below ahead", -4, "fwd", 96], ["above behind", 22, "back", 24]]) { + const round = open(); + const bat = put(round, "bat", x, { y, hp: 5 }); + bat.awake = true; + bat.stunMs = 1e9; + launch(round); + const r = rocketsOf(round).find((h) => h.dir === dir); + const y0 = r.y; + run(round, 160); + assert.ok(r.dead || Math.sign(r.vy) === Math.sign(y - y0), `${name}: it bends toward the monster (vy ${r.vy})`); + assert.ok(r.dead || Math.abs(Math.hypot(r.vx, r.vy) - (dir === "fwd" ? arm.ROCKET_SPEED : arm.ROCKET_BACK_SPEED)) < 0.5, `${name}: speed is kept`); + } + // A monster on the rocket's line, or on the other side, changes nothing. + const level = open(); + const walker = put(level, "zombie", 96, { hp: 5 }); + walker.stunMs = 1e9; + launch(level); + const f = rocketsOf(level)[0]; + run(level, 100); + assert.equal(f.vy, 0, "level with it: straight on"); + const behind = open(); + const bat = put(behind, "bat", 24, { y: 22, hp: 5 }); + bat.awake = true; + bat.stunMs = 1e9; + launch(behind); + const ahead = rocketsOf(behind)[0]; + run(behind, 100); + assert.equal(ahead.vy, 0, "a monster behind does not bend the rocket going ahead"); +}); + +test("Ghoul Rush's up rocket climbs straight, then curves over and homes on a flyer ahead or above, and arcs forward and drops with nothing there", () => { + // A bat on high, ahead. + const round = open(); + const bat = put(round, "bat", 90, { y: 24, hp: 5 }); + bat.awake = true; + bat.stunMs = 1e9; + launch(round); + const up = rocketsOf(round)[1]; + const x0 = up.x; + run(round, arm.ROCKET_UP_MS - 20); + assert.equal(up.x, x0, "straight up"); + assert.ok(up.vy > 0); + run(round, 1400); + assert.ok(bat.dead, "it homed on the bat"); + // A bat overhead and a little behind: above counts wherever it is in view. + const over = open(); + const high = put(over, "bat", 52, { y: 26, hp: 5 }); + high.awake = true; + high.stunMs = 1e9; + launch(over); + run(over, 1800); + assert.ok(high.dead, "above and a little behind counts"); + // Nothing to chase: up, over, forward and down onto the floor, ahead of him. + const none = open(); + launch(none); + const u = rocketsOf(none)[1]; + let peak = 0; + let boom = null; + for (let t = 0; t < 2000 && !boom; t += 4) { + ghoul.advance(none, 4, steady); + if (rocketsOf(none).includes(u)) peak = Math.max(peak, u.y); + boom = boomsOf(none).find((b) => b.y < 9 && b.x > 64) || null; + } + assert.ok(peak > 20, `a high arc (${peak})`); + assert.ok(boom, "it came down on the floor"); + assert.ok(boom.x > 75, `ahead of him (${boom.x})`); + assert.ok(!rocketsOf(none).includes(u)); +}); + +test("Ghoul Rush's up rocket facing left arcs left", () => { + const round = open(); + standAt(round, 120, -1); + launch(round); + let boom = null; + for (let t = 0; t < 2000 && !boom; t += 4) { + ghoul.advance(round, 4, steady); + boom = boomsOf(round).find((b) => b.y < 9 && b.x < 118) || null; + } + assert.ok(boom, "it came down"); + assert.ok(boom.x < 100, `ahead of him, to the left (${boom.x})`); +}); + +test("Ghoul Rush's rockets each go off on a monster, on a wall and on the floor, and at the end of their life", () => { + // On a monster: the ahead rocket stops on the first one it meets. + const round = open(); + const near = put(round, "zombie", 80, { hp: 3 }); + const far = put(round, "zombie", 130, { hp: 3 }); + near.stunMs = far.stunMs = 1e9; + launch(round); + run(round, 400); + assert.ok(near.dead, "the near one is blown up"); + assert.ok(!far.dead, "the far one was shielded by it"); + assert.equal(rocketsOf(round).filter((h) => h.dir === "fwd").length, 0); + // A wall: ground that steps up ahead. + const wall = open(); + wall.spec = { ...wall.spec, ground: [[0, 90, 6], [90, 400, 30]], shelves: [] }; + launch(wall); + run(wall, 300); + assert.ok(boomsOf(wall).some((b) => Math.abs(b.x - 90) < 3), "gone off at the wall"); + assert.equal(rocketsOf(wall).filter((h) => h.dir === "fwd").length, 0); + // The floor: a rocket pointing down. + const floor = open(); + launch(floor); + const f = rocketsOf(floor)[0]; + f.vx = 0; + f.vy = -50; + run(floor, 200); + assert.ok(boomsOf(floor).some((b) => b.y <= 7), "gone off on the floor"); + // The end of its life: nothing in the way for the ahead rocket. + const far2 = roomOf(null, "hall"); + far2.spec = { ...far2.spec, ground: [[0, 900, 6]], length: 900, shelves: [] }; + standAt(far2, 20); + launch(far2); + const fw = rocketsOf(far2)[0]; + run(far2, arm.ROCKET_LIFE_MS - 40); + assert.ok(rocketsOf(far2).includes(fw), "still flying just before"); + run(far2, 80); + assert.ok(!rocketsOf(far2).includes(fw), "gone at ROCKET_LIFE_MS"); + assert.ok(boomsOf(far2).some((b) => b.x > 200), "it went off where it was"); + assert.ok(arm.ROCKET_LIFE_MS >= 1800 && arm.ROCKET_LIFE_MS <= 2200); +}); + +test("Ghoul Rush's rocket blast is wider, kills ordinary monsters and hits each monster in it once", () => { + assert.ok(arm.ROCKET_BLAST_R >= 6, "bigger"); + const round = open(); + const lead = put(round, "zombie", 82, { hp: 100 }); + const inside = [put(round, "zombie", 85.2, { hp: 100 }), put(round, "glutton", 87.2, { hp: 100 })]; + const out = put(round, "zombie", 96, { hp: 100 }); + for (const m of [lead, ...inside, out]) m.stunMs = 1e9; + launch(round); + run(round, 500); + for (const m of [lead, ...inside]) assert.equal(m.hp, 100 - arm.ROCKET_DMG, "hit once each, by the blast"); + assert.equal(out.hp, 100, "outside the radius"); + // Anything ordinary dies of one blast. + const kill = open(); + const tough = [put(kill, "skeleton", 81, {}), put(kill, "zombie", 83, {}), put(kill, "glutton", 86, {})]; + for (const m of tough) m.stunMs = 1e9; + const score = kill.score; + launch(kill); + run(kill, 500); + assert.ok(tough.every((m) => m.dead), "all dead"); + assert.equal(kill.stats.kills, 3); + assert.ok(kill.score > score); + assert.ok(events(kill, "kill").every((e) => e.how === "blast")); + assert.equal(kill.drops.length, 0, "no drops"); + assert.ok(arm.ROCKET_DMG >= 20); +}); + +test("Ghoul Rush's rocket spares what cannot be hit just now, the unseen", () => { + const round = open(); + const unseen = put(round, "zombie", 82, { hp: 5 }); + unseen.unseen = true; + const hurtMe = put(round, "zombie", 80, { hp: 5 }); + hurtMe.stunMs = 1e9; + launch(round); + run(round, 500); + assert.ok(hurtMe.dead); + assert.ok(!unseen.dead, "unseen is not hit"); +}); + +test("Ghoul Rush's rockets on a boss go through armBossDamage: scaled, capped in all, a guard shows and a hidden boss is missed", () => { + const fight = fightOf("manor", "ballroom"); + const b = fight.boss; + b.stunMs = 1e9; + standAt(fight, b.x - 7); + const hp = b.hp; + launch(fight); + run(fight, 2400); + assert.equal(b.state, "fight", "not killed"); + assert.ok(b.hp < hp); + assert.ok(hp - b.hp <= 3 * arm.ROCKET_BOSS, "at most three weapon hits"); + assert.equal(fight.armBossDmg, hp - b.hp, "counted by armBossDamage"); + assert.equal(rocketsOf(fight).length, 0); + // Deep in a run the same rockets take the same share of a tougher boss. + const deep = fightOf("manor", "ballroom", 7); + deep.boss.stunMs = 1e9; + standAt(deep, deep.boss.x - 7); + const before = deep.boss.hp; + launch(deep); + run(deep, 1500); + assert.ok(before - deep.boss.hp > hp - b.hp, "more off a tougher boss"); + // Past the share cap every hit is 1, the three rockets together. + const capped = fightOf("manor", "ballroom"); + capped.boss.stunMs = 1e9; + capped.armBossDmg = capped.spec.bossHp * arm.ARM_BOSS_SHARE; + standAt(capped, capped.boss.x - 7); + const ch = capped.boss.hp; + launch(capped); + run(capped, 1500); + assert.ok(ch - capped.boss.hp >= 1 && ch - capped.boss.hp <= 3, "1 a hit past the cap"); + // A guard shows and nothing is taken. + const mourn = fightOf("graveyard", "angel"); + const m = mourn.boss; + m.act = "weep"; + m.stunMs = 1e9; + const mh = m.hp; + standAt(mourn, m.x - 7); + launch(mourn); + run(mourn, 1500); + assert.equal(m.hp, mh, "guarded"); + assert.ok(events(mourn, "bossBlock").length >= 1); + // A hidden boss is missed: the blast takes nothing off it. + const tommy = fightOf("mine", "seam"); + tommy.boss.hidden = true; + tommy.boss.stunMs = 1e9; + standAt(tommy, tommy.boss.x - 7); + const th = tommy.boss.hp; + launch(tommy); + run(tommy, 1500); + assert.equal(tommy.boss.hp, th); +}); + +test("Ghoul Rush's rockets never hurt Planny, who stands in their blasts", () => { + const round = open(); + const lives = round.lives; + round.you.safeMs = 0; + // A wall right at his back and a monster in his face: blasts on top of him. + round.spec = { ...round.spec, ground: [[0, 62, 6], [62, 400, 30]], shelves: [] }; + const z = put(round, "zombie", 56, { hp: 5 }); + z.stunMs = 1e9; + launch(round); + run(round, 1500); + assert.equal(round.lives, lives); + assert.equal(round.you.out, 0); + assert.equal(events(round, "lose").length, 0); + assert.ok(z.dead, "but it blew up the monster beside him"); +}); + +test("Ghoul Rush's rocket sparks are multicolored, thrown behind, 6 to 10 a frame, and fade inside half a second", () => { + assert.deepEqual([...arm.SPARK_COLORS], ["#ff3b30", "#ff9500", "#ffe14d", "#3ddc5a", "#33e0ff", "#ff4fd8"]); + const round = open(); + launch(round); + const [fwd] = rocketsOf(round); + const n0 = round.sparkN || 0; + run(round, 200); + const shed = (round.sparkN - n0) / 3; + const perFrame = (shed / 200) * (1000 / 60); + assert.ok(perFrame >= 6 && perFrame <= 10, `per 60 fps frame (${perFrame})`); + const live = fwd.sparks; + assert.ok(live.length > 10); + assert.equal(new Set(live.map((p) => p.c)).size, 6, "all six colors"); + assert.ok(live.every((p) => p.life <= arm.SPARK_LIFE_MS + arm.SPARK_LIFE_VARY + 1 && p.age < p.life)); + assert.ok(live.every((p) => p.x < fwd.x + 0.5), "trailing back behind a rocket flying ahead"); + assert.ok(arm.SPARK_LIFE_MS + arm.SPARK_LIFE_VARY <= 450); + // The same spacing at a slower frame rate: by distance. + const a = open(); + const b = open(); + launch(a); + launch(b); + for (let t = 0; t < 240; t += 4) ghoul.advance(a, 4, steady); + for (let t = 0; t < 240; t += 40) ghoul.advance(b, 40, steady); + assert.ok(Math.abs(a.sparkN - b.sparkN) <= 8, `frame-rate independent (${a.sparkN} v ${b.sparkN})`); +}); + +test("Ghoul Rush's sparks draw no random number, do not shift the rng and replay the same, and are capped", () => { + const real = Math.random; + Math.random = () => { + throw new Error("Math.random drawn"); + }; + try { + const draws = []; + const rng = () => { + draws.push(1); + return 0.5; + }; + const play = (fire) => { + const round = open(); + if (fire) launch(round, 2); + for (let t = 0; t < 700; t += 4) ghoul.advance(round, 4, rng); + return JSON.stringify(round.hazards.map((h) => h.sparks || null)); + }; + const a = play(true); + const withRockets = draws.length; + const b = play(true); + assert.equal(a, b, "the same sparks every time"); + assert.ok(a.length > 1000); + draws.length = 0; + play(false); + assert.equal(withRockets, draws.length, "no rng draw for rockets or sparks"); + // Volley after volley never passes the cap. + const heavy = open(); + let most = 0; + for (let v = 0; v < 8; v++) { + heavy.armCool = 0; + heavy.tap = null; + launch(heavy, 2); + for (let t = 0; t < 120; t += 4) { + ghoul.advance(heavy, 4, steady); + most = Math.max(most, sparkTotal(heavy)); + } + } + assert.ok(most > 150, `plenty of sparks (${most})`); + assert.ok(most <= arm.SPARK_CAP, `capped at ${arm.SPARK_CAP} (${most})`); + } finally { + Math.random = real; + } +}); + +test("Ghoul Rush's rockets carry between rooms in the bag, and are cleared by a room change and a life lost, endless lives change nothing", () => { + const round = roomOf("wing", "kitchen"); + standAt(round, 40); + launch(round, 3); + assert.equal(rocketsOf(round).length, 3); + assert.equal(round.arms[0].n, 2); + through(round); + assert.equal(rocketStuff(round), 0, "a room change clears them"); + assert.equal(round.arms[0].kind, "rocket"); + assert.equal(round.arms[0].n, 2, "and the bag stays"); + const dead = open(); + launch(dead, 3); + dead.you.safeMs = 0; + ghoul.lose(dead, "bone"); + for (let i = 0; i < 600 && dead.phase !== "play"; i++) ghoul.advance(dead, 16, steady); + run(dead, 40); + assert.equal(rocketStuff(dead), 0, "a respawn clears them"); + assert.equal(dead.arms[0].n, 2); + const infinite = open(); + infinite.infinite = true; + launch(infinite); + assert.equal(rocketsOf(infinite).length, 3); + assert.equal(ghoul.POWERS.rocket.max, 6); +}); + +test("Ghoul Rush's rockets and their sparks freeze while the game is paused", () => { + const { g, round } = game(); + standAt(round, 60); + give(round, "rocket", 2); + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + g.tick(100); + const rs = rocketsOf(round); + assert.equal(rs.length, 3); + const at = rs.map((h) => [h.x, h.y, h.t, h.sparks.length]); + g.pause(); + g.tick(500); + assert.deepEqual(rs.map((h) => [h.x, h.y, h.t, h.sparks.length]), at, "paused"); + g.resume(); + g.tick(100); + assert.ok(rs[0].t > at[0][2]); +}); + +test("Ghoul Rush's rocket launch sounds once per volley with a quieter copy, and the blasts share one sound", () => { + const played = []; + const noop = () => {}; + const kit = { tone: (name, v) => played.push([name, v]), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 0 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: ghoul }; + react({ type: "armUse", kind: "rocket", x: 1, y: 1, face: 1 }, kit); + assert.equal(played.length, 2); + assert.ok(played.every(([name]) => name === "ghoulArmRocket"), "the wired rocket tone, no new file"); + assert.ok(played[0][1] > played[1][1], "the volley's, then a lower copy for the other two"); + assert.ok(ghoulSfx.default.tones.ghoulArmRocket); + played.length = 0; + react({ type: "armBoom", x: 1, y: 1 }, kit); + assert.equal(played.length, 1); + assert.ok(ghoulSfx.default.tones[played[0][0]]); + // Three blasts at once raise a few events at most, one use event a volley. + const round = open(); + launch(round); + run(round, 2200); + assert.ok(events(round, "armBoom").length >= 1 && events(round, "armBoom").length <= 3); + assert.equal(events(round, "armUse").length, 1); +}); + +test("Ghoul Rush's rockets, their sparks and their burst draw in a dark room and a lit one, and light the dark", () => { + for (const dark of [false, true]) { + const { g, round } = game(); + round.dark = dark; + standAt(round, 60); + const z = put(round, "zombie", 84, { hp: 3 }); + z.stunMs = 1e9; + give(round, "rocket", 2); + g.key("action"); + g.tick(8); + g.release("action"); + g.tick(8); + g.key("action"); + g.tick(16); + g.release("action"); + let flight = false; + let burst = false; + for (let i = 0; i < 40; i++) { + g.tick(32); + flight ||= rocketsOf(round).some((h) => h.sparks.length > 4); + burst ||= boomsOf(round).length > 0; + } + assert.ok(flight, `sparks in flight, dark ${dark}`); + assert.ok(burst, `a burst, dark ${dark}`); + } + const round = open(); + launch(round); + const lit = []; + rocketArt({ circle: () => {} }).lights({ round }, (...a) => lit.push(a)); + assert.ok(lit.length >= 4, "three heads and the muzzle"); + assert.ok(lit.every(([, , r, s]) => r >= 8 && s > 0)); +}); + +/* ------------------------------------------------------------------- bosses */ + +test("Ghoul Rush's boss takes a weapon's damage scaled to its hp at this depth, and past 35% of its hp in a fight only 1 a hit", () => { + const fight = fightOf("manor", "ballroom"); + const b = fight.boss; + const near = () => fight.hazards.push({ kind: "stick", x: b.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + b.stunMs = 1e9; + const hp0 = b.hp; + near(); + run(fight, 12); + assert.equal(hp0 - b.hp, arm.DYN_BOSS_DMG, "8 at the first depth"); + // Deep in a run it takes the same share of a tougher boss. + const deep = fightOf("manor", "ballroom", 7); + assert.ok(deep.boss.max > hp0); + deep.boss.stunMs = 1e9; + const before = deep.boss.hp; + deep.hazards.push({ kind: "stick", x: deep.boss.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(deep, 12); + assert.equal(before - deep.boss.hp, Math.round((arm.DYN_BOSS_DMG * deep.boss.max) / hp0)); + // The cap: use the numbers straight on. + const cap = fightOf("manor", "ballroom"); + cap.boss.stunMs = 1e9; + let taken = 0; + for (let i = 0; i < 40 && cap.boss.state === "fight"; i++) { + const was = cap.boss.hp; + cap.hazards.push({ kind: "stick", x: cap.boss.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(cap, 12); + const d = was - cap.boss.hp; + taken += d; + if (taken > cap.boss.max * arm.ARM_BOSS_SHARE + arm.DYN_BOSS_DMG) assert.equal(d, 1, "past the cap only 1"); + } + assert.ok(cap.armBossDmg <= cap.boss.max * arm.ARM_BOSS_SHARE + arm.DYN_BOSS_DMG); +}); + +test("Ghoul Rush's weapons respect a boss's guard and a hidden boss, and a weapon that fells a boss leaves the hazards tidy", () => { + // Mother Mourning, weeping: shrugs it off, and it shows. + const mourn = fightOf("graveyard", "angel"); + const m = mourn.boss; + m.act = "weep"; + m.stunMs = 1e9; + const hp = m.hp; + mourn.hazards.push({ kind: "stick", x: m.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(mourn, 12); + assert.equal(m.hp, hp, "guarded"); + assert.ok(events(mourn, "bossBlock").length >= 1); + // The Tommyknocker, hidden in the seam. + const tommy = fightOf("mine", "seam"); + tommy.boss.hidden = true; + tommy.boss.stunMs = 1e9; + const th = tommy.boss.hp; + tommy.hazards.push({ kind: "stick", x: tommy.boss.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(tommy, 12); + assert.equal(tommy.boss.hp, th); + // A blast that fells him, with other hazards still alive on the list. + const end = fightOf("manor", "ballroom"); + end.boss.hp = 1; + end.boss.stunMs = 1e9; + end.hazards.push({ kind: "armSalt", x: 10, y: 6, life: 1e6, max: 1e6, tick: 1e6, bossDone: 0, w: arm.SALT_W, h: 1, live: 0, cause: "" }); + end.hazards.push({ kind: "stick", x: end.boss.x, y: 6, vx: 0, vy: 0, fuse: 4, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(end, 40); + assert.equal(end.boss.state, "down"); + assert.ok(end.hazards.every(Boolean), "no holes"); +}); + +test("Ghoul Rush's Tuning Fork strikes the Choirmaster's pipes, a stake too, harder than a bolt", () => { + const fight = fightOf("chapel", "choir"); + const b = fight.boss; + assert.ok(b.pipes?.length === 4); + b.stunMs = 1e9; + const p = b.pipes[0]; + const hp = p.hp; + fight.hazards.push({ kind: "armRing", x: p.x, y: 6, r: 0, life: arm.RING_MS, max: arm.RING_MS, hit: [], hitPipe: [], hitBoss: false, w: 1, h: 1, live: 0, cause: "" }); + standAt(fight, p.x - 1); + fight.lockX = fight.spec.arena; + run(fight, arm.RING_MS + 8); + assert.equal(p.hp, hp - arm.RING_PIPE); + assert.ok(events(fight, "pipeHit").length >= 1); + assert.equal(b.hp, b.max, "he stays guarded"); +}); + +test("Ghoul Rush's Flash Powder and Bear Trap hold a boss still for a moment, and the Matron's beam goes dark", () => { + const fight = fightOf("sanatorium", "ward"); + const b = fight.boss; + const hp = b.hp; + fight.hazards.push({ kind: "armPod", pay: "flash", x: b.x - 2, y: b.y + 1, vx: 0, vy: -10, spin: 0, w: 0.8, h: 0.8, live: 0, cause: "" }); + run(fight, 200); + assert.ok(b.stunMs > 0, "dazed"); + assert.ok(events(fight, "armDaze").length === 1); + assert.equal(hp - b.hp, arm.FLASH_BOSS_DMG); + const t = b.t; + const heat = b.heat; + run(fight, 300); + assert.equal(b.heat, heat, "no heat builds"); + assert.ok(b.t > t); + const trap = fightOf("village", "green"); + const beast = trap.boss; + trap.hazards.push({ kind: "armTrap", x: beast.x, y: beast.y, vy: 0, rest: true, arm: 0, life: 1e6, shut: 0, w: 2.4, h: 1, live: 0, cause: "" }); + const was = beast.hp; + run(trap, 8); + assert.equal(was - beast.hp, arm.TRAP_BOSS); + assert.ok(beast.stunMs > 0, "pinned"); + // A guarded boss is neither hurt nor held: that would only cut short the moment she can be hurt. + const weep = fightOf("graveyard", "angel"); + const angel = weep.boss; + angel.act = "weep"; + const her = angel.hp; + weep.hazards.push({ kind: "armTrap", x: angel.x, y: angel.y, vy: 0, rest: true, arm: 0, life: 1e6, shut: 0, w: 2.4, h: 1, live: 0, cause: "" }); + weep.hazards.push({ kind: "armPod", pay: "flash", x: angel.x, y: angel.y + 1, vx: 0, vy: -10, spin: 0, w: 0.8, h: 0.8, live: 0, cause: "" }); + ghoul.advance(weep, 4, steady); + assert.equal(angel.hp, her); + assert.ok(!(angel.stunMs > 0), "no daze"); +}); + +test("Ghoul Rush's boss at half hp gives an empty bag its stage's weapon, once a fight, and never while you hold one", () => { + const fight = fightOf("wing", "crypt"); + fight.boss.stunMs = 1e9; + fight.boss.hp = Math.floor(fight.boss.max / 2); + run(fight, 8); + assert.deepEqual(fight.drops.map((d) => d.kind), ["skillet"]); + fight.drops.length = 0; + run(fight, 8); + assert.equal(fight.drops.length, 0, "once"); + const holding = fightOf("wing", "crypt"); + holding.boss.stunMs = 1e9; + holding.arms = [{ kind: "dyn", n: 1 }]; + holding.boss.hp = Math.floor(holding.boss.max / 2); + run(holding, 8); + assert.equal(holding.drops.length, 0); +}); + +/* ---------------------------------------------------------------- Bat wings */ + +test("Ghoul Rush's Bat wings catch a fall down a pit: no life or die spent, he flies back to where he last stood, no key working, safe on landing, and the wings are spent", () => { + const round = roomOf("manor", "gallery"); + ghoul.applyPower(round, "wings"); + round.dice = 2; + round.you.garlic = true; + round.you.safeMs = 0; + standAt(round, 96); + run(round, 8); + const lives = round.lives; + // Off the edge at 100 and down the pit. + Object.assign(round.you, { x: 104, state: "air", vy: 0, face: 1 }); + round.input.right = true; + for (let k = 0; k < 500 && !round.you.lift; k++) ghoul.advance(round, 4, steady); + round.input.right = false; + assert.ok(round.you.lift, "they caught him"); + assert.equal(round.phase, "play", "no crash, no roll"); + assert.equal(round.effects.wings, 0, "spent at once"); + assert.equal(events(round, "wingSave").length, 1); + assert.equal(events(round, "lose").length, 0); + // No key works on the way, not even a double tap. + round.input.left = true; + give(round, "stake", 1); + tapTap(round); + assert.equal(round.arms[0].n, 1, "nothing thrown in flight"); + run(round, ghoul.WING_SAVE_MS / 2); + assert.ok(round.you.y > ghoul.PIT_Y, "on the way up"); + round.input.left = false; + run(round, ghoul.WING_SAVE_MS / 2 + 8); + const you = round.you; + assert.equal(you.lift, null); + assert.equal(you.state, "run", "standing"); + assert.equal(you.y, 6); + assert.ok(you.x > 80 && you.x <= 98.5, `back on the ledge he fell from, clear of its edge (${you.x})`); + assert.ok(you.safeMs > 0, "still safe as he lands"); + assert.equal(round.lives, lives); + assert.equal(round.dice, 2, "no die spent"); + assert.equal(you.garlic, true, "the shield is kept"); + // He can play on, and a second fall, wings gone, costs a life as ever. + run(round, 8); + assert.equal(round.phase, "play"); + Object.assign(you, { x: 104, state: "air", vy: 0, safeMs: 0 }); + round.dice = 0; + for (let k = 0; k < 500 && round.phase === "play"; k++) ghoul.advance(round, 4, steady); + assert.equal(round.phase, "crash"); + assert.equal(round.lives, lives - 1); + assert.equal(events(round, "wingSave").length, 1, "no second save"); +}); + +test("Ghoul Rush's Bat wings carry him back up to a shelf he fell from, and a life lost in flight drops the carry", () => { + const round = roomOf("manor", "gallery"); + ghoul.applyPower(round, "wings"); + const [x0, x1, top] = round.spec.shelves[0]; + Object.assign(round.you, { x: (x0 + x1) / 2, y: top, state: "run", shelf: 0, vy: 0, safeMs: 1e9 }); + round.camX = Math.max(0, round.you.x - 36); + run(round, 8); + const x = round.you.x; + Object.assign(round.you, { state: "air", y: ghoul.PIT_Y + 0.1, vy: -60, shelf: -1 }); + run(round, 12); + assert.ok(round.you.lift); + run(round, ghoul.WING_SAVE_MS + 8); + assert.equal(round.you.y, top); + assert.equal(round.you.shelf, 0, "on the shelf"); + assert.ok(Math.abs(round.you.x - x) <= 10); + // The clock running out mid-flight. + const late = roomOf("manor", "gallery"); + ghoul.applyPower(late, "wings"); + standAt(late, 96); + run(late, 8); + Object.assign(late.you, { x: 104, state: "air", y: ghoul.PIT_Y + 0.1, vy: -60 }); + run(late, 12); + assert.ok(late.you.lift); + ghoul.lose(late, "time"); + assert.equal(late.you.lift, null); + assert.equal(late.phase, "crash"); +}); + +/* ------------------------------------------------------- placing and dropping */ + +test("Ghoul Rush's every stage has a weapon of its own in every room, each only there, and the hall teaches a stick early", () => { + for (const st of ghoul.STAGES) { + const own = STAGE_ARMS[st.id]; + assert.ok(own, `${st.id} has its own`); + for (const id of st.rooms) { + const room = ghoul.roomById(id); + // A ride (the Runaway Cart) has no floor to place one on; what you carry still works. + if (room.ride) continue; + const weapons = room.items.filter((i) => ghoul.POWERS[i[0]].arm).map((i) => i[0]); + assert.ok(weapons.includes(own), `${id} has ${own}`); + assert.ok(weapons.length >= 1 && weapons.length <= 2 + (st.id === "mine" ? 1 : 0), `${id}: ${weapons}`); + for (const w of weapons) assert.ok(w === own || COMMON.includes(w), `${id}: ${w} is its stage's or common`); + } + } + const hall = ghoul.roomById("hall"); + const stick = hall.items.find((i) => i[0] === "dyn"); + assert.ok(stick && stick[1] < 60, "the first thing you find"); + for (const [stage, kind] of Object.entries(STAGE_ARMS)) { + if (kind === "dyn") continue; + assert.equal(ghoul.powerHere({ dark: true, stage }, kind), true); + assert.equal(ghoul.powerHere({ dark: true, stage: stage === "manor" ? "wing" : "manor" }, kind), false, `${kind} elsewhere`); + assert.equal(ghoul.powerHere({ dark: true, stage: null }, kind), false, `${kind} in the hall`); + } + // Every placed weapon is in the room's loot as itself. + const round = roomOf(null, "hall"); + const at = round.spec.items.findIndex((i) => i[0] === "dyn"); + assert.equal(round.loot[at], "dyn"); +}); + +test("Ghoul Rush's weapons drop from their own band of a kill's roll, with no extra draw: never from pickPower, mostly the common ones, the stage's own first", () => { + const rnd = ghoul.seeded(3); + for (const stage of [null, ...Object.keys(STAGE_ARMS)]) { + for (let i = 0; i < 300; i++) { + for (const dropping of [false, true]) assert.ok(!ghoul.POWERS[pickPower(rnd, { dark: i % 2 === 0, stage }, "", dropping)].arm, `${stage}`); + } + } + assert.equal(armDrop({ stage: "wing" }, 0), "skillet"); + assert.equal(armDrop({ stage: "wing" }, ARM_DROP_OWN - 0.01), "skillet"); + assert.ok(COMMON.includes(armDrop({ stage: "wing" }, ARM_DROP_OWN + 0.01))); + assert.ok(COMMON.includes(armDrop({ stage: null }, 0)), "the hall has none of its own"); + const seen = new Set(); + for (let t = 0; t < 1; t += 0.01) seen.add(armDrop({ stage: null }, t)); + assert.deepEqual([...seen].sort(), [...COMMON].sort()); + // Exactly one draw for a kill, drop or no drop. + const round = roomOf(null, "hall"); + standAt(round, 40); + const m = put(round, "zombie", 60); + let draws = 0; + ghoul.kill(round, m, "shot", () => (draws++, 0.07 + ghoul.DROP_CANDY + ARM_DROP / 2)); + assert.equal(draws, 1); + assert.equal(round.drops.length, 1); + assert.ok(ghoul.POWERS[round.drops[0].kind].arm); + // A horde kill leaves nothing, as ever. + const horde = put(round, "zombie", 62, { horde: true }); + round.drops.length = 0; + ghoul.kill(round, horde, "shot", () => 0.38); + assert.equal(round.drops.length, 0); +}); + +test("Ghoul Rush's stage select comes with the stage's weapon and the common ones full, to try them", () => { + const round = ghoul.newRound(5); + round.dice = 0; + round.practice = true; + round.phase = "select"; + const at = ghoul.STAGES.findIndex((s) => s.id === "wing"); + round.select = { at, room: 0 }; + assert.equal(ghoul.takeSelect(round), true); + assert.equal(round.arms[0].kind, "skillet"); + assert.equal(round.arms[0].n, ghoul.POWERS.skillet.max); + assert.deepEqual(round.arms.map((a) => a.kind).sort(), ["dyn", "rocket", "skillet", "stake"]); +}); + +/* ------------------------------------------------------------- art and sound */ + +test("Ghoul Rush's weapons all draw and every sound they name exists", () => { + const tones = ghoulSfx.default.tones; + for (const [name, def] of Object.entries(ARMS_SFX.tones)) { + assert.ok(name.startsWith("ghoulArm"), name); + assert.ok(tones[name], `${name} merged`); + for (const l of def.layers) { + assert.ok(l.gain > 0 && l.gain <= 1, `${name} gain`); + assert.ok((l.delay || 0) + l.seconds <= 1.2, `${name} ends in time`); + } + } + const noop = () => {}; + const played = []; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 0 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: ghoul }; + for (const kind of ALL) react({ type: "armUse", kind, x: 1, y: 1, face: 1 }, kit); + for (const type of ["armBounce", "armClang", "armTurn", "armSalt", "armFlash", "armSnap", "armDaze", "armBoom"]) react({ type, kind: "zombie", x: 1, y: 1 }, kit); + for (const name of played) assert.ok(tones[name], `${name} exists`); + // A real frame with every weapon on the field and in the air, in a boss's room, the HUD showing each badge. + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const round = g.round; + round.phase = "play"; + round.you.safeMs = 1e9; + for (const kind of ALL) { + round.arms = [{ kind, n: 2 }]; + round.armCool = 0; + round.tap = null; + g.key("action"); + g.tick(8); + g.release("action"); + g.tick(8); + g.key("action"); + g.tick(40); + g.release("action"); + g.tick(320); + round.drops.push({ id: 0, kind, x: round.you.x + 5, y: 12, vx: 0, vy: 0, life: 900, rest: true }); + g.tick(16); + } + assert.ok(round.score >= 0); +}); diff --git a/scripts/test-web-console-activities-ghoul-bones.mjs b/scripts/test-web-console-activities-ghoul-bones.mjs new file mode 100644 index 0000000..38c3f83 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-bones.mjs @@ -0,0 +1,458 @@ +// Web console tests, Ghoul Rush's Old Rattlebones: his volley and slam, the skull he throws like a boomerang (and is headless without), the bone rain and the skeletons he raises once his rage begins, the double slam, and what each move looks and sounds like. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as bn from "../src/web-console/public/activities/ghoul-bones.js"; +import { LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-bones-draw.js"; +import { VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the East Wing's Crypt with the boss awake and fighting, you +// safe, his next attack held off until a test starts one. +function crypt() { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["wing"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "crypt") through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + round.events.length = 0; + round.boss.t = -1e9; + round.you.safeMs = 1e9; + return round; +} + +function standAt(round, x, shelf = -1) { + const y = shelf >= 0 ? round.spec.shelves[shelf][2] : ghoul.groundAt(round.spec, x); + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face: 1 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +// He stands `gap` to the right of you, in the middle of the arena. +function faceOff(round, gap = 18) { + const b = round.boss; + standAt(round, round.spec.arena + 30); + b.x = round.you.x + gap; + b.y = ghoul.groundAt(round.spec, b.x); + round.you.safeMs = 1e9; + return b; +} + +// Starts his `act` at once, and runs it out of its windup. +function wind(round, act) { + const b = round.boss; + b.act = act; + b.windup = 1; + ghoul.advance(round, 4, steady); +} + +const step = (round, ms = 4, random = steady) => ghoul.advance(round, ms, random); + +test("Ghoul Rush: Old Rattlebones has 90 hp, attacks every 1250 ms (950 in his rage), and his hint tells you to jump the skull and then aim for it", () => { + assert.equal(ghoul.BOSSES.bones.hp, 90); + assert.equal(ghoul.BONES_MS, 1250); + assert.equal(ghoul.BONES_RAGE_MS, 950); + assert.match(ghoul.BOSSES.bones.sub, /skull/i); + const round = crypt(); + assert.equal(round.boss.hp, round.spec.bossHp); + assert.ok(round.boss.hp >= 90); +}); + +test("Ghoul Rush: Old Rattlebones' first attack is a volley, then each is picked at random, never the same one three times running, and bone rain waits for his rage", () => { + const b = { attacks: 0, raged: false }; + assert.equal(bn.pickAct(b, () => 0.99), "volley", "the first is always a volley"); + const seen = new Set(); + for (const r of [0, 0.34, 0.67, 0.99]) { + const act = bn.pickAct({ attacks: 1, raged: false, last: ["volley", "slam"] }, () => r); + seen.add(act); + } + assert.deepEqual([...seen].sort(), ["skull", "slam", "volley"], "all three, and no rain"); + assert.ok(!bn.pickAct({ attacks: 1, raged: false }, () => 0.99).includes("rain")); + assert.notEqual(bn.pickAct({ attacks: 3, raged: true, last: ["slam", "slam"] }, () => 0.5), "slam", "not a third slam"); + const rain = bn.pickAct({ attacks: 3, raged: true, last: ["slam", "volley"] }, () => 0.99); + assert.equal(rain, "rain", "bone rain is open in the rage"); + // Run for real: a long fight never repeats an act three times in a row. + const round = crypt(); + const b2 = faceOff(round); + b2.t = 0; + const acts = []; + let seed = 7; + const random = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + for (let ms = 0; ms < 120000; ms += 4) { + ghoul.advance(round, 4, random); + if (round.boss.state !== "fight") break; + for (const e of round.events) { + if (e.type === "windup" && e.boss) acts.push(e.act); + else if (e.type === "skullWind") acts.push("skull"); + else if (e.type === "rainWind") acts.push("rain"); + } + round.events.length = 0; + round.you.safeMs = 1e9; + b2.hp = b2.max; + } + assert.ok(acts.length > 30, `many attacks (${acts.length})`); + assert.equal(acts[0], "volley"); + for (let i = 2; i < acts.length; i++) assert.ok(!(acts[i] === acts[i - 1] && acts[i] === acts[i - 2]), `no three ${acts[i]} in a row`); + assert.ok(["volley", "slam", "skull"].every((a) => acts.includes(a)), "and all three get thrown"); + assert.ok(!acts.includes("rain"), "no rain before the rage"); +}); + +test("Ghoul Rush: a volley throws one bone at each VOLLEY scale, and a slam sends a shockwave both ways that a jump clears", () => { + const round = crypt(); + faceOff(round); + wind(round, "volley"); + assert.equal(events(round, "throw").length, ghoul.VOLLEY.length, "a volley"); + assert.ok(events(round, "throw").every((e) => e.by === "bones")); + round.bones.length = 0; + wind(round, "slam"); + assert.deepEqual(round.waves.map((w) => w.dir).sort(), [-1, 1]); + assert.equal(events(round, "slam").length, 1, "one slam, no echo outside the rage"); + step(round, 600); + assert.equal(round.waves.filter((w) => w.dir === 1).length > 0, true); + const wave = (jumped) => { + const r = crypt(); + standAt(r, r.spec.arena + 30); + r.you.safeMs = 0; + r.waves.push({ x: r.you.x + 8, y: 6, dir: -1, life: 6000 }); + let hit = false; + for (let ms = 0; ms < 1000 && !hit; ms += 4) { + if (jumped && Math.abs(r.waves[0]?.x - r.you.x) < 4 && r.you.state === "run" && r.you.vy === 0 && !r.input.jump) { + r.input.jump = ghoul.JUMP_BUFFER_MS; + r.input.up = true; + } + step(r); + hit = r.phase !== "play"; + } + return hit; + }; + assert.equal(wave(false), true, "standing still, the wave hits"); + assert.equal(wave(true), false, "a jump clears it"); +}); + +test("Ghoul Rush: his skull flies out level at your chest, turns past you and curves back to his neck, headless meanwhile", () => { + const round = crypt(); + const b = faceOff(round); + b.act = "skull"; + b.windup = bn.SKULL_WINDUP_MS; + step(round, bn.SKULL_WINDUP_MS - 20); + assert.equal(b.headless, undefined, "still has his head while he winds up"); + assert.equal(round.hazards.length, 0); + step(round, 40); + const h = round.hazards.find((q) => q.kind === "skull"); + assert.ok(h, "the skull is out"); + assert.equal(b.headless, true); + assert.equal(events(round, "skullThrow").length, 1); + assert.ok(Math.abs(h.fy - (round.you.y + ghoul.SHOT_Y)) < 0.01, "at your chest"); + assert.equal(h.dir, -1, "toward you"); + let past = false; + let ys = []; + let turned = false; + let home = false; + for (let ms = 0; ms < 6000 && !home; ms += 4) { + step(round); + const s = round.hazards.find((q) => q.kind === "skull"); + if (!s) { + home = true; + break; + } + if (s.state === "out") ys.push(s.fy); + if (s.state === "back") turned = true; + if (s.x < round.you.x - 1) past = true; + assert.equal(b.headless, true, "headless the whole flight"); + } + assert.ok(past, "it goes past you"); + assert.ok(turned, "and turns"); + assert.ok(home, "and comes home"); + assert.ok(ys.every((y) => Math.abs(y - ys[0]) < 1e-9), "level going out"); + assert.equal(b.headless, false, "his head is back"); + assert.equal(events(round, "skullBack").length, 1); + assert.equal(events(round, "skullTurn").length, 1); + assert.equal(b.t < 100, true, "his next attack waits a full beat from the catch"); +}); + +test("Ghoul Rush: the skull hurts you if you stand, and a jump clears it going out and again coming back", () => { + const fly = (jump) => { + const round = crypt(); + const b = faceOff(round); + round.you.safeMs = 0; + b.act = "skull"; + b.windup = 1; + let lost; + let jumps = 0; + for (let ms = 0; ms < 8000; ms += 4) { + const s = round.hazards.find((q) => q.kind === "skull"); + if (jump && s && Math.abs(s.x - round.you.x) < 7 && round.you.state === "run" && round.you.vy === 0 && !round.input.jump) { + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = true; + jumps++; + } + step(round); + if (round.phase !== "play") { + lost = round.events.find((e) => e.type === "lose")?.cause; + break; + } + if (b.headless === false && ms > 400) break; + } + return { lost, jumps, back: b.headless === false }; + }; + assert.equal(fly(false).lost, "skull", "standing, the skull takes a life"); + const done = fly(true); + assert.equal(done.lost, undefined, "jumping, it passes"); + assert.ok(done.jumps >= 2 && done.jumps <= 3, `a jump going and a jump coming back (${done.jumps})`); + assert.equal(done.back, true); +}); + +test("Ghoul Rush: while the skull is out his body takes single shots with no weak spot, and a bolt to the skull does three, used up on it, with a beat before the next counts", () => { + const round = crypt(); + const b = faceOff(round); + const head = () => ({ x: b.x - b.w / 2 - 0.3, y: b.y + b.h * 0.9, vx: 80, vy: 0, gone: 0 }); + let hp = b.hp; + round.shots.push(head()); + step(round); + assert.equal(b.hp, hp - 2, "his skull on his shoulders: double"); + wind(round, "skull"); + assert.equal(b.headless, true); + hp = b.hp; + b.x += 0; + round.shots.push(head()); + step(round); + assert.equal(b.hp, hp - 1, "headless, the neck is just body"); + // A bolt to the skull itself. + const sk = round.hazards.find((q) => q.kind === "skull"); + hp = b.hp; + round.shots.push({ x: sk.x + 1, y: sk.fy, vx: -80, vy: 0, gone: 0 }); + step(round); + assert.equal(b.hp, hp - bn.SKULL_HIT, "the skull takes SKULL_HIT"); + assert.equal(round.shots.length, 0, "the bolt is used up"); + assert.ok(events(round, "bossHit").some((e) => e.how === "skull" && e.kind === "bones"), "a hit event carrying kind"); + hp = b.hp; + const again = round.hazards.find((q) => q.kind === "skull"); + round.shots.push({ x: again.x + 1, y: again.fy, vx: -80, vy: 0, gone: 0 }); + step(round); + assert.equal(b.hp, hp, "no second hit inside the stagger"); + assert.equal(round.shots.length, 0, "but the bolt is still eaten"); + step(round, bn.SKULL_STAGGER_MS + 20); + const later = round.hazards.find((q) => q.kind === "skull"); + if (later) { + round.shots.push({ x: later.x + 1, y: later.fy, vx: -80, vy: 0, gone: 0 }); + step(round); + assert.equal(b.hp, hp - bn.SKULL_HIT, "after the stagger it counts again"); + } +}); + +test("Ghoul Rush: his skull in flight does not hurt a boss that is already down, and killing him with it out clears it", () => { + const round = crypt(); + const b = faceOff(round); + wind(round, "skull"); + b.hp = bn.SKULL_HIT; + const sk = round.hazards.find((q) => q.kind === "skull"); + round.shots.push({ x: sk.x + 1, y: sk.fy, vx: -80, vy: 0, gone: 0 }); + step(round); + assert.equal(b.state, "down"); + assert.equal(round.hazards.length, 0); + step(round, 100); + assert.equal(round.hazards.length, 0); +}); + +test("Ghoul Rush: at half his hp he shakes and his eyes flare (one event), attacks faster, and a slam comes in a double with the second wave a beat behind", () => { + const round = crypt(); + const b = faceOff(round); + b.hp = Math.ceil(b.max / 2) + 1; + step(round); + assert.ok(!b.raged); + b.hp = Math.floor(b.max / 2); + step(round); + assert.equal(b.raged, true); + assert.equal(events(round, "bonesRage").length, 1); + assert.ok(b.shake > 0, "he shakes"); + step(round, bn.BONES_SHAKE_MS + 20); + step(round, 200); + assert.equal(events(round, "bonesRage").length, 1, "only the once"); + // The cadence: the next attack winds up BONES_RAGE_MS after the shake. + b.t = 0; + round.events.length = 0; + step(round, bn.BONES_RAGE_MS - 20); + assert.equal(events(round, "windup").length + events(round, "skullWind").length + events(round, "rainWind").length, 0); + step(round, 40); + assert.equal(events(round, "windup").length + events(round, "skullWind").length + events(round, "rainWind").length, 1, "winds up on the rage beat"); + // A double slam. + round.events.length = 0; + b.windup = 0; + b.t = -1e9; + round.waves.length = 0; + wind(round, "slam"); + assert.equal(round.waves.length, 2, "the first pair"); + const xs = round.waves.map((w) => w.x); + step(round, bn.DOUBLE_GAP_MS - 20); + assert.equal(round.waves.length, 2); + step(round, 40); + assert.equal(round.waves.length, 4, "the second pair a beat later"); + assert.equal(events(round, "slam").length, 2); + assert.equal(events(round, "slam")[1].echo, true); + const gap = Math.abs(round.waves[0].x - round.waves[2].x); + assert.ok(gap > 10 && gap < 30, `waves ${gap.toFixed(1)} apart: ${xs.join()}`); +}); + +test("Ghoul Rush: in his rage bone rain throws bones up that come down at spots around you, each on a shadow first, and a bone landing on you costs a life unless lives are endless", () => { + const round = crypt(); + const b = faceOff(round); + b.raged = true; + b.raiseIn = 1e9; + wind(round, "rain"); + const bones = round.hazards.filter((h) => h.kind === "rain"); + assert.equal(bones.length, bn.RAIN_N, "a handful"); + assert.equal(events(round, "rainThrow").length, 1); + assert.ok(bones.every((h) => h.warn >= bn.RAIN_WARN_MS - 8 && h.live === 0 && h.cause === "rain"), "all in shadow"); + assert.ok(bones.some((h) => Math.abs(h.x - round.you.x) < 2), "one near where you stand"); + assert.ok(bones.every((h) => Math.abs(h.x - round.you.x) < bn.RAIN_SPREAD * 3), "all around you"); + assert.equal(new Set(bones.map((h) => h.warn)).size, bn.RAIN_N, "landing one after another"); + // Standing in a shadow when the bone lands costs a life. + const lives = round.lives; + const spot = bones.find((h) => Math.abs(h.x - round.you.x) < 2); + standAt(round, spot.x); + round.you.safeMs = 0; + step(round, bn.RAIN_WARN_MS - 100); + assert.equal(round.phase, "play", "the shadow alone does nothing"); + step(round, bn.RAIN_STAGGER_MS * bn.RAIN_N + 200); + assert.equal(round.phase, "crash"); + assert.equal(round.lives, lives - 1); + assert.equal(events(round, "lose")[0].cause, "rain"); + assert.ok(events(round, "rainLand").length >= 1); + // Endless lives: the same bone, no life. + const inf = crypt(); + inf.infinite = true; + const b2 = faceOff(inf); + b2.raged = true; + b2.raiseIn = 1e9; + wind(inf, "rain"); + const mine = inf.hazards.find((h) => h.kind === "rain" && Math.abs(h.x - inf.you.x) < 2); + standAt(inf, mine.x); + inf.you.safeMs = 0; + const before = inf.lives; + step(inf, bn.RAIN_WARN_MS + bn.RAIN_STAGGER_MS * bn.RAIN_N); + assert.equal(inf.lives, before, "endless lives skip the loss"); + assert.ok(events(inf, "lose").length >= 1); + // Moving off the spot in time is safe. + const safe = crypt(); + const b3 = faceOff(safe); + b3.raged = true; + b3.raiseIn = 1e9; + wind(safe, "rain"); + const xsAll = safe.hazards.filter((h) => h.kind === "rain").map((h) => h.x); + let free = safe.spec.arena + 3; + while (xsAll.some((x) => Math.abs(x - free) < bn.RAIN_W + 1)) free += 0.5; + standAt(safe, free); + safe.you.safeMs = 0; + step(safe, bn.RAIN_WARN_MS + bn.RAIN_STAGGER_MS * bn.RAIN_N + bn.RAIN_LIVE_MS * 2 + 100); + assert.equal(safe.phase, "play", "between the bones is safe"); + assert.equal(safe.hazards.filter((h) => h.kind === "rain").length, 0, "and they are gone after"); +}); + +test("Ghoul Rush: in his rage he has skeletons come up out of the floor, the floor cracking first, never more than two about", () => { + const round = crypt(); + const b = faceOff(round); + b.raged = true; + b.raiseIn = 0; + step(round); + const crack = round.hazards.find((h) => h.kind === "raise"); + assert.ok(crack, "the floor cracks"); + assert.equal(events(round, "raiseWind").length, 1); + assert.ok(Math.abs(crack.x - round.you.x) >= 6 && Math.abs(crack.x - b.x) >= b.w / 2 + 2, "clear of you and of him"); + step(round, bn.RAISE_WARN_MS - 20); + assert.equal(round.monsters.length, 0, "not yet"); + step(round, 40); + assert.equal(round.monsters.filter((m) => m.kind === "skeleton").length, 1, "up it comes"); + assert.equal(events(round, "raised").length, 1); + // Over a long fight, never more than two. + round.events.length = 0; + let most = 0; + let raised = 0; + for (let ms = 0; ms < 60000; ms += 8) { + step(round, 8); + round.you.safeMs = 1e9; + b.t = -1e9; + const alive = round.monsters.filter((m) => m.kind === "skeleton" && !m.dead).length + round.hazards.filter((h) => h.kind === "raise").length; + most = Math.max(most, alive); + raised += events(round, "raised").length; + round.events.length = 0; + } + assert.equal(most, bn.MAX_BONY, "two at most, and he gets to two"); + assert.equal(raised, 1, "a second came up, and none past the cap"); + // Shoot one down and he raises another after a beat. + round.monsters.length = 0; + b.raiseIn = 0; + step(round, 8); + assert.ok(round.hazards.some((h) => h.kind === "raise"), "a freed place is filled"); + // Not before the rage. + const calm = crypt(); + faceOff(calm); + calm.boss.raiseIn = 0; + step(calm, 3000); + assert.equal(calm.hazards.filter((h) => h.kind === "raise").length + calm.monsters.length, 0); +}); + +test("Ghoul Rush: his fall clears the skull, the rain and the cracks, and a life lost mid-fight puts his head back on", () => { + const round = crypt(); + const b = faceOff(round); + b.raged = true; + b.raiseIn = 0; + step(round); + wind(round, "rain"); + assert.ok(round.hazards.length > 3); + b.hp = 1; + round.shots.push({ x: b.x - b.w / 2 - 0.3, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + step(round); + assert.equal(b.state, "down"); + assert.equal(round.hazards.length, 0); + const lost = crypt(); + const b2 = faceOff(lost); + b2.hp = 60; + wind(lost, "skull"); + assert.equal(lost.boss.headless, true); + ghoul.lose(lost, "skull"); + step(lost, ghoul.CRASH_MS + 10); + assert.equal(lost.hazards.length, 0); + assert.ok(!lost.boss.headless, "a new boss in the arena"); + assert.equal(lost.boss.hp, 60, "with the hp kept"); +}); + +test("Ghoul Rush: Old Rattlebones' new moves each play one sound, and the new deaths have their words and sounds", () => { + const names = new Set(Object.values(VOICES).flatMap((v) => Object.values(v))); + const heard = (e) => { + const played = []; + const floats = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: (x, y, text) => floats.push(text), ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6 }; + react(e, kit); + return { played, voices: played.filter((n) => names.has(n)), floats }; + }; + const at = { x: 10, y: 6, kind: "bones" }; + for (const type of ["skullWind", "skullThrow", "rainWind", "bonesRage"]) assert.equal(heard({ ...at, type }).voices.length, 1, `${type}: one voice`); + for (const type of ["skullBack", "skullTurn", "rainThrow", "rainLand", "raiseWind", "raised"]) { + const { played } = heard({ ...at, type }); + assert.ok(played.length <= 2 && played.length >= (type === "raised" ? 0 : 1), `${type}: ${played.join()}`); + assert.equal(heard({ ...at, type }).voices.length, 0, `${type}: no cry on top`); + } + // A bolt to the skull plays the boss's hurt cry once, like any boss hit. + assert.equal(heard({ type: "bossHit", kind: "bones", x: 1, y: 1, how: "skull" }).voices.length, 1); + // Every cause that can take a life here has its words and a sound. + for (const cause of ["skull", "rain"]) assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], cause); + assert.ok(!/\u2014/.test(Object.values(LOSE_WORDS).join("")), "no em dash"); +}); diff --git a/scripts/test-web-console-activities-ghoul-carnival.mjs b/scripts/test-web-console-activities-ghoul-carnival.mjs new file mode 100644 index 0000000..75a923b --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-carnival.mjs @@ -0,0 +1,2015 @@ +// Web console tests, Ghoul Rush's Midnight Carnival stage: its four rooms (the Midway, the Hall of Mirrors, the Funhouse with its conveyor floors, the Big Top), grinners that honk out acid balloons, marionettes that drop on their strings, Mirror You that copies your moves and shots half a second late, strongmen that lob barbells, circus hounds that leap through hoops of fire, Cotton Candy and the Custard Pie (found only here), and the Ringmaster, whose puppet hangs on three strings: cut them all and he is open for four seconds. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as cv from "../src/web-console/public/activities/ghoul-carnival.js"; +import * as arm from "../src/web-console/public/activities/ghoul-arms.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-carnival-draw.js"; +import { PILL_WORDS, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import { BONES } from "../src/web-console/public/activities/ghoul-bones.js"; +import { GRAVEYARD } from "../src/web-console/public/activities/ghoul-graveyard.js"; +import { GROUNDS } from "../src/web-console/public/activities/ghoul-grounds.js"; +import { CHAPEL } from "../src/web-console/public/activities/ghoul-chapel.js"; +import { SANATORIUM } from "../src/web-console/public/activities/ghoul-sanatorium.js"; +import { VILLAGE } from "../src/web-console/public/activities/ghoul-village.js"; +import { MINE } from "../src/web-console/public/activities/ghoul-mine.js"; +import { CART } from "../src/web-console/public/activities/ghoul-cart.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the carnival drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); +// Fire tapped twice, as the keys do it. +const tapTap = (round) => { + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + ghoul.releaseFire(round); +}; +// The four rooms that are walked; the dark ride (a bonus round) between the funhouse and the Big Top has its own suite (ghoul-ride). +const ROOM_IDS = ["midway", "mirrors", "funhouse", "bigtop"]; +const STAGE_ROOMS = ["midway", "mirrors", "funhouse", "darkride", "bigtop"]; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Carnival's room `id`, reached the way play reaches it, nothing +// woken: every spawner spent, the horde held back. +function carnivalRound(id) { + const round = ghoul.newRound(5); + round.lives = 3; + round.dice = 0; + through(round); + round.offer = ["carnival"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.bonus = 1e9; + round.dark = false; + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face, ducking: false }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +function until(round, done, ms = 4000, random = steady) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); +} + +// Runs `ms`, returning each event of `type` as [ms since the start, event]. +function log(round, ms, type, random = steady) { + const got = []; + round.events.length = 0; + const t0 = round.clock; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + for (const e of round.events) if (e.type === type) got.push([round.clock - t0, e]); + round.events.length = 0; + } + return got; +} + +// Runs until an event of `type` is on the field (leaving it there) or `ms` pass; the event, or null. +function upTo(round, type, ms = 4000, random = steady) { + round.events.length = 0; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + const e = round.events.find((x) => x.type === type); + if (e) return e; + } + return null; +} + +// A bolt arriving from the left at height `y` on the thing `m` (a monster or the boss). +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played }; +}; + +// The Big Top with the Ringmaster awake (the fight on), Planny in the arena. +function bigtopFight({ x } = {}) { + const round = carnivalRound("bigtop"); + standAt(round, round.spec.arena + 12); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 16, steady); + assert.equal(round.boss.state, "fight"); + if (x !== undefined) standAt(round, x); + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +// Puts the Ringmaster's next move at once: `act` with `wait` ms to go. +const choose = (round, act, wait = 1) => Object.assign(round.boss, { act, wait }); +// The Ringmaster's script at `move`, picked at once (the puppet walks at you the while). +const scriptTo = (round, move) => { + round.boss.moves = cv.SCRIPT.indexOf(move); + return choose(round, "idle", 1); +}; + +// The three strings as the pack lays them (head, left hand, right hand), as segments. +const segs = (b) => cv.stringSegs(b); +// A bolt placed on string `i` at height `y` (the string's x there). +const onString = (b, i, y) => { + const g = segs(b)[i]; + const t = (g.y0 - y) / (g.y0 - g.y1); + return { x: g.x0 + (g.x1 - g.x0) * t, y }; +}; + +/* ------------------------------------------------------------ the stage */ + +test("Ghoul Rush's Midnight Carnival is a stage of three rooms, the dark ride (a bonus round) and the Big Top, its monsters and boss joined to the game's, with a place for each kind, conveyor belts in the funhouse, last in the list", () => { + const st = ghoul.stageById("carnival"); + assert.deepEqual(st.rooms, STAGE_ROOMS); + assert.deepEqual(cv.CARNIVAL_ROOMS, STAGE_ROOMS); + assert.equal(st.boss, "ringmaster"); + assert.equal(st.title, "The Midnight Carnival"); + assert.equal(st.sub, "Every game is rigged in its favor"); + assert.equal(ghoul.STAGES.at(-2), st, "the last stage in the list but the Frozen Lake"); + for (const kind of Object.keys(cv.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], cv.MONSTERS[kind], `${kind} is a monster`); + assert.deepEqual(Object.keys(cv.MONSTERS).sort(), ["balloon", "circushound", "grinner", "marionette", "mirror", "strongman"]); + assert.equal(ghoul.BOSSES.ringmaster, cv.BOSSES.ringmaster); + assert.equal(cv.BOSSES.ringmaster.sub, "Shoot the strings, not the puppet"); + assert.equal(ghoul.BOSSES.ringmaster.hp, 90); + assert.ok(ghoul.MONSTERS.grinner.hp === 4 && ghoul.MONSTERS.marionette.hp === 4 && ghoul.MONSTERS.mirror.hp === 3 && ghoul.MONSTERS.balloon.hp === 1 && ghoul.MONSTERS.strongman.hp === 14 && ghoul.MONSTERS.circushound.hp === 3); + assert.equal(ghoul.MONSTERS.strongman.stomp, true, "a strongman is stompable"); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [midway, mirrors, funhouse, bigtop] = ROOM_IDS.map((id) => ghoul.roomById(id)); + assert.deepEqual([midway.title, mirrors.title, funhouse.title, bigtop.title], ["Midway", "Hall of Mirrors", "Funhouse", "The Big Top"]); + assert.deepEqual([midway.sub, mirrors.sub, funhouse.sub, bigtop.sub], ["Every game is rigged in its favor", "Only one of you is real", "The laughter is coming from inside the walls", "Shoot the strings, not the puppet"]); + const returning = ["zombie", "bat", "crawl", "ghost", "hound"]; + for (const room of [midway, mirrors, funhouse]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + const floss = room.items.find((i) => i[0] === "floss"); + const pie = room.items.find((i) => i[0] === "pie"); + assert.ok(floss && pie, `${room.id}: Cotton Candy and the Custard Pie`); + const firstNew = Math.min(...room.spawns.filter((s) => s[0] in cv.MONSTERS).map((s) => s[1])); + assert.ok(floss[1] < firstNew + 40 && pie[1] < firstNew + 40, `${room.id}: the stage's power-up and weapon come before what they answer`); + assert.ok(room.spawns.some((s) => s[0] in cv.MONSTERS), `${room.id}: some of the new monsters`); + assert.ok(room.spawns.some((s) => returning.includes(s[0])), `${room.id}: some returning ones`); + // The key shelf has a board right under it, so a run at the key climbs it. + assert.ok(room.shelves.some(([a, b, y]) => y === 15 && a <= room.key[0] && b >= room.key[0]), `${room.id}: a step under the key shelf`); + assert.equal(room.dark, null, `${room.id}: dark or lit by the roll`); + } + assert.ok(bigtop.items.some((i) => i[0] === "floss") && bigtop.items.some((i) => i[0] === "pie"), "the boss room has both too"); + assert.equal(bigtop.boss, "ringmaster"); + assert.equal(bigtop.horde.length, 0); + assert.deepEqual(bigtop.shelves.map((s) => s[2]).sort((a, b) => a - b), [12, 12, 16.5, 16.5, 22], "trapeze boards at 12, 16.5 and 22"); + // Where each new kind turns up: the monsters mixed in, harder in order, the first room eased. + const count = (room, kind) => room.spawns.filter((s) => s[0] === kind).length; + assert.ok(count(midway, "grinner") >= 2 && count(midway, "strongman") === 1 && count(midway, "circushound") === 1, "the Midway: grinners, one strongman, one hound"); + assert.ok(!midway.spawns.some((s) => s[0] === "mirror" || s[0] === "marionette"), "no mirrors or marionettes in the first room"); + assert.ok(count(mirrors, "mirror") >= 3, "the Hall of Mirrors is full of reflections"); + assert.ok(count(funhouse, "marionette") >= 4 && count(funhouse, "mirror") >= 2, "the Funhouse: marionettes in the rafters, and mirrors"); + assert.ok(midway.spawns.length <= mirrors.spawns.length && mirrors.spawns.length <= funhouse.spawns.length); + assert.ok(midway.hordeMs > mirrors.hordeMs && mirrors.hordeMs > funhouse.hordeMs, "the horde quickens"); + assert.equal(midway.hordeMs, 3200); + assert.ok(midway.horde.length <= 2 && !midway.horde.includes("circushound"), "the first room's horde is gentle"); + // A marionette hangs just over a standing head, over a floor. + for (const s of funhouse.spawns.filter((q) => q[0] === "marionette")) { + const floor = ghoul.groundAt(funhouse, s[1]); + assert.ok(floor > -Infinity && Math.abs(s[2] - floor - 4.8) < 0.05, `the marionette at ${s[1]} hangs 4.8 over its floor`); + assert.ok(!funhouse.shelves.some(([a, b, y]) => s[1] + 2 >= a && s[1] - 2 <= b && y > s[2] - 1 && y < s[2] + 6), `the marionette at ${s[1]} hangs clear of the boards`); + } + // The belts: flat floor, clear of a pit, much weaker than a run, and only in the funhouse. + assert.equal(midway.belts.length + mirrors.belts.length + bigtop.belts.length, 0, "belts only in the funhouse"); + assert.ok(funhouse.belts.length >= 3); + for (const [a, b, speed] of funhouse.belts) { + const g = ghoul.groundAt(funhouse, a); + assert.ok(b > a && Math.abs(speed) > 0 && Math.abs(speed) <= ghoul.RUN_SPEED / 2, `the belt ${a} to ${b} is gentle`); + for (let x = a; x <= b; x += 2) assert.equal(ghoul.groundAt(funhouse, x), g, `no pit or step in the belt at ${x}`); + for (let x = b; x <= b + 6; x += 1) assert.equal(ghoul.groundAt(funhouse, x) > -Infinity, true, `no pit within 6 of the belt's end at ${x}`); + for (let x = a - 6; x <= a; x += 1) assert.equal(ghoul.groundAt(funhouse, x) > -Infinity, true, `no pit within 6 of the belt's start at ${x}`); + } + // The room field passes through the room builder. + assert.deepEqual(ghoul.roomFor("funhouse").belts, funhouse.belts); + assert.deepEqual(ghoul.roomFor("hall").belts, []); + assert.ok(LOOKS.midway.pack === "carnival" && LOOKS.bigtop.carnival); +}); + +test("Ghoul Rush's Carnival shares no hazard, monster, boss, act or tick-state name with another stage's pack (the packs' tables are merged by name)", () => { + for (const key of ["monsters", "bosses", "hazards", "move", "boss", "act", "solid", "harmless", "platform", "kill", "weak", "swoops", "guard"]) { + for (const other of [BONES, GRAVEYARD, GROUNDS, CHAPEL, SANATORIUM, VILLAGE, MINE, CART, arm.ARMS]) { + for (const name of Object.keys(cv.CARNIVAL[key] || {})) assert.ok(!(other[key] && name in other[key]), `${key}.${name} is also ${other.id}'s`); + } + } + assert.ok(cv.CARNIVAL.hazards.pfoot && cv.CARNIVAL.hazards.lash); + assert.equal(typeof ghoul.POWERS.floss, "object"); + assert.equal(ghoul.POWERS.pie.arm, true); + assert.equal(ghoul.POWERS.pie.stage, "carnival"); +}); + +test("Ghoul Rush's Carnival power-ups are found only here: Cotton Candy as a timed power-up (10 s), the Custard Pie as the stage's weapon", () => { + assert.equal(ghoul.POWERS.floss.stage, "carnival"); + assert.equal(ghoul.POWERS.floss.ms, 10000); + assert.ok(ghoul.TIMED.includes("floss")); + assert.equal(PILL_WORDS.floss, "FLOSS"); + const there = carnivalRound("midway"); + const elsewhere = ghoul.newRound(5); + elsewhere.dice = 0; + assert.equal(ghoul.powerHere(there, "floss"), true); + assert.equal(ghoul.powerHere(elsewhere, "floss"), false); + assert.equal(ghoul.powerHere(there, "pie"), true); + assert.equal(ghoul.powerHere(elsewhere, "pie"), false); + const seen = new Set(); + for (let i = 0; i < 400; i++) seen.add(pickPower(() => (i * 0.6180339) % 1, elsewhere, "", true)); + assert.ok(!seen.has("floss") && !seen.has("pie"), "never a random drop elsewhere"); + assert.equal(ghoul.default && true, true); + ghoul.applyPower(there, "floss"); + assert.equal(there.effects.floss, 10000); + ghoul.advance(there, 10000 + 8, steady); + assert.equal(there.effects.floss, 0); + assert.equal(events(there, "expire").filter((e) => e.kind === "floss").length, 1); + // The pie: a double tap throws it, a pickup is 2 (never over 4), it carries on. + const bag = carnivalRound("midway"); + standAt(bag, 30); + arm.fillBag(bag, "carnival"); + assert.ok(bag.arms.some((a) => a.kind === "pie"), "a practice round brings the stage's weapon"); + const fresh = carnivalRound("midway"); + fresh.drops.push({ id: 0, kind: "pie", x: 40, y: 8, vx: 0, vy: 0, life: 9000, rest: true }); + standAt(fresh, 40); + ghoul.advance(fresh, 40, steady); + assert.deepEqual(fresh.arms.map((a) => [a.kind, a.n]), [["pie", 2]]); +}); + +/* ----------------------------------------------------------------- belts */ + +test("Ghoul Rush's conveyor belts carry Planny along at their speed while he stands on the floor in one (on top of his running), never in the air, never on a board, and a belt can run him off a pit's edge", () => { + const round = carnivalRound("funhouse"); + const [[a, b, speed]] = round.spec.belts.filter((s) => s[2] > 0); + const mid = (a + b) / 2; + standAt(round, mid); + round.you.safeMs = 1e9; + const x0 = round.you.x; + run(round, 1000); + assert.ok(Math.abs(round.you.x - x0 - speed) < 0.6, `stands still, carried ${speed} a second (${round.you.x - x0})`); + assert.equal(round.you.belt, speed); + // Running with it adds, against it takes away. + standAt(round, mid); + run(round, 500, { right: true }); + assert.ok(Math.abs(round.you.x - mid - (ghoul.RUN_SPEED + speed) / 2) < 0.8, "with the belt"); + standAt(round, mid, -1); + run(round, 500, { left: true }); + assert.ok(Math.abs(mid - round.you.x - (ghoul.RUN_SPEED - speed) / 2) < 0.8, "against it, still forward"); + // The other way round for a belt that runs left. + const [[c, d, back]] = round.spec.belts.filter((s) => s[2] < 0); + standAt(round, (c + d) / 2); + const x1 = round.you.x; + run(round, 1000); + assert.ok(Math.abs(x1 - round.you.x + back) < 0.6 && round.you.x < x1, "a left belt carries left"); + // Off the belt, nothing carries him. + standAt(round, a - 3); + const x2 = round.you.x; + run(round, 600); + assert.equal(round.you.x, x2); + assert.equal(round.you.belt, 0); + // In the air above a belt: not carried. + standAt(round, mid); + Object.assign(round.you, { y: ghoul.groundAt(round.spec, mid) + 8, vy: 0, state: "air" }); + ghoul.advance(round, 40, steady); + assert.equal(round.you.belt, 0); + // Not on a board over it. + const shelf = round.spec.shelves.findIndex(([x0, x1]) => x0 >= a && x1 <= b); + if (shelf >= 0) { + const [s0, s1, sy] = round.spec.shelves[shelf]; + standAt(round, (s0 + s1) / 2, 1, sy, shelf); + const x3 = round.you.x; + run(round, 500); + assert.equal(round.you.x, x3, "a board is not a belt"); + } + // At a belt's end the floor goes on, so he is not carried into the pit past it. + standAt(round, b - 0.5); + run(round, 2000); + assert.ok(round.you.x > b && round.you.x < b + 0.1 && round.you.state === "run", "stops where the belt ends"); +}); + +/* ---------------------------------------------------- grinners, balloons */ + +test("Ghoul Rush's grinner walks at you to 14 away, honks (480 ms of wind-up) and a balloon is born, again every 3.4 s, never more than 4 balloons alive", () => { + const round = carnivalRound("midway"); + standAt(round, 40); + round.you.safeMs = 1e9; + const g = put(round, "grinner", 80); + const honks = log(round, 9000, "grinnerHonk"); + assert.ok(honks.length >= 2, "honks more than once"); + assert.ok(Math.abs(honks[0][0] - cv.GRIN_FIRST_MS) < 120, `the first honk comes ${cv.GRIN_FIRST_MS} ms in (${honks[0][0]})`); + assert.ok(Math.abs(honks[1][0] - honks[0][0] - (cv.HONK_MS + cv.GRIN_MS)) < 60, `then every ${cv.GRIN_MS} ms after the balloon (${honks[1][0] - honks[0][0]})`); + assert.ok(Math.abs(g.x - round.you.x) <= cv.GRIN_KEEP + 1.5 && Math.abs(g.x - round.you.x) > cv.GRIN_KEEP - 3, `it keeps ${cv.GRIN_KEEP} off (${g.x - round.you.x})`); + assert.ok(round.monsters.filter((m) => m.kind === "balloon").length >= 1); + // Never more than the cap. + const crowd = carnivalRound("midway"); + standAt(crowd, 40); + crowd.you.safeMs = 1e9; + put(crowd, "grinner", 60); + put(crowd, "grinner", 70); + put(crowd, "grinner", 76); + let most = 0; + for (let t = 0; t < 30000; t += 4) { + ghoul.advance(crowd, 4, steady); + crowd.you.safeMs = 1e9; + most = Math.max(most, crowd.monsters.filter((m) => m.kind === "balloon" && !m.dead).length); + crowd.monsters.forEach((m) => { + if (m.kind === "balloon") m.life = 1e9; + }); + } + assert.ok(most <= cv.BALLOON_CAP && most >= 3, `${most} balloons at most`); +}); + +test("Ghoul Rush's balloon drifts at you at chest height, pops into an acid puddle when shot (2 s, then gone), costs a life on you, and pops by itself after 9 s", () => { + const round = carnivalRound("midway"); + standAt(round, 40); + const m = put(round, "balloon", 70, { y: 12, life: undefined }); + run(round, 2200); + assert.ok(m.x < 70 - 10, "it drifts toward you"); + assert.ok(Math.abs(m.y - (round.you.y + cv.BALLOON_RISE)) < 0.8, `level with your chest (${m.y})`); + // Shot: a pop, a puddle where it was, lying for BALLOON_PUDDLE_MS. + const shot = carnivalRound("midway"); + standAt(shot, 40); + shot.you.safeMs = 1e9; + const b = put(shot, "balloon", 55, { y: 7 }); + b.life = 1e9; + shot.round = null; + bolt(shot, b, b.y + 1); + shot.events.length = 0; + ghoul.advance(shot, 40, steady); + const pop = events(shot, "balloonPop")[0]; + assert.ok(pop, "a pop"); + assert.equal(shot.puddles.length, 1); + assert.equal(shot.puddles[0].life, cv.BALLOON_PUDDLE_MS - (shot.clock % 4 ? 0 : 0) - (shot.puddles[0].life === cv.BALLOON_PUDDLE_MS ? 0 : cv.BALLOON_PUDDLE_MS - shot.puddles[0].life)); + assert.ok(Math.abs(shot.puddles[0].x - pop.x) < 0.01 && shot.puddles[0].y === 6); + run(shot, cv.BALLOON_PUDDLE_MS + 100); + assert.equal(shot.puddles.length, 0, "the puddle is short-lived"); + // The puddle burns whoever stands in it. + const lie = carnivalRound("midway"); + standAt(lie, 40); + lie.puddles.push({ id: 9, x: 40, y: 6, life: cv.BALLOON_PUDDLE_MS }); + lie.you.safeMs = 0; + ghoul.advance(lie, 8, steady); + assert.equal(events(lie, "lose")[0]?.cause, "acid"); + // On you, it costs a life, the cause balloon. + const on = carnivalRound("midway"); + standAt(on, 40); + put(on, "balloon", 40.5, { y: 6.5 }).life = 1e9; + until(on, () => events(on, "lose").length > 0, 600); + assert.equal(events(on, "lose")[0]?.cause, "balloon"); + // On its own it pops after BALLOON_LIFE_MS, harmlessly (no points, a puddle under it). + const own = carnivalRound("midway"); + standAt(own, 10); + own.you.safeMs = 1e9; + const far = put(own, "balloon", 150, { y: 10 }); + far.vx = 0; + const score = own.score; + const pops = log(own, cv.BALLOON_LIFE_MS + 500, "balloonPop"); + assert.equal(pops.length, 1); + assert.ok(pops[0][0] >= cv.BALLOON_LIFE_MS - 100 && pops[0][0] <= cv.BALLOON_LIFE_MS + 100, `popped at ${pops[0][0]}`); + assert.equal(own.score, score, "a balloon that pops itself is worth nothing"); + // Over a pit there is nothing to drip on. + const pit = carnivalRound("midway"); + standAt(pit, 20); + const over = put(pit, "balloon", 284, { y: 10 }); + over.life = 1e9; + ghoul.hurt(pit, over, 1, "shot", steady); + assert.equal(pit.puddles.length, 0); + assert.equal(events(pit, "balloonPop")[0]?.floor, null); +}); + +/* ---------------------------------------------------------- marionettes */ + +test("Ghoul Rush's marionette hangs on its string, jerks when you pass under it (380 ms), drops, lands and dances at you", () => { + const round = carnivalRound("funhouse"); + standAt(round, 40); + round.you.safeMs = 1e9; + const m = put(round, "marionette", 64, { y: 10.8 }); + assert.equal(m.act, "hang"); + run(round, 600); + assert.equal(m.act, "hang", "hangs while you are not under it"); + assert.equal(m.y, 10.8); + standAt(round, 62); + round.you.safeMs = 1e9; + const t0 = round.clock; + const jerk = upTo(round, "marionetteJerk", 200); + assert.ok(jerk, "it jerks as you pass under"); + assert.equal(m.act, "warn"); + const drop = upTo(round, "marionetteDrop", 600); + assert.ok(drop && Math.abs(round.clock - t0 - cv.MARION_WARN_MS) < 60, `then drops ${cv.MARION_WARN_MS} ms later`); + assert.equal(m.act, "drop"); + const land = upTo(round, "marionetteLand", 1200); + assert.ok(land && m.y === 6 && m.act === "dance", "lands on the floor and dances"); + assert.equal(land.floor, 6); + // It dances at you and a touch costs a life, the cause marionette. + standAt(round, 40); + round.you.safeMs = 0; + run(round, 4000); + assert.equal(events(round, "lose")[0]?.cause, "marionette"); + // Walking under it with your head above its feet (a jump over it, or on a board) does not set it off. + const high = carnivalRound("funhouse"); + standAt(high, 64); + const n = put(high, "marionette", 64, { y: 10.8 }); + Object.assign(high.you, { y: 12, state: "air", vy: 0 }); + high.you.safeMs = 1e9; + ghoul.advance(high, 8, steady); + assert.equal(n.act, "hang"); + // Out of view it sleeps too. + const away = carnivalRound("funhouse"); + standAt(away, 20); + const o = put(away, "marionette", 300, { y: 10.8 }); + run(away, 400); + assert.equal(o.act, "hang"); +}); + +test("Ghoul Rush's marionette dies to one bolt on its string (over its head, or the top of its body), else takes 4 hits to the body; once dropped there is no string to cut", () => { + const strung = () => { + const round = carnivalRound("funhouse"); + standAt(round, 20); + round.you.safeMs = 1e9; + return { round, m: put(round, "marionette", 64, { y: 10.8 }) }; + }; + // A bolt crossing the string over its head. + let { round, m } = strung(); + round.shots.push({ x: 62, y: 20, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.ok(m.dead || !round.monsters.includes(m), "one bolt on the string kills it"); + assert.equal(events(round, "stringCut")[0]?.what, "marionette"); + // The top of its body is the string's end. + ({ round, m } = strung()); + round.shots.push({ x: 62, y: 10.8 + 4.5, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.ok(!round.monsters.includes(m), "a bolt at the top of the body cuts it too"); + // The body below that takes 4 hits. + ({ round, m } = strung()); + for (let i = 1; i <= 4; i++) { + round.shots.push({ x: 62, y: 10.8 + 1.5, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.equal(round.monsters.includes(m), i < 4, `${i} hits to the body`); + } + assert.equal(events(round, "stringCut").length, 0); + // Dropped and dancing, the top of the body is just the body. + ({ round, m } = strung()); + Object.assign(m, { act: "dance", y: 6 }); + round.shots.push({ x: 62, y: 6 + 4.5, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.ok(round.monsters.includes(m) && m.hp === 3, "one hit"); + // A stomp on a dancer kills it. + ({ round, m } = strung()); + Object.assign(m, { act: "dance", y: 6 }); + standAt(round, 64, 1, 6 + 5); + round.you.vy = -30; + Object.assign(round.you, { state: "air" }); + until(round, () => events(round, "stomp").length > 0, 400); + assert.equal(events(round, "stomp").length, 1); +}); + +/* ---------------------------------------------------------- Mirror You */ + +// A mirror 30 right of Planny, stepped out and copying, nothing else about. +function mirrorPair() { + const round = carnivalRound("mirrors"); + standAt(round, 60); + round.you.safeMs = 1e9; + const m = put(round, "mirror", 90); + return { round, m }; +} + +test("Ghoul Rush's Mirror You waits in its panel (not solid) till you are within 38, steps out over 600 ms, then copies you", () => { + const { round, m } = mirrorPair(); + assert.equal(m.act, "wait"); + assert.equal(ghoul.solid(m), false); + standAt(round, 30); + run(round, 400); + assert.equal(m.act, "wait", "too far"); + standAt(round, 60); + round.you.safeMs = 1e9; + const step = upTo(round, "mirrorStep", 100); + assert.ok(step); + assert.equal(m.act, "step"); + assert.equal(ghoul.solid(m), false, "not solid while stepping out"); + const t0 = round.clock; + until(round, () => m.act === "copy", 1000); + assert.ok(Math.abs(round.clock - t0 - cv.MIRROR_STEP_MS) < 40, "600 ms"); + assert.equal(ghoul.solid(m), true); +}); + +test("Ghoul Rush's Mirror You moves where you moved, the other way, 500 ms late (and your jumps, ducking and facing), drifting a little at you", () => { + const { round, m } = mirrorPair(); + until(round, () => m.act === "copy", 1500); + round.you.safeMs = 1e9; + // Stand still 1 s: it only drifts at you. + const x0 = m.x; + run(round, 1000); + assert.ok(Math.abs(x0 - m.x - cv.MIRROR_DRIFT) < 0.6, `drifts ${cv.MIRROR_DRIFT} a second at you (${x0 - m.x})`); + // Run right for 300 ms: the mirror moves left, but not for the first 500 ms. + standAt(round, 60); + round.you.safeMs = 1e9; + const x1 = m.x; + const me = round.you.x; + run(round, 300, { right: true }); + const ran = round.you.x - me; + assert.ok(ran > 9, "ran"); + assert.ok(x1 - m.x < 2.5, `still (drift only) before the delay (${x1 - m.x})`); + run(round, 520); + assert.ok(x1 - m.x > ran - 1.5 && x1 - m.x < ran + 4, `then the other way, as far (${x1 - m.x} for ${ran})`); + assert.equal(m.dir, 1 * -1, "facing the other way"); + // A jump: it jumps 500 ms later, as high. + standAt(round, 60); + round.you.safeMs = 1e9; + m.y = ghoul.groundAt(round.spec, m.x); + round.input.up = true; + ghoul.jump(round); + let apex = 0; + let mapex = 0; + let tUp = -1; + for (let t = 0; t < 1600; t += 4) { + ghoul.advance(round, 4, steady); + if (round.you.y - 6 > apex) apex = round.you.y - 6; + if (m.y - ghoul.groundAt(round.spec, m.x) > 0.5 && tUp < 0) tUp = t; + mapex = Math.max(mapex, m.y - ghoul.groundAt(round.spec, m.x)); + } + assert.ok(apex > 10 && Math.abs(mapex - apex) < 1.5, `jumps as high (${mapex} for ${apex})`); + round.input.up = false; + assert.ok(tUp >= 440 && tUp <= 580, `after 500 ms (${tUp})`); + // Ducking is copied. + standAt(round, 60); + round.you.safeMs = 1e9; + run(round, 300, { down: true }); + run(round, 300, { down: true }); + assert.equal(m.duck, true); +}); + +test("Ghoul Rush's Mirror You fires a bolt for each bolt you fire, 500 ms late, back at you; its bolt and yours cancel where they meet (a thrown weapon destroys it and flies on)", () => { + const { round, m } = mirrorPair(); + until(round, () => m.act === "copy", 1500); + m.hp = 99; + m.x = 90; + round.you.safeMs = 1e9; + standAt(round, 60, -1); + round.you.safeMs = 1e9; + // Face away from it and fire once: its bolt comes (it faces the other way: toward you). + const t0 = round.clock; + run(round, 20, { fire: true }); + const shot = upTo(round, "mirrorShot", 900); + assert.ok(shot, "it fires"); + assert.ok(Math.abs(round.clock - t0 - cv.MIRROR_DELAY_MS) < 60, `about ${cv.MIRROR_DELAY_MS} ms late (${round.clock - t0})`); + assert.equal(shot.dir, 1, "it fires the way you faced, mirrored"); + assert.equal(round.twist.bolts.length >= 1, true); + // Facing it, you fire at it and it fires back at you: the other way from the first. + const facing = carnivalRound("mirrors"); + standAt(facing, 60, 1); + facing.you.safeMs = 1e9; + const f = put(facing, "mirror", 90); + until(facing, () => f.act === "copy", 1500); + f.hp = 99; + f.x = 90; + standAt(facing, 60, 1); + facing.you.safeMs = 1e9; + run(facing, 20, { fire: true }); + const fshot = upTo(facing, "mirrorShot", 900); + assert.equal(fshot.dir, -1, "you faced right: it faces left, at you"); + // Its bolt hits you at chest height when you stand, and misses a ducked you. + const hit = (ducked) => { + const r = carnivalRound("mirrors"); + standAt(r, 60); + r.you.ducking = ducked; + r.input.down = ducked; + r.twist = null; + ghoul.advance(r, 8, steady); + r.you.safeMs = 0; + r.twist.bolts.push({ x: 70, y: 6 + cv.MBOLT_Y, vx: -cv.MBOLT_V, gone: 0 }); + until(r, () => events(r, "lose").length > 0, 600); + return events(r, "lose")[0]?.cause; + }; + assert.equal(hit(false), "mirrorbolt", "a bolt on a standing you"); + assert.equal(hit(true), undefined, "a bolt over a ducked you"); + // Cancelling: your bolt and its bolt meet in the air. + const meet = carnivalRound("mirrors"); + standAt(meet, 50); + meet.you.safeMs = 1e9; + meet.twist = null; + ghoul.advance(meet, 8, steady); + meet.twist.bolts.push({ x: 70, y: 8.4, vx: -cv.MBOLT_V, gone: 0 }); + meet.shots.push({ x: 56, y: 8.4, vx: 130, vy: 0, gone: 0 }); + const cancel = upTo(meet, "mirrorCancel", 400); + assert.ok(cancel, "they cancel"); + assert.equal(meet.twist.bolts.length, 0); + assert.equal(meet.shots.length, 0); + assert.ok(Math.abs(cancel.x - 63) < 4, `where they met (${cancel.x})`); + // A thrown weapon breaks the bolt and flies on. + const weapon = carnivalRound("mirrors"); + standAt(weapon, 50); + weapon.you.safeMs = 1e9; + weapon.twist = null; + ghoul.advance(weapon, 8, steady); + weapon.twist.bolts.push({ x: 70, y: 8.4, vx: -cv.MBOLT_V, gone: 0 }); + weapon.shots.push({ arm: "stake", x: 56, y: 8.4, vx: 96, vy: 0, gone: 0, t: 0, spin: 0, dmg: 4, bossDmg: 4, pierce: true }); + upTo(weapon, "mirrorCancel", 400); + assert.equal(weapon.twist.bolts.length, 0); + assert.equal(weapon.shots.length, 1, "the stake flies on"); +}); + +test("Ghoul Rush's Mirror You shatters when it dies; a pied one (stunned) copies nothing and fires nothing for the stun", () => { + const { round, m } = mirrorPair(); + until(round, () => m.act === "copy", 1500); + round.you.safeMs = 1e9; + // Pied: it stands for the stun, whatever you do, and does not catch up after. + m.stunMs = arm.PIE_STUN_MS; + m.hp = 99; + const at = m.x; + run(round, 1000, { right: true, fire: true }); + assert.equal(m.x, at, "stands still"); + assert.equal(events(round, "mirrorShot").length, 0, "fires nothing"); + run(round, arm.PIE_STUN_MS); + const after = m.x; + assert.ok(Math.abs(after - at) < cv.MIRROR_DRIFT * 3 + 1, `no leap to catch up (${after - at})`); + // Dead, it shatters. + m.hp = 1; + round.events.length = 0; + bolt(round, m, m.y + 2.4); + round.shots[0].x = m.x - 3; + ghoul.advance(round, 40, steady); + assert.equal(events(round, "mirrorShatter").length, 1); + assert.equal(events(round, "kill")[0]?.kind, "mirror"); + // A mirror cannot walk into a pit: it stays at the edge. + const edge = carnivalRound("mirrors"); + standAt(edge, 340); + edge.you.safeMs = 1e9; + const e = put(edge, "mirror", 372); + until(edge, () => e.act === "copy", 1500); + run(edge, 1500); + standAt(edge, 340); + run(edge, 1500, { right: true }); + assert.ok(ghoul.groundAt(edge.spec, e.x) > -Infinity && e.x >= 368, `never over the pit (${e.x})`); +}); + +/* ------------------------------------------------------------ strongmen */ + +test("Ghoul Rush's strongman lumbers at you, winds up 600 ms and lobs a barbell in an arc every 3.4 s from 10 to 46 away (cause barbell); a stomp kills it", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + const s = put(round, "strongman", 70); + const winds = log(round, 9000, "strongWind"); + assert.ok(winds.length >= 2, "winds up again and again"); + assert.ok(Math.abs(winds[0][0] - cv.STRONG_FIRST_MS) < 150, `${winds[0][0]}`); + const throws = round.events.length >= 0 && log(round, 0, "throw"); + assert.ok(Array.isArray(throws)); + const again = carnivalRound("midway"); + standAt(again, 30); + again.you.safeMs = 1e9; + put(again, "strongman", 80); + const first = upTo(again, "strongWind", 4000); + assert.ok(first); + const t0 = again.clock; + const thrown = upTo(again, "throw", 1000); + assert.ok(thrown && thrown.kind === "barbell" && thrown.by === "strongman", "a barbell thrown"); + assert.ok(Math.abs(again.clock - t0 - cv.STRONG_WIND_MS) < 40, "600 ms after the wind-up"); + assert.equal(again.bones.find((b) => b.kind === "barbell").cause, "barbell"); + // The throw is one strongThrow beside the game's throw, and the landing one barbellLand (no clatter). + assert.equal(events(again, "strongThrow").length, 1, "one strongThrow with the throw"); + assert.equal(events(again, "barbellLand").length, 0, "not landed yet"); + until(again, () => events(again, "barbellLand").length > 0, 3000); + assert.equal(events(again, "barbellLand").length, 1, "the barbell lands once"); + assert.equal(events(again, "clatter").length, 0, "the landing is not also a clatter"); + // A barbell on you costs a life, the cause barbell. + const hit = carnivalRound("midway"); + standAt(hit, 40); + hit.you.safeMs = 0; + hit.bones.push({ id: 99, kind: "barbell", x: 40, y: 7, vx: 0, vy: 0, spin: 0, life: 4000, cause: "barbell" }); + ghoul.advance(hit, 8, steady); + assert.equal(events(hit, "lose")[0]?.cause, "barbell"); + // Too close it does not throw, only walks. + const close = carnivalRound("midway"); + standAt(close, 60); + close.you.safeMs = 1e9; + put(close, "strongman", 64).cool = 0; + run(close, 1500); + assert.equal(events(close, "strongWind").length, 0); + // A stomp takes 4 off its 14. + const stomp = carnivalRound("midway"); + const q = put(stomp, "strongman", 64); + standAt(stomp, 64, 1, 6 + q.h + 1); + Object.assign(stomp.you, { state: "air", vy: -30 }); + until(stomp, () => events(stomp, "stomp").length > 0, 400); + assert.equal(q.hp, 10); + assert.equal(s.kind, "strongman"); +}); + +/* --------------------------------------------------------- circus hounds */ + +test("Ghoul Rush's circus hound prowls at you, crouches 450 ms within 24 (the hoop flares), leaps in an arc that comes down where you stand, rests 800 ms and does it again", () => { + const round = carnivalRound("midway"); + standAt(round, 90); + round.you.safeMs = 1e9; + const h = put(round, "circushound", 60); + const crouch = upTo(round, "houndCrouch", 3000); + assert.ok(crouch, "it crouches"); + assert.equal(h.act, "crouch"); + const t0 = round.clock; + const leap = upTo(round, "houndLeap", 1000); + assert.ok(leap && Math.abs(round.clock - t0 - cv.HOUND_CROUCH_MS) < 40, "450 ms later it leaps"); + assert.equal(h.act, "leap"); + assert.equal(h.vy, cv.HOUND_VY); + let apex = 0; + until(round, () => (apex = Math.max(apex, h.y - 6), h.act === "rest"), 1500); + assert.ok(apex > 4 && apex < 6.5, `a ${apex} high arc`); + assert.equal(h.act, "rest"); + assert.equal(events(round, "houndLand").length, 1, "one houndLand when the leap ends"); + // It came down where Planny stood (he was safe, so we see where it landed). + assert.ok(Math.abs(h.x - 90) < 1.5, `landed on you (${h.x})`); + const rested = h.wait; + assert.ok(rested > cv.HOUND_REST_MS - 100); + // Standing, it costs a life, the cause circushound. + const hit = carnivalRound("midway"); + standAt(hit, 90); + hit.you.safeMs = 0; + put(hit, "circushound", 70, { act: "crouch", wait: 1 }); + until(hit, () => events(hit, "lose").length > 0, 2000); + assert.equal(events(hit, "lose")[0]?.cause, "circushound"); + // A jump clears it. + const jump = carnivalRound("midway"); + standAt(jump, 90); + put(jump, "circushound", 70, { act: "crouch", wait: 1 }); + jump.you.safeMs = 0; + ghoul.advance(jump, 200, steady); + ghoul.jump(jump); + until(jump, () => jump.you.state === "run" && jump.you.y === 6 && jump.clock > 400, 1500); + // A long arc: it can leap 24 across. + const far = carnivalRound("midway"); + standAt(far, 90); + far.you.safeMs = 1e9; + const f = put(far, "circushound", 67, { act: "crouch", wait: 1 }); + until(far, () => f.act === "rest", 1500); + assert.ok(Math.abs(f.x - 90) < 1.5, "23 across"); + assert.equal(cv.CARNIVAL.swoops.circushound({ act: "leap" }), true); + assert.equal(cv.CARNIVAL.swoops.circushound({ act: "prowl" }), false); +}); + +test("Ghoul Rush's circus hound's leap is a swoop: a ducked Planny is passed over and it comes back for him again and again, never biting a ducked one; a caged one is not there to hit until it has burst out", () => { + const round = carnivalRound("midway"); + standAt(round, 90); + round.you.safeMs = 0; + round.input.down = true; + put(round, "circushound", 70); + run(round, 9000, { down: true }); + assert.equal(events(round, "lose").length, 0, "9 s of leaps over a ducked Planny"); + assert.ok(events(round, "houndLeap").length >= 3, "it kept leaping"); + const caged = carnivalRound("bigtop"); + standAt(caged, 150); + const c = put(caged, "circushound", 120, { act: "burst", wait: cv.HOUND_BURST_MS }); + assert.equal(ghoul.solid(c), false); + bolt(caged, c, 8); + caged.shots[0].x = 118; + ghoul.advance(caged, 40, steady); + assert.equal(c.hp, 3, "a bolt goes through it"); + run(caged, cv.HOUND_BURST_MS + 100); + assert.equal(ghoul.solid(c), true); + assert.notEqual(c.act, "burst"); +}); + +/* ---------------------------------------------------------- Cotton Candy */ + +test("Ghoul Rush's Cotton Candy: a bolt that hits a monster slows it to half for 3 s (a thrown weapon does not), only while the power-up lasts", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + const z = put(round, "zombie", 60); + z.hp = 99; + bolt(round, z, z.y + 2); + ghoul.advance(round, 40, steady); + assert.ok(!(z.hasteMs > 0), "no power-up, no stickiness"); + ghoul.applyPower(round, "floss"); + bolt(round, z, z.y + 2); + ghoul.advance(round, 40, steady); + assert.equal(z.haste, cv.FLOSS_SLOW); + assert.ok(z.hasteMs > cv.FLOSS_SLOW_MS - 100 && z.hasteMs <= cv.FLOSS_SLOW_MS); + assert.equal(z.floss, true); + assert.ok(events(round, "flossStick").length >= 1); + // It walks at half speed meanwhile. + const walk = (slow) => { + const r = carnivalRound("midway"); + standAt(r, 30); + r.you.safeMs = 1e9; + const m = put(r, "zombie", 90); + if (slow) Object.assign(m, { hasteMs: 3000, haste: 0.5 }); + const x = m.x; + run(r, 2000); + return x - m.x; + }; + assert.ok(Math.abs(walk(true) * 2 - walk(false)) < 2.5, "half the distance"); + // A thrown weapon is no sticky bolt. + const w = carnivalRound("midway"); + standAt(w, 30); + ghoul.applyPower(w, "floss"); + const t = put(w, "zombie", 60); + t.hp = 99; + w.shots.push({ arm: "stake", x: 56, y: t.y + 2, vx: 96, vy: 0, gone: 0, t: 0, spin: 0, dmg: 1, bossDmg: 1, pierce: true }); + ghoul.advance(w, 40, steady); + assert.ok(!(t.hasteMs > 0)); +}); + +/* ----------------------------------------------------------- Custard Pie */ + +const pies = (round) => round.hazards.filter((h) => h.kind === "armPie"); +const goops = (round) => round.hazards.filter((h) => h.kind === "armGoop"); + +test("Ghoul Rush's Custard Pie: a double tap throws a long lob that lands about 45 ahead, splats there, aims by facing, and carries on between rooms", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + round.arms = [{ kind: "pie", n: 2 }]; + tapTap(round); + assert.deepEqual(round.arms.map((q) => [q.kind, q.n]), [["pie", 1]]); + assert.equal(pies(round).length, 1); + assert.equal(round.hazards.filter((h) => h.kind === "armPod").length, 0, "no longer a pod"); + assert.equal(events(round, "armUse").length, 1); + const splat = upTo(round, "armSplat", 3000); + assert.ok(splat && splat.y === 6, "lands on the floor"); + const range = splat.x - 30; + assert.ok(range >= 40 && range <= 52, `lands 40 to 52 ahead (${range})`); + // Aimed by facing: the other way it lands behind. + const back = carnivalRound("midway"); + standAt(back, 150, -1); + back.arms = [{ kind: "pie", n: 1 }]; + tapTap(back); + const b = upTo(back, "armSplat", 3000); + assert.ok(b && b.x < 150 - 40, "thrown to the left it lands to the left"); + // It stays in the bag across rooms. + const next = carnivalRound("mirrors"); + next.arms = round.arms; + assert.deepEqual(next.arms.map((q) => [q.kind, q.n]), [["pie", 1]]); +}); + +test("Ghoul Rush's Custard Pie sheds goop every 2.5 of travel (or 90 ms), which falls to the floor and lies there 3.5 s as a puddle; it draws no random number", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + round.arms = [{ kind: "pie", n: 1 }]; + tapTap(round); + const seen = new Set(); + const spacing = []; + let last = null; + for (let t = 0; t < 1500; t += 4) { + ghoul.advance(round, 4, never); + for (const g of goops(round)) { + if (seen.has(g)) continue; + seen.add(g); + if (last !== null) spacing.push(g.x - last); + last = g.x; + } + } + assert.ok(seen.size >= 15, `a trail of blobs (${seen.size})`); + assert.ok(spacing.every((d) => d > 0 && d <= arm.PIE_DROP_X + 0.4), `spaced about 2.5 apart (${spacing.slice(0, 5)})`); + const lying = goops(round).filter((g) => g.rest); + assert.ok(lying.length >= 10, "puddles lie along the path"); + assert.ok(lying.every((g) => g.y >= 6) && lying.some((g) => g.y === 6), "on the floor or the nearest board below"); + assert.ok(lying.every((g) => g.live === 0 && g.cause === ""), "harmless to Planny by their data"); + const first = lying[0]; + assert.ok(first.life > 0 && first.life <= arm.PIE_GOOP_MS); + run(round, first.life + 100, {}, never); + assert.ok(!goops(round).includes(first), "gone after its life"); + run(round, arm.PIE_GOOP_MS + 200, {}, never); + assert.equal(goops(round).length, 0, "all gone"); + assert.equal(arm.PIE_GOOP_MS, 3500); +}); + +test("Ghoul Rush's Custard Pie goop is cream, not a platform: Planny walks under and through it unharmed, and the floor and boards are unchanged", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.arms = [{ kind: "pie", n: 1 }]; + const before = JSON.stringify(round.spec.shelves); + const ground = ghoul.groundAt(round.spec, 60); + tapTap(round); + const lives = round.lives; + for (let t = 0; t < 5000; t += 4) { + round.input.right = t > 300; + ghoul.advance(round, 4, steady); + } + round.input.right = false; + assert.equal(round.lives, lives, "no life lost"); + assert.equal(ghoul.groundAt(round.spec, 60), ground); + assert.equal(JSON.stringify(round.spec.shelves), before); + assert.ok(round.phase === "play"); +}); + +test("Ghoul Rush's Custard Pie stuns and damages every monster under the arc a tick a blob, and the stun is refreshed while it stays in the goop", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + round.arms = [{ kind: "pie", n: 1 }]; + const row = [42, 52, 62, 72].map((x) => put(round, "zombie", x)); + const away = put(round, "zombie", 120); + for (const m of [...row, away]) m.hp = 99; + tapTap(round); + run(round, 1400, {}, steady); + for (const m of row) { + assert.ok(m.stunMs > 0 && m.pied, `stunned and pied (x ${m.x})`); + assert.ok(m.hp < 99, `damaged (x ${m.x})`); + assert.ok(99 - m.hp <= 8, `a few ticks, not a stream (${99 - m.hp})`); + } + assert.ok(!(away.stunMs > 0) && away.hp === 99, "not the one off to the side"); + // Held while it stands in goop, beyond the stun's own length. + const m = row[1]; + const x0 = m.x; + run(round, 2000, {}, steady); + assert.ok(goops(round).some((g) => g.rest && Math.abs(g.x - m.x) < g.w / 2 + m.w / 2), "a puddle is under it"); + assert.ok(m.stunMs > 0 && Math.abs(m.x - x0) < 0.01, "held in the goop"); + // The same blob never hurts it twice. + const hp = m.hp; + run(round, 600, {}, steady); + assert.equal(m.hp, hp, "no repeat damage from the same blobs"); + // Afterwards it wakes. + run(round, arm.PIE_GOOP_MS + arm.PIE_GOOP_STUN_MS + 500, {}, steady); + assert.ok(!(m.stunMs > 0)); +}); + +test("Ghoul Rush's Custard Pie reaches monsters hanging in the air under its arc, and a lob clears a whole row of weak walkers; their kills drop nothing", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + round.arms = [{ kind: "pie", n: 1 }]; + const row = [44, 48, 52, 70, 74].map((x) => put(round, "zombie", x)); + for (const m of row) m.hp = 1; + const far = put(round, "zombie", 120); + far.hp = 99; + const high = put(round, "balloon", 58, { y: 9 }); + high.hp = 99; + tapTap(round); + run(round, 1500, {}, steady); + assert.ok(row.every((m) => m.dead || m.hp <= 0), "every weak one under the arc is gone"); + assert.equal(far.hp, 99); + assert.ok(high.pied && high.hp < 99, "one in the air under the arc is hit too"); + assert.ok(arm.PIE_SPLAT_DMG > arm.PIE_GOOP_DMG, "the splat hits harder than a blob"); + assert.equal(round.drops.length, 0, "area kills drop nothing"); +}); + +test("Ghoul Rush's Custard Pie on a boss: goop and the splat go through the arm damage rule with no stun, a guard shows a block, a hidden boss is not hit", () => { + const fight = bigtopFight(); + choose(fight, "open", 1e9); + Object.assign(fight.boss, { open: true, y: 6, puppet: "down" }); + fight.arms = [{ kind: "pie", n: 1 }]; + standAt(fight, fight.boss.x - 40); + fight.you.safeMs = 1e9; + const hp = fight.boss.hp; + tapTap(fight); + upTo(fight, "armSplat", 3000); + assert.ok(fight.boss.hp < hp && !(fight.boss.stunMs > 0), "hurt, not stunned"); + assert.ok(fight.armBossDmg > 0, "counted by armBossDamage"); + const guard = bigtopFight(); + guard.arms = [{ kind: "pie", n: 1 }]; + guard.boss.y = 6; + standAt(guard, guard.boss.x - 30); + tapTap(guard); + upTo(guard, "armSplat", 3000); + assert.equal(guard.boss.hp, guard.boss.max); + assert.ok(events(guard, "bossBlock").length >= 1, "a block shows"); + const hidden = bigtopFight(); + choose(hidden, "open", 1e9); + Object.assign(hidden.boss, { open: true, y: 6, puppet: "down", hidden: true }); + hidden.arms = [{ kind: "pie", n: 1 }]; + standAt(hidden, hidden.boss.x - 30); + tapTap(hidden); + upTo(hidden, "armSplat", 3000); + assert.equal(hidden.boss.hp, hidden.boss.max); +}); + +test("Ghoul Rush's Custard Pie sounds once each: one armUse and one armSplat, and the puddles' soft splat reuses the wired tone, rate limited", () => { + const round = carnivalRound("midway"); + standAt(round, 30); + round.you.safeMs = 1e9; + round.arms = [{ kind: "pie", n: 1 }]; + tapTap(round); + const seen = []; + for (let t = 0; t < 6000; t += 4) { + ghoul.advance(round, 4, never); + for (const e of round.events) seen.push(e.type); + round.events.length = 0; + } + assert.equal(seen.filter((t) => t === "armUse").length, 1); + assert.equal(seen.filter((t) => t === "armSplat").length, 1); + const soft = seen.filter((t) => t === "armGoop").length; + assert.ok(soft >= 1 && soft <= 6, `a few soft splats, not one a blob (${soft})`); + assert.deepEqual(heard({ type: "armGoop" }).played, ["ghoulPieSplat"]); + assert.deepEqual(heard({ type: "armSplat" }).played, ["ghoulPieSplat"]); +}); + +/* ----------------------------------------------------------- Ringmaster */ + +test("Ghoul Rush's Ringmaster waits high over the ring with his puppet hanging on three strings, the puppet walks at you, and nothing can hurt him (the shots show a block)", () => { + const round = bigtopFight(); + const b = round.boss; + assert.equal(b.kind, "ringmaster"); + assert.equal(b.y, cv.PLAT_Y, "on his gantry"); + assert.equal(b.puppet, "up"); + assert.equal(b.open, false); + assert.equal(b.strings.length, 3); + assert.ok(b.strings.every((s) => s.hp === cv.STRING_HP)); + assert.equal(b.hp, ghoul.BOSSES.ringmaster.hp); + assert.equal(b.max, b.hp); + // The gantry follows the puppet; the puppet walks at you. + standAt(round, round.spec.arena + 12); + const px = b.px; + run(round, 1500); + assert.ok(b.px < px - 6, `the puppet walks toward you (${px} to ${b.px})`); + assert.ok(Math.abs(b.x - b.px) < 8, "the gantry follows it"); + // Shots at the Ringmaster are blocked while the puppet is up. + bolt(round, b, b.y + 3); + round.shots[0].x = b.x - 5; + round.events.length = 0; + ghoul.advance(round, 60, steady); + assert.equal(b.hp, b.max); + assert.ok(events(round, "bossBlock").length >= 1); + assert.equal(cv.CARNIVAL.guard.ringmaster({ open: false }), true); + assert.equal(cv.CARNIVAL.guard.ringmaster({ open: true }), false); +}); + +test("Ghoul Rush's puppet stomps: 750 ms of shadow where it will land, then a foot 9 wide for 280 ms and a shockwave each way (cause puppet), and a board is safe", () => { + const round = bigtopFight(); + const b = round.boss; + round.you.safeMs = 0; + standAt(round, 200 - 40); + round.you.safeMs = 1e9; + b.px = 140; + b.x = 140; + scriptTo(round, "stomp"); + const wind = upTo(round, "puppetWind", 200); + assert.ok(wind, "the shadow comes first"); + assert.equal(wind.x, b.px); + const t0 = round.clock; + const st = upTo(round, "puppetStomp", 1200); + assert.ok(st && Math.abs(round.clock - t0 - cv.STOMP_WIND_MS) < 40, `${cv.STOMP_WIND_MS} ms later (${round.clock - t0})`); + const foot = round.hazards.find((h) => h.kind === "pfoot"); + assert.ok(foot && foot.w === cv.PFOOT_W && foot.live <= cv.STOMP_LIVE_MS && foot.live > cv.STOMP_LIVE_MS - 12 && foot.cause === "puppet"); + assert.equal(round.waves.filter((w) => w.kind === "puppet").length, 2); + assert.deepEqual(round.waves.map((w) => w.dir).sort(), [-1, 1]); + // Under the foot costs a life; on a board over it does not. + for (const [on, cause] of [[false, "puppet"], [true, undefined]]) { + const r = bigtopFight(); + r.boss.px = 140; + r.boss.x = 140; + if (on) standAt(r, 146, 1, 12, 0); + else standAt(r, 140); + r.you.safeMs = 0; + choose(r, "stompWind", 1); + until(r, () => events(r, "lose").length > 0 || events(r, "puppetStomp").length > 0, 1000); + run(r, 400); + assert.equal(events(r, "lose")[0]?.cause, cause, on ? "a board is safe" : "under the foot"); + } + // The shockwave: jump it or lose a life, the cause puppet. + const wave = bigtopFight(); + wave.boss.px = 140; + wave.boss.x = 140; + standAt(wave, 160); + wave.you.safeMs = 0; + choose(wave, "stompWind", 1); + until(wave, () => events(wave, "lose").length > 0, 1500); + assert.equal(events(wave, "lose")[0]?.cause, "puppet"); + const dodged = bigtopFight(); + dodged.boss.px = 140; + dodged.boss.x = 140; + standAt(dodged, 160); + dodged.you.safeMs = 0; + choose(dodged, "stompWind", 1); + until(dodged, () => dodged.waves.length > 0, 1000); + for (let t = 0; t < 1400 && !events(dodged, "lose").length; t += 4) { + const w = dodged.waves.find((q) => q.dir === 1); + if (w && w.x > 150 && w.x - dodged.you.x < 5 && dodged.you.state === "run") ghoul.jump(dodged); + ghoul.advance(dodged, 4, steady); + } + assert.equal(events(dodged, "lose").length, 0); +}); + +test("Ghoul Rush's Ringmaster cracks his whip twice in his script: 700 ms of warning, then a lash chest high along the level you stand on (ducking passes under it, standing does not); a board is hit too", () => { + const lash = (setup) => { + const r = bigtopFight(); + setup(r); + r.you.safeMs = 0; + scriptTo(r, "whip"); + return r; + }; + const r = lash((q) => standAt(q, q.boss.x - 20)); + const wind = upTo(r, "lashWind", 200); + assert.ok(wind); + const t0 = r.clock; + const crack = upTo(r, "lashCrack", 1200); + assert.ok(crack && Math.abs(r.clock - t0 - cv.LASH_WIND_MS) < 40, `${cv.LASH_WIND_MS} ms of warning`); + const h = r.hazards.find((q) => q.kind === "lash"); + assert.ok(h && h.cause === "lash" && h.live <= cv.LASH_LIVE_MS && h.live > cv.LASH_LIVE_MS - 12 && h.w === cv.LASH_LEN); + assert.equal(h.y, 6 + cv.LASH_Y); + assert.equal(h.h, cv.LASH_H); + assert.ok(cv.LASH_Y > ghoul.DUCK_H, "over a ducked head"); + assert.ok(cv.LASH_Y < ghoul.HIT_H && cv.LASH_Y + cv.LASH_H > ghoul.HIT_H - 1, "through a standing one's chest"); + // Standing: a life, the cause lash. Ducked: passed under. Jumping: over it. + const outcome = (how) => { + const q = lash((s) => standAt(s, s.boss.x - 20)); + if (how === "duck") q.input.down = true; + if (how === "jump") q.input.up = true; + let done = false; + for (let t = 0; t < 2400 && !events(q, "lose").length && !done; t += 4) { + ghoul.advance(q, 4, steady); + if (how === "jump" && q.boss.act === "lashWind" && q.boss.wait < 120 && q.you.state === "run") ghoul.jump(q); + if (events(q, "lashCrack").length && q.hazards.every((x) => x.kind !== "lash")) done = true; + } + return events(q, "lose")[0]?.cause; + }; + assert.equal(outcome("stand"), "lash"); + assert.equal(outcome("duck"), undefined, "ducked under it"); + assert.equal(outcome("jump"), undefined, "jumped it"); + // On a board the whip comes at the board's level (down or a jump answers it). + const board = lash((s) => standAt(s, 150, 1, 22, 2)); + until(board, () => board.hazards.some((q) => q.kind === "lash"), 1500); + const bh = board.hazards.find((q) => q.kind === "lash"); + assert.equal(bh.y, 22 + cv.LASH_Y, "at the board's level"); + // And it is locked 150 ms before the crack: dropping off late does not move it. + assert.equal(cv.LASH_LOCK_MS, 150); +}); + +test("Ghoul Rush's puppet strings: a bolt that crosses one cuts into it (3 hits), all three cut and the puppet collapses; the head string is out of reach of the floor, a hand string is reached in a jump", () => { + const round = bigtopFight(); + const b = round.boss; + b.px = 150; + b.x = 150; + const g = segs(b); + assert.equal(g.length, 3); + assert.ok(g[0].y1 === cv.PUP_HEAD_Y && g[1].y1 === cv.PUP_HAND_Y && g[2].y1 === cv.PUP_HAND_Y); + // From the floor, a level bolt at 8.4 crosses none of them. + round.shots.push({ x: 140, y: 8.4, vx: 130, vy: 0, gone: 0 }); + run(round, 400); + assert.ok(b.strings.every((s) => s.hp === cv.STRING_HP), "the floor's bolt crosses no string"); + // A hand string is crossed at jump height (chest 20.4). + const p = onString(b, 1, 20); + round.shots.push({ x: p.x - 1, y: p.y, vx: 130, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.equal(b.strings[1].hp, cv.STRING_HP - 1); + assert.equal(events(round, "stringHit")[0]?.what, "puppet"); + // A bolt crosses a string once, however long it takes to pass. + const once = bigtopFight(); + once.boss.px = 150; + once.boss.x = 150; + const q = onString(once.boss, 2, 20); + once.shots.push({ x: q.x - 3, y: 20, vx: 20, vy: 0, gone: 0 }); + run(once, 600); + assert.equal(once.boss.strings[2].hp, cv.STRING_HP - 1); + // The head string is higher than a jump from the floor reaches. + const head = onString(b, 0, 25); + assert.ok(head.y > 6 + 12 + 2.4 - 0.5, "needs a board"); + // Cutting: three hits on each. + for (let i = 0; i < 3; i++) { + for (const s of [0, 1, 2]) { + if (b.strings[s].hp <= 0) continue; + const at = onString(b, s, s === 0 ? 27 : 20); + round.shots.push({ x: at.x - 1, y: at.y, vx: 130, vy: 0, gone: 0 }); + ghoul.advance(round, 20, steady); + } + } + assert.ok(b.strings.every((s) => s.hp <= 0)); + assert.equal(events(round, "stringCut").filter((e) => e.what === "puppet").length, 3); + assert.equal(events(round, "puppetDown").length, 1); + assert.equal(b.puppet, "down"); + assert.equal(b.act, "fall"); + // A thrown weapon cuts the string and flies on, once. + const stake = bigtopFight(); + stake.boss.px = 150; + stake.boss.x = 150; + const sp = onString(stake.boss, 1, 20); + stake.shots.push({ arm: "stake", x: sp.x - 2, y: 20, vx: 96, vy: 0, gone: 0, t: 0, spin: 0, dmg: 4, bossDmg: 4, pierce: true }); + ghoul.advance(stake, 100, steady); + assert.equal(stake.boss.strings[1].hp, cv.STRING_HP - 1, "once"); + assert.equal(stake.shots.length, 1, "and flies on"); + // Only while the puppet is up. + const down = bigtopFight(); + down.boss.puppet = "down"; + down.boss.px = 150; + down.boss.x = 150; + down.shots.push({ x: 149, y: 20, vx: 130, vy: 0, gone: 0 }); + assert.doesNotThrow(() => ghoul.advance(down, 40, steady)); +}); + +test("Ghoul Rush's Ringmaster, puppet down: the gantry lowers him in 500 ms, he is open 4 s (only then can he be hurt), climbs back in 700 ms, and ties the strings again", () => { + const round = bigtopFight(); + const b = round.boss; + b.px = 150; + b.x = 150; + standAt(round, 120); + for (const s of b.strings) s.hp = 1; + for (let i = 0; i < 3; i++) { + const at = onString(b, i, i === 0 ? 27 : 20); + round.shots.push({ x: at.x - 1, y: at.y, vx: 130, vy: 0, gone: 0 }); + ghoul.advance(round, 20, steady); + } + assert.equal(b.act, "fall"); + const t0 = round.clock; + const open = upTo(round, "ringOpen", 1500); + assert.ok(open && Math.abs(round.clock - t0 - cv.DESCEND_MS) < 40, `open ${cv.DESCEND_MS} ms later (${round.clock - t0})`); + assert.equal(b.open, true); + assert.equal(b.y, 6, "on the ring's floor"); + assert.ok(Math.abs(b.x - 120) >= 9, "lands clear of you"); + // Now he can be hurt: a bolt does 1, a stomp more. + const hp = b.hp; + standAt(round, b.x - 14); + bolt(round, b, b.y + 3); + ghoul.advance(round, 40, steady); + assert.equal(b.hp, hp - 1); + assert.equal(events(round, "bossHit").at(-1).kind, "ringmaster"); + // He stays open 4 s, then climbs. + const t1 = round.clock; + const climb = upTo(round, "ringClimb", 5000); + assert.ok(climb && Math.abs(round.clock - t1 - (cv.OPEN_MS - 40)) < 150, `open about ${cv.OPEN_MS} ms (${round.clock - t1})`); + assert.equal(b.open, false); + bolt(round, b, b.y + 3); + round.shots[0].x = b.x - 4; + const hp2 = b.hp; + ghoul.advance(round, 40, steady); + assert.equal(b.hp, hp2, "closed again"); + const t2 = round.clock; + const tie = upTo(round, "ringString", 2000); + assert.ok(tie && Math.abs(round.clock - t2 - cv.CLIMB_MS) < 60, `${cv.CLIMB_MS} ms to climb`); + assert.equal(b.puppet, "up"); + assert.equal(b.y, cv.PLAT_Y); + assert.ok(b.strings.every((s) => s.hp === cv.STRING_HP)); + // And the cycle goes on: the next move comes after the rest. + run(round, 4000); + assert.ok(["puppetWind", "lashWind", "puppetCrouch", "puppetRear"].some((type) => events(round, type).length >= 1), "a move comes after the rest"); + assert.ok(Math.abs(b.px - b.x) < 12, "the puppet is back up near him"); + // Killed while open, he falls and the door opens (a life too). + const kill = bigtopFight(); + Object.assign(kill.boss, { puppet: "down", act: "open", open: true, y: 6, wait: 1e9, hp: 1 }); + standAt(kill, kill.boss.x - 14); + bolt(kill, kill.boss, kill.boss.y + 3); + ghoul.advance(kill, 40, steady); + assert.equal(kill.boss.state, "down"); + assert.equal(events(kill, "bossDown")[0]?.kind, "ringmaster"); + assert.equal(kill.hasKey, true); +}); + +test("Ghoul Rush's Ringmaster rages at half his hp: every wait 0.75 as long, the strings take 5 hits, and hounds are let out of the cages (2, then one each time he ties the strings), never more than 3 alive", () => { + const round = bigtopFight(); + const b = round.boss; + assert.equal(b.raged, false); + Object.assign(b, { puppet: "down", act: "open", open: true, y: 6, wait: 1e9 }); + b.hp = Math.floor(b.max / 2) + 1; + standAt(round, b.x - 14); + bolt(round, b, b.y + 3); + ghoul.advance(round, 40, steady); + assert.equal(b.raged, true); + assert.equal(events(round, "ringRage").length, 1); + assert.equal(events(round, "cageOpen").length, 2); + const hounds = round.monsters.filter((m) => m.kind === "circushound"); + assert.equal(hounds.length, 2); + assert.deepEqual(hounds.map((m) => m.x).sort((a, c) => a - c), [round.spec.arena + 8, round.spec.length - 8]); + assert.ok(hounds.every((m) => m.act === "burst")); + // They burst out and hunt. + round.you.safeMs = 1e9; + run(round, 1500); + assert.ok(hounds.every((m) => m.act !== "burst")); + // He ties the strings tighter and lets a third out; never a fourth. + b.wait = 1; + b.act = "open"; + run(round, 200); + until(round, () => events(round, "ringString").length > 0, 3000); + assert.ok(b.strings.every((s) => s.hp === cv.RAGE_STRING_HP), "5 hits a string now"); + assert.equal(round.monsters.filter((m) => m.kind === "circushound" && !m.dead).length, 3); + b.act = "open"; + b.wait = 1; + run(round, 200); + until(round, () => events(round, "ringString").length > 1, 3000); + assert.ok(round.monsters.filter((m) => m.kind === "circushound" && !m.dead).length <= cv.HOUND_CAP); + // His waits are shorter. + const calm = bigtopFight(); + const raged = bigtopFight(); + raged.boss.raged = true; + for (const r of [calm, raged]) { + standAt(r, 150); + r.boss.px = 150; + r.boss.x = 150; + choose(r, "stompWind", 1); + } + const rest = (r) => { + until(r, () => r.boss.act === "rest", 1000); + return r.boss.wait; + }; + const w1 = rest(calm); + const w2 = rest(raged); + assert.ok(Math.abs(w2 / w1 - cv.RAGE_QUICK) < 0.05, `${w2} against ${w1}`); +}); + +/* ------------------------------------------------ the puppet on the move */ + +// The puppet on the stalk at `px` (the gantry over it), Planny at `you`, safe from everything. +const stalking = (round, px, you) => { + Object.assign(round.boss, { px, x: px, act: "stalk", wait: 1e9, again: false }); + standAt(round, you); + round.you.safeMs = 1e9; + return round.boss; +}; +const lane = (round, b) => ({ lo: round.spec.arena + ghoul.ARENA_POCKET + b.w / 2, hi: round.spec.length - ghoul.ARENA_POCKET - b.w / 2 }); + +test("Ghoul Rush's puppet stalks you between moves: it walks at 10 a second (under your run, at any depth), stops 8 to 10 short, faces you and holds there; Cotton Candy does not slow it", () => { + assert.ok(cv.PUP_V >= 9 && cv.PUP_V <= 11); + assert.ok(cv.PUP_V * 1.4 < ghoul.RUN_SPEED, "never faster than you run, at the deepest pace"); + assert.ok(cv.STALK_STOP >= 8 && cv.STALK_STOP <= 10); + for (const side of [1, -1]) { + const round = bigtopFight(); + const b = stalking(round, side > 0 ? 185 : 130, side > 0 ? 125 : 190); + const x0 = b.px; + run(round, 1000); + assert.ok(Math.abs(Math.abs(x0 - b.px) - cv.PUP_V) < 0.6, `about ${cv.PUP_V} a second (${Math.abs(x0 - b.px)})`); + assert.equal(b.pdir, -side, "turned to face you"); + assert.ok(b.walk > 9 && b.walk < 11, `walking at ${b.walk}`); + assert.ok(Math.abs(b.x - b.px) <= cv.GANTRY_LAG, "the gantry follows"); + until(round, () => Math.abs(b.px - round.you.x) <= cv.STALK_STOP + 0.01, 9000); + const gap = Math.abs(b.px - round.you.x); + assert.ok(gap >= 8 && gap <= 10, `stops ${gap} short`); + run(round, 1500); + assert.ok(Math.abs(Math.abs(b.px - round.you.x) - gap) < 0.05, "and holds there"); + assert.equal(b.walk, 0, "standing"); + } + // Cotton Candy slows monsters a bolt hits; the boss is not one (shots at him are blocked), so it walks as ever. + const round = bigtopFight(); + round.effects.floss = 9000; + const b = stalking(round, 185, 125); + round.shots.push({ x: b.x - 6, y: b.y + 3, vx: 80, vy: 0, gone: 0 }); + const x0 = b.px; + run(round, 1000); + assert.ok(!(b.hasteMs > 0), "no haste on the boss"); + assert.ok(Math.abs(x0 - b.px - cv.PUP_V) < 0.6, "walks at its own pace"); +}); + +test("Ghoul Rush's puppet leaps: a crouch of 580 ms, then a flight of 800 ms or more to where you stood when it left the ground (further on if you were running), a shadow at the spot the whole way, and a landing that is the stomp's foot and shockwaves", () => { + assert.ok(cv.CROUCH_MS >= 500 && cv.CROUCH_MS <= 600); + assert.ok(cv.LEAP_MIN_MS >= 700); + const round = bigtopFight(); + const b = round.boss; + b.px = b.x = 175; + standAt(round, 130); + round.you.safeMs = 1e9; + scriptTo(round, "leap"); + const crouch = upTo(round, "puppetCrouch", 100); + assert.ok(crouch, "an event as it crouches"); + assert.equal(b.act, "crouch"); + const t0 = round.clock; + // He moves during the crouch: the spot is where he is when it leaves the ground. + standAt(round, 124); + round.you.safeMs = 1e9; + let low = 0; + const leap = upTo(round, "puppetLeap", 1200); + assert.ok(leap && Math.abs(round.clock - t0 - cv.CROUCH_MS) < 40, `${cv.CROUCH_MS} ms of crouch (${round.clock - t0})`); + assert.ok(b.crouch > 0.9, "right down at the end"); + assert.equal(leap.toX, 124); + assert.equal(b.toX, 124); + assert.ok(b.airMs >= cv.LEAP_MIN_MS && b.airMs <= cv.LEAP_MAX_MS); + // Then he is free to go anywhere: the spot does not follow him, the shadow (b.toX, drawn all the way) stays. + standAt(round, 150); + round.you.safeMs = 1e9; + const t1 = round.clock; + let peak = 0; + let still = true; + round.events.length = 0; + while (round.clock - t1 < 2500 && !events(round, "puppetStomp").length) { + ghoul.advance(round, 4, steady); + peak = Math.max(peak, b.lift); + if (b.act === "leap" && b.toX !== 124) still = false; + } + const stomp = events(round, "puppetStomp")[0]; + assert.ok(stomp, "it comes down"); + assert.ok(round.clock - t1 >= 700, `a flight of ${round.clock - t1} ms is long enough to read`); + assert.ok(round.clock - t1 <= cv.LEAP_MAX_MS + 40); + assert.ok(still, "the spot is locked for the whole flight"); + assert.ok(Math.abs(peak - cv.LEAP_H) < 0.6, `up ${peak}`); + assert.equal(stomp.x, 124); + assert.equal(b.px, 124); + const foot = round.hazards.find((h) => h.kind === "pfoot"); + assert.ok(foot && foot.x === 124 && foot.w === cv.PFOOT_W && foot.cause === "puppet"); + assert.deepEqual(round.waves.filter((w) => w.kind === "puppet").map((w) => w.dir).sort(), [-1, 1], "a shockwave each way"); + assert.ok(b.squash > 0, "a squash on landing"); + assert.equal(b.lift, 0); + // The wind-up and flight are warning enough: over half a second before a foot can land. + assert.ok(cv.CROUCH_MS + cv.LEAP_MIN_MS >= 500); + // Running: the spot is further on. + const runner = bigtopFight(); + runner.boss.px = runner.boss.x = 175; + standAt(runner, 120); + runner.you.safeMs = 1e9; + scriptTo(runner, "leap"); + runner.input.right = true; + const rl = upTo(runner, "puppetLeap", 1500); + runner.input.right = false; + assert.ok(rl && Math.abs(rl.toX - (runner.you.x + cv.LEAP_LEAD)) < 1.2, `toX ${rl.toX} for you at ${runner.you.x}`); + // The foot hurts if you stay put (cause puppet), not if you step away, and a board is safe. + const outcome = (how) => { + const r = bigtopFight(); + r.boss.px = r.boss.x = 175; + standAt(r, 130); + r.you.safeMs = 0; + scriptTo(r, "leap"); + if (how === "board") { + until(r, () => r.boss.act === "leap", 1500); + standAt(r, 134, 1, 16.5, 1); + } else until(r, () => r.boss.act === "leap", 1500); + r.you.safeMs = 0; + if (how === "step") standAt(r, 175); + r.you.safeMs = 0; + until(r, () => events(r, "lose").length > 0 || (events(r, "puppetStomp").length > 0 && r.boss.act === "rest"), 3000); + run(r, 250); + return events(r, "lose")[0]?.cause; + }; + assert.equal(outcome("stay"), "puppet"); + assert.equal(outcome("step"), undefined, "stepped away from the shadow"); + assert.equal(outcome("board"), undefined, "on a board over the foot"); + // The shockwaves after the landing are jumped as ever. + const wave = bigtopFight(); + wave.boss.px = wave.boss.x = 175; + standAt(wave, 130); + wave.you.safeMs = 1e9; + scriptTo(wave, "leap"); + until(wave, () => wave.boss.act === "leap", 1500); + standAt(wave, 150); + wave.you.safeMs = 0; + until(wave, () => wave.waves.some((w) => w.kind === "puppet"), 2500); + for (let t = 0; t < 1500 && !events(wave, "lose").length; t += 4) { + const w = wave.waves.find((q) => q.dir === 1); + if (w && w.x < wave.you.x && wave.you.x - w.x < 6 && wave.you.state === "run") ghoul.jump(wave); + ghoul.advance(wave, 4, steady); + } + assert.equal(events(wave, "lose").length, 0, "a jump clears the shockwave"); +}); + +test("Ghoul Rush's puppet charges: it rears 780 ms (backing off for a run-up), runs the floor at 40 a second to the wall, crashes and is dazed for a second (a hit on its body counts for nothing, the strings can still be cut)", () => { + assert.ok(cv.REAR_MS >= 700 && cv.REAR_MS <= 800); + assert.ok(cv.CHARGE_V >= 38 && cv.CHARGE_V <= 42); + assert.ok(cv.CHARGE_H >= 6 && cv.CHARGE_H <= 7); + assert.equal(cv.CRASH_MS, 1000); + const round = bigtopFight(); + const b = round.boss; + const { lo } = lane(round, b); + b.px = b.x = 150; + standAt(round, 130); + round.you.safeMs = 1e9; + scriptTo(round, "charge"); + assert.ok(upTo(round, "puppetRear", 100), "an event as it rears"); + assert.equal(b.cdir, -1, "at you"); + const t0 = round.clock; + const px0 = b.px; + const go = upTo(round, "puppetCharge", 1200); + assert.ok(go && Math.abs(round.clock - t0 - cv.REAR_MS) < 40, `${cv.REAR_MS} ms of rearing (${round.clock - t0})`); + assert.ok(b.px > px0 + 4, `backed off for a run-up (${px0} to ${b.px})`); + const box = round.hazards.find((h) => h.kind === "pcharge"); + assert.ok(box && box.w === cv.CHARGE_W && box.h === cv.CHARGE_H && box.cause === "puppet"); + const x1 = b.px; + run(round, 250); + const speed = (x1 - b.px) / 0.25; + assert.ok(Math.abs(speed - cv.CHARGE_V) < 2, `${speed} a second`); + assert.equal(box.x, b.px, "its hit box rides with it"); + // A hit on his body counts for nothing; a string is still cut. + const hp = b.hp; + bolt(round, b, b.y + 3); + round.shots.at(-1).x = b.x - 3; + ghoul.advance(round, 40, steady); + assert.equal(b.hp, hp); + const crash = upTo(round, "puppetCrash", 3000); + assert.ok(crash && crash.big, "crashes at the wall"); + assert.equal(b.px, lo, "at the arena's wall"); + assert.equal(b.act, "crash"); + assert.equal(b.dazed, true); + assert.ok(!round.hazards.some((h) => h.kind === "pcharge"), "its hit box is gone"); + const t2 = round.clock; + const wall = b.px; + const p = onString(b, 1, 20); + round.shots.push({ x: p.x - 1, y: p.y, vx: 130, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.equal(b.strings[1].hp, cv.STRING_HP - 1, "the strings can be cut while it is dazed"); + assert.equal(b.hp, hp, "and its body still takes nothing"); + until(round, () => b.act === "rest", 1500); + assert.ok(Math.abs(round.clock - t2 - cv.CRASH_MS) < 100, `dazed ${round.clock - t2} ms`); + assert.equal(b.px, wall, "stays where it crashed"); + assert.equal(b.dazed, false); +}); + +test("Ghoul Rush's charge hurts on the floor (ducking does not help), a normal jump clears it with room to spare, and a board is safe", () => { + const setup = () => { + const r = bigtopFight(); + r.boss.px = r.boss.x = 150; + standAt(r, 125); + r.you.safeMs = 1e9; + scriptTo(r, "charge"); + upTo(r, "puppetCharge", 1500); + return r; + }; + // Stand, or duck: a life, cause puppet. + for (const duck of [false, true]) { + const r = setup(); + r.you.safeMs = 0; + if (duck) r.input.down = true; + until(r, () => events(r, "lose").length > 0 || r.boss.act === "crash", 2500); + assert.equal(events(r, "lose")[0]?.cause, "puppet", duck ? "a duck does not pass under" : "standing"); + } + // A jump (up held, the normal jump) at the right time clears it; find how wide the right time is. + const jumpedAt = (offset) => { + const r = setup(); + const b = r.boss; + r.you.safeMs = 0; + const gap = b.px - r.you.x; + const arrive = (gap - (cv.CHARGE_W + ghoul.HIT_W) / 2) / cv.CHARGE_V; + const start = r.clock; + let jumped = false; + for (let t = 0; t < 2500 && !events(r, "lose").length && r.boss.act === "charge"; t += 4) { + if (!jumped && (r.clock - start) / 1000 >= arrive + offset) { + ghoul.jump(r); + jumped = true; + } + r.input.up = r.you.state === "air"; + ghoul.advance(r, 4, steady); + } + return events(r, "lose").length === 0; + }; + let best = 0; + let run0 = 0; + for (let off = -0.45; off <= 0.1; off += 0.01) { + run0 = jumpedAt(off) ? run0 + 1 : 0; + best = Math.max(best, run0); + } + assert.ok(best >= 15, `a window of ${best * 10} ms to jump it in`); + assert.equal(jumpedAt(-0.19), true, "mid-window"); + assert.equal(jumpedAt(-0.7), false, "too early lands in front of it"); + // On a board over it: nothing. + const r = setup(); + standAt(r, 120, 1, 12, 0); + r.you.safeMs = 0; + until(r, () => events(r, "lose").length > 0 || r.boss.act === "crash", 2500); + assert.equal(events(r, "lose").length, 0, "a board is over its box"); + assert.ok(cv.CHARGE_H <= 6 + 1 && ghoul.JUMP_TOP > cv.CHARGE_H + 4, "the box is far under a jump's height"); +}); + +test("Ghoul Rush's strings follow the puppet: the gantry slides after it at a lag, so the strings angle; their endpoints and hit areas move with it, tighten on a leap, and a bolt crossing the moved, slanted segment cuts it", () => { + const round = bigtopFight(); + const b = stalking(round, 185, 125); + const before = segs(b).map((g) => ({ ...g })); + assert.ok(before.every((g) => Math.abs(g.x1 - g.x0) < 7), "tied up straight at first"); + run(round, 1500); + const now = segs(b); + assert.ok(Math.abs(b.px - 185) > 12, "it has walked"); + now.forEach((g, i) => assert.ok(Math.abs(g.x1 - before[i].x1 - (b.px - 185)) < 0.01, `string ${i}'s end went with it`)); + assert.ok(b.x - b.px > 2 && b.x - b.px <= cv.GANTRY_LAG, `the gantry lags (${b.x - b.px})`); + assert.ok(cv.GANTRY_V < cv.PUP_V, "and is slower"); + assert.ok(Math.abs(now[0].x0 - now[0].x1) > 2, "so the head string slants"); + assert.equal(b.y, cv.PLAT_Y, "the gantry stays high"); + assert.ok(b.y > 6 + 12 + 6 + ghoul.HIT_H + 4, "out of reach of a jump from the top board"); + // A bolt where the string was before it walked misses; where it is now, hits (the slanted part too). + const old = before[1]; + round.shots.push({ x: old.x1, y: 20, vx: 0, vy: 0, gone: 0 }); + run(round, 120); + assert.equal(b.strings[1].hp, cv.STRING_HP, "the old place is empty"); + const p = onString(b, 1, 20); + round.shots.push({ x: p.x, y: 20, vx: 0, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.equal(b.strings[1].hp, cv.STRING_HP - 1, "the new place is hit"); + const h = onString(b, 0, 32); + assert.ok(Math.abs(h.x - b.px) > 0.8, "high on the head string it is off the puppet's own x"); + round.shots.length = 0; + round.shots.push({ x: h.x, y: 32, vx: 0, vy: 0, gone: 0 }); + ghoul.advance(round, 40, steady); + assert.equal(b.strings[0].hp, cv.STRING_HP - 1, "a bolt across the slanted part cuts into it"); + const beside = h.x + 2.5; + round.shots.length = 0; + round.shots.push({ x: beside, y: 32, vx: 0, vy: 0, gone: 0 }); + const hp = b.strings[0].hp; + ghoul.advance(round, 8, steady); + assert.equal(b.strings[0].hp, hp, "a bolt well to the side of it misses"); + // On a leap the puppet rises and the strings tighten (shorter, ends higher), and hold where the limbs are. + const jump = bigtopFight(); + const jb = jump.boss; + jb.px = jb.x = 175; + standAt(jump, 130); + jump.you.safeMs = 1e9; + const rest = segs(jb); + scriptTo(jump, "leap"); + until(jump, () => jb.lift > cv.LEAP_H - 0.3, 3000); + const apex = segs(jb); + assert.ok(apex[0].y1 > rest[0].y1 + 8, "the head rides up"); + const drop = (g) => g.y0 - g.y1; + assert.ok(drop(apex[0]) < drop(rest[0]) - 8, `taut: it hangs ${drop(apex[0]).toFixed(1)} against ${drop(rest[0]).toFixed(1)}`); + assert.ok(apex[1].y1 > rest[1].y1 + 8 && apex[2].y1 > rest[2].y1 + 8, "and the hands"); + const q = onString(jb, 2, apex[2].y1 + 2); + jump.shots.push({ x: q.x, y: q.y, vx: 0, vy: 0, gone: 0 }); + ghoul.advance(jump, 8, steady); + assert.equal(jb.strings[2].hp, cv.STRING_HP - 1, "the lifted hand string is cut where it is"); + // The limbs' places are kept on the boss for the drawing, the same as the strings use. + assert.deepEqual(jb.pts.map((pt) => pt.map((n) => Math.round(n * 100))), cv.limbs(jb).map((pt) => pt.map((n) => Math.round(n * 100)))); +}); + +test("Ghoul Rush's puppet stops when all three strings are cut (mid-charge too), does not move while he is open, and when he ties the strings again it resumes beside him", () => { + const round = bigtopFight(); + const b = round.boss; + b.px = b.x = 160; + standAt(round, 125); + round.you.safeMs = 1e9; + scriptTo(round, "charge"); + upTo(round, "puppetCharge", 1500); + run(round, 300); + assert.ok(round.hazards.some((h) => h.kind === "pcharge")); + for (const s of b.strings) s.hp = 1; + for (const i of [0, 1, 2]) { + const at = onString(b, i, i === 0 ? 30 : 22); + round.shots.push({ x: at.x - 0.8, y: at.y, vx: 130, vy: 0, gone: 0 }); + ghoul.advance(round, 8, steady); + } + assert.equal(b.puppet, "down"); + assert.equal(b.act, "fall"); + const px = b.px; + ghoul.advance(round, 8, steady); + assert.ok(!round.hazards.some((h) => h.kind === "pcharge"), "no more charge box"); + assert.equal(b.lift, 0); + run(round, 2500); + assert.equal(b.px, px, "it lies where it fell, not moving"); + assert.equal(b.act, "open"); + // He climbs and ties the strings: the puppet is up beside him and goes on. + const tie = upTo(round, "ringString", 6000); + assert.ok(tie); + assert.equal(b.puppet, "up"); + assert.ok(Math.abs(b.px - b.x) < 0.01, "up where he stands"); + assert.ok(b.px >= lane(round, b).lo && b.px <= lane(round, b).hi); + assert.equal(b.act, "rest"); + const at0 = b.px; + standAt(round, at0 - 40); + round.you.safeMs = 1e9; + run(round, 1500); + assert.ok(Math.abs(b.px - at0) > 3, "and it walks again"); +}); + +test("Ghoul Rush's Ringmaster works to a script, no random draw: leap, stomp, whip, charge, leap, whip, a stalk, and round again; enraged he cracks the whip twice running and every wait is 0.75 as long; each move sounds once", () => { + assert.deepEqual([...cv.SCRIPT], ["leap", "stomp", "whip", "charge", "leap", "whip", "stalk"]); + const sequence = (raged, picks) => { + const round = bigtopFight(); + const b = round.boss; + b.raged = raged; + standAt(round, 125); + round.you.safeMs = 1e9; + const seq = []; + const counts = {}; + const walking = (a) => a === "idle" || a === "rest" || a === "stalk"; + let was = b.act; + for (let t = 0; t < 400000 && seq.length < picks; t += 4) { + ghoul.advance(round, 4, never); + round.you.safeMs = 1e9; + for (const e of round.events) counts[e.type] = (counts[e.type] || 0) + 1; + round.events.length = 0; + if (walking(was) && b.act !== was) seq.push(b.move); + was = b.act; + } + return { seq, counts }; + }; + const { seq, counts } = sequence(false, 14); + assert.deepEqual(seq, [...cv.SCRIPT, ...cv.SCRIPT], "in order, twice round"); + // Each move sounds once: its wind-up event once per move (a leap's landing is the stomp's foot). + assert.equal(counts.puppetCrouch, 4); + assert.equal(counts.puppetLeap, 4); + assert.equal(counts.puppetRear, 2); + assert.equal(counts.puppetCharge, 2); + assert.equal(counts.puppetCrash, 2); + assert.equal(counts.lashWind, 4); + assert.equal(counts.lashCrack, 4); + assert.equal(counts.puppetWind, 2); + assert.equal(counts.puppetStomp, 6, "two stomps and four landings"); + // Enraged: each whip is cracked twice running, and the second takes no place in the script. + const fury = sequence(true, 12).seq; + assert.deepEqual(fury.slice(0, 11), ["leap", "stomp", "whip", "whip", "charge", "leap", "whip", "whip", "stalk", "leap", "stomp"]); + // The waits are 0.75 as long. + const waits = [false, true].map((raged) => { + const r = bigtopFight(); + r.boss.raged = raged; + stalking(r, 150, 125); + r.boss.moves = cv.SCRIPT.indexOf("stalk"); + choose(r, "idle", 1); + until(r, () => r.boss.move === "stalk" && r.boss.act === "stalk" && r.boss.wait > 100, 400); + return r.boss.wait; + }); + assert.ok(Math.abs(waits[1] / waits[0] - cv.RAGE_QUICK) < 0.05, `${waits[1]} against ${waits[0]}`); + const rest = [false, true].map((raged) => { + const r = bigtopFight(); + r.boss.raged = raged; + stalking(r, 150, 125); + r.boss.moves = 0; + r.boss.px = r.boss.x = 150; + choose(r, "idle", 1); + until(r, () => r.boss.act === "crouch", 100); + until(r, () => r.boss.act === "rest", 4000); + return r.boss.wait; + }); + assert.ok(Math.abs(rest[1] / rest[0] - cv.RAGE_QUICK) < 0.05, `a leap's rest, ${rest[1]} against ${rest[0]}`); +}); + +test("Ghoul Rush's Ringmaster and everything else here draw no random number", () => { + const fight = bigtopFight(); + fight.boss.hp = fight.boss.max; + fight.boss.px = 150; + fight.boss.x = 150; + standAt(fight, 120); + fight.you.safeMs = 1e9; + run(fight, 45000, {}, never); + for (const type of ["puppetWind", "puppetStomp", "puppetCrouch", "puppetLeap", "puppetRear", "puppetCharge", "puppetCrash", "lashWind", "lashCrack"]) assert.ok(events(fight, type).length > 0, `${type} happened without a random draw`); + choose(fight, "stalk", 1e9); + for (let i = 0; i < 3; i++) { + const at = onString(fight.boss, 1, 20); + fight.boss.strings[i].hp = 1; + fight.shots.push({ x: onString(fight.boss, i, i === 0 ? 27 : 20).x - 1, y: i === 0 ? 27 : 20, vx: 130, vy: 0, gone: 0 }); + run(fight, 20, {}, never); + assert.ok(at); + } + fight.boss.hp = Math.floor(fight.boss.max / 2); + run(fight, 8000, {}, never); + for (const type of ["puppetDown", "ringOpen", "ringRage", "cageOpen", "ringClimb", "ringString"]) assert.ok(events(fight, type).length > 0, `${type} happened without a random draw`); + // The monsters: no draw either. + const mid = carnivalRound("funhouse"); + standAt(mid, 62); + mid.you.safeMs = 1e9; + put(mid, "marionette", 64, { y: 10.8 }); + put(mid, "grinner", 120); + put(mid, "strongman", 110); + put(mid, "circushound", 100); + put(mid, "mirror", 90); + mid.arms = [{ kind: "pie", n: 2 }]; + // Thrown the other way, so its cream is not what these monsters are doing. + mid.you.face = -1; + tapTap(mid); + mid.you.face = 1; + const seen = new Set(); + for (let t = 0; t < 12000; t += 4) { + ghoul.advance(mid, 4, never); + mid.you.safeMs = 1e9; + for (const e of mid.events) seen.add(e.type); + mid.events.length = 0; + } + for (const type of ["marionetteDrop", "grinnerHonk", "houndLeap", "houndLand", "strongWind", "strongThrow", "barbellLand", "mirrorStep", "armSplat"]) assert.ok(seen.has(type), `${type} happened without a random draw`); +}); + +/* -------------------------------------------------------------- endless */ + +test("Ghoul Rush's endless lives (round.infinite) spare every new way to lose a life: a grinner, a balloon, an acid puddle, a marionette, a mirror and its bolt, a strongman, a barbell, a circus hound, the puppet's foot and its shockwave, its leap and its charge, the whip, and the Ringmaster himself", () => { + const costs = (id, setup, cause, { fight = false } = {}) => { + for (const infinite of [false, true]) { + const round = fight ? bigtopFight() : carnivalRound(id); + round.infinite = infinite; + round.you.safeMs = 0; + setup(round); + until(round, () => events(round, "lose").length > 0, 3000); + const e = events(round, "lose")[0]; + assert.equal(e?.cause, cause, `${cause}: a life is lost`); + assert.equal(round.lives, infinite ? 3 : 2, `${cause}: ${infinite ? "spared" : "costs one"}`); + } + }; + costs("midway", (r) => (standAt(r, 40), put(r, "grinner", 40.5)), "grinner"); + costs("midway", (r) => (standAt(r, 40), (put(r, "balloon", 40.5, { y: 6.5 }).life = 1e9)), "balloon"); + costs("midway", (r) => (standAt(r, 40), r.puddles.push({ id: 1, x: 40, y: 6, life: 2000 })), "acid"); + costs("funhouse", (r) => (standAt(r, 40), put(r, "marionette", 40.5, { act: "dance" })), "marionette"); + costs("mirrors", (r) => (standAt(r, 40), put(r, "mirror", 40.5, { act: "copy", cursor: 0, px: 40, at: 0, rise: 0, duck: false })), "mirror"); + costs("mirrors", (r) => (standAt(r, 40), (r.twist = null), ghoul.advance(r, 8, steady), r.you.safeMs = 0, r.twist.bolts.push({ x: 41, y: 8.8, vx: -80, gone: 0 })), "mirrorbolt"); + costs("midway", (r) => (standAt(r, 40), put(r, "strongman", 40.5)), "strongman"); + costs("midway", (r) => (standAt(r, 40), r.bones.push({ id: 7, kind: "barbell", x: 40, y: 7, vx: 0, vy: 0, spin: 0, life: 4000, cause: "barbell" })), "barbell"); + costs("midway", (r) => (standAt(r, 40), put(r, "circushound", 40.5)), "circushound"); + costs("bigtop", (r) => (standAt(r, 140), (r.boss.px = 140), (r.boss.x = 140), choose(r, "stompWind", 1)), "puppet", { fight: true }); + costs("bigtop", (r) => (standAt(r, 140), (r.boss.px = 140), (r.boss.x = 140), scriptTo(r, "leap")), "puppet", { fight: true }); + costs("bigtop", (r) => (standAt(r, 125), (r.boss.px = 150), (r.boss.x = 150), scriptTo(r, "charge")), "puppet", { fight: true }); + costs("bigtop", (r) => (standAt(r, 140), r.hazards.push({ kind: "lash", x: 140, y: 8.7, w: 40, h: 1.6, dir: 1, live: 200, max: 200, cause: "lash" })), "lash", { fight: true }); + costs("bigtop", (r) => (Object.assign(r.boss, { puppet: "down", act: "open", open: true, y: 6, wait: 1e9 }), standAt(r, r.boss.x - 3)), "ringmaster", { fight: true }); +}); + +/* ---------------------------------------------------- voices and drawing */ + +test("Ghoul Rush's Carnival: every new kind has a voice for every act, each a real tone, and every event of the pack plays its own sound exactly once", () => { + const listed = { + grinner: ["appear", "honk", "hurt", "die"], + balloon: ["appear", "die"], + marionette: ["appear", "jerk", "drop", "land", "cut", "hurt", "die"], + mirror: ["appear", "step", "shot", "cancel", "shatter", "hurt", "die"], + strongman: ["appear", "die", "hurt", "land", "throw", "wind"], + circushound: ["appear", "crouch", "die", "hurt", "land", "leap"], + ringmaster: ["wake", "puppetWind", "stomp", "down", "open", "climb", "tie", "lashWind", "crack", "stringHit", "stringCut", "cage", "rage", "hurt", "die"], + floss: ["active", "stick"], + }; + for (const [kind, acts] of Object.entries(listed)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + for (const kind of [...Object.keys(cv.MONSTERS), ...Object.keys(cv.BOSSES)]) assert.ok(VOICES[kind] && (VOICES[kind].die || VOICES[kind].die === undefined) && VOICES[kind].die, `${kind} has a voice and a death`); + // Every event the pack emits is answered by one act, played once and nothing else. + for (const type of cv.EVENTS) assert.ok(EVENT_VOICE[type], `${type} is heard`); + for (const type of Object.keys(EVENT_VOICE)) assert.ok(cv.EVENTS.includes(type), `${type} is an event of the pack`); + assert.equal(new Set(cv.EVENTS).size, cv.EVENTS.length); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(listed[kind].includes(act), `${type}: ${kind} ${act} is a listed act`); + const extra = type === "stringHit" || type === "stringCut" ? { what: "puppet" } : {}; + const played = heard({ type, kind, ...extra }).played; + assert.equal(played.filter((n) => Object.values(VOICES[kind]).includes(n)).length >= 1, true, `${type}: plays ${kind}'s voice`); + assert.equal(new Set(played).size, played.length, `${type}: once`); + } + // Each listed act is the voice of some event (or the game's own play of it). + const reached = new Set(Object.values(EVENT_VOICE).map(([kind, act]) => `${kind}.${act}`)); + const theGames = ["grinner.appear", "grinner.hurt", "grinner.die", "balloon.appear", "balloon.die", "marionette.appear", "marionette.hurt", "marionette.die", "mirror.appear", "mirror.hurt", "mirror.die", "strongman.appear", "strongman.hurt", "strongman.die", "circushound.appear", "circushound.hurt", "circushound.die", "ringmaster.wake", "ringmaster.hurt", "ringmaster.die", "floss.active", "marionette.cut", "ringmaster.stringCut", "ringmaster.stringHit", "mirror.shatter"]; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(reached.has(`${kind}.${act}`) || theGames.includes(`${kind}.${act}`), `${kind}.${act} is played by something`); + const once = (e, kind, act) => { + const played = heard(e).played; + assert.equal(played.filter((n) => n === VOICES[kind][act]).length, 1, `${e.type}: ${kind} ${act} once`); + }; + for (const kind of ["grinner", "balloon", "marionette", "mirror", "strongman", "circushound"]) once({ type: "spawn", kind }, kind, "appear"); + once({ type: "bossWake", kind: "ringmaster" }, "ringmaster", "wake"); + once({ type: "bossHit", kind: "ringmaster", how: "shot" }, "ringmaster", "hurt"); + once({ type: "bossDown", kind: "ringmaster", points: 1 }, "ringmaster", "die"); + once({ type: "hit", kind: "grinner" }, "grinner", "hurt"); + once({ type: "kill", kind: "strongman", mult: 1, how: "shot", points: 1 }, "strongman", "die"); + once({ type: "kill", kind: "circushound", mult: 1, how: "shot", points: 1 }, "circushound", "die"); + once({ type: "power", kind: "floss", points: 50 }, "floss", "active"); + // The barbell leaves his hands (the game's own throw event comes with it and stays silent), lands, and the hound lands. + const flight = heard({ type: "throw", kind: "barbell", by: "strongman" }).played.concat(heard({ type: "strongThrow", kind: "strongman" }).played); + assert.deepEqual(flight.filter((n) => n === "swoosh"), [], "the barbell throw is not also a swoosh"); + assert.equal(flight.filter((n) => n === "ghoulStrongmanThrow").length, 1, "the barbell throw plays the strongman's tone once"); + once({ type: "strongThrow", kind: "strongman" }, "strongman", "throw"); + once({ type: "barbellLand", kind: "barbell" }, "strongman", "land"); + once({ type: "houndLand", kind: "circushound" }, "circushound", "land"); + assert.equal(VOICES.strongman.throw, "ghoulStrongmanThrow"); + assert.equal(VOICES.strongman.land, "ghoulStrongmanLand"); + assert.equal(VOICES.circushound.land, "ghoulCircusHoundLand"); +}); + +test("Ghoul Rush's Carnival: every new way to die has its words and its own sound", () => { + for (const cause of ["grinner", "balloon", "marionette", "mirror", "mirrorbolt", "strongman", "barbell", "circushound", "ringmaster", "puppet", "lash"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Carnival draws: every room, every monster in every act, the strings and the puppet in each move (the stalk, the crouch, the leap, the landing, the rear, the charge, the crash), the whip, the foot and the waves, Mirror You's bolts, Cotton Candy and a pied monster, and the stage's card, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["carnival"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { + grinner: [{ act: "walk" }, { act: "honk", wait: 200 }], + balloon: [{ act: "float", y: 10 }, { act: "float", y: 10, pied: true, stunMs: 1000 }], + marionette: [{ act: "hang", y: 10.8 }, { act: "warn", y: 10.8, wait: 200 }, { act: "drop", y: 8, vy: -20 }, { act: "dance" }], + mirror: [{ act: "wait" }, { act: "step", wait: 300 }, { act: "copy", dir: -1, rise: 0, duck: false }, { act: "copy", dir: 1, rise: 3, duck: true }], + strongman: [{ act: "walk" }, { act: "wind", wait: 300 }], + circushound: [{ act: "prowl" }, { act: "crouch", wait: 200 }, { act: "leap", vx: 20, vy: 10, y: 10 }, { act: "rest", wait: 300 }, { act: "burst", wait: 200 }], + }; + for (const id of ROOM_IDS) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + for (const floss of [0, 5000]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + r.hazards.length = 0; + r.waves.length = 0; + r.effects.floss = floss; + standAt(r, id === "bigtop" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + r.twist = null; + ghoul.advance(r, 8, steady); + r.twist.bolts.push({ x: r.you.x + 12, y: 8.8, vx: -80, gone: 0 }); + for (const [kind, list] of Object.entries(acts)) { + list.forEach((over, i) => { + const m = put(r, kind, r.you.x + 6 + i * 5, { wait: 1e9, force: true, ...over }); + if (floss) Object.assign(m, { floss: true, hasteMs: 2000, haste: 0.5 }); + }); + } + r.hazards.push({ kind: "pfoot", x: r.you.x + 20, y: 6, w: 9, h: 6, live: 100, max: 280, cause: "puppet" }, { kind: "lash", x: r.you.x + 40, y: 8.7, w: 40, h: 1.6, dir: 1, live: 100, max: 240, cause: "lash" }, { kind: "armSplat", x: r.you.x + 30, y: 6, life: 200, max: 420, w: 8, h: 1, live: 0, cause: "" }, { kind: "armPie", x: r.you.x + 20, y: 14, vx: 50, vy: 0, spin: 1, t: 300, dist: 0, since: 0, n: 3, hit: [], w: 0.8, h: 0.8, live: 0, cause: "" }, { kind: "armGoop", x: r.you.x + 18, y: 10, vx: 0, vy: 0, rest: false, fall: 0, life: 3500, max: 3500, n: 1, hit: [], w: 3.2, h: 1, live: 0, cause: "" }, { kind: "armGoop", x: r.you.x + 22, y: 6, vx: 0, vy: 0, rest: true, fall: 0, life: 2000, max: 3500, n: 3, hit: [], w: 3.2, h: 1, live: 0, cause: "" }, { kind: "armGoop", x: r.you.x + 26, y: 6, vx: 0, vy: 0, rest: true, fall: 0, life: 300, max: 3500, n: 4, hit: [], w: 3.2, h: 1, live: 0, cause: "" }); + r.waves.push({ x: r.you.x + 15, y: 6, dir: 1, life: 2000, kind: "puppet", cause: "puppet" }); + r.bones.push({ id: 99, kind: "barbell", x: r.you.x + 10, y: 12, vx: 0, vy: 0, spin: 1, life: 4000, cause: "barbell" }); + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const act of ["idle", "rest", "stalk", "stompWind", "lashWind", "crouch", "leap", "landed", "rear", "charge", "crash", "fall", "open", "climb"]) { + const down = act === "fall" || act === "open" || act === "climb"; + const pose = act === "landed" ? { act: "rest", squash: 200 } : { act }; + Object.assign(r.boss, { ...pose, wait: 1e9, total: 800, puppet: down ? "down" : "up", open: act === "open", dir: -1, y: act === "open" ? 6 : act === "fall" ? 20 : cv.PLAT_Y, lashY: 8.7, lashDir: -1, fromX: r.you.x + 30, toX: r.you.x + 12, air: 300, airMs: 900, cdir: -1 }); + if (act === "charge") r.hazards.push({ kind: "pcharge", x: r.boss.px, y: 6, w: cv.CHARGE_W, h: cv.CHARGE_H, live: 1, max: 1, dir: -1, cause: "puppet" }); + if (act === "idle") r.boss.strings.forEach((s, i) => (s.hp = i + 1)); + g.tick(16); + } + Object.assign(r.boss, { raged: true, puppet: "up", act: "idle", y: cv.PLAT_Y, open: false }); + r.boss.strings.forEach((s) => (s.hp = s.max)); + } + for (let k = 0; k < 20; k++) g.tick(16); + r.you.safeMs = 1e9; + } + } + } + assert.ok(r.spec.id === "bigtop", "got to the Big Top and drew it"); + // Cotton Candy and the pie as they sit in a room, and in the bag. + for (const kind of ["floss", "pie"]) { + const p = carnivalRound("midway"); + p.drops.push({ id: 1, kind, x: 30, y: 8, vx: 0, vy: 0, life: 9000, rest: true }); + g.tick(16); + ghoul.applyPower(p, kind); + } + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["carnival", "mine"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Carnival's card"); +}); + +test("Ghoul Rush's leap shows its landing shadow at the locked spot for the whole flight (and the charge shows its lane while it rears), in a lit room and a dark one", () => { + for (const dark of [true, false]) { + const calls = []; + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : name === "ellipse" ? (...a) => calls.push(a) : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["carnival"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + while (r.spec.id !== "bigtop") through(r); + r.phase = "play"; + r.dark = dark; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + standAt(r, r.spec.arena + ghoul.BOSS_LOCK + 2); + r.you.safeMs = 1e9; + g.tick(16); + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + const shadowAt = (x) => calls.some(([cx, , rx, ry]) => Math.abs(cx - x) < 0.01 && ry === 0.7 && rx > 1); + for (const air of [0, 200, 400, 600, 780]) { + Object.assign(r.boss, { act: "leap", wait: 1e9, fromX: 170, toX: 128, air, airMs: 900, puppet: "up", open: false }); + calls.length = 0; + g.tick(16); + assert.ok(shadowAt(128), `a shadow at the landing spot ${air} ms into the flight (${dark ? "dark" : "lit"})`); + } + Object.assign(r.boss, { act: "rest", wait: 1e9 }); + calls.length = 0; + g.tick(16); + assert.ok(!shadowAt(128), "none when it is not in the air"); + // The charge's lane while it rears is a line of dashes along the floor, not an ellipse; it draws without a fault. + Object.assign(r.boss, { act: "rear", wait: 300, total: 780, cdir: -1, px: 170 }); + assert.doesNotThrow(() => g.tick(16)); + } +}); + +test("Ghoul Rush's stage select lists the Carnival and takes you straight into each of its rooms", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.stageSelect(); + const r = g.round; + assert.equal(r.phase, "select"); + const at = ghoul.STAGES.findIndex((s) => s.id === "carnival"); + assert.equal(at, ghoul.STAGES.length - 2); + for (let i = 0; i < at; i++) ghoul.steerSelect(r, 1, 0); + for (let i = 0; i < 4; i++) ghoul.steerSelect(r, 0, 1); + assert.equal(r.select.at, at); + assert.equal(r.select.room, 4); + ghoul.takeSelect(r); + assert.equal(r.spec.id, "bigtop"); + assert.equal(r.stage, "carnival"); + assert.ok(r.arms.some((a) => a.kind === "pie"), "the stage's weapon is in the bag"); + g.tick(16); +}); diff --git a/scripts/test-web-console-activities-ghoul-cart.mjs b/scripts/test-web-console-activities-ghoul-cart.mjs new file mode 100644 index 0000000..fbb83f4 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-cart.mjs @@ -0,0 +1,1301 @@ +// Web console tests, Ghoul Rush's Runaway Cart (the Deep Seam Mine's ride room): its shape (between the Collapse and the Seam, every gap clears at the cart's speed with a jump, every beam can be ducked, checkpoints spaced, the clock covers the ride), the cart's speed on slopes, leaning and braking, its jump and its steering in the air, a ramp's launch, landing on the upper or the lower line of a split, a fall into the chasm and the respawn at the last checkpoint, ducking under a beam, rubble, crates (two shots break one), the boulder behind, the buffer stop and the door, the ledge imp, a canary's slide of rubble, endless lives for every new cause, a voice for every event, the drawing, and a bot that rides the whole room. +// Run with: node --test scripts/test-web-console-activities-ghoul-cart.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as ct from "../src/web-console/public/activities/ghoul-cart.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, LOOKS as CART_LOOKS, VOICES as CART_VOICES } from "../src/web-console/public/activities/ghoul-cart-draw.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES, bonusTick, hudLayout, react } from "../src/web-console/public/activities/ghoul-draw.js"; +import { BONUS_FLOOR, BONUS_HEARTS, diceFor, endBonus, heartsText, makeBonus } from "../src/web-console/public/activities/ghoul-bonus.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the cart drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Runaway Cart reached the way play reaches it, nothing woken: +// every spawner spent, the horde held back, the clocks long. +function cartRound(keepBonus = false) { + const round = ghoul.newRound(5); + round.lives = 3; + round.dice = 0; + through(round); + round.offer = ["mine"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "cart") through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.timeMs = 1e9; + round.bonus = 1e9; + round.events.length = 0; + // The ride's mechanics are tested with lives at stake; the bonus round's own rules are tested at the end (bonusCart). + if (!keepBonus) round.bonusRound = null; + return round; +} + +// The same round over a ride of its own (a plain track to measure the cart on). +function synth(ride) { + const round = cartRound(); + round.spec = { ...round.spec, start: 10, ground: [[0, 5, 0]], ride: { time: 1e9, stop: 1e6, beams: [], rubble: [], crates: [], checks: [], ...ride } }; + ct.CART.place[0](round, {}); + return round; +} + +// The cart on line `line` of the ride at `x`, at speed `v`. +function cartAt(round, x, line, { v = ct.CART_V, safe = false } = {}) { + const y = ct.trackY(round.spec.ride, line, x); + assert.ok(y !== null, `line ${line} runs under ${x}`); + Object.assign(round.you, { x, y, vy: 0, state: "run", shelf: -1, face: 1, out: 0, safeMs: safe ? 1e9 : 0, ducking: false }); + Object.assign(round.cart, { line, v, coyote: 0, peak: y, boulder: x - ct.BOULDER_GAP, near: false, brake: false }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 24)); +} + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = typeof keys[k] === "number" ? 0 : false; +} + +function until(round, done, ms = 6000, random = steady) { + let t = 0; + for (; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); + return t; +} + +const press = (round) => { + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = true; +}; + +// Runs until the cart is back on a track after a jump, returning where. +function untilLanded(round, ms = 4000) { + until(round, () => round.cart.line >= 0 || round.phase !== "play", ms); + return { x: round.you.x, y: round.you.y, line: round.cart.line }; +} + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played }; +}; + +const ROOM = ghoul.roomById("cart"); +const R = ROOM.ride; +const lines = ct.linesOf(R); +const floorOf = (x) => ghoul.groundAt(ROOM, x); + +/* -------------------------------------------------------------- the room */ + +test("Ghoul Rush's Runaway Cart is the Mine's fourth room, between the Collapse and the Seam: dark, no key, no boss, a ride about 60 to 75 seconds long, a bonus round, and its monsters joined to the game's", () => { + const st = ghoul.stageById("mine"); + assert.deepEqual(st.rooms, ["shaft", "tunnels", "collapse", "cart", "seam"]); + assert.equal(st.boss, "tommy"); + assert.deepEqual([ROOM.title, ROOM.sub], ["The Runaway Cart", "The brakes went in 1891"]); + assert.equal(ROOM.dark, true); + assert.equal(ROOM.key, null); + assert.equal(ROOM.boss, null); + assert.equal(ROOM.bonus, true, "a bonus round"); + assert.ok(ROOM.length >= 2400 && ROOM.length <= 3000, `${ROOM.length} units long`); + assert.ok(ghoul.ROOM_MUSIC.cart === "ghoulCart" && ghoulSfx.default.music.ghoulCart, "its own music"); + assert.ok(Object.isFrozen(R) && Object.isFrozen(R.track) && Object.isFrozen(R.track[0][0]), "frozen all the way down"); + assert.ok(ROOM.horde.length && ROOM.hordeMs > 0, "a horde of bats"); + for (const k of ROOM.horde) assert.ok(ghoul.MONSTERS[k], `${k} is a monster`); + for (const kind of Object.keys(ct.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], ct.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.MONSTERS.ledgeimp.hp, 2); + assert.equal(LOOKS.cart, CART_LOOKS.cart); + assert.equal(LOOKS.cart.pack, "cart"); + // The ground is the cave floor at the start and the end only. + assert.equal(ROOM.ground.length, 2); + assert.ok(ROOM.ground[0][1] < 60 && ROOM.ground[1][0] > ROOM.length - 60, "floor only at the ends"); + assert.ok(ROOM.door > R.stop && ROOM.door > ROOM.length - 14, "the door past the buffer stop, at the room's end"); + assert.ok(floorOf(R.stop + 2) > -Infinity, "floor to step out onto"); + // Lines run left to right, their points rising in x; the first starts at the cart. + for (const L of lines) for (let i = 0; i + 1 < L.pts.length; i++) assert.ok(L.pts[i + 1][0] > L.pts[i][0], "x rises"); + assert.ok(ct.trackY(R, 0, ROOM.start) > floorOf(ROOM.start), "the cart starts on the track over the floor"); + assert.equal(lines.at(-1).x1, R.stop, "the last line ends at the buffer stop"); + // The ride, at the cart's speed, takes 60 to 75 seconds. + const secs = (R.stop - ROOM.start) / ct.CART_V; + assert.ok(secs >= 60 && secs <= 75, `${secs.toFixed(1)} s at CART_V`); + // Gentle enough to ride: no slope steeper than the cart can climb. + for (const L of lines) for (let i = 0; i + 1 < L.pts.length; i++) assert.ok(Math.abs((L.pts[i + 1][1] - L.pts[i][1]) / (L.pts[i + 1][0] - L.pts[i][0])) <= 0.55, "slopes no steeper than 0.55"); + // The camera has room: the track stays between the floor and the roof. + for (const L of lines) for (const [, y] of L.pts) assert.ok(y > ct.DERAIL_Y + 2 && y < 36, `a track height of ${y}`); + // The clock covers the ride comfortably (and respawns refill it). + assert.equal(ghoul.timeFor(ghoul.roomFor("cart")), R.time); + assert.ok(R.time >= 1.6 * secs * 1000, `a ${R.time} ms clock for a ${secs.toFixed(0)} s ride`); +}); + +test("Ghoul Rush's Runaway Cart: every gap clears at CART_V with a jump (pressed at the edge or 1.5 early), a ramp's launch alone clears its short gap, and no obstacle comes too soon after a jump", () => { + lines.forEach((L, i) => { + if (i === lines.length - 1) return; + const end = L.pts.at(-1); + for (const early of [0, 1.5]) { + const x = L.x1 - early; + const s = ct.slopeOf(R, i, x); + const got = ct.flight(R, x, ct.trackY(R, i, x), ct.CART_JUMP_V + s * ct.CART_V, ct.CART_V, 0, floorOf); + assert.ok(got, `line ${i}: a jump ${early} short of its end at ${L.x1} lands`); + assert.ok(got.line !== i && got.x - lines[got.line].x0 >= 1.5, `line ${i}: lands on line ${got.line} at ${got.x?.toFixed(1)}, ${(got.x - lines[got.line].x0).toFixed(1)} past its start`); + assert.ok(lines[got.line].x1 - got.x >= 6, `line ${i}: ${(lines[got.line].x1 - got.x).toFixed(1)} of track left after landing`); + } + // Coasting on (no press) over a ramp's short gap, or off a dead end, it either lands or it derails; a ramp (rising at its end) with a gap under 10 must land. + const slope = ct.slopeOf(R, i, L.x1); + const next = lines.map((q, j) => [j, q.x0 - L.x1]).filter(([j, gap]) => j !== i && gap > 0).sort((a, b) => a[1] - b[1])[0]; + if (slope >= ct.RAMP_SLOPE && next && next[1] < 10) { + const got = ct.flight(R, L.x1, end[1], slope * ct.CART_V + ct.RAMP_POP, ct.CART_V, 0, floorOf); + assert.ok(got && got.line === next[0] && got.x - lines[next[0]].x0 >= 2, `line ${i}: the ramp's launch clears the ${next[1]} wide gap`); + } + }); + // At least one ramp and one short hop, one long jump, and the big one last. + const gaps = lines.slice(0, -1).filter((L) => ct.linesAt(R, L.x1).length === 1).map((L, i) => [i, Math.min(...lines.filter((q) => q.x0 > L.x1).map((q) => q.x0 - L.x1))]); + assert.ok(gaps.some(([, g]) => g <= 10) && gaps.some(([, g]) => g >= 16), "a small gap and a big one"); + assert.equal(Math.max(...gaps.map(([, g]) => g)), gaps.at(-1)[1], "the last gap is the biggest"); + // Obstacles on one line come far enough apart for a jump to land and the next to start. + lines.forEach((L, i) => { + // A wall of crates (each within 4 of the next) is one obstacle: jumped or shot as one. + const xs = [...R.rubble.filter((q) => q[1] === i).map((q) => q[0]), ...R.crates.filter((q) => q[1] === i).map((q) => q[0])]; + if (i < lines.length - 1) xs.push(L.x1); + xs.sort((a, b) => a - b); + const apart = xs.filter((x, k) => k === 0 || x - xs[k - 1] > 4); + for (let k = 1; k < apart.length; k++) assert.ok(apart[k] - apart[k - 1] >= 24, `line ${i}: ${apart[k - 1]} then ${apart[k]}`); + }); +}); + +test("Ghoul Rush's Runaway Cart: every beam can be ducked under and not stood up to, and none comes soon after a jump", () => { + assert.ok(R.beams.length >= 3, "a stretch of beams"); + for (const [x0, x1, y] of R.beams) { + assert.ok(x1 > x0 && x1 - x0 <= 8, "a beam across the track"); + let needDuck = false; + lines.forEach((L, i) => { + for (let x = Math.max(x0, L.x0); x <= Math.min(x1, L.x1); x += 0.5) { + const clear = y - ct.trackY(R, i, x); + if (clear >= ghoul.HIT_H + 0.5) continue; + assert.ok(clear > ghoul.DUCK_H + 0.3 && clear < ghoul.HIT_H - 0.3, `a beam at ${x0}: ${clear.toFixed(2)} over line ${i}, ducking needs ${ghoul.DUCK_H} and standing ${ghoul.HIT_H}`); + needDuck = true; + } + }); + assert.ok(needDuck, `the beam at ${x0} is over a line`); + // No rubble, crate or gap within a jump before it or after it, on the lines under it. + lines.forEach((L, i) => { + if (x1 < L.x0 || x0 > L.x1) return; + const marks = [...R.rubble.filter((q) => q[1] === i).map((q) => q[0]), ...R.crates.filter((q) => q[1] === i).map((q) => q[0]), L.x0, L.x1]; + for (const m of marks) assert.ok(m <= x0 - 20 || m >= x1 + 20, `beam ${x0} and a jump at ${m}`); + }); + } +}); + +test("Ghoul Rush's Runaway Cart: checkpoints every 190 to 340 units, each on a track, and passed in order", () => { + const xs = [ROOM.start, ...R.checks, R.stop]; + for (let i = 1; i < xs.length; i++) assert.ok(xs[i] - xs[i - 1] >= 190 && xs[i] - xs[i - 1] <= 340, `${xs[i - 1]} to ${xs[i]}`); + for (const x of R.checks) assert.ok(ct.linesAt(R, x).length >= 1, `a track under the checkpoint at ${x}`); + const round = cartRound(); + cartAt(round, R.checks[0] - 6, ct.linesAt(R, R.checks[0] - 6)[0][0], { safe: true }); + run(round, 600); + assert.deepEqual(events(round, "checkpoint").map((e) => e.n), [1]); + assert.equal(round.cart.check, 0); +}); + +/* ------------------------------------------------------------- the cart */ + +// A long flat track and a long slope each way, to measure the cart on. +const FLAT = [[[0, 20], [4000, 20]]]; +const DOWN = [[[0, 3000], [4000, -1000]]]; + +test("Ghoul Rush's Runaway Cart rolls at CART_V on the flat, faster down a slope and slower up one, never past CART_MIN or CART_MAX", () => { + const flat = synth({ track: FLAT }); + run(flat, 2000, { }, never); + assert.equal(flat.cart.v, ct.CART_V); + assert.ok(Math.abs(flat.you.x - (10 + ct.CART_V * 2)) < 0.5, "it covers CART_V a second"); + // A gentle slope each way settles at CART_V - SLOPE_G * slope / RELAX. + const grade = (s) => synth({ track: [[[0, 300], [600, 300 + 600 * s]]] }); + const down = grade(-0.25); + run(down, 3000); + assert.ok(Math.abs(down.cart.v - (ct.CART_V + (ct.SLOPE_G * 0.25) / ct.RELAX)) < 0.6, `down: ${down.cart.v.toFixed(1)}`); + const up = grade(0.25); + run(up, 3000); + assert.ok(Math.abs(up.cart.v - (ct.CART_V - (ct.SLOPE_G * 0.25) / ct.RELAX)) < 0.6, `up: ${up.cart.v.toFixed(1)}`); + assert.ok(up.cart.v < ct.CART_V && down.cart.v > ct.CART_V); + // A steep one hits the walls of its range. + const steepDown = grade(-0.8); + run(steepDown, 3000); + assert.equal(steepDown.cart.v, ct.CART_MAX); + const steepUp = grade(0.9); + run(steepUp, 3000); + assert.equal(steepUp.cart.v, ct.CART_MIN); + // A real descent in the room speeds the cart up. + const real = cartRound(); + cartAt(real, 295, 1); + run(real, 800); + assert.ok(real.cart.v > ct.CART_V + 5, `the camelback's descent: ${real.cart.v.toFixed(1)}`); +}); + +test("Ghoul Rush's Runaway Cart: right leans forward (to CART_V + LEAN_ACC / RELAX on the flat, CART_MAX at most), left brakes (to CART_MIN), and letting go settles back to CART_V", () => { + const lean = synth({ track: FLAT }); + run(lean, 6000, { right: true }); + assert.ok(Math.abs(lean.cart.v - (ct.CART_V + ct.LEAN_ACC / ct.RELAX)) < 0.2, `leaning: ${lean.cart.v.toFixed(2)}`); + assert.ok(lean.cart.v < ct.CART_MAX); + run(lean, 6000); + assert.ok(Math.abs(lean.cart.v - ct.CART_V) < 0.1, "settles back"); + const brake = synth({ track: FLAT }); + run(brake, 600, { left: true }); + assert.ok(brake.cart.v < ct.CART_V - 8, `braking for 0.6 s: ${brake.cart.v.toFixed(1)}`); + assert.equal(events(brake, "cartBrake").length, 1, "one screech per brake"); + run(brake, 3000, { left: true }); + assert.equal(brake.cart.v, ct.CART_MIN); + const steep = synth({ track: DOWN }); + run(steep, 3000, { right: true }); + assert.equal(steep.cart.v, ct.CART_MAX, "leaning down a slope still tops out"); + // Always facing right, whatever is held. + assert.equal(brake.you.face, 1); +}); + +test("Ghoul Rush's Runaway Cart jumps about 14 high for about three quarters of a second (a gap of about 30 at CART_V), a press saved for a landing jumps on it, one just after a track's end still jumps, and the jump is not cut short", () => { + const round = synth({ track: FLAT }); + const y0 = round.you.y; + press(round); + let top = y0; + const x0 = round.you.x; + let ms = 0; + for (; ms < 3000 && (ms === 0 || round.cart.line < 0); ms += 4) { + ghoul.advance(round, 4, steady); + top = Math.max(top, round.you.y); + round.input.up = true; + } + round.input.up = false; + assert.ok(Math.abs(top - y0 - (ct.CART_JUMP_V ** 2) / (2 * ct.CART_G)) < 0.3 && top - y0 > 13.5 && top - y0 < 14.6, `rose ${(top - y0).toFixed(2)}`); + assert.ok(ms > 720 && ms < 780, `${ms} ms in the air`); + assert.ok(Math.abs(round.you.x - x0 - 30) < 1.5, `covered ${(round.you.x - x0).toFixed(1)}`); + assert.equal(events(round, "cartJump").length, 1); + assert.equal(events(round, "cartLand").length, 1); + assert.equal(events(round, "cartLand")[0].big, false); + // Letting up go early does not cut it. + const hop = synth({ track: FLAT }); + press(hop); + hop.input.up = false; + const t = until(hop, () => hop.cart.line < 0, 100); + until(hop, () => hop.cart.line >= 0, 3000); + assert.ok(hop.you.y === 20 && events(hop, "cartJump").length === 1); + // A press in the air a moment before landing jumps as it lands. + const buf = synth({ track: FLAT }); + press(buf); + until(buf, () => buf.cart.line < 0, 100); + until(buf, () => buf.you.vy < 0 && buf.you.y - 20 < 3, 2000); + press(buf); + until(buf, () => events(buf, "cartLand").length === 1, 600); + until(buf, () => events(buf, "cartJump").length === 2, 400); + assert.equal(events(buf, "cartJump").length, 2, "a second jump on landing"); + // A press a moment after running off the end of a track still jumps; much later it does not. + const edge = synth({ track: [[[0, 20], [60, 20]], [[100, 20], [300, 20]]] }); + until(edge, () => edge.cart.line < 0, 4000); + run(edge, 40); + press(edge); + run(edge, 8); + assert.equal(events(edge, "cartJump").length, 1, "within COYOTE_MS"); + const late = synth({ track: [[[0, 20], [60, 20]], [[100, 20], [300, 20]]] }); + until(late, () => late.cart.line < 0, 4000); + run(late, ct.COYOTE_MS + 40); + press(late); + run(late, 8); + assert.equal(events(late, "cartJump").length, 0, "too late"); + // A fall from a height lands big. + const drop = synth({ track: [[[0, 60], [100, 60]], [[110, 20], [300, 20]]] }); + until(drop, () => drop.cart.line < 0, 4000); + untilLanded(drop); + assert.equal(events(drop, "cartLand")[0].big, true); +}); + +test("Ghoul Rush's Runaway Cart steers in the air: right stretches the jump and left shortens it, modestly", () => { + const land = (keys) => { + const round = synth({ track: [[[0, 20], [300, 20]], [[300, 20], [600, 20]]] }); + cartAt(round, 100, 0); + press(round); + Object.assign(round.input, keys); + until(round, () => round.cart.line < 0, 100); + Object.assign(round.input, keys); + const x0 = round.you.x; + until(round, () => round.cart.line >= 0, 3000); + round.input.left = round.input.right = false; + return round.you.x - x0; + }; + const plain = land({}); + const wide = land({ right: true }); + const short = land({ left: true }); + assert.ok(wide > plain + 2 && wide < plain + 9, `right ${wide.toFixed(1)} vs ${plain.toFixed(1)}`); + assert.ok(short < plain - 2 && short > plain - 9, `left ${short.toFixed(1)} vs ${plain.toFixed(1)}`); + // And the speed it leaves with is what it lands with. + const round = synth({ track: FLAT }); + press(round); + until(round, () => round.cart.line < 0, 100); + run(round, 300, { right: true }); + const v = round.cart.v; + assert.ok(v > ct.CART_V + 3 && v <= ct.CART_V + ct.AIR_ACC * 0.4, `${v.toFixed(1)}`); + until(round, () => round.cart.line >= 0, 3000); + assert.ok(round.cart.v >= v - 0.1, "carried to the landing"); +}); + +test("Ghoul Rush's Runaway Cart: a track ending rising is a ramp that launches the cart along its slope (a short gap needs no jump), and it lands on the line under it", () => { + const round = cartRound(); + cartAt(round, lines[1].x1 - 38, 1); + round.input.right = false; + until(round, () => events(round, "cartLaunch").length > 0, 2000); + const launch = events(round, "cartLaunch")[0]; + assert.ok(launch, "a launch off the ramp"); + assert.equal(round.cart.line, -1, "in the air"); + assert.ok(round.you.vy > 20, `launched up at ${round.you.vy.toFixed(1)}`); + assert.ok(Math.abs(launch.x - lines[1].x1) < 0.01); + const at = untilLanded(round); + assert.equal(at.line, 2, "landed on the line past the gap"); + assert.equal(events(round, "lose").length, 0); + assert.ok(at.x - lines[2].x0 >= 2, "well onto it"); + // Off a flat end with no ramp and no press: it falls off. + const flat = cartRound(); + cartAt(flat, lines[0].x1 - 6, 0); + run(flat, 1500); + assert.equal(events(flat, "cartLaunch").length, 0); + assert.equal(events(flat, "lose")[0]?.cause, "derail"); +}); + +test("Ghoul Rush's Runaway Cart lands on whichever line is under it: the split's upper line after a jump, the lower after rolling on, and the lower line dead-ends at a ramp that a jump takes back up", () => { + const forkAt = lines[3].pts[1][0]; + // Jump at the fork: the upper line. + const up = cartRound(); + cartAt(up, forkAt - 6, 3); + run(up, 100); + press(up); + run(up, 8); + assert.equal(up.cart.line, -1); + assert.equal(untilLanded(up).line, 4, "the upper line"); + // Roll on: down the dive to the lower deck. + const low = cartRound(); + cartAt(low, forkAt - 6, 3); + run(low, 1200); + assert.equal(low.cart.line, 3, "still on the lower line"); + assert.ok(low.you.y < 10, `down on the lower deck (${low.you.y.toFixed(1)})`); + assert.equal(events(low, "lose").length, 0); + // Its end: a ramp, then nothing; a jump goes back up to the upper line, none falls. + const end = lines[3].x1; + const take = cartRound(); + cartAt(take, end - 25, 3); + run(take, 400); + until(take, () => take.you.x > end - 3, 3000); + press(take); + run(take, 8); + assert.equal(untilLanded(take).line, 4, "back up onto the upper line"); + assert.equal(events(take, "lose").length, 0); + const fall = cartRound(); + cartAt(fall, end - 25, 3); + run(fall, 3000); + assert.equal(events(fall, "lose")[0]?.cause, "derail"); + // A jump from the ramp's top lands further than from the flat: the ramp adds its own rise. + assert.ok(ct.flight(R, end, lines[3].pts.at(-1)[1], ct.CART_JUMP_V + 0.4 * ct.CART_V, ct.CART_V).y > 20); + // Two lines under one x: the highest it crossed going down. + const both = ct.linesAt(R, 750); + assert.deepEqual(both.map(([line]) => line), [4, 3]); +}); + +/* ------------------------------------------------------ falling and checkpoints */ + +test("Ghoul Rush's Runaway Cart: falling off the track into the chasm costs a life (cause derail) and puts the cart back at the start, or at the last checkpoint passed, at CART_V, with the boulder BOULDER_GAP behind and every crate whole", () => { + const round = cartRound(); + cartAt(round, lines[0].x1 - 6, 0); + const lives = round.lives; + until(round, () => events(round, "lose").length > 0, 3000); + assert.equal(round.lives, lives - 1); + const lost = events(round, "lose"); + assert.equal(lost.length, 1); + assert.equal(lost[0].cause, "derail"); + assert.equal(round.phase, "crash"); + until(round, () => round.phase === "play", 3000); + assert.equal(round.phase, "play"); + assert.equal(round.you.x, ROOM.start, "back at the start: no checkpoint passed"); + assert.equal(round.you.y, ct.trackY(R, 0, ROOM.start)); + assert.equal(round.cart.v, ct.CART_V); + assert.equal(round.cart.boulder, ROOM.start - ct.BOULDER_GAP); + assert.ok(round.you.safeMs > 0, "safe a moment"); + // Past the second checkpoint: back at it, not at the start. + const later = cartRound(); + cartAt(later, R.checks[1] + 10, ct.linesAt(R, R.checks[1] + 10)[0][0], { safe: true }); + run(later, 100); + assert.equal(later.cart.check, 1); + later.cart.crates[0] = 0; + cartAt(later, lines[2].x1 - 1, 2); + later.cart.check = 1; + run(later, 1500); + assert.equal(events(later, "lose")[0]?.cause, "derail"); + until(later, () => later.phase === "play", 3000); + assert.equal(later.you.x, R.checks[1]); + assert.equal(later.you.y, ct.linesAt(R, R.checks[1])[0][1]); + assert.equal(later.cart.line, ct.linesAt(R, R.checks[1])[0][0]); + assert.equal(later.cart.v, ct.CART_V); + assert.equal(later.cart.boulder, R.checks[1] - ct.BOULDER_GAP); + assert.deepEqual([...later.cart.crates], R.crates.map(() => ct.CRATE_HP), "every crate whole again"); + assert.equal(later.cart.check, 1, "the checkpoint is kept"); + assert.ok(later.camX > R.checks[1] - 60, "the camera is back with it"); + // The clock starts over with the life. + assert.equal(later.timeMs, R.time); + // Garlic does not save you from the chasm. + const garlic = cartRound(); + cartAt(garlic, lines[0].x1 - 6, 0); + garlic.you.garlic = true; + run(garlic, 1500); + assert.equal(events(garlic, "lose")[0]?.cause, "derail"); + // Even while safe after a respawn. + const safe = cartRound(); + cartAt(safe, lines[0].x1 - 6, 0, { safe: true }); + run(safe, 1500); + assert.equal(events(safe, "lose")[0]?.cause, "derail"); +}); + +test("Ghoul Rush's Runaway Cart: the last checkpoint passed is the one kept, and passing one again does nothing", () => { + const round = cartRound(); + const x = R.checks[2] + 4; + cartAt(round, x, ct.linesAt(R, x)[0][0], { safe: true }); + run(round, 100); + assert.deepEqual(events(round, "checkpoint").map((e) => e.n), [1, 2, 3], "the ones behind are passed in order at once"); + assert.equal(round.cart.check, 2); + round.events.length = 0; + run(round, 400); + assert.equal(events(round, "checkpoint").length, 0); +}); + +/* ------------------------------------------------------ the obstacles */ + +test("Ghoul Rush's Runaway Cart: a beam costs a life (cause beam) to a cart sitting up, and passes over one ducked down into it; a jump into it hits it too", () => { + const [x0, x1, y] = R.beams[0]; + const stand = cartRound(); + cartAt(stand, x0 - 12, 3); + run(stand, 700); + assert.equal(events(stand, "lose")[0]?.cause, "beam"); + assert.equal(events(stand, "cartCrash")[0]?.what, "beam"); + const duck = cartRound(); + cartAt(duck, x0 - 12, 3); + run(duck, 700, { down: true }); + assert.equal(events(duck, "lose").length, 0); + assert.ok(duck.you.x > x1 && duck.you.y + ghoul.HIT_H > y, "right through it, ducking"); + assert.equal(events(duck, "cartDuck").length, 1); + // Ducking only on the track, and never while a jump is pressed. + const midair = cartRound(); + cartAt(midair, x0 - 40, 3); + press(midair); + run(midair, 60, { down: true }); + assert.equal(midair.you.ducking, false, "no ducking in the air"); + // Standing back up after: the hit box is full height again. + assert.equal(duck.you.ducking, true); + run(duck, 20); + assert.equal(duck.you.ducking, false); + // A jump into the beam hits it. + const jump = cartRound(); + cartAt(jump, x0 - 8, 3); + press(jump); + run(jump, 400); + assert.equal(events(jump, "lose")[0]?.cause, "beam"); + // Safe after a respawn: it passes through. + const safe = cartRound(); + cartAt(safe, x0 - 12, 3, { safe: true }); + run(safe, 700); + assert.equal(events(safe, "lose").length, 0); +}); + +test("Ghoul Rush's Runaway Cart: rubble on the rails wrecks a cart that meets it (cause crash) and is jumped", () => { + const [x, line] = R.rubble[0]; + const hit = cartRound(); + cartAt(hit, x - 20, line); + run(hit, 1200); + const lost = events(hit, "lose"); + assert.equal(lost[0]?.cause, "crash"); + assert.equal(events(hit, "cartCrash")[0]?.what, "rubble"); + const over = cartRound(); + cartAt(over, x - 20, line); + run(over, 250); + press(over); + run(over, 900); + assert.equal(events(over, "lose").length, 0); + assert.ok(over.you.x > x + 5); + // A jump too early comes down before it and the cart rolls into it all the same. + const early = cartRound(); + cartAt(early, x - 30, line); + press(early); + run(early, 1500); + assert.equal(events(early, "lose")[0]?.cause, "crash"); + // The Garlic shield takes the hit once and the cart rolls on. + const garlic = cartRound(); + cartAt(garlic, x - 20, line); + garlic.you.garlic = true; + run(garlic, 1200); + assert.equal(events(garlic, "lose").length, 0); + assert.equal(garlic.you.garlic, false); +}); + +test("Ghoul Rush's Runaway Cart: a crate is broken by two bolts (or jumped); one bolt only cracks it, and the cart that meets it whole is wrecked (cause crash)", () => { + const [x, line] = R.crates[0]; + const round = cartRound(); + cartAt(round, x - 20, line); + round.you.safeMs = 1e9; + const bolt = () => round.shots.push({ x: round.you.x + 2, y: round.you.y + ghoul.SHOT_Y, vx: 130, vy: 0, gone: 0 }); + bolt(); + run(round, 400); + assert.equal(events(round, "crateHit").length, 1); + assert.equal(round.cart.crates[0], 1, "one bolt cracks it"); + assert.equal(events(round, "crateBreak").length, 0); + bolt(); + run(round, 400); + assert.equal(events(round, "crateBreak").length, 1); + assert.equal(round.cart.crates[0], 0, "the second breaks it"); + // Broken, it is out of the way. + cartAt(round, x - 8, line); + run(round, 600); + assert.equal(events(round, "lose").length, 0, "rolled through where it stood"); + assert.ok(round.you.x > x + 3); + // A bolt that misses it high goes on. + const high = cartRound(); + cartAt(high, x - 20, line, { safe: true }); + high.shots.push({ x: x - 5, y: ct.trackY(R, line, x) + ct.CRATE_H + 2, vx: 130, vy: 0, gone: 0 }); + run(high, 200); + assert.equal(high.cart.crates[0], ct.CRATE_HP); + // Whole, it wrecks the cart. + const hit = cartRound(); + cartAt(hit, x - 20, line); + run(hit, 1200); + assert.equal(events(hit, "lose")[0]?.cause, "crash"); + assert.equal(events(hit, "cartCrash")[0]?.what, "crate"); + // Or it is jumped. + const over = cartRound(); + cartAt(over, x - 20, line); + run(over, 250); + press(over); + run(over, 900); + assert.equal(events(over, "lose").length, 0); + // Fire held from the cart really does break it: the blaster does the shooting. + const fire = cartRound(); + const [fx, fline] = R.crates[1]; + cartAt(fire, fx - 30, fline); + fire.input.fire = true; + until(fire, () => fire.cart.crates[1] === 0 || fire.phase !== "play", 3000); + fire.input.fire = false; + assert.equal(fire.cart.crates[1], 0, "two bolts from the cart"); + assert.equal(events(fire, "lose").length, 0); +}); + +test("Ghoul Rush's Runaway Cart: the boulder starts BOULDER_GAP behind, rolls at BOULDER_V, rumbles as it nears and flattens a cart that brakes too long (cause boulder), and a cart rolling on is never caught", () => { + const round = synth({ track: FLAT }); + assert.equal(round.cart.boulder, round.you.x - ct.BOULDER_GAP); + run(round, 1000); + assert.ok(Math.abs(round.cart.boulder - (10 - ct.BOULDER_GAP + ct.BOULDER_V)) < 0.2); + assert.equal(events(round, "boulderNear").length, 0, "far behind: quiet"); + // Never more than BOULDER_FAR behind however fast you go. + const fast = synth({ track: DOWN }); + run(fast, 6000, { right: true }); + assert.ok(fast.you.x - fast.cart.boulder <= ct.BOULDER_FAR + 0.5, "kept in reach"); + assert.ok(fast.you.x - fast.cart.boulder > ct.BOULDER_FAR - 1); + // Brake on the flat: it closes at BOULDER_V - CART_MIN, warns, rumbles louder, then catches you (and no random number is drawn). + const slow = synth({ track: FLAT }); + slow.input.left = true; + const when = until(slow, () => slow.phase !== "play", 12000, never); + slow.input.left = false; + assert.equal(events(slow, "lose")[0]?.cause, "boulder", `flattened after ${when} ms`); + assert.equal(events(slow, "cartCrash")[0]?.what, "boulder"); + assert.ok(when > 2500 && when < 8000, `${when} ms`); + const near = events(slow, "boulderNear"); + assert.ok(near.length >= 2, "it rumbles more than once as it nears"); + assert.ok(near.at(-1).level > near[0].level, "louder the closer"); + assert.equal(slow.cart.rumble > 0.5, true); + // Reset behind the cart after the life lost. + until(slow, () => slow.phase === "play", 3000); + assert.equal(slow.cart.boulder, slow.you.x - ct.BOULDER_GAP); + // Dawdling after a respawn does catch you too, but not at once: the gap is a head start. + slow.input.left = true; + run(slow, 2000); + assert.equal(slow.phase, "play", "not within two seconds"); + slow.input.left = false; + // The garlic shield sends the boulder back instead. + const garlic = synth({ track: FLAT }); + garlic.you.garlic = true; + garlic.input.left = true; + until(garlic, () => !garlic.you.garlic || garlic.phase !== "play", 12000); + garlic.input.left = false; + assert.equal(garlic.phase, "play"); + assert.ok(garlic.you.x - garlic.cart.boulder > 10, "knocked back"); +}); + +/* -------------------------------------------------------- the whole ride */ + +// A bot that rides the whole room: it jumps at the end of a line and at rubble, crates and slides, ducks the beams, leans when the boulder is near, and takes the upper line of the first fork (the lower, safe line of the second). +function rideBot(round) { + const { you, cart: c, input: inp } = round; + const Rd = round.spec.ride; + inp.left = inp.right = inp.down = false; + if (round.phase !== "play" || !c || c.done) { + inp.up = false; + return; + } + const L = ct.linesOf(Rd); + let jump = false; + // Leaning forward keeps the boulder off when it closes in (the chase). + if (you.x - c.boulder < 40) inp.right = true; + if (c.line >= 0) { + if (L[c.line].x1 - you.x < 2.2 && L[c.line].x1 < Rd.stop) jump = true; + const ahead = (x) => x - you.x > 3 && x - you.x < 7; + for (const [x, line] of Rd.rubble) if (line === c.line && ahead(x)) jump = true; + Rd.crates.forEach(([x, line], i) => { + if (line === c.line && c.crates[i] > 0 && x - you.x > 3 && x - you.x < 8) jump = true; + }); + for (const s of c.slides) if (s.down && s.line === c.line && ahead(s.x)) jump = true; + for (const [x0, x1] of Rd.beams) if (you.x > x0 - 9 && you.x < x1 + 3) inp.down = true; + if (c.line === 3 && you.x > Rd.track[3][1][0] - 3 && you.x < Rd.track[3][1][0]) jump = true; + } + if (jump) press(round); + else inp.up = false; +} + +function ride(round, limit = 90000, bot = rideBot) { + const seen = { lost: [], marks: [] }; + let t = 0; + for (; t < limit && round.phase !== "clear" && !round.over; t += 16) { + bot(round); + // Once out of the cart, the bot walks to the door. + if (round.cart && round.cart.done && round.phase === "play") round.input.right = true; + ghoul.advance(round, 16, steady); + for (const e of round.events) { + if (e.type === "lose") seen.lost.push(e.cause); + if (e.type === "checkpoint" || e.type === "cartStop") seen.marks.push(e.type); + } + if (round.cart && !round.cart.done) { + const off = round.you.x - round.camX; + assert.ok(off > 4 && off < 70, `the cart stays in view (${off.toFixed(1)} from the left edge at ${round.you.x.toFixed(0)})`); + } + round.events.length = 0; + } + return { ...seen, ms: t }; +} + +test("Ghoul Rush's Runaway Cart: a bot that jumps at gaps and rubble and ducks the beams rides the whole room to the buffer stop and the door in 60 to 75 seconds without losing a life, past every checkpoint, the camera never losing the cart", () => { + const round = cartRound(); + round.lives = 3; + const got = ride(round, 90000, rideBot); + assert.equal(round.phase, "clear", "through the door"); + assert.deepEqual(got.lost, []); + assert.equal(round.lives, 3); + assert.deepEqual(got.marks, [...R.checks.map(() => "checkpoint"), "cartStop"]); + assert.ok(got.ms > 60000 && got.ms < 76000, `${got.ms} ms`); + assert.equal(round.hasKey, true, "the door opened at the buffer stop"); + assert.ok(round.score > 0, "the souls along the way count"); +}); + +test("Ghoul Rush's Runaway Cart: the cart stops at the buffer, Planny steps out onto the cave floor and walks to the door, which opens at the stop and nowhere before it", () => { + const round = cartRound(); + cartAt(round, R.stop - 8, lines.length - 1, { safe: true }); + assert.equal(round.hasKey, false); + run(round, 600); + round.input.right = true; + assert.equal(events(round, "cartStop").length, 1); + assert.equal(round.cart.done, true); + assert.equal(round.hasKey, true); + assert.equal(round.you.state, "run"); + assert.equal(round.you.y, floorOf(round.you.x), "on the floor, not on a track"); + assert.equal(round.camLead, 0); + assert.equal(round.phase, "play"); + until(round, () => round.phase === "clear", 2500, steady); + round.input.right = false; + assert.equal(round.phase, "clear", "through the door"); + assert.equal(events(round, "clear").length, 1); + // And the next room is the Seam, the boss, with no cart left. + run(round, ghoul.CLEAR_MS + 100); + assert.equal(round.spec.id, "seam"); + assert.equal(round.cart, null); + assert.equal(round.camLead, 0); + // Standing at the door with the door open finishes the room straight away (the drawing test relies on it). + const door = cartRound(); + Object.assign(door.you, { x: ROOM.door, y: floorOf(ROOM.door), vy: 0, state: "run", shelf: -1, out: 0, safeMs: 0 }); + door.hasKey = true; + run(door, 20); + assert.equal(door.phase, "clear"); +}); + +test("Ghoul Rush's Runaway Cart: a bot with monsters about and the blaster held rides it to the door, losing a few lives at most, and always from the last checkpoint", () => { + const round = ghoul.newRound(9); + round.dice = 0; + through(round); + round.offer = ["mine"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "cart") through(round); + round.phase = "play"; + round.lives = 99; + round.timeMs = 1e9; + const bot = (r) => { + rideBot(r); + r.input.fire = true; + }; + const got = ride(round, 150000, bot); + assert.equal(round.phase, "clear", "through the door"); + assert.ok(got.lost.length <= 8, `${got.lost.length} lives lost: ${got.lost.join(", ")}`); + for (const cause of got.lost) assert.ok(["bat", "crash", "beam", "derail", "boulder"].includes(cause), cause); +}); + +test("Ghoul Rush's Runaway Cart: any other room is untouched by the ride (no cart, no camera lead), and the cart is not there after the room", () => { + const round = ghoul.newRound(5); + round.dice = 0; + assert.equal(round.cart, null); + assert.equal(round.camLead, 0); + const shaft = ghoul.newRound(5); + shaft.dice = 0; + through(shaft); + shaft.offer = ["mine"]; + shaft.phaseMs = 0; + ghoul.pickStage(shaft, 0); + shaft.phase = "play"; + assert.equal(shaft.cart, null); + assert.equal(shaft.camLead, 0); + assert.equal(shaft.you.x, shaft.spec.start); + // The ride's camera leads further than a walker's, and further the faster it goes. + const slow = synth({ track: FLAT }); + const fast = synth({ track: FLAT }); + fast.cart.v = ct.CART_MAX; + run(slow, 20); + run(fast, 20); + assert.ok(slow.camLead > 0 && fast.camLead > slow.camLead, `${slow.camLead.toFixed(1)} to ${fast.camLead.toFixed(1)}`); + const walk = cartRound(); + assert.ok(walk.camLead >= ct.CAM_AHEAD - 0.01); +}); + +/* ---------------------------------------------- the ledge imp and the canary */ + +test("Ghoul Rush's Runaway Cart: a ledge imp waits on its ledge, crouches when the cart is near, leaps at where the cart will be and steals your light (never a life); shot, it drops the light back", () => { + const round = cartRound(); + cartAt(round, 875, 4); + const imp = ghoul.spawnMonster(round, "ledgeimp", 903, 30, { rise: 0, awake: true }); + assert.equal(imp.act, "perch"); + run(round, 4); + assert.equal(imp.act, "crouch", "the cart is within LEDGE_NEAR of it"); + const got = []; + until(round, () => { + if (imp.act === "leap" && !got.length) got.push(events(round, "ledgeLeap")[0]); + return round.you.dimMs > 0 || imp.dead || round.phase !== "play"; + }, 4000); + assert.ok(got[0], "it leaps"); + assert.equal(round.phase, "play", "no life lost"); + assert.equal(round.lives, 3); + assert.ok(round.you.dimMs > 0 && round.you.dimBy === imp.id, "the light is stolen"); + assert.equal(events(round, "impSteal").length, 1); + assert.equal(imp.stole, true); + // Kill it and the light comes back at once. + imp.act = "fall"; + ghoul.hurt(round, imp, 99, "shot", steady); + assert.equal(round.you.dimMs, 0); + assert.equal(events(round, "impDrop").length, 1); + // Jumping it: the leap goes under. + const jumper = cartRound(); + cartAt(jumper, 875, 4); + const imp2 = ghoul.spawnMonster(jumper, "ledgeimp", 903, 30, { rise: 0, awake: true }); + run(jumper, 4); + until(jumper, () => imp2.act === "leap", 1000); + press(jumper); + run(jumper, 700); + assert.equal(jumper.you.dimMs, 0, "it went under the jump"); + // A Hard Hat is knocked off instead. + const hat = cartRound(); + cartAt(hat, 875, 4); + hat.you.hat = true; + const imp3 = ghoul.spawnMonster(hat, "ledgeimp", 903, 30, { rise: 0, awake: true }); + until(hat, () => !hat.you.hat || imp3.dead, 4000); + assert.equal(hat.you.hat, false); + assert.equal(hat.you.dimMs, 0); + assert.equal(events(hat, "hatKnock").length, 1); + // A shot imp on its ledge never leaps. + const shot = cartRound(); + cartAt(shot, 875, 4); + const imp4 = ghoul.spawnMonster(shot, "ledgeimp", 903, 30, { rise: 0, awake: true }); + ghoul.hurt(shot, imp4, 99, "shot", steady); + run(shot, 1500); + assert.equal(events(shot, "ledgeLeap").length, 0); +}); + +test("Ghoul Rush's Runaway Cart: a canary's scream brings a slide of rubble onto the track ahead after a warning, and it wrecks a cart that does not jump it", () => { + const round = cartRound(); + cartAt(round, 750, 4, { safe: true }); + round.events.push({ type: "canaryScream", kind: "canary", x: 770, y: 30, n: 0 }); + run(round, 8); + const warn = events(round, "slideWarn")[0]; + assert.ok(warn, "dust first"); + assert.ok(warn.x > round.you.x + 15 && warn.x < round.you.x + 70, `${warn.x - round.you.x} ahead`); + assert.equal(round.cart.slides.length, 1); + assert.equal(events(round, "slideFall").length, 0); + run(round, ct.SLIDE_WARN_MS); + assert.equal(events(round, "slideFall").length, 1); + // The same scream is only answered once. + run(round, 100); + assert.equal(round.cart.slides.length, 1); + // Rolling into it costs a life, jumping it does not. + const hit = cartRound(); + cartAt(hit, 750, 4); + hit.events.push({ type: "canaryScream", kind: "canary", x: 770, y: 30, n: 0 }); + run(hit, 3000); + assert.equal(events(hit, "lose")[0]?.cause, "crash"); + assert.equal(events(hit, "cartCrash")[0]?.what, "rubble"); + const over = cartRound(); + cartAt(over, 750, 4); + over.events.push({ type: "canaryScream", kind: "canary", x: 770, y: 30, n: 0 }); + until(over, () => over.cart.slides.some((s) => s.down), 3000); + const s = over.cart.slides[0]; + until(over, () => s.x - over.you.x < 6, 3000); + press(over); + run(over, 1200); + assert.equal(events(over, "lose").length, 0); + // Never on thin air: no slide where no track is under the spot. + const gap = cartRound(); + cartAt(gap, lines[2].x1 - 50, 2); + gap.events.push({ type: "canaryScream", kind: "canary", x: 380, y: 30, n: 0 }); + run(gap, 8); + assert.equal(gap.cart.slides.length, 0); + // And the real canary's scream does bring it. + const real = cartRound(); + cartAt(real, 750, 4, { safe: true }); + const bird = ghoul.spawnMonster(real, "canary", 770, 30, { rise: 0, awake: true }); + until(real, () => events(real, "canaryScream").length > 0, 3000); + assert.ok(bird && events(real, "canaryScream").length >= 1); + run(real, 20); + assert.ok(events(real, "slideWarn").length >= 1, "the real scream starts a slide"); +}); + +/* ---------------------------------------------------- endless lives and sounds */ + +test("Ghoul Rush's Runaway Cart: every new way to lose a life goes through struck or lose, so the endless-lives code spares them all", () => { + const causes = { derail: [lines[0].x1 - 6, 0], beam: [R.beams[0][0] - 12, 3], crash: [R.rubble[0][0] - 20, R.rubble[0][1]] }; + for (const [cause, [x, line]] of Object.entries(causes)) { + const round = cartRound(); + round.infinite = true; + cartAt(round, x, line); + run(round, 1500); + assert.equal(events(round, "lose")[0]?.cause, cause, cause); + assert.equal(round.lives, 3, `${cause}: endless lives`); + } + const crate = cartRound(); + crate.infinite = true; + cartAt(crate, R.crates[0][0] - 20, R.crates[0][1]); + run(crate, 1500); + assert.equal(events(crate, "lose")[0]?.cause, "crash"); + assert.equal(crate.lives, 3); + const slow = synth({ track: FLAT }); + slow.infinite = true; + slow.input.left = true; + until(slow, () => slow.phase !== "play", 12000); + assert.equal(events(slow, "lose")[0]?.cause, "boulder"); + assert.equal(slow.lives, 3); + // Every cause is words and a sound of its own. + for (const cause of ["beam", "crash", "boulder", "derail"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Runaway Cart: every event the pack emits has a voice, each a real tone played once, and the ledge imp has one for each act", () => { + const listed = { + cart: ["jump", "land", "launch", "brake", "duck", "crash", "stop", "check"], + crate: ["hit", "break"], + boulder: ["near"], + slide: ["warn", "fall"], + ledgeimp: ["appear", "leap", "hurt", "die"], + }; + for (const [kind, acts] of Object.entries(listed)) assert.deepEqual(Object.keys(CART_VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + for (const type of ct.EVENTS) assert.ok(EVENT_VOICE[type] || ["impSteal", "impDrop", "hatKnock"].includes(type), `${type} is heard`); + for (const type of Object.keys(EVENT_VOICE)) assert.ok(ct.EVENTS.includes(type), `${type} is an event of the pack`); + assert.equal(new Set(ct.EVENTS).size, ct.EVENTS.length); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(listed[kind].includes(act), `${type}: ${kind} ${act} is a listed act`); + assert.deepEqual(heard({ type, kind: kind === "ledgeimp" ? kind : undefined, level: 1 }).played, [VOICES[kind][act]], `${type}: ${kind} ${act}, once`); + } + // Each listed act is the voice of an event or of the game's own play of it. + const reached = new Set(Object.values(EVENT_VOICE).map(([kind, act]) => `${kind}.${act}`)); + const theGames = ["ledgeimp.appear", "ledgeimp.hurt", "ledgeimp.die"]; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(reached.has(`${kind}.${act}`) || theGames.includes(`${kind}.${act}`), `${kind}.${act} is played by something`); + const once = (e, kind, act) => assert.equal(heard(e).played.filter((n) => n === VOICES[kind][act]).length, 1, `${e.type}: ${kind} ${act} once`); + once({ type: "spawn", kind: "ledgeimp" }, "ledgeimp", "appear"); + once({ type: "hit", kind: "ledgeimp" }, "ledgeimp", "hurt"); + once({ type: "kill", kind: "ledgeimp", mult: 1, how: "shot", points: 1 }, "ledgeimp", "die"); + // The imp's theft is the Mine's own, played once as well. + assert.deepEqual(heard({ type: "impSteal", kind: "ledgeimp" }).played, [VOICES.imp.steal]); +}); + +/* --------------------------------------------------------------- drawing */ + +test("Ghoul Rush's Runaway Cart draws: the room in a lit and a dark one, the cart on the track, in the air and ducking, a crash, the beams, rubble, whole and broken crates, a slide's dust and its heap, the boulder near and far, the ledge imp in each act, and the stage's card", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["mine"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + while (r.spec.id !== "cart") through(r); + r.lives = 99; + const spots = [[ROOM.start + 40, 0], [lines[3].pts[1][0] - 6, 3], [R.beams[0][0] - 5, 3], [R.rubble[0][0] - 10, 0], [R.crates[0][0] - 10, 2], [812, 4], [lines[3].x1 - 20, 3], [R.stop - 30, lines.length - 1]]; + for (const dark of [true, false]) { + for (const [x, line] of spots) { + r.dark = dark; + r.phase = "play"; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + cartAt(r, x, line, { safe: true }); + r.cart.crates[0] = x < 300 ? 1 : 2; + r.cart.crates[1] = 0; + r.cart.slides = [{ x: x + 20, line, y: ct.trackY(R, line, x) ?? 10, warn: 400, down: false }, { x: x + 30, line, y: ct.trackY(R, line, x) ?? 10, warn: 0, down: true }]; + for (const act of ["perch", "crouch", "leap", "fall"]) ghoul.spawnMonster(r, "ledgeimp", x + 8 + (act.length % 4) * 3, 24, { rise: 0, awake: true, act, wait: 1e9, vx: 0, vy: 0, stole: act === "fall" }); + for (const air of [false, true]) { + if (air) Object.assign(r.you, { state: "air", vy: 20, y: r.you.y + 4 }); + if (air) r.cart.line = -1; + r.you.ducking = x > R.beams[0][0] - 8 && !air; + r.cart.boulder = x - (air ? 2 : 30); + for (let k = 0; k < 4; k++) g.tick(16); + r.monsters.length = 0; + r.you.safeMs = 1e9; + cartAt(r, x, line, { safe: true }); + } + } + } + assert.equal(r.spec.id, "cart"); + // The crash and the stop on the way out, the next room and the card. + r.you.safeMs = 0; + cartAt(r, R.rubble[0][0] - 3, R.rubble[0][1]); + for (let k = 0; k < 30; k++) g.tick(16); + assert.ok(r.bonusRound.hearts < r.bonusRound.max || r.phase !== "play", "the crash draws too"); + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.stageSelect(); + const p = pick.round; + const at = ghoul.STAGES.findIndex((s) => s.id === "mine"); + for (let i = 0; i < at; i++) ghoul.steerSelect(p, 1, 0); + for (let i = 0; i < 3; i++) ghoul.steerSelect(p, 0, 1); + assert.equal(p.select.room, 3); + pick.tick(16); + ghoul.takeSelect(p); + assert.equal(p.spec.id, "cart"); + assert.equal(p.dark, true, "always dark"); + assert.equal(p.cart.line, 0); + assert.equal(p.you.y, ct.trackY(R, 0, ROOM.start)); + pick.tick(16); +}); + +/* ----------------------------------------------------------- the bonus round */ + +// The ride as play reaches it, with its bonus round (cartRound turns it off for the ride's own tests). +const bonusCart = () => cartRound(true); + +// A bot that rides without jumping the first heap of rubble (so it costs a heart). +const hurtBot = (r) => { + rideBot(r); + // A respawn wakes the room's monsters again; this ride is about the heap alone. + for (const st of r.spawns) st.over = true; + r.monsters.length = 0; + if (r.you.x > 70 && r.you.x < 86 && r.cart && !r.cart.done && r.bonusRound.hearts === 5) { + r.input.up = false; + r.input.jump = 0; + } +}; + +const awardKit = { ROOM_POINTS: 300, award: (rd, pts) => (rd.score += pts) }; + +test("Ghoul Rush's bonus round: the Runaway Cart is one (room flag bonus), a round gets five hearts of its own on entering it, none in any other room, and the intro shows first", () => { + assert.equal(ROOM.bonus, true); + assert.equal(ghoul.roomById("shaft").bonus, false); + assert.equal(ghoul.roomById("seam").bonus, false); + assert.equal(BONUS_HEARTS, 5); + const round = ghoul.newRound(5); + round.dice = 0; + round.lives = 3; + assert.equal(round.bonusRound, null, "not in the hall"); + through(round); + round.offer = ["mine"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + assert.equal(round.bonusRound, null, "not in the shaft"); + while (round.spec.id !== "cart") through(round); + const b = round.bonusRound; + assert.deepEqual({ hearts: b.hearts, max: b.max, dice: b.dice, over: b.over }, { hearts: 5, max: 5, dice: 0, over: false }); + assert.equal(round.phase, "ready"); + assert.ok(round.phaseMs > 1500, `${round.phaseMs} ms to read the banner`); + assert.equal(events(round, "bonusStart").length, 1); + assert.ok(round.events.findLastIndex((e) => e.type === "bonusStart") < round.events.findLastIndex((e) => e.type === "room"), "the bonus banner comes before the room's name"); + assert.equal(round.lives, 3); + assert.equal(b.perf.total, R.beams.length + R.rubble.length + R.crates.length); + // The pill, drawn where the lives are, marked BONUS. + const hud = { room: "A", stage: "B", time: 9, timeLow: false, bonus: 5, hearts: heartsText(b), chain: 0, chainFill: 1, key: false, effects: [], gauge: null, arm: null }; + const pills = hudLayout(20, 900, 3, hud, 30).map((q) => q.text); + assert.ok(pills.includes("BONUS ♥♥♥♥♥"), pills.join("|")); + assert.ok(!pills.includes("BONUS 5"), "the time bonus pill gives way to it"); + b.hearts = 2; + assert.equal(heartsText(b), "BONUS ♥♥♡♡♡"); +}); + +test("Ghoul Rush's bonus round: a hit costs one bonus heart and no life, the ride rolls on with a blinking safe moment, no respawn; Lucky dice in hand are not rolled; Garlic still saves the heart; a derail costs a heart too", () => { + const round = bonusCart(); + round.dice = 4; + const [x, line] = R.rubble.find(([rx]) => rx > R.checks[1] + 40); + cartAt(round, x - 10, line); + round.cart.check = 1; + run(round, 600); + assert.equal(events(round, "lose")[0]?.cause, "crash"); + assert.equal(events(round, "lose")[0].hearts, 4); + assert.equal(round.bonusRound.hearts, 4); + assert.equal(round.lives, 3, "the run's lives are untouched"); + assert.equal(round.dice, 4, "and so are the dice (none rolled for a bonus heart)"); + assert.equal(round.phase, "play", "the ride never stops for a heart"); + assert.ok(round.you.x > x - 10, "and he is not sent back"); + assert.ok(round.you.safeMs > 0, "safe a moment (he blinks)"); + assert.ok(round.you.safeMs <= ghoul.BONUS_SAFE_MS, "a brief one"); + assert.equal(events(round, "respawn").length, 0, "no respawn"); + assert.equal(round.bonusRound.perf.hits.length, 1, "the heap is noted as hit"); + assert.equal(round.over, false); + // Garlic is spent first. + const garlic = bonusCart(); + cartAt(garlic, R.rubble[0][0] - 10, R.rubble[0][1]); + garlic.you.garlic = true; + run(garlic, 800); + assert.equal(garlic.bonusRound.hearts, 5); + assert.equal(garlic.you.garlic, false); + // A fall off the track costs a heart as well, whatever protects him. + const fall = bonusCart(); + cartAt(fall, lines[0].x1 - 6, 0); + fall.you.garlic = true; + run(fall, 1500); + assert.equal(events(fall, "lose")[0]?.cause, "derail"); + assert.equal(fall.bonusRound.hearts, 4); + assert.equal(fall.lives, 3); + assert.equal(fall.phase, "play", "a derail keeps the ride going"); + assert.ok(fall.cart.line >= 0 && fall.you.state === "run", "and puts him back on the track"); + assert.ok(fall.you.safeMs > 0 || fall.you.garlic === false, "safe a moment"); +}); + +test("Ghoul Rush's bonus round: the fifth lost heart ends it with no dice and no cost to the run (no game over), and the run goes on to the next room with its dice, lives and score", () => { + const round = bonusCart(); + round.dice = 2; + const score = round.score; + for (let i = 0; i < 5; i++) { + assert.equal(round.phase, "play", `heart ${i + 1}`); + cartAt(round, lines[0].x1 - 6, 0); + round.you.safeMs = 0; + run(round, 1500); + until(round, () => round.phase !== "crash", 3000); + if (i < 4) until(round, () => round.phase === "play", 3000); + } + const b = round.bonusRound; + assert.equal(b.hearts, 0); + assert.equal(b.over, true); + assert.equal(b.won, false); + assert.deepEqual({ ...b.result }, { won: false, dice: 0, gained: 0 }); + const end = events(round, "bonusEnd"); + assert.equal(end.length, 1); + assert.equal(end[0].won, false); + assert.equal(end[0].dice, 0); + assert.equal(round.over, false, "no game over"); + assert.equal(round.lives, 3, "no run life lost"); + assert.equal(round.dice, 2, "dice untouched"); + assert.ok(round.score >= score, "candy picked up on the way counts, nothing is taken"); + assert.equal(round.phase, "clear"); + assert.ok(round.phaseMs <= ghoul.CARD_LOST_MS && ghoul.CARD_LOST_MS <= 2600, "a short card"); + // On to the Seam, as ever. + run(round, ghoul.CARD_LOST_MS + 100); + assert.equal(round.spec.id, "seam"); + assert.equal(round.bonusRound, null); + assert.equal(round.cart, null); + assert.equal(round.lives, 3); + assert.equal(round.dice, 2); + assert.equal(round.phase, "ready"); + // A life lost there is a run life as always, and the dice roll for it. + round.phase = "play"; + ghoul.lose(round, "zombie"); + assert.equal(round.phase, "roll", "the carried dice are rolled"); +}); + +test("Ghoul Rush's bonus round: endless lives (round.infinite) spare the hearts as they spare lives, through the same lose path", () => { + const round = bonusCart(); + round.infinite = true; + for (let i = 0; i < 7; i++) { + cartAt(round, lines[0].x1 - 6, 0); + round.you.safeMs = 0; + run(round, 1500); + until(round, () => round.phase === "play", 3000); + } + assert.ok(events(round, "lose").length >= 7); + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.bonusRound.over, false); + assert.equal(round.lives, 3); +}); + +test("Ghoul Rush's bonus round: finishing alive pays 3 to 9 Lucky dice, added to the run's, more for a better ride (hearts, clean passes, things shot or broken)", () => { + const clean = bonusCart(); + const got = ride(clean, 120000, rideBot); + assert.equal(clean.phase, "clear"); + assert.deepEqual(got.lost, []); + const b = clean.bonusRound; + assert.equal(b.over, true); + assert.equal(b.won, true); + assert.equal(b.hearts, 5); + assert.ok(b.dice >= BONUS_FLOOR && b.dice <= ghoul.MAX_DICE, `${b.dice} dice`); + assert.equal(clean.dice, b.dice, "added to the run's"); + assert.deepEqual({ ...b.result }, { won: true, dice: b.dice, gained: b.dice }); + assert.equal(clean.lives, 3); + // A hit costs a heart and a clean pass: fewer dice than the clean ride. + const hurt = bonusCart(); + const got2 = ride(hurt, 120000, hurtBot); + assert.equal(hurt.phase, "clear"); + assert.ok(got2.lost.length >= 1, "it hit the first heap"); + assert.ok(hurt.bonusRound.dice >= BONUS_FLOOR, "never under the floor"); + assert.ok(hurt.bonusRound.dice < b.dice, `${hurt.bonusRound.dice} dice against ${b.dice}`); + // Shooting on the way raises it: with the blaster held and the monsters about, crates break and bats fall. + const shooter = bonusCart(); + for (const st of shooter.spawns) st.over = false; + shooter.hordeMs = 3000; + shooter.lives = 99; + shooter.bonusRound.hearts = 99; + const shoot = (r) => { + rideBot(r); + r.input.fire = true; + }; + ride(shooter, 150000, shoot); + assert.equal(shooter.phase, "clear"); + assert.ok(shooter.bonusRound.perf.acts + (shooter.stats.kills - shooter.bonusRound.perf.kills0) >= 8, "crates broken and monsters shot"); + assert.ok(shooter.bonusRound.dice >= BONUS_FLOOR + 1); +}); + +test("Ghoul Rush's bonus round: the dice formula (floor 3, up to six more by hearts, clean obstacles, things shot or broken, and no braking), the cap at nine, and braking costs the steady die", () => { + const mk = (hearts, perf = {}) => { + const b = makeBonus({ stats: { kills: 0 } }); + b.hearts = hearts; + Object.assign(b.perf, { total: 10 }, perf); + return b; + }; + const all = Array.from({ length: 10 }, (_, i) => `o${i}`); + assert.equal(diceFor(mk(1, { hits: all, steady: false })), 3, "the floor"); + assert.equal(diceFor(mk(1, { hits: [], steady: false })), 3 + 2, "clean only"); + assert.equal(diceFor(mk(5, { hits: all, steady: false })), 5, "hearts only"); + assert.equal(diceFor(mk(3, { hits: all, steady: false })), 4); + assert.equal(diceFor(mk(5, { hits: [], acts: 8, steady: true })), 9, "a perfect ride is the cap"); + assert.equal(diceFor(mk(5, { hits: [], acts: 7, steady: true })), 8, "one short of the goal"); + assert.equal(diceFor(mk(5, { hits: all.slice(0, 5), acts: 8, steady: true })), 3 + 2 + 1 + 1 + 1); + assert.ok(diceFor(mk(5, { hits: [], acts: 99 })) <= ghoul.MAX_DICE); + assert.equal(diceFor(mk(5, { hits: [], acts: 0, total: 0 })), 3 + 2 + 0 + 0 + 1, "no obstacles counted"); + // Kills count with the acts. + assert.equal(diceFor(mk(5, { hits: [], acts: 4, goal: 8 }), 4), 9); + // The cap on the run's dice: eight in hand and a nine-die ride leaves nine. + const round = bonusCart(); + round.dice = 8; + Object.assign(round.bonusRound.perf, { hits: [], acts: 8 }); + assert.equal(endBonus(round, true, awardKit), true); + assert.equal(round.dice, ghoul.MAX_DICE); + assert.equal(round.bonusRound.dice, 9, "earned nine"); + assert.equal(round.bonusRound.gained, 1, "one more fits"); + assert.equal(endBonus(round, true, awardKit), false, "ends once"); + // Braking: a short brake is fine, too long is no steady hand. + const brake = bonusCart(); + cartAt(brake, 300, 1, { safe: true }); + run(brake, 1000, { left: true }); + assert.equal(brake.bonusRound.perf.steady, true); + const more = bonusCart(); + cartAt(more, 2100, 9, { safe: true }); + more.cart.boulder = 2000; + run(more, ct.STEADY_BRAKE_MS + 400, { left: true }); + assert.equal(more.bonusRound.perf.steady, false); + assert.ok(more.bonusRound.perf.brakeMs > ct.STEADY_BRAKE_MS); +}); + +test("Ghoul Rush's bonus round: the card, the pills and the heart-lost words draw (won with dice tumbling in, lost, a heart down), and click as each die lands", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["mine"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + while (r.spec.id !== "cart") through(r); + assert.ok(g.hud.hearts.startsWith("BONUS ♥♥♥♥♥")); + r.phase = "play"; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + for (let k = 0; k < 4; k++) g.tick(16); + // A heart down. + ghoul.lose(r, "crash"); + for (let k = 0; k < 4; k++) g.tick(16); + assert.ok(g.hud.hearts.includes("♡")); + for (const won of [false, true]) { + r.phase = "play"; + r.bonusRound.over = false; + r.bonusRound.hearts = 4; + r.you.out = 0; + r.you.safeMs = 0; + const b = r.bonusRound; + endBonus(r, won, awardKit); + const dice = b.dice; + for (let k = 0; k < (won ? 400 : 30) && r.phase === "clear"; k++) g.tick(16); + assert.equal(b.won, won); + assert.equal(dice > 0, won); + } + // The tones: one click per die that has landed, once each. + const played = []; + const fx = {}; + const kit = { tone: (n) => played.push(n), fx }; + const round2 = { bonusRound: { over: true, won: true, dice: 5, cardMs: 4600 }, phase: "clear", phaseMs: 4600 - 2300 }; + bonusTick(round2, kit); + assert.equal(fx.bonusLanded, 5, "all five by 2.3 s"); + assert.equal(played.filter((n) => n === "thunk").length, 5); + bonusTick(round2, kit); + assert.equal(played.filter((n) => n === "thunk").length, 5, "each lands once"); + assert.ok(heard({ type: "bonusEnd", won: true, dice: 5, x: 10, y: 6 }, { fx: {} }).played.includes("fanfare")); + const banner = []; + heard({ type: "bonusStart", hearts: 5, max: 5 }, { banner: (t, sub) => banner.push([t, sub]) }); + assert.equal(banner[0][0], "BONUS ROUND"); + assert.ok(banner[0][1].includes("5 hearts")); + const floats = []; + heard({ type: "lose", cause: "crash", hearts: 2, lives: 3 }, { float: (x, y, text) => floats.push(text) }); + assert.ok(floats.includes("2 hearts left")); + const respawn = []; + heard({ type: "respawn", hearts: 1, lives: 3 }, { banner: (t, sub) => respawn.push(sub) }); + assert.equal(respawn[0], "1 bonus heart left"); +}); + +test("Ghoul Rush's Runaway Cart: the chase (the boulder surges 1.55 times faster over a span) flattens a cart that never leans and spares one that holds right, and warns once", () => { + const [x0, x1, mult] = R.surge[0]; + assert.equal(ct.surgeAt(R, x0 - 1), 1); + assert.equal(ct.surgeAt(R, x0 + 1), mult); + assert.equal(ct.surgeAt(R, x1 + 1), 1); + const chase = (lean) => { + const round = cartRound(); + const line = ct.linesAt(R, x0 - 4)[0][0]; + cartAt(round, x0 - 4, line); + round.cart.boulder = round.you.x - ct.BOULDER_GAP; + let t = 0; + for (; t < 12000 && round.you.x < x1 + 10 && round.phase === "play"; t += 16) { + rideBot(round); + round.input.right = lean; + ghoul.advance(round, 16, steady); + } + return { round, lost: events(round, "lose")[0]?.cause }; + }; + const slack = chase(false); + assert.equal(slack.lost, "boulder", "never leaning, it is caught"); + const lean = chase(true); + assert.equal(lean.lost, undefined, `leaning, it stays ahead (${lean.lost} at ${lean.round.you.x.toFixed(0)}, gap ${(lean.round.you.x - lean.round.cart.boulder).toFixed(1)}, v ${lean.round.cart.v.toFixed(1)})`); + assert.equal(events(lean.round, "boulderSurge").length, 1); + assert.ok(lean.round.you.x - lean.round.cart.boulder > ct.BOULDER_CATCH + 5); +}); diff --git a/scripts/test-web-console-activities-ghoul-chapel.mjs b/scripts/test-web-console-activities-ghoul-chapel.mjs new file mode 100644 index 0000000..1c2d018 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-chapel.mjs @@ -0,0 +1,1109 @@ +// Web console tests, Ghoul Rush's Chapel stage: its four rooms, gargoyles that are stone on their perch and dive when you pass under, choir ghosts whose song quickens the monsters near them, censer monks and their smoke, bats in the bells, the bell toll that freezes everything for a second, Holy Water (found only here), and the Choirmaster, whose organ pipes guard him and whose columns of notes have one gap each. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as ch from "../src/web-console/public/activities/ghoul-chapel.js"; +import { LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-chapel-draw.js"; +import { PILL_WORDS, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import * as sfxChapel from "../src/web-console/public/activities/ghoul-sfx-chapel.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Chapel's room `id`, reached the way play reaches it, +// nothing woken: every spawner spent, the horde held back. +function chapelRound(id) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["chapel"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, steady); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +// Runs until `done()` (or `ms` have passed), 4 ms at a time. +function until(round, done, ms = 4000) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, steady); +} + +// Runs `ms`, returning each event of `type` as [the round's clock, event]. +function log(round, ms, type, random = steady) { + const got = []; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + for (const e of round.events) if (e.type === type) got.push([round.clock, e]); + round.events.length = 0; + } + return got; +} + +// A bolt arriving from the left at height `y` on the monster `m`. +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +const heard = (e, extra = {}) => { + const played = []; + const floats = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: (x, y, text) => floats.push(text), ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played, floats }; +}; + +test("Ghoul Rush's Chapel is a stage of three rooms and the Choir's, its monsters and boss joined to the game's, with Holy Water and a place for each kind", () => { + const st = ghoul.stageById("chapel"); + assert.deepEqual(st.rooms, ["nave", "tower", "loft", "choir"]); + assert.equal(st.boss, "choirmaster"); + assert.equal(st.title, "The Chapel"); + assert.equal(st.sub, "Service is still in session"); + for (const kind of Object.keys(ch.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], ch.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.choirmaster, ch.BOSSES.choirmaster); + assert.equal(ch.BOSSES.choirmaster.sub, "Silence the pipes one by one"); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [nave, tower, loft, choir] = st.rooms.map((id) => ghoul.roomById(id)); + for (const room of [nave, tower, loft]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + assert.ok(room.items.some((i) => i[0] === "holy"), `${room.id}: Holy Water`); + assert.ok(room.spawns.some((s) => s[0] in ch.MONSTERS), `${room.id}: some of the new monsters`); + } + assert.equal(choir.boss, "choirmaster"); + assert.equal(choir.horde.length, 0); + assert.ok(choir.shelves.length >= 3, "boards for the staff's higher gaps"); + // The tower and the choir are where the bell tolls; they get harder in order. + assert.deepEqual([nave.toll, tower.toll, loft.toll, choir.toll], [0, 12000, 0, 12000]); + assert.ok(nave.spawns.length <= tower.spawns.length && tower.spawns.length <= loft.spawns.length); + assert.ok(nave.hordeMs > tower.hordeMs && tower.hordeMs > loft.hordeMs); + // The nave has pews to hop along, the tower a climb of stacked boards, bells with bats in them and gargoyles. + assert.ok(nave.shelves.filter((s) => s[2] === 11).length >= 6, "pews"); + assert.ok(tower.spawns.some((s) => s[0] === "bellbat") && tower.spawns.some((s) => s[0] === "gargoyle")); + assert.ok(loft.spawns.some((s) => s[0] === "gargoyle") && loft.spawns.some((s) => s[0] === "monk") && loft.spawns.some((s) => s[0] === "chorister")); + // The monsters keep their places. + assert.equal(ch.MONSTERS.gargoyle.perch, true, "a spawn row names the height of its perch"); + assert.equal(ch.MONSTERS.bellbat.hp, 1); + assert.equal(ch.MONSTERS.chorister.hp, 3); + assert.equal(ch.MONSTERS.monk.hp, 4); +}); + +/* ------------------------------------------------------- the gargoyle */ + +test("Ghoul Rush's gargoyle is stone on its perch: shots glance off, a stomp does nothing and it hurts nothing", () => { + const round = chapelRound("loft"); + standAt(round, 30); + round.you.safeMs = 1e9; + const g = put(round, "gargoyle", 90, { y: 30 }); + assert.equal(g.act, "perch"); + assert.equal(ghoul.solid(g), false, "stone: nothing touches it"); + round.shots.push({ x: 87, y: 31, vx: 80, vy: 0, gone: 0 }); + run(round, 120); + assert.equal(g.hp, g.max, "the bolt glanced off"); + assert.ok(events(round, "glance").length >= 1, "and said so"); + assert.equal(round.shots.length, 0, "the bolt is spent"); + // Standing in its place on the board hurts nothing. + Object.assign(round.you, { x: 90, y: 30, state: "run" }); + run(round, 20); + assert.equal(events(round, "lose").length, 0); + // Landing on its head is no stomp. + standAt(round, 90, 1, 40); + Object.assign(round.you, { state: "air", vy: -20, safeMs: 1e9 }); + until(round, () => round.you.y <= 30.5, 400); + assert.equal(events(round, "stomp").length, 0, "a stomp does nothing"); + assert.equal(g.act, "perch"); +}); + +test("Ghoul Rush's gargoyle wakes when you pass under it, dives at you, then flies back to its perch and turns to stone again", () => { + const round = chapelRound("loft"); + standAt(round, 90 + ch.GARGOYLE_NEAR + 8); + round.you.safeMs = 1e9; + const g = put(round, "gargoyle", 90, { y: 30 }); + run(round, 200); + assert.equal(g.act, "perch", "you are not under it"); + // Level with it (on its board), near, is not passing under. + const level = chapelRound("loft"); + standAt(level, 114, 1, 15, 0); + level.you.safeMs = 1e9; + const l = put(level, "gargoyle", 118, { y: 15 }); + run(level, 300); + assert.equal(l.act, "perch"); + // Under it: it shakes loose, still stone. + standAt(round, 90 - ch.GARGOYLE_NEAR + 2, 1); + round.you.safeMs = 1e9; + run(round, 8); + assert.equal(g.act, "wake"); + assert.equal(events(round, "gargoyleWake").length, 1); + assert.equal(ghoul.solid(g), false, "still stone while it shakes"); + run(round, ch.GARGOYLE_WAKE_MS - 40); + assert.equal(g.act, "wake"); + assert.equal(g.y, 30); + run(round, 80); + assert.equal(g.act, "dive"); + assert.equal(events(round, "gargoyleDive").length, 1); + assert.equal(ghoul.solid(g), true, "flesh and stone, hurting, hit by a bolt"); + // It comes down at where you are, fast. + const y0 = g.y; + run(round, 300); + assert.ok(g.y < y0 - 5 && g.x < 90, `it dives (${g.x.toFixed(1)}, ${g.y.toFixed(1)})`); + // Then it goes back up to its perch and sits there stone again. + round.you.safeMs = 1e9; + until(round, () => g.act === "perch", 6000); + assert.equal(g.act, "perch"); + assert.equal(events(round, "gargoylePerch").length, 1); + assert.deepEqual([g.x, g.y], [90, 30], "back where it began"); + assert.equal(ghoul.solid(g), false); +}); + +test("Ghoul Rush's diving gargoyle hurts you, can be shot or stomped while it flies, and a stomp on a perched one does nothing", () => { + const round = chapelRound("loft"); + standAt(round, 60); + put(round, "gargoyle", 66, { y: 30 }); + run(round, ch.GARGOYLE_WAKE_MS + 600); + assert.equal(events(round, "lose")[0]?.cause, "gargoyle"); + const shot = chapelRound("loft"); + standAt(shot, 60); + shot.you.safeMs = 1e9; + const d = put(shot, "gargoyle", 90, { y: 20, act: "dive", dive: -1, vx: 0, vy: 0 }); + assert.equal(ghoul.solid(d), true); + for (let k = 0; k < 4; k++) bolt(shot, d, d.y + 2); + ghoul.advance(shot, 4, steady); + assert.ok(d.hp < d.max, "a bolt hurts it in the air"); + // Landing on one in the air is a stomp. + const top = chapelRound("loft"); + top.you.safeMs = 1e9; + const s = put(top, "gargoyle", 90, { y: 12, act: "dive", dive: -1, vx: 0, vy: 0 }); + standAt(top, 90, 1, 12 + s.h + 3); + Object.assign(top.you, { state: "air", vy: -20, safeMs: 1e9 }); + until(top, () => events(top, "stomp").length > 0, 600); + assert.equal(events(top, "stomp").length, 1, "stomped from above"); + assert.equal(s.dead, true); +}); + +test("Ghoul Rush's Holy Water breaks a stone gargoyle even while it perches", () => { + const round = chapelRound("loft"); + standAt(round, 30); + round.you.safeMs = 1e9; + ghoul.applyPower(round, "holy"); + const g = put(round, "gargoyle", 90, { y: 30 }); + round.shots.push({ x: 87, y: 31, vx: 80, vy: 0, gone: 0 }); + run(round, 120); + assert.equal(round.monsters.includes(g), false, "gone"); + assert.equal(events(round, "kill")[0]?.how, "holy"); + assert.equal(events(round, "glance").length, 0); +}); + +/* ------------------------------------------------------- the choir ghost */ + +test("Ghoul Rush's choir ghost drifts toward you, sings for 2.5 s now and then, and while it sings the monsters near it move 1.4 times as fast", () => { + const travel = (sing) => { + const round = chapelRound("nave"); + standAt(round, 20); + round.you.safeMs = 1e9; + const c = put(round, "chorister", 70, { y: 20, songIn: sing ? 0 : 1e9 }); + const z = put(round, "monk", 64, { throwIn: 1e9 }); + const x0 = z.x; + run(round, 1000); + return { c, z, moved: x0 - z.x, round }; + }; + const quiet = travel(false); + const loud = travel(true); + assert.ok(loud.moved > quiet.moved * 1.25, `sped up (${loud.moved.toFixed(2)} to ${quiet.moved.toFixed(2)})`); + assert.ok(loud.moved < quiet.moved * 1.6, "by about 1.4"); + // The song: one event to start, one to stop, 2.5 s apart. + const round = chapelRound("nave"); + standAt(round, 20); + round.you.safeMs = 1e9; + const c = put(round, "chorister", 60, { y: 20, songIn: 0 }); + const start = log(round, 40, "choirSing"); + assert.equal(start.length, 1); + assert.ok(c.sing > 0); + const stop = log(round, ch.SONG_MS + 100, "choirHush"); + assert.equal(stop.length, 1); + assert.ok(Math.abs(stop[0][0] - start[0][0] - ch.SONG_MS) < 60, `${stop[0][0] - start[0][0]} ms`); + assert.equal(c.sing, 0); + // It drifts toward you slowly, and sings again later. + assert.ok(c.x < 60, "drifting your way"); + assert.ok(ch.MONSTERS.chorister.speed <= 6); + // Far from the singer a monster is not quickened; a monster of the singer's own is. + const far = chapelRound("nave"); + standAt(far, 20); + far.you.safeMs = 1e9; + put(far, "chorister", 80, { y: 12, songIn: 0 }); + const near = put(far, "monk", 70, { throwIn: 1e9 }); + const away = put(far, "monk", 80 + ch.HASTE_RANGE + 10, { throwIn: 1e9 }); + run(far, 100); + assert.ok(near.hasteMs > 0, "the near one is quickened"); + assert.ok(!(away.hasteMs > 0), "the far one is not"); + run(far, ch.SONG_MS + 400); + assert.ok(!(near.hasteMs > 0), "and slows once it stops"); +}); + +/* ----------------------------------------------------------- the monk */ + +test("Ghoul Rush's censer monk walks at you and puffs a harmless cloud of smoke about 10 wide that lasts 4 s", () => { + const round = chapelRound("nave"); + standAt(round, 20); + round.you.safeMs = 1e9; + const m = put(round, "monk", 50, { throwIn: 0 }); + const x0 = m.x; + run(round, 20); + assert.equal(events(round, "censerWind").length, 1); + assert.equal(round.hazards.length, 0, "the censer swings first"); + run(round, ch.CENSER_WIND_MS + 40); + assert.equal(events(round, "smokePuff").length, 1); + const cloud = round.hazards.find((h) => h.kind === "smoke"); + assert.ok(cloud, "a cloud"); + assert.equal(cloud.w, 10); + assert.ok(m.x < x0, "it walked at you"); + // Harmless: standing in it costs nothing. + Object.assign(round.you, { x: cloud.x, safeMs: 0 }); + round.monsters.length = 0; + run(round, 400); + assert.equal(events(round, "lose").length, 0); + assert.equal(cloud.life > 0, true); + // It thins away after about 4 s and not before. + const left = cloud.life; + run(round, left - 100); + assert.ok(round.hazards.includes(cloud)); + run(round, 140); + assert.equal(round.hazards.includes(cloud), false); + assert.ok(left > ch.SMOKE_MS - 700 && left <= ch.SMOKE_MS); + // Never more than SMOKE_CAP at once, and a shot monk (4 bolts) dies. + const crowd = chapelRound("nave"); + standAt(crowd, 20); + crowd.you.safeMs = 1e9; + for (let k = 0; k < 6; k++) put(crowd, "monk", 60 + k * 3, { throwIn: 0, windup: 5 }); + run(crowd, 200); + assert.ok(crowd.hazards.filter((h) => h.kind === "smoke").length <= ch.SMOKE_CAP); + assert.equal(ghoul.MONSTERS.monk.hp, 4); +}); + +/* ---------------------------------------------------------- bell bats */ + +test("Ghoul Rush's bell bats roost in a bell, harmless, until the bell tolls; then a flock of three bursts out and swoops at you", () => { + const round = chapelRound("tower"); + standAt(round, 60); + round.you.safeMs = 1e9; + const roost = put(round, "bellbat", 120, { y: 38 }); + assert.equal(roost.act, "roost"); + assert.equal(ghoul.solid(roost), false, "nothing touches a bat in its bell"); + round.shots.push({ x: 116, y: 39, vx: 80, vy: 0, gone: 0 }); + run(round, 80); + assert.equal(roost.hp, roost.max, "a bolt goes through"); + round.twist = { next: 5, swing: false, frozen: false }; + run(round, 20); + assert.equal(events(round, "toll").length, 1); + const bellBurst = events(round, "bellBurst"); + assert.equal(bellBurst.length, 1); + assert.equal(bellBurst[0].n, 3); + const flock = round.monsters.filter((m) => m.kind === "bellbat" && m.act === "swoop"); + assert.equal(flock.length, 3, "a flock of three"); + assert.ok(flock.every((m) => m.hp === 1), "one bolt each"); + // Frozen for the toll, they then swoop at you like the house bat. + run(round, ch.TOLL_STUN_MS + 50); + const xs = flock.map((m) => m.x); + run(round, 1500); + assert.ok(flock.some((m, i) => Math.abs(m.x - xs[i]) > 8), "they swoop"); + // Another toll, another flock: never more than BAT_CAP flying. + for (let k = 0; k < 4; k++) { + round.twist.next = 5; + run(round, ch.TOLL_STUN_MS + 60); + round.you.safeMs = 1e9; + } + assert.ok(round.monsters.filter((m) => m.kind === "bellbat" && m.act !== "roost").length <= ch.BAT_CAP); + // A roost off screen lets nobody out. + const off = chapelRound("tower"); + standAt(off, 20); + off.you.safeMs = 1e9; + put(off, "bellbat", 400, { y: 38 }); + off.twist = { next: 5, swing: false, frozen: false }; + run(off, 20); + assert.equal(events(off, "bellBurst").length, 0); + // A horde bat comes swooping, no roost. + const horde = chapelRound("tower"); + standAt(horde, 20); + const h = put(horde, "bellbat", 60, { y: 30, ...ch.CHAPEL.horde.bellbat }); + assert.equal(h.act, "swoop"); + assert.equal(ghoul.solid(h), true); +}); + +/* ------------------------------------------------------------ the toll */ + +test("Ghoul Rush's bell swings visibly for 1.2 s, then tolls: the tower and the choir toll about every 12 s, the other rooms never", () => { + const round = chapelRound("tower"); + standAt(round, 20); + round.you.safeMs = 1e9; + round.timeMs = 1e9; + const swings = []; + const tolls = []; + const ends = []; + for (let t = 0; t < 30000; t += 4) { + ghoul.advance(round, 4, steady); + round.you.safeMs = 1e9; + for (const e of round.events) { + if (e.type === "bellSwing") swings.push(round.clock); + if (e.type === "toll") tolls.push(round.clock); + if (e.type === "tollEnd") ends.push(round.clock); + } + round.events.length = 0; + // The bell as a hazard to draw while it swings. + if (swings.length && !tolls.length) assert.ok(round.hazards.some((h) => h.kind === "bell"), "the bell is drawn while it swings"); + } + assert.equal(tolls.length, 2, "two tolls in 30 s"); + assert.ok(Math.abs(tolls[0] - 12000 * ch.TOLL_FIRST) < 60, `the first at ${tolls[0]}`); + assert.ok(Math.abs(tolls[1] - tolls[0] - 12000) < 60, `then every 12 s (${tolls[1] - tolls[0]})`); + assert.ok(Math.abs(tolls[0] - swings[0] - ch.SWING_MS) < 60, "the swing warns for 1.2 s"); + assert.ok(Math.abs(ends[0] - tolls[0] - ch.TOLL_STUN_MS) < 60, "and it thaws a second after"); + for (const id of ["nave", "loft"]) { + const r = chapelRound(id); + standAt(r, 20); + r.timeMs = 1e9; + r.you.safeMs = 1e9; + run(r, 14000); + assert.equal(r.stunMs, 0, `${id}: no bell`); + assert.equal(events(r, "toll").length, 0); + } +}); + +test("Ghoul Rush's toll freezes you and every monster for a second: no run, jump or shot, gravity still takes you down, and bolts already flying still hit", () => { + const round = chapelRound("tower"); + standAt(round, 20); + round.you.safeMs = 1e9; + round.timeMs = 1e9; + const z = put(round, "monk", 70, { throwIn: 1e9 }); + const c = put(round, "chorister", 100, { y: 20, songIn: 1e9 }); + round.twist = { next: 5, swing: false, frozen: false }; + run(round, 8); + assert.ok(round.stunMs > 900, "frozen"); + assert.equal(events(round, "toll").length, 1); + const at = { you: round.you.x, z: z.x, c: [c.x, c.y] }; + // Every key does nothing. + round.input.right = true; + round.input.fire = true; + round.input.up = true; + round.input.jump = ghoul.JUMP_BUFFER_MS; + run(round, 600); + assert.equal(round.you.x, at.you, "no running"); + assert.equal(round.you.y, ghoul.groundAt(round.spec, 20), "no jumping"); + assert.equal(round.shots.length, 0, "no shooting"); + assert.equal(z.x, at.z, "the monk stands"); + assert.deepEqual([c.x, c.y], at.c, "the ghost hangs"); + // Gravity still applies: in the air you come down. + Object.assign(round.you, { y: 30, vy: 0, state: "air", shelf: -1 }); + run(round, 300); + assert.ok(round.you.y < 30 - 5, `falling (${round.you.y.toFixed(1)})`); + assert.equal(round.you.x, at.you); + // A bolt in flight still hits a frozen monster. + round.stunMs = 800; + round.input.right = false; + const target = put(round, "monk", 90, { throwIn: 1e9 }); + const hp = target.hp; + round.shots.push({ x: 80, y: target.y + 2, vx: 80, vy: 0, gone: 0 }); + run(round, 200); + assert.ok(target.hp < hp, "a bolt in flight hits"); + assert.ok(round.stunMs > 0, "still frozen"); + // About a second in all, then everything moves again. + until(round, () => !(round.stunMs > 0)); + assert.equal(events(round, "tollEnd").length, 0, "the thaw is told on the next slice"); + round.input.right = true; + round.input.fire = false; + round.input.up = false; + run(round, 400); + assert.ok(round.you.x > at.you + 5, "you run again"); + assert.ok(z.x < at.z, "and the monk walks again"); + assert.equal(events(round, "tollEnd").length, 1); +}); + +test("Ghoul Rush's toll lasts TOLL_STUN_MS (about a second) and freezes what monsters threw, the notes included, but not a bolt", () => { + const round = chapelRound("tower"); + standAt(round, 20); + round.you.safeMs = 1e9; + round.timeMs = 1e9; + round.hazards.push({ kind: "note", x: 60, y: 10, w: 1.6, h: 1.6, v: 20, live: 1, life: 7000, cause: "note" }); + round.bones.push({ id: 9e9, kind: "bone", x: 70, y: 20, vx: 5, vy: 0, spin: 0, life: 4000 }); + round.twist = { next: 5, swing: false, frozen: false }; + run(round, 8); + const note = round.hazards.find((h) => h.kind === "note"); + const x0 = note.x; + const bx = round.bones[0].x; + run(round, ch.TOLL_STUN_MS - 100); + assert.equal(note.x, x0, "the note hangs"); + assert.equal(round.bones[0].x, bx, "so does a thrown bone"); + const frozenFor = log(round, 400, "tollEnd"); + assert.equal(frozenFor.length, 1); + run(round, 100); + assert.ok(note.x < x0, "and flies again"); + // A death or a new life puts the freeze away. + round.twist = { next: 5, swing: false, frozen: false }; + run(round, 8); + assert.ok(round.stunMs > 0); + ghoul.lose(round, "zombie"); + run(round, ghoul.CRASH_MS + ghoul.READY_MS + 40); + assert.equal(round.stunMs, 0); + assert.ok(round.twist.next > 12000 * ch.TOLL_FIRST - 1000 && !round.twist.frozen, "the bell starts over with the room"); +}); + +/* --------------------------------------------------------- holy water */ + +test("Holy Water is found only in The Chapel: no drop elsewhere ever picks it, a placed one elsewhere is swapped, and it lasts 10 s", () => { + assert.equal(ghoul.POWERS.holy.stage, "chapel"); + assert.equal(ghoul.POWERS.holy.ms, 10000); + assert.ok(ghoul.TIMED.includes("holy"), "a timed power-up, shown in the pill"); + assert.equal(PILL_WORDS.holy, "HOLY"); + const home = chapelRound("nave"); + assert.equal(ghoul.powerHere(home, "holy"), true); + assert.ok(home.loot.includes("holy"), "placed ones stay"); + const picked = new Set(); + const random = ghoul.seeded(9); + for (let k = 0; k < 400; k++) picked.add(pickPower(random, home)); + assert.ok(picked.has("holy"), "drops here can be Holy Water"); + const hall = ghoul.newRound(3); + hall.dice = 0; + assert.equal(ghoul.powerHere(hall, "holy"), false); + const away = chapelRound("nave"); + away.stage = "grounds"; + assert.equal(ghoul.powerHere(away, "holy"), false); + for (let k = 0; k < 400; k++) { + assert.notEqual(pickPower(random, away), "holy"); + assert.notEqual(pickPower(random, hall), "holy"); + } + for (const base of ghoul.ROOMS) if (!["nave", "tower", "loft", "choir"].includes(base.id)) assert.ok(!base.items.some((i) => i[0] === "holy"), `${base.id} places none`); + const timed = chapelRound("nave"); + ghoul.applyPower(timed, "holy"); + assert.equal(timed.effects.holy, 10000); + ghoul.advance(timed, ghoul.POWERS.holy.ms + 8, steady); + assert.equal(timed.effects.holy, 0); +}); + +test("Holy Water splashes: a bolt does 1 damage to every monster within 4 of what it hit, and double to a ghost, a choir ghost or a wraith", () => { + const hit = (holy, kind, over = {}) => { + const round = chapelRound("nave"); + standAt(round, 20); + round.you.safeMs = 1e9; + if (holy) ghoul.applyPower(round, "holy"); + const m = put(round, kind, 60, kind === "zombie" || kind === "monk" ? over : { y: 10, ...over }); + const near = put(round, "zombie", 62.5); + const far = put(round, "zombie", 60 + ch.HOLY_SPLASH + 4); + bolt(round, m, m.y + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, 4, steady); + return { m, near, far, round }; + }; + const plain = hit(false, "zombie"); + assert.equal(plain.near.hp, plain.near.max, "nothing splashes without it"); + const holy = hit(true, "zombie"); + assert.equal(holy.m.max - holy.m.hp, 1, "the hit one takes one"); + assert.equal(holy.near.max - holy.near.hp, 1, "the one next to it takes one"); + assert.equal(holy.far.hp, holy.far.max, "one beyond 4 does not"); + assert.equal(events(holy.round, "holySplash").length, 1); + // Double to ghost kinds. + for (const kind of ["ghost", "chorister", "wraith"]) { + const plainHit = hit(false, kind, kind === "ghost" ? { phase: 600 } : kind === "wraith" ? { act: "hover" } : {}); + const holyHit = hit(true, kind, kind === "ghost" ? { phase: 600 } : kind === "wraith" ? { act: "hover" } : {}); + assert.equal(plainHit.m.max - plainHit.m.hp, 1, `${kind}: one without it`); + assert.equal(holyHit.m.max - holyHit.m.hp, 2, `${kind}: two with it`); + } + // A monster that is not a ghost kind takes the one. + const monk = hit(true, "monk"); + assert.equal(monk.m.max - monk.m.hp, 1); + // A splash kills too, with its kill and its points. + const kill = chapelRound("nave"); + standAt(kill, 20); + kill.you.safeMs = 1e9; + ghoul.applyPower(kill, "holy"); + const a = put(kill, "zombie", 60); + const b = put(kill, "bellbat", 61, { act: "swoop", y: 8 }); + bolt(kill, a, a.y + 2); + ghoul.advance(kill, 4, steady); + ghoul.advance(kill, 4, steady); + assert.equal(b.dead, true, "a bat caught in the splash falls"); + assert.equal(events(kill, "kill").some((e) => e.kind === "bellbat"), true); +}); + +/* ------------------------------------------------------ the Choirmaster */ + +// The choir, you in the arena, the Choirmaster awake: pipes made, his +// baton down, nothing spewing, the bell far off. +function choirFight() { + const round = chapelRound("choir"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + ghoul.advance(round, 8, steady); + round.you.safeMs = 1e9; + round.events.length = 0; + hold(round); + return round; +} + +// Holds him in place: no columns, no ghosts, no toll. +function hold(round) { + const b = round.boss; + b.act = "idle"; + b.wait = 1e9; + for (const p of b.pipes) p.spewIn = 1e9; + round.twist = { next: 1e9, swing: false, frozen: false }; +} + +const staff = (round) => ch.ROWS.map((r) => round.spec.ground.find(([a, c]) => a <= round.boss.x && c >= round.boss.x)[2] + r); + +test("The Choirmaster glides to his organ and conducts: four pipes of 8 hp stand in the arena, and while any sounds he cannot be hurt by a bolt or a stomp", () => { + const round = chapelRound("choir"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + const b = round.boss; + assert.equal(b.kind, "choirmaster"); + assert.equal(b.state, "intro"); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(b.state, "fight"); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + assert.equal(b.pipes.length, 4); + assert.deepEqual(b.pipes.map((p) => p.hp), [8, 8, 8, 8]); + assert.ok(b.pipes.every((p) => p.on), "all four sound"); + assert.deepEqual(b.pipes.map((p) => p.x - round.spec.arena), [...ch.PIPE_AT]); + assert.ok(b.pipes.every((p) => p.y === 6), "on the arena's floor"); + const home = round.spec.length - ch.HOME_FROM_END; + assert.notEqual(b.x, home, "he is not there yet"); + until(round, () => b.x === home, 4000); + assert.equal(b.x, home, "he takes his place"); + assert.equal(b.dir, -1, "facing you"); + hold(round); + // Guarded: a bolt into him is blocked, a stomp too. + const hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, hp); + assert.ok(events(round, "bossBlock").length >= 1, "it glances off"); + standAt(round, b.x, 1, b.y + b.h + 0.5); + Object.assign(round.you, { state: "air", vy: -10, safeMs: 1e9, shelf: -1 }); + until(round, () => events(round, "stomp").length > 0, 400); + assert.equal(b.hp, hp, "no stomp hurts him either"); + // His touch is his own. + standAt(round, b.x - 3); + round.you.safeMs = 0; + run(round, 20); + assert.equal(events(round, "lose")[0]?.cause, "choirmaster"); +}); + +test("The Choirmaster's pipes take shots from the floor or a board, one at a time in a row; shoot one to nothing and it is silenced, silence all four and he is open", () => { + const round = choirFight(); + const b = round.boss; + const [p0, p1, p2, p3] = b.pipes; + // A bolt from the floor at chest height hits the first sounding pipe in line. + standAt(round, p0.x - 12); + round.you.face = 1; + round.you.safeMs = 1e9; + round.input.fire = true; + run(round, 300); + round.input.fire = false; + assert.ok(p0.hp < 8, "the first pipe takes it"); + assert.equal(p1.hp, 8, "not the ones behind it"); + assert.ok(events(round, "pipeHit").length >= 2); + // From a board too. + const shelf = round.spec.shelves[1]; + standAt(round, p0.x - 6, 1, shelf[2], 1); + round.you.safeMs = 1e9; + const before = p0.hp; + round.input.fire = true; + run(round, 120); + round.input.fire = false; + assert.ok(p0.hp < before, "a bolt from a board reaches it"); + // Silence it: the event, the pipe quiet, and a bolt now goes on to the next. + p0.hp = 1; + round.shots.length = 0; + round.shots.push({ x: p0.x - 3, y: p0.y + 4, vx: 80, vy: 0, gone: 0 }); + round.events.length = 0; + run(round, 60); + assert.equal(p0.on, false); + assert.equal(events(round, "pipeSilence").length, 1); + assert.equal(events(round, "pipeSilence")[0].left, 3); + assert.equal(events(round, "choirOpen").length, 0, "three still sound"); + round.shots.push({ x: p0.x - 3, y: p0.y + 4, vx: 80, vy: 0, gone: 0 }); + run(round, 250); + assert.ok(p1.hp < 8, "past the silent one to the next"); + const hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, hp, "still guarded with three left"); + for (const p of [p1, p2, p3]) { + p.hp = 1; + round.shots.push({ x: p.x - 3, y: p.y + 4, vx: 80, vy: 0, gone: 0 }); + run(round, 60); + } + assert.deepEqual(b.pipes.map((p) => p.on), [false, false, false, false]); + assert.equal(events(round, "choirOpen").length, 1, "open when the last goes quiet"); + assert.equal(events(round, "pipeSilence").length, 4); + // Open: a bolt hurts him, the hit carries his kind. + round.events.length = 0; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, hp - 1); + assert.equal(events(round, "bossHit")[0]?.kind, "choirmaster"); + // And a stomp does 3. + standAt(round, b.x, 1, b.y + b.h + 0.5); + Object.assign(round.you, { state: "air", vy: -10, safeMs: 1e9, shelf: -1 }); + until(round, () => events(round, "stomp").length > 0, 400); + assert.equal(b.hp, hp - 1 - ghoul.STOMP_DAMAGE); +}); + +test("A sounding pipe spews a ghost now and then, never more than three ghosts alive at once, and a silent pipe spews none", () => { + const round = choirFight(); + const b = round.boss; + b.pipes[0].on = false; + b.pipes.forEach((p) => (p.spewIn = 0)); + let most = 0; + const from = new Set(); + for (let t = 0; t < 14000; t += 4) { + ghoul.advance(round, 4, steady); + round.you.safeMs = 1e9; + round.twist.next = 1e9; + b.act = "idle"; + b.wait = 1e9; + most = Math.max(most, round.monsters.filter((m) => m.kind === "ghost").length); + for (const e of round.events) if (e.type === "pipeSpew") from.add(e.pipe); + round.events.length = 0; + if (t % 1000 === 0) round.monsters = round.monsters.filter((m, i) => m.kind !== "ghost" || i % 2); + } + assert.ok(most >= 2, "ghosts do come"); + assert.ok(most <= ch.GHOST_CAP, `never more than ${ch.GHOST_CAP} (${most})`); + assert.equal(from.has(0), false, "the silent pipe spews none"); + assert.ok(from.size >= 2, "the others do"); + // The ghosts come out high on the pipes. + const one = choirFight(); + one.boss.pipes.forEach((p, i) => (p.spewIn = i ? 1e9 : 0)); + run(one, 20); + const ghost = one.monsters.find((m) => m.kind === "ghost"); + assert.ok(ghost && ghost.y > 6 + ch.PIPE_H[0] * 0.5 && Math.abs(ghost.x - one.boss.pipes[0].x) < 3); +}); + +/* --------------------------------------------------------- the notes */ + +// The surfaces you can stand on in the choir's arena: the floor and each board. +const levels = (spec) => [{ y: 6, shelf: -1, x: spec.arena + 40 }, ...spec.shelves.map(([a, b, y], i) => ({ y, shelf: i, x: (a + b) / 2 }))]; + +test("The Choirmaster raises his baton, then a column of notes flies at you along the lines of a staff: four notes, one gap, and be at the gap's height when it passes", () => { + const round = choirFight(); + const b = round.boss; + Object.assign(b, { act: "idle", wait: 0, gap: 1 }); + const cue = log(round, 700, "notesCue"); + assert.equal(cue.length, 1, "the baton goes up first"); + assert.equal(cue[0][1].gap, 1); + assert.equal(round.hazards.filter((h) => h.kind === "note").length, 0, "no notes yet"); + const launched = log(round, 100, "notes"); + assert.equal(launched.length, 1); + const notes = round.hazards.filter((h) => h.kind === "note"); + assert.equal(notes.length, 4, "four notes"); + assert.equal(launched[0][1].gap, 1); + const rows = notes.map((n) => n.row).sort(); + assert.deepEqual(rows, [0, 2, 3, 4], "row 1 is the gap"); + const want = staff(round); + for (const n of notes) assert.ok(Math.abs(n.y + ch.NOTE / 2 - want[n.row]) < 1e-9, "on the staff's lines"); + assert.equal(ch.ROWS.length, 5, "five lines"); + assert.ok(ch.ROWS.every((r, i) => !i || Math.abs(r - ch.ROWS[i - 1] - ch.ROW_GAP) < 1e-9), "evenly spaced"); + assert.ok(notes.every((n) => n.x < b.x - b.w / 2), "from him, flying your way"); + const x0 = notes[0].x; + run(round, 500); + assert.ok(notes[0].x < x0 - 8, "and it flies"); + assert.ok(Math.abs((x0 - notes[0].x) / 0.5 - ch.NOTE_V) < 1, "at NOTE_V"); + // Then another a column's time on. + hold(round); + Object.assign(b, { act: "idle", wait: ch.COLUMN_MS }); + const next = log(round, ch.COLUMN_MS + 100, "notesCue"); + assert.equal(next.length, 1); +}); + +test("Every column of notes can be passed: for each gap a surface in the arena (the floor or a board) clears all the rest, and standing anywhere else costs a life", () => { + const spec = ghoul.roomFor("choir"); + const fits = (g, feet) => ch.ROWS.every((row, i) => i === g || feet + ghoul.HIT_H <= 6 + row - ch.NOTE / 2 - 0.05 || feet >= 6 + row + ch.NOTE / 2 + 0.05); + const floors = levels(spec); + const margin = (g, feet) => Math.min(...ch.ROWS.filter((_, i) => i !== g).map((row) => Math.max(6 + row - ch.NOTE / 2 - (feet + ghoul.HIT_H), feet - (6 + row + ch.NOTE / 2)))).toFixed(1); + const safe = []; + for (let g = 0; g < ch.GAPS; g++) { + const ok = floors.filter((l) => fits(g, l.y)); + assert.ok(ok.length >= 1, `gap ${g}: a surface that clears it`); + safe.push(ok[0]); + assert.ok(Number(margin(g, ok[0].y)) >= 0.5, `gap ${g}: with room to spare (${margin(g, ok[0].y)})`); + // And it is the surface for this gap alone. + assert.equal(floors.filter((l) => fits(g, l.y)).length, 1, `gap ${g}: one surface`); + } + // Played out with the real round: stand there and nothing hurts; stand anywhere else and a note does. + for (let g = 0; g < ch.GAPS; g++) { + for (const [at, level] of floors.entries()) { + const round = choirFight(); + const b = round.boss; + until(round, () => b.x === round.spec.length - ch.HOME_FROM_END, 4000); + hold(round); + Object.assign(b, { gap: g, act: "idle", wait: 0 }); + standAt(round, level.x, 1, level.y, level.shelf); + round.you.safeMs = 0; + for (let t = 0; t < 8000 && round.phase === "play"; t += 4) { + ghoul.advance(round, 4, steady); + if (b.act === "idle" && b.wait < 1e8) b.wait = 1e9; + } + const lost = events(round, "lose"); + if (level === safe[g]) assert.equal(lost.length, 0, `gap ${g}, standing on level ${at}: untouched`); + else { + assert.equal(lost.length, 1, `gap ${g}, standing on level ${at}: hit`); + assert.equal(lost[0].cause, "note"); + } + } + } +}); + +test("Every column can be reached from the one before: the next gap is the same height or one step either side, over a long fight", () => { + const round = choirFight(); + const gaps = []; + const rand = ghoul.seeded(11); + round.boss.act = "idle"; + round.boss.wait = 0; + for (let t = 0; t < 70000; t += 4) { + ghoul.advance(round, 4, rand); + round.you.safeMs = 1e9; + round.boss.pipes.forEach((p) => (p.spewIn = 1e9)); + round.twist.next = 1e9; + for (const e of round.events) if (e.type === "notes" && !e.pair) gaps.push(e.gap); + round.events.length = 0; + } + assert.ok(gaps.length >= 15, `${gaps.length} columns`); + assert.ok(gaps.every((g) => g >= 0 && g < ch.GAPS), "gaps within the staff"); + assert.ok(gaps.every((g, i) => !i || Math.abs(g - gaps[i - 1]) <= 1), "each within a step of the last"); + assert.equal(new Set(gaps).size, ch.GAPS, "and they vary through every height"); +}); + +test("A jump from the floor clears the third gap too, with a window of about a fifth of a second to time it in", () => { + const spec = ghoul.roomFor("choir"); + const x = spec.arena + 12; + const clears = (jumpAt) => { + const r = choirFight(); + hold(r); + standAt(r, x); + r.you.safeMs = 0; + const base = 6; + // A column of four notes, row 2 (the gap) missing, 66 units off, flying at NOTE_V. + ch.ROWS.forEach((row, i) => { + if (i !== 2) r.hazards.push({ kind: "note", x: x + 66, y: base + row - ch.NOTE / 2, w: ch.NOTE, h: ch.NOTE, row: i, v: ch.NOTE_V, live: 1, life: 7000, cause: "note" }); + }); + for (let t = 0; t < 4400 && r.phase === "play"; t += 4) { + r.input.up = t >= jumpAt && t < jumpAt + 500; + if (t === jumpAt) r.input.jump = ghoul.JUMP_BUFFER_MS; + ghoul.advance(r, 4, steady); + } + return events(r, "lose").length === 0; + }; + const wins = []; + for (let jumpAt = 2400; jumpAt <= 3200; jumpAt += 20) wins.push(clears(jumpAt)); + const ok = wins.filter(Boolean).length; + assert.ok(ok >= 7, `a window of jump times clears it (${ok} of ${wins.length} at 20 ms)`); + assert.ok(ok < wins.length - 5, "and a bad jump does not"); + assert.equal(clears(0), false, "standing on the floor with the gap high up is hit"); +}); + +/* ----------------------------------------------------------- the rage */ + +test("The Choirmaster at half his hp: a rage that is told, silenced pipes sounding again one at a time every 6 s (guarding him again), faster notes, and now and then two columns close together", () => { + const round = choirFight(); + const b = round.boss; + b.pipes.forEach((p) => { + p.on = false; + p.hp = 0; + }); + b.hp = b.max * 0.5 + 1; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, b.max * 0.5); + assert.equal(events(round, "choirRage").length, 1, "the rage is told"); + assert.equal(b.raged, true); + assert.deepEqual(b.pipes.map((p) => p.on), [false, false, false, false], "none yet"); + // One every 6 s, one at a time. + const sounds = log(round, ch.RESOUND_MS * 4 + 200, "pipeSound"); + assert.equal(sounds.length, 4, "all four, one by one"); + for (let i = 1; i < sounds.length; i++) assert.ok(Math.abs(sounds[i][0] - sounds[i - 1][0] - ch.RESOUND_MS) < 60, `${sounds[i][0] - sounds[i - 1][0]} apart`); + assert.equal(new Set(sounds.map((s) => s[1].pipe)).size, 4, "a different pipe each time"); + assert.ok(b.pipes.every((p) => p.on && p.hp === p.max), "each at full hp"); + // While any sounds, he is guarded again. + const hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, hp); +}); + +test("The Choirmaster in his rage conducts faster: notes at NOTE_V_RAGE, a column every 2.3 s, and sometimes a second column 1.1 s behind the first, its gap next to the first's", () => { + const round = choirFight(); + const b = round.boss; + b.pipes.forEach((p) => (p.on = false)); + b.hp = b.max * 0.5 - 1; + b.raged = true; + b.resoundIn = 1e9; + const random = ghoul.seeded(5); + Object.assign(b, { act: "idle", wait: 0, gap: 1 }); + const pairs = []; + const notes = []; + let speed = null; + for (let t = 0; t < 40000; t += 4) { + ghoul.advance(round, 4, random); + round.you.safeMs = 1e9; + round.twist.next = 1e9; + for (const e of round.events) if (e.type === "notes") notes.push([round.clock, e]); + round.events.length = 0; + speed ||= round.hazards.find((h) => h.kind === "note")?.v; + } + assert.ok(notes.length >= 10); + for (let i = 0; i < notes.length; i++) if (notes[i][1].pair) pairs.push([notes[i - 1], notes[i]]); + assert.ok(pairs.length >= 2, "pairs"); + for (const [first, second] of pairs) { + assert.ok(Math.abs(second[0] - first[0] - ch.PAIR_MS) < 60, `${second[0] - first[0]} ms behind`); + assert.ok(Math.abs(second[1].gap - first[1].gap) === 1, "its gap next to the first's"); + } + // A column (or a pair) every 2.3 s after the last, plus the baton's 0.7 s. + let spaced = 0; + for (let i = 1; i < notes.length; i++) { + if (notes[i][1].pair) continue; + assert.ok(Math.abs(notes[i][0] - notes[i - 1][0] - ch.COLUMN_RAGE_MS - ch.CUE_MS) < 80, `a column every 2.3 s (${notes[i][0] - notes[i - 1][0]})`); + spaced++; + } + assert.ok(spaced >= 5); + // Faster notes. + assert.equal(speed, ch.NOTE_V_RAGE * round.spec.pace); + assert.ok(ch.NOTE_V_RAGE > ch.NOTE_V && ch.COLUMN_RAGE_MS < ch.COLUMN_MS); + // Without the rage, the same draws give no pairs. + const calm = choirFight(); + Object.assign(calm.boss, { act: "idle", wait: 0, gap: 1 }); + const calmPairs = []; + for (let t = 0; t < 12000; t += 4) { + ghoul.advance(calm, 4, () => 0.1); + calm.you.safeMs = 1e9; + calm.boss.pipes.forEach((p) => (p.spewIn = 1e9)); + calm.twist.next = 1e9; + for (const e of calm.events) if (e.type === "notes" && e.pair) calmPairs.push(e); + calm.events.length = 0; + } + assert.equal(calmPairs.length, 0); +}); + +test("The Choirmaster's toll freezes him, his pipes' ghosts and his notes in mid-air too, though a bolt in flight still hits a pipe or him; and his fall puts every note away", () => { + const round = choirFight(); + const b = round.boss; + until(round, () => b.x === round.spec.length - ch.HOME_FROM_END, 4000); + b.act = "idle"; + b.wait = 0; + round.twist.next = 5; + run(round, 8); + assert.ok(round.stunMs > 0, "the bell tolled in the fight"); + round.hazards.push({ kind: "note", x: 150, y: 10, w: 1.6, h: 1.6, v: 20, live: 1, life: 7000, cause: "note" }); + const before = { x: b.x, wait: b.wait, act: b.act, note: 150, spew: b.pipes[0].spewIn }; + run(round, 500); + assert.equal(b.x, before.x); + assert.equal(b.wait, before.wait, "his timers stand still"); + assert.equal(b.pipes[0].spewIn, before.spew); + assert.equal(round.hazards.find((h) => h.kind === "note").x, before.note); + // A bolt in flight hits the pipe. + const p = b.pipes[0]; + round.shots.push({ x: p.x - 3, y: p.y + 4, vx: 80, vy: 0, gone: 0 }); + run(round, 60); + assert.equal(p.hp, 7, "a pipe is hit while frozen"); + // The fall of the boss puts every note away and ends the bell. + b.pipes.forEach((q) => (q.on = false)); + b.hp = 1; + round.stunMs = 0; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.state, "down"); + assert.equal(round.hazards.length, 0); + assert.equal(round.hasKey, true); +}); + +test("The Choirmaster is tougher and stays his own: hp ~100 more each stage deeper, a bolt hit carries his kind, and the endless-lives code spares a life from every new way to die", () => { + assert.equal(ch.BOSSES.choirmaster.hp, 100); + assert.equal(ch.BOSSES.choirmaster.points, 3500); + assert.equal([ch.BOSSES.choirmaster.w, ch.BOSSES.choirmaster.h].join("x"), "8x17"); + const deep = ghoul.roomFor("choir", 3); + assert.ok(deep.bossHp > ch.BOSSES.choirmaster.hp); + for (const cause of ["gargoyle", "chorister", "monk", "bellbat", "choirmaster", "note"]) { + const round = choirFight(); + round.infinite = true; + const lives = round.lives; + ghoul.lose(round, cause); + assert.equal(round.lives, lives, `${cause} costs none`); + } + // A note, spared by endless lives, still ends in a crash and a respawn. + const round = choirFight(); + round.infinite = true; + const lives = round.lives; + round.hazards.push({ kind: "note", x: round.you.x, y: round.you.y, w: 1.6, h: 1.6, v: 0, live: 1, life: 7000, cause: "note" }); + round.you.safeMs = 0; + run(round, 20); + assert.equal(events(round, "lose")[0]?.cause, "note"); + assert.equal(round.lives, lives); +}); + +/* ---------------------------------------------------- voices and drawing */ + +test("Ghoul Rush's Chapel: every new kind has a voice for every act and every new event plays exactly one picked sound", () => { + const own = { + gargoyle: ["appear", "wake", "dive", "perch", "glance", "hurt", "die"], + chorister: ["appear", "sing", "hush", "hurt", "die"], + monk: ["appear", "censer", "smoke", "hurt", "die"], + bellbat: ["appear", "burst", "hurt", "die"], + bell: ["swing", "toll"], + holy: ["splash"], + choirmaster: ["wake", "cue", "notes", "pipeSpew", "pipeHit", "pipeSilence", "pipeSound", "open", "rage", "hurt", "die"], + }; + for (const [kind, acts] of Object.entries(own)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const names = Object.values(VOICES).flatMap((v) => Object.values(v)); + const cases = [ + [{ type: "glance", kind: "gargoyle" }, "gargoyle", "glance"], + [{ type: "gargoyleWake", kind: "gargoyle" }, "gargoyle", "wake"], + [{ type: "gargoyleDive", kind: "gargoyle" }, "gargoyle", "dive"], + [{ type: "gargoylePerch", kind: "gargoyle" }, "gargoyle", "perch"], + [{ type: "choirSing", kind: "chorister" }, "chorister", "sing"], + [{ type: "choirHush", kind: "chorister" }, "chorister", "hush"], + [{ type: "censerWind", kind: "monk" }, "monk", "censer"], + [{ type: "smokePuff", kind: "monk" }, "monk", "smoke"], + [{ type: "bellBurst", kind: "bellbat" }, "bellbat", "burst"], + [{ type: "bellSwing", ms: 1200 }, "bell", "swing"], + [{ type: "toll", ms: 1000 }, "bell", "toll"], + [{ type: "holySplash", n: 1 }, "holy", "splash"], + [{ type: "pipeSpew", kind: "choirmaster" }, "choirmaster", "pipeSpew"], + [{ type: "pipeHit", kind: "choirmaster" }, "choirmaster", "pipeHit"], + [{ type: "pipeSilence", kind: "choirmaster", left: 2 }, "choirmaster", "pipeSilence"], + [{ type: "pipeSound", kind: "choirmaster" }, "choirmaster", "pipeSound"], + [{ type: "choirOpen", kind: "choirmaster" }, "choirmaster", "open"], + [{ type: "choirRage", kind: "choirmaster" }, "choirmaster", "rage"], + [{ type: "notesCue", kind: "choirmaster", gap: 1 }, "choirmaster", "cue"], + [{ type: "notes", kind: "choirmaster", gap: 1, pair: false }, "choirmaster", "notes"], + [{ type: "bossWake", kind: "choirmaster" }, "choirmaster", "wake"], + [{ type: "bossHit", kind: "choirmaster", how: "shot" }, "choirmaster", "hurt"], + [{ type: "bossHit", kind: "choirmaster", how: "splash" }, "choirmaster", "hurt"], + [{ type: "bossDown", kind: "choirmaster", points: 1 }, "choirmaster", "die"], + [{ type: "hit", kind: "gargoyle" }, "gargoyle", "hurt"], + [{ type: "kill", kind: "monk", mult: 1, how: "shot", points: 1 }, "monk", "die"], + [{ type: "kill", kind: "gargoyle", mult: 1, how: "holy", points: 1 }, "gargoyle", "die"], + [{ type: "spawn", kind: "chorister" }, "chorister", "appear"], + [{ type: "spawn", kind: "bellbat" }, "bellbat", "appear"], + ]; + for (const [e, kind, act] of cases) { + const played = heard(e).played; + assert.ok(played.includes(VOICES[kind][act]), `${e.type}: ${kind} ${act}`); + assert.equal(played.filter((n) => names.includes(n)).length, 1, `${e.type} plays exactly one picked sound`); + } + // The quiet ones: the thaw after a toll, and a glance off a stone gargoyle plays only its glance. + assert.equal(heard({ type: "tollEnd", x: 10, y: 20 }).played.filter((n) => names.includes(n)).length, 0, "the thaw is quiet"); + assert.deepEqual(heard({ type: "glance", kind: "gargoyle", x: 5, y: 5 }).played, [VOICES.gargoyle.glance], "a glance plays only the glance"); + assert.deepEqual(heard({ type: "bossHit", kind: "choirmaster", how: "splash", x: 5, y: 5 }).played.filter((n) => n !== "bump"), [VOICES.choirmaster.hurt], "a splash on him is one hurt"); + // The sounds exist, live in the stage's own file, and are named by kind and act. + const merged = ghoulSfx.default.tones; + const cap = (w) => w[0].toUpperCase() + w.slice(1); + for (const kind of Object.keys(own)) { + for (const [act, name] of Object.entries(VOICES[kind])) { + assert.ok(merged[name]?.layers?.length, `${kind}.${act}: ${name} is in the merged tones`); + assert.ok(sfxChapel.CHAPEL_SFX.tones[name], `${name} lives in ghoul-sfx-chapel.js`); + assert.equal(name, `ghoul${cap(kind)}${cap(act)}`, "named by kind and act"); + } + } + assert.equal(Object.keys(sfxChapel.CHAPEL_SFX.tones).length, Object.values(own).flat().length, "no tone is unused"); + assert.deepEqual(Object.keys(sfxChapel.CHAPEL_SFX.music), ["ghoulNave", "ghoulTower", "ghoulLoft", "ghoulChoir"]); + for (const room of ["nave", "tower", "loft", "choir"]) assert.ok(sfxChapel.CHAPEL_SFX.music[ghoul.ROOM_MUSIC[room]], `${room} has its own track`); + assert.equal(Object.hasOwn(ghoulSfx.default.music, ghoul.ROOM_MUSIC.nave), true); + // Every new event says something (a float, a banner or a sound). + assert.deepEqual(heard({ type: "toll", ms: 1000 }).floats, ["Frozen!"]); + assert.deepEqual(heard({ type: "pipeSilence", kind: "choirmaster", left: 0 }).floats, ["Silent!"]); +}); + +test("Ghoul Rush's Chapel: every new way to die has its words and its own sound", () => { + for (const cause of ["gargoyle", "chorister", "monk", "bellbat", "choirmaster", "note"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Chapel draws: every room, every monster in every act, the Choirmaster in each move with his pipes sounding and silent, the notes, the smoke and the bell, and the stage's card, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["chapel"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { gargoyle: ["perch", "wake", "dive", "return"], chorister: [""], monk: [""], bellbat: ["roost", "swoop"] }; + for (const id of ["nave", "tower", "loft", "choir"]) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + standAt(r, id === "choir" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + for (const [kind, list] of Object.entries(acts)) { + list.forEach((act, i) => put(r, kind, r.you.x + 6 + i * 5, { act: act || undefined, y: kind === "monk" ? undefined : 12, sing: kind === "chorister" ? 1000 : 0, windup: kind === "monk" ? 200 : 0, vx: 4, vy: -3 })); + } + r.twist = { next: 1e9, swing: false, frozen: false }; + r.hazards.push({ kind: "smoke", x: r.you.x + 8, y: 6, w: 10, h: 8, live: 0, life: 2000, age: 1000, cause: "smoke" }, { kind: "bell", x: r.camX + 48, y: 42, w: 0, h: 0, live: 0, p: 0.6, cause: "bell" }, { kind: "note", x: r.you.x + 20, y: 10, w: 1.6, h: 1.6, v: 0, live: 1, life: 5000, row: 1, cause: "note" }); + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const sounding of [true, false]) { + r.boss.pipes?.forEach((p) => (p.on = sounding)); + for (const act of ["glide", "idle", "cue", "pair"]) { + Object.assign(r.boss, { act, wait: 1e9, dir: -1 }); + g.tick(16); + } + } + r.stunMs = 500; + g.tick(16); + r.stunMs = 0; + } + for (let k = 0; k < 20; k++) g.tick(16); + r.you.safeMs = 1e9; + } + } + assert.ok(r.spec.id === "choir", "got to the choir and drew it"); + // The stage's card on the pick screen. + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["chapel", "grounds"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Chapel's card"); +}); diff --git a/scripts/test-web-console-activities-ghoul-dice.mjs b/scripts/test-web-console-activities-ghoul-dice.mjs new file mode 100644 index 0000000..a125f15 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-dice.mjs @@ -0,0 +1,482 @@ +// Web console tests, Ghoul Rush's Lucky die: it comes only from a kill, stacks to nine and lasts the run; when a life would be lost one rolls: a 4 to 6 brings Planny back (the monsters in view blown apart in an ordinary room, a boss's room untouched; a 5 adds a heart, a 6 a heart and a Garlic shield), a 3 or 2 costs the life and leaves a gift for the respawn, a 1 only laughs. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import { pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import { react } from "../src/web-console/public/activities/ghoul-draw.js"; +import { toneNames } from "../src/web-console/public/tones.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); +// A random that plays `values` in order, then 0.5. +const rolls = (...values) => { + const rest = values.slice(); + return () => (rest.length ? rest.shift() : 0.5); +}; +const SIX = 0.99; +const FIVE = 0.7; +const FOUR = 0.55; +const THREE = 0.4; +const TWO = 0.2; +const ONE = 0; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +function stand(round, x) { + Object.assign(round.you, { x, y: ghoul.groundAt(round.spec, x), vx: 0, vy: 0, state: "run", shelf: -1, coyote: 0, drop: -1, out: 0, safeMs: 0 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 30)); +} + +// A quiet round in the hall, Planny standing at x = 100, nothing awake. +function hall(dice = 0) { + const round = ghoul.newRound(5); + round.lives = 3; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + stand(round, 100); + round.dice = dice; + round.events.length = 0; + return round; +} + +function zombie(round, x) { + return ghoul.spawnMonster(round, "zombie", x, ghoul.groundAt(round.spec, x), { rise: 0, awake: true }); +} + +// Into the stage `id`, up to its room `room`, quiet, Planny safe. +function inRoom(round, id, room) { + through(round); + round.offer = [id]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== room) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.events.length = 0; + return round; +} + +test("Ghoul Rush: a Lucky die is as common as a 1UP, comes only as a drop, and is never placed in a room or swapped in for a placed power-up", () => { + assert.equal(ghoul.POWERS.die.weight, ghoul.POWERS.life.weight); + assert.equal(ghoul.POWERS.die.drop, true); + assert.equal(ghoul.POWERS.die.ms, undefined, "not a timed power-up"); + for (const room of ghoul.ROOMS) { + const spec = ghoul.roomFor(room.id); + assert.ok(![...spec.items, ...spec.sky].some(([kind]) => kind === "die"), `${room.id} places none`); + } + const round = hall(); + let dropped = 0; + for (let k = 0; k < 400; k++) { + const r = k / 400; + assert.notEqual(pickPower(() => r, round), "die", "never picked for a placed one"); + assert.notEqual(pickPower(() => r, round, "life"), "die"); + if (pickPower(() => r, round, "", true) === "die") dropped++; + } + assert.ok(dropped > 0, "but dropped now and then"); + for (let seed = 1; seed <= 40; seed++) assert.ok(!ghoul.newRound(seed).loot.includes("die")); + // A kill whose roll lands on the die's slice drops it. + const dark = hall(); + dark.dark = true; + const m = zombie(dark, 120); + const values = [0, 0.99]; + ghoul.kill(dark, m, "shot", () => values.shift() ?? 0); + assert.equal(dark.drops.length, 1, "a kill drops a power-up on a low roll"); +}); + +test("Ghoul Rush: picking up Lucky dice stacks them to nine, then pays points like a 1UP at its cap, and the dice show in a pill", () => { + const round = hall(); + const drop = { id: 1, kind: "die", x: round.you.x, y: round.you.y + 1, vx: 0, vy: 0, life: 9000, rest: true }; + round.drops.push(drop); + ghoul.advance(round, 4, steady); + assert.equal(round.dice, 1); + assert.equal(round.drops.length, 0); + assert.equal(events(round, "power")[0].kind, "die"); + for (let k = 0; k < 8; k++) ghoul.applyPower(round, "die"); + assert.equal(round.dice, ghoul.MAX_DICE); + assert.equal(ghoul.MAX_DICE, 9); + const score = round.score; + ghoul.applyPower(round, "die"); + assert.equal(round.dice, 9, "capped"); + assert.equal(round.score - score, ghoul.POWER_POINTS * 10, "points instead"); + const canvas = { getContext: () => null }; + const game = ghoul.default.create({ canvas }); + game.start(); + game.round.dice = 0; + assert.ok(!game.hud.effects.some((e) => /DICE/.test(e.text)), "no pill without dice"); + game.round.dice = 3; + const pill = game.hud.effects.find((e) => /DICE/.test(e.text)); + assert.equal(pill.text, "DICE x3"); + assert.equal(pill.color, ghoul.POWERS.die.color); +}); + +test("Ghoul Rush: dice carry over to the next room and the next stage, and a new round starts with three", () => { + const round = hall(4); + round.hasKey = true; + through(round); + assert.equal(round.phase, "pick"); + assert.equal(round.dice, 4); + round.offer = ["manor"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + assert.equal(round.dice, 4, "into the stage"); + through(round); + assert.equal(round.dice, 4, "into its next room"); + assert.equal(ghoul.newRound(9).dice, ghoul.START_DICE); +}); + +test("Ghoul Rush: a fresh run holds 3 Lucky dice, a lost life with one in hand starts the roll, and the dice carry into the hall and the first stage pick", () => { + assert.equal(ghoul.START_DICE, 3); + const round = ghoul.newRound(5); + assert.equal(round.dice, 3, "a run starts with three"); + assert.equal(round.spec.id, "hall"); + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + stand(round, 100); + ghoul.lose(round, "zombie"); + assert.equal(round.phase, "roll", "a lost life with a die in hand rolls"); + assert.equal(round.dice, 2, "the roll spends one"); + const next = ghoul.newRound(5); + next.hasKey = true; + through(next); + assert.equal(next.phase, "pick"); + assert.equal(next.dice, 3, "into the first stage pick"); + next.offer = ["manor"]; + next.phaseMs = 0; + ghoul.pickStage(next, 0); + assert.equal(next.dice, 3, "into the stage"); +}); + +test("Ghoul Rush: a death with dice holds and rolls just one; a six saves Planny where he stood with a heart and the Garlic shield, the room not reset, and the other dice are kept", () => { + const round = hall(3); + const far = zombie(round, round.camX + ghoul.FIELD_W + 40); + far.hp = 3; + const x = round.you.x; + assert.equal(ghoul.lose(round, "zombie"), true); + assert.equal(round.phase, "roll"); + assert.equal(round.lives, 3, "no life lost yet"); + assert.equal(round.dice, 2, "the die is in hand"); + assert.equal(events(round, "diceStart").length, 1); + assert.equal(events(round, "diceRoll").length, 1); + assert.equal(events(round, "lose").length, 0, "not lost"); + const random = rolls(SIX); + // Half way through: tumbling, no face yet. + ghoul.advance(round, ghoul.TUMBLE_MS / 2, random); + assert.equal(round.phase, "roll"); + assert.equal(events(round, "diceFace").length, 0); + // It lands, and holds its beat. + ghoul.advance(round, ghoul.TUMBLE_MS / 2 + 8, random); + assert.deepEqual(events(round, "diceFace").map((e) => e.face), [6]); + assert.equal(round.phase, "roll"); + ghoul.advance(round, ghoul.ROLL_MS - ghoul.TUMBLE_MS, random); + assert.equal(events(round, "diceRoll").length, 1, "no second die"); + assert.equal(events(round, "diceSaved").length, 1); + assert.equal(events(round, "diceFail").length, 0); + assert.equal(round.phase, "play", "back in play at once"); + assert.equal(round.dice, 2, "the others are kept"); + assert.equal(round.lives, 4, "a heart on top"); + assert.equal(round.you.x, x); + assert.equal(round.you.garlic, true); + assert.ok(round.you.safeMs > 0 && round.you.safeMs <= ghoul.SAFE_MS); + assert.equal(round.you.out, 0); + assert.equal(round.roll, null); + assert.equal(events(round, "lose").length, 0); + assert.equal(events(round, "respawn").length, 0); + assert.equal(round.roomLost, false); + assert.ok(round.monsters.includes(far) && !far.dead, "a monster out of view is left where it stands"); + assert.equal(far.hp, 3); +}); + +test("Ghoul Rush: the same random rolls the same face, and each slice of the die lands on its face", () => { + const face = (value) => { + const round = hall(5); + ghoul.lose(round, "bone"); + ghoul.advance(round, ghoul.ROLL_MS, rolls(value)); + return events(round, "diceFace").map((e) => e.face); + }; + assert.deepEqual(face(0.4), face(0.4)); + assert.deepEqual([ONE, 0.2, 0.4, 0.6, 0.8, SIX].flatMap(face), [1, 2, 3, 4, 5, 6]); +}); + +test("Ghoul Rush: a 5 saves him with a heart and no shield, a 4 just saves him, and a heart past the cap is points", () => { + const five = hall(1); + ghoul.lose(five, "zombie"); + ghoul.advance(five, ghoul.ROLL_MS + 8, rolls(FIVE)); + assert.equal(five.phase, "play"); + assert.equal(five.lives, 4); + assert.equal(five.you.garlic, false); + const four = hall(1); + ghoul.lose(four, "zombie"); + ghoul.advance(four, ghoul.ROLL_MS + 8, rolls(FOUR)); + assert.equal(four.phase, "play"); + assert.equal(four.lives, 3); + assert.equal(four.you.garlic, false); + assert.ok(four.you.safeMs > 0, "still safe a moment"); + const held = hall(1); + held.you.garlic = true; + ghoul.lose(held, "pit"); + ghoul.advance(held, ghoul.ROLL_MS + 8, rolls(FOUR)); + assert.equal(held.you.garlic, true, "a shield he already held stays"); + const full = hall(1); + full.lives = 9; + const score = full.score; + ghoul.lose(full, "zombie"); + ghoul.advance(full, ghoul.ROLL_MS + 8, rolls(FIVE)); + assert.equal(full.lives, 9, "capped"); + assert.ok(full.score > score, "points instead"); +}); + +test("Ghoul Rush: a 3 costs the life and he comes back with Rapid fire and a Garlic shield, a 2 with Bottle Rockets and a Garlic shield", () => { + for (const [value, check] of [ + [THREE, (round) => assert.equal(round.effects.rapid, ghoul.POWERS.rapid.ms)], + [TWO, (round) => assert.deepEqual(round.arms.map((a) => [a.kind, a.n]), [["rocket", ghoul.POWERS.rocket.sticks]])], + ]) { + const round = hall(2); + ghoul.lose(round, "zombie"); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(value)); + assert.equal(round.phase, "crash", "the life is lost"); + assert.equal(round.lives, 2); + assert.equal(round.dice, 1, "and no second die is rolled"); + assert.equal(round.you.garlic, false, "not until he is back"); + assert.equal(events(round, "diceGift").length, 0); + ghoul.advance(round, ghoul.CRASH_MS + 8, steady); + assert.equal(round.phase, "ready"); + assert.equal(round.you.garlic, true); + check(round); + assert.equal(events(round, "diceGift").length, 1); + assert.equal(round.diceGift, 0, "spent"); + // The next loss, with no die, leaves him nothing (long enough alive to earn no quick-fall shield). + round.you.aliveMs = 1e9; + round.dice = 0; + round.phase = "play"; + round.you.garlic = false; + round.you.safeMs = 0; + ghoul.lose(round, "zombie"); + ghoul.advance(round, ghoul.CRASH_MS + 8, steady); + assert.equal(round.you.garlic, false, "the gift comes once"); + assert.equal(events(round, "diceGift").length, 1); + check(round); + } +}); + +test("Ghoul Rush: a 1 costs the life and leaves nothing, with its laugh and its words", () => { + const round = hall(2); + ghoul.lose(round, "zombie"); + ghoul.advance(round, ghoul.ROLL_MS - 8, rolls(ONE)); + assert.equal(round.phase, "roll", "the beat has not finished"); + ghoul.advance(round, 16, steady); + assert.deepEqual(events(round, "diceFace").map((e) => e.face), [1]); + assert.equal(events(round, "diceFail").length, 1); + assert.equal(events(round, "diceSaved").length, 0); + assert.equal(round.dice, 1); + assert.equal(round.lives, 2); + assert.equal(round.phase, "crash"); + assert.equal(events(round, "lose").length, 1); + ghoul.advance(round, ghoul.CRASH_MS + 8, steady); + assert.equal(round.phase, "ready", "and the room starts over"); + assert.equal(events(round, "diceGift").length, 0); + assert.equal(round.arms.length, 0); + assert.equal(round.effects.rapid || 0, 0); + assert.equal(ghoul.DICE_FACES[1].line, "Better Luck Next Time"); +}); + +test("Ghoul Rush: on the last heart a 5 or 6 saves him in place, a 2, 3 or 4 pays one heart and he respawns as usual, a 1 loses the run", () => { + const saved = hall(1); + saved.lives = 1; + ghoul.lose(saved, "zombie"); + ghoul.advance(saved, ghoul.ROLL_MS + 8, rolls(FIVE)); + assert.equal(saved.lives, 2, "saved in place, with the 5's heart"); + assert.equal(saved.over, false); + assert.equal(saved.phase, "play"); + for (const face of [TWO, THREE, FOUR]) { + const mercy = hall(1); + mercy.lives = 1; + ghoul.lose(mercy, "zombie"); + ghoul.advance(mercy, ghoul.ROLL_MS + 8, rolls(face)); + assert.equal(events(mercy, "diceHeart").length, 1, "a heart is paid"); + assert.equal(mercy.phase, "crash", "the loss goes ahead"); + ghoul.advance(mercy, ghoul.CRASH_MS + 40, steady); + assert.notEqual(mercy.phase, "crash", "past the crash"); + assert.equal(mercy.lives, 1, "one heart left"); + assert.equal(mercy.over, false); + assert.ok(["ready", "play"].includes(mercy.phase), `respawned as usual (${mercy.phase})`); + assert.equal(mercy.diceGift, 0, "no gift on top"); + } + // Not on the last heart: a 3 is a gift, a 4 a save, as ever. + const plenty = hall(1); + plenty.lives = 2; + ghoul.lose(plenty, "zombie"); + ghoul.advance(plenty, ghoul.ROLL_MS + 8, rolls(FOUR)); + assert.equal(plenty.lives, 2); + assert.equal(events(plenty, "diceHeart").length, 0); + const lost = hall(1); + lost.lives = 1; + ghoul.lose(lost, "zombie"); + ghoul.advance(lost, ghoul.ROLL_MS + ghoul.CRASH_MS + 40, rolls(ONE)); + assert.equal(lost.lives, 0); + assert.equal(lost.over, true); +}); + +test("Ghoul Rush: endless lives never roll the dice", () => { + const round = hall(3); + round.infinite = true; + ghoul.lose(round, "zombie"); + assert.equal(round.phase, "crash"); + assert.equal(round.dice, 3, "kept"); + assert.equal(round.lives, 3); + assert.equal(events(round, "diceStart").length, 0); +}); + +test("Ghoul Rush: the clock running out can be saved too, with some time back", () => { + const round = hall(1); + round.timeMs = 5; + ghoul.advance(round, 8, steady); + assert.equal(round.phase, "roll"); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(SIX)); + assert.equal(round.phase, "play"); + assert.ok(round.timeMs > ghoul.SAVED_TIME_MS - 100 && round.timeMs <= ghoul.SAVED_TIME_MS); + assert.equal(round.lives, 4, "and a six's heart"); +}); + +test("Ghoul Rush: a pit fall rolls too, and a save puts Planny back on the last solid ground he stood on, clear of the edge", () => { + const pitRoom = ghoul.ROOMS.find((r) => ghoul.roomFor(r.id).ground.some((p, i, all) => i + 1 < all.length && p[1] < all[i + 1][0])); + assert.ok(pitRoom, "some room has a pit"); + const stage = ghoul.STAGES.find((st) => st.rooms.includes(pitRoom.id)); + const round = inRoom(ghoul.newRound(5), stage.id, pitRoom.id); + round.lives = 3; + round.dice = 1; + const g = round.spec.ground; + const at = g.findIndex((p, i) => i + 1 < g.length && p[1] < g[i + 1][0]); + const edge = g[at][1] - 0.2; + const y = g[at][2]; + stand(round, edge); + round.input.right = true; + ghoul.advance(round, 4, steady); + assert.equal(round.you.restX, round.you.x); + // Off the edge and down. + Object.assign(round.you, { x: g[at][1] + 2, y: ghoul.PIT_Y - 1, state: "air", vy: -20 }); + round.input.right = false; + round.you.safeMs = 1e9; + ghoul.advance(round, 4, steady); + assert.equal(round.phase, "roll"); + assert.equal(events(round, "diceStart")[0].cause, "pit"); + assert.equal(round.lives, 3); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(FOUR)); + assert.equal(round.phase, "play"); + const you = round.you; + assert.equal(you.y, y); + assert.equal(you.state, "run"); + assert.ok(you.x < g[at][1] - 1.9, "back from the edge"); + assert.ok(ghoul.groundAt(round.spec, you.x - 2) === y && ghoul.groundAt(round.spec, you.x + 2) === y, "with ground to both sides"); + assert.equal(you.garlic, false, "a 4 gives no shield"); + assert.equal(round.lives, 3); + // A low roll and the fall costs the life. + const lost = inRoom(ghoul.newRound(5), stage.id, pitRoom.id); + lost.dice = 1; + Object.assign(lost.you, { y: ghoul.PIT_Y - 1, state: "air", vy: -20 }); + lost.lives = 3; + lost.you.safeMs = 1e9; + ghoul.advance(lost, 4, steady); + ghoul.advance(lost, ghoul.ROLL_MS + 8, rolls(0.2)); + assert.equal(lost.lives, 2); + assert.equal(lost.phase, "crash"); +}); + +test("Ghoul Rush: in an ordinary room a saved life blows apart every monster in view, for their points but with nothing dropped, and leaves the ones out of view", () => { + const round = hall(1); + round.you.x = 100; + const near = [zombie(round, 110), zombie(round, 130), zombie(round, round.camX + 5)]; + const far = zombie(round, round.camX + ghoul.FIELD_W + 40); + const score = round.score; + ghoul.lose(round, "zombie"); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(SIX)); + assert.equal(round.phase, "play"); + assert.ok(near.every((m) => m.dead), "all in view are dead"); + assert.ok(!far.dead && round.monsters.includes(far), "the one out of view lives"); + assert.deepEqual(round.monsters, [far], "the dead are cleared away"); + assert.equal(events(round, "diceBlast").length, 3); + assert.equal(events(round, "diceSaved")[0].blasted, 3); + assert.equal(events(round, "kill").length, 3); + assert.ok(round.score > score, "their points count"); + assert.equal(round.drops.length, 0, "and they leave nothing"); + assert.equal(round.you.garlic, true, "the shield stays too"); + // Any saving face blows them apart, not only a six. + const four = hall(1); + const by = zombie(four, 110); + ghoul.lose(four, "zombie"); + ghoul.advance(four, ghoul.ROLL_MS + 8, rolls(FOUR)); + assert.ok(by.dead); +}); + +test("Ghoul Rush: in a boss's room a saved life blows nothing apart, and the boss is untouched", () => { + const round = inRoom(ghoul.newRound(5), "wing", "crypt"); + round.you.safeMs = 0; + round.boss.state = "fight"; + round.boss.t = -1e9; + const hp = round.boss.hp; + const m = ghoul.spawnMonster(round, "zombie", round.you.x + 6, ghoul.groundAt(round.spec, round.you.x + 6), { rise: 0, awake: true }); + round.dice = 1; + round.events.length = 0; + ghoul.lose(round, "bones"); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(SIX)); + assert.equal(round.phase, "play"); + assert.ok(!m.dead && round.monsters.includes(m), "the monster stands"); + assert.equal(round.boss.hp, hp); + assert.equal(round.boss.state, "fight"); + assert.equal(events(round, "diceBlast").length, 0); + assert.equal(events(round, "diceSaved")[0].blasted, 0); + assert.equal(round.you.garlic, true); + assert.ok(round.you.safeMs > 0, "the safe moment covers him"); +}); + +test("Ghoul Rush: every step of the roll has a look and a sound, and the revive's jingle plays once", () => { + const round = hall(3); + zombie(round, 110); + ghoul.lose(round, "zombie"); + ghoul.advance(round, ghoul.ROLL_MS + 8, rolls(SIX)); + const played = []; + const fx = {}; + const kit = { + tone: (name) => played.push(name), + burst() {}, + float() {}, + ring() {}, + banner() {}, + shake() {}, + flash() {}, + glow() {}, + splat() {}, + floorAt: () => 6, + markFurthest() {}, + roomBanner() {}, + fx, + monsters: ghoul.MONSTERS, + powers: ghoul.POWERS, + bosses: ghoul.BOSSES, + g: { READY_MS: ghoul.READY_MS, BOSS_INTRO_MS: ghoul.BOSS_INTRO_MS, CLEAR_MS: ghoul.CLEAR_MS }, + }; + for (const e of round.events) react(e, kit); + assert.equal(played.filter((n) => n === "ghoulLuckySave").length, 1); + for (const type of ["diceStart", "diceRoll", "diceFace", "diceSaved", "diceBlast", "diceFail", "diceGift"]) { + const sounds = []; + const face = type === "diceSaved" ? 5 : 3; + react({ type, face, x: 10, y: 6, n: 1 }, { ...kit, tone: (n) => sounds.push(n) }); + if (type !== "diceBlast") assert.ok(sounds.length, `${type} has a sound`); + } + // A 1 laughs, with the mechanical laugh, and the toll stays out of its way. + const laugh = []; + react({ type: "diceFace", face: 1, x: 10, y: 6 }, { ...kit, tone: (n) => laugh.push(n) }); + assert.deepEqual(laugh, ["ghoulDiceLaugh"]); + const after = []; + react({ type: "diceFail", face: 1, x: 10, y: 6 }, { ...kit, tone: (n) => after.push(n) }); + assert.deepEqual(after, []); + assert.ok(toneNames().includes("ghoulDiceLaugh"), "the laugh is a tone"); + assert.ok(fx.lucky && fx.lucky.life > 0, "the word starts to sweep"); +}); diff --git a/scripts/test-web-console-activities-ghoul-frozen.mjs b/scripts/test-web-console-activities-ghoul-frozen.mjs new file mode 100644 index 0000000..26e56c5 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-frozen.mjs @@ -0,0 +1,1635 @@ +// Web console tests, Ghoul Rush's Frozen Lake stage: its rooms (Ice Fishing Huts, Snowbound Lodge, The Black Ice, the Widow's Web), slippery ice and thin ice that cracks and breaks, under-ice hands, snow shades you only see by their footprints, frozen ghouls that slide and shatter, ice wraiths whose dive leaves you frozen, Hot Cocoa and the Road Flare (found only here), and the Frost Widow, whose veil melts only to a burning barrel or a flare. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as fz from "../src/web-console/public/activities/ghoul-frozen.js"; +import * as fl from "../src/web-console/public/activities/ghoul-flare.js"; +import * as arm from "../src/web-console/public/activities/ghoul-arms.js"; +import { PILL_WORDS, STAGE_ARMS, armDrop, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import { BONES } from "../src/web-console/public/activities/ghoul-bones.js"; +import { GRAVEYARD } from "../src/web-console/public/activities/ghoul-graveyard.js"; +import { GROUNDS } from "../src/web-console/public/activities/ghoul-grounds.js"; +import { CHAPEL } from "../src/web-console/public/activities/ghoul-chapel.js"; +import { SANATORIUM } from "../src/web-console/public/activities/ghoul-sanatorium.js"; +import { VILLAGE } from "../src/web-console/public/activities/ghoul-village.js"; +import { MINE } from "../src/web-console/public/activities/ghoul-mine.js"; +import { CART } from "../src/web-console/public/activities/ghoul-cart.js"; +import { CARNIVAL } from "../src/web-console/public/activities/ghoul-carnival.js"; +import { LOOKS, VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, SILENT } from "../src/web-console/public/activities/ghoul-frozen-draw.js"; +import { FROZEN_SFX } from "../src/web-console/public/activities/ghoul-sfx-frozen.js"; +import { SLED_SFX } from "../src/web-console/public/activities/ghoul-sfx-sled.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the frozen lake drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); +// Fire tapped twice, as the keys do it. +const tapTap = (round) => { + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + ghoul.releaseFire(round); +}; +// The four rooms that are walked, and the stage's five with the bonus sled ride between the Black Ice and the Widow's Web (its own suite: ghoul-sled). +const ROOM_IDS = ["huts", "lodge", "blackice", "widow"]; +const STAGE_ROOMS = ["huts", "lodge", "blackice", "sled", "widow"]; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Frozen Lake's room `id` at `depth` stages cleared, reached the way play reaches it, nothing woken: every spawner spent, the horde held back. +function frozenRound(id, depth = 0) { + const round = ghoul.newRound(5); + round.lives = 3; + round.dice = 0; + through(round); + for (let i = 0; i < depth; i++) round.cleared.push(`stage${i}`); + round.offer = ["frozen"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.bonus = 1e9; + round.dark = false; + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face, ducking: false, slide: 0, glide: false, onIce: false, heldMs: 0 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +function until(round, done, ms = 4000, random = steady) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); +} + +// Runs until an event of `type` is on the field (leaving it there) or `ms` pass; the event, or null. +function upTo(round, type, ms = 4000, random = steady) { + round.events.length = 0; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + const e = round.events.find((x) => x.type === type); + if (e) return e; + } + return null; +} + +// A bolt arriving from the left at height `y` on the thing `m` (a monster or the boss). +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +// The Widow's Web with her awake (the fight on), Planny in the arena. +function widowFight({ x, depth = 0 } = {}) { + const round = frozenRound("widow", depth); + standAt(round, round.spec.arena + 12); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 16, steady); + assert.equal(round.boss.state, "fight"); + if (x !== undefined) standAt(round, x); + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +const tile = (round, i = 0) => round.thin.tiles[i]; + +/* ------------------------------------------------------------ the stage */ + +test("Ghoul Rush's Frozen Lake is a stage of three rooms and the Widow's Web, its monsters and boss joined to the game's, with a place for each kind, ice and thin ice in the rooms, last in the list", () => { + const st = ghoul.stageById("frozen"); + assert.deepEqual(st.rooms, STAGE_ROOMS); + assert.deepEqual(fz.FROZEN_ROOMS, STAGE_ROOMS); + assert.equal(st.boss, "frostwidow"); + assert.equal(st.title, "The Frozen Lake"); + assert.equal(st.sub, "The ice remembers who fell through"); + assert.equal(ghoul.STAGES.at(-1), st, "the last stage in the list"); + for (const kind of Object.keys(fz.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], fz.MONSTERS[kind], `${kind} is a monster`); + assert.deepEqual(Object.keys(fz.MONSTERS).sort(), ["frozen", "hand", "icewraith", "shade"]); + assert.equal(ghoul.BOSSES.frostwidow, fz.BOSSES.frostwidow); + assert.equal(fz.BOSSES.frostwidow.sub, "Melt her veil, then her heart"); + assert.deepEqual([ghoul.BOSSES.frostwidow.w, ghoul.BOSSES.frostwidow.h, ghoul.BOSSES.frostwidow.hp, ghoul.BOSSES.frostwidow.points], [10, 15, 90, 3000]); + assert.ok(ghoul.MONSTERS.hand.hp === 2 && ghoul.MONSTERS.shade.hp === 3 && ghoul.MONSTERS.frozen.hp === 4 && ghoul.MONSTERS.icewraith.hp === 2); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const picks = { huts: "ghoulHuts", lodge: "ghoulLodge", blackice: "ghoulBlackIce", sled: "ghoulSledRide", widow: "ghoulWidow" }; + const stageMusic = Object.assign({}, FROZEN_SFX.music, SLED_SFX.music); + for (const [id, tone] of Object.entries(picks)) { + assert.equal(ghoul.ROOM_MUSIC[id], tone, `${id} plays its own track`); + assert.ok(stageMusic[tone] && stageMusic[tone].voices, `${tone} is a track in the stage's own sfx module`); + assert.ok(ghoulSfx.default.music[tone], `${tone} is merged into the game's music`); + } + assert.equal(new Set(Object.values(picks)).size, 5, "five different tracks"); + const [huts, lodge, blackice, widow] = ROOM_IDS.map((id) => ghoul.roomById(id)); + assert.deepEqual([huts.title, lodge.title, blackice.title, widow.title], ["Ice Fishing Huts", "Snowbound Lodge", "The Black Ice", "The Widow's Web"]); + assert.deepEqual([huts.sub, lodge.sub, blackice.sub, widow.sub], ["The lines are all pulled taut", "The fire went out a long time ago", "Faces under the surface follow you", "Melt her veil, then her heart"]); + const returning = ["zombie", "bat", "skel"]; + for (const room of [huts, lodge, blackice]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + const cocoa = room.items.find((i) => i[0] === "cocoa"); + const flare = room.items.find((i) => i[0] === "flare"); + assert.ok(cocoa && flare, `${room.id}: Hot Cocoa and a Road Flare`); + const firstNew = Math.min(...room.spawns.filter((s) => s[0] in fz.MONSTERS).map((s) => s[1])); + assert.ok(cocoa[1] < firstNew + 60 && flare[1] < firstNew + 60, `${room.id}: the stage's power-up and weapon come before what they answer`); + assert.ok(room.spawns.some((s) => s[0] in fz.MONSTERS), `${room.id}: some of the new monsters`); + assert.ok(room.spawns.some((s) => returning.includes(s[0])), `${room.id}: some returning ones`); + assert.ok(room.ice.length >= 2 && room.thin.length >= 2, `${room.id}: ice and thin ice`); + // The key shelf has a board right under it, so a run at the key climbs it. + assert.ok(room.shelves.some(([a, b, y]) => y === 24 && a <= room.key[0] && b >= room.key[0]), `${room.id}: the key on a shelf 24 up`); + assert.ok(room.shelves.some(([a, b, y]) => y === 15 && a <= room.key[0] && b >= room.key[0]), `${room.id}: a step under the key shelf`); + assert.equal(room.dark, null, `${room.id}: dark or lit by the roll`); + } + assert.ok(widow.items.some((i) => i[0] === "cocoa") && widow.items.some((i) => i[0] === "flare"), "the boss room has both too"); + assert.equal(widow.boss, "frostwidow"); + assert.equal(widow.horde.length, 0); + assert.ok(widow.ice.length && widow.thin.length === 0, "the arena is ice, with no thin tiles"); + // Where each new kind turns up: harder in order. + const count = (room, kind) => room.spawns.filter((s) => s[0] === kind).length; + assert.ok(count(huts, "hand") <= 2 && count(huts, "shade") === 1 && count(huts, "icewraith") === 1, "the Huts: two hands, one shade, one wraith"); + assert.ok(count(lodge, "shade") >= 3, "the Lodge is full of shades"); + assert.ok(count(blackice, "hand") >= 6 && count(blackice, "icewraith") >= 2, "the Black Ice: hands everywhere, wraiths"); + assert.ok(huts.thin.length <= lodge.thin.length && lodge.thin.length < blackice.thin.length, "more thin ice in order"); + assert.ok(blackice.thin.length >= 8, "the Black Ice is full of thin patches"); + assert.ok(huts.spawns.length <= lodge.spawns.length && lodge.spawns.length <= blackice.spawns.length); + assert.ok(huts.hordeMs > lodge.hordeMs && lodge.hordeMs > blackice.hordeMs, "the horde quickens"); + // The room fields pass through the room builder, and exist (empty) everywhere else. + assert.deepEqual(ghoul.roomFor("huts").ice, huts.ice); + assert.deepEqual(ghoul.roomFor("blackice").thin, blackice.thin); + assert.deepEqual(ghoul.roomFor("hall").ice, []); + assert.deepEqual(ghoul.roomFor("hall").thin, []); + // The ice lies on level floor; the thin tiles each on one level piece, with floor of their own piece clear either side and between. + for (const room of [huts, lodge, blackice, widow]) { + for (const [a, b] of room.ice) { + const piece = room.ground.find(([x0, x1]) => a >= x0 && b <= x1); + assert.ok(piece, `${room.id}: the ice ${a} to ${b} lies on one piece of floor`); + } + const tiles = [...room.thin].sort((p, q) => p[0] - q[0]); + tiles.forEach(([a, b], i) => { + const piece = room.ground.find(([x0, x1]) => a >= x0 && b <= x1); + assert.ok(piece, `${room.id}: the thin tile ${a} to ${b} is on one level piece`); + assert.ok(a - piece[0] >= 6 && piece[1] - b >= 6, `${room.id}: the tile ${a} keeps 6 of its piece clear either side`); + assert.ok(b - a >= 5 && ghoul.jumpHeightAt(b - a + 0.6) >= 0.6 + 4, `${room.id}: the tile ${a} is wide enough to mean something and narrow enough to jump with room to spare`); + if (i) assert.ok(a - tiles[i - 1][1] >= 6, `${room.id}: solid floor between the tiles at ${tiles[i - 1][0]} and ${a}`); + assert.ok(room.ice.some(([x0, x1]) => a >= x0 && b <= x1) || room.id === "lodge", `${room.id}: the tile ${a} on the ice`); + }); + } + assert.ok(ghoul.default.create && ghoul.stageById("frozen")); +}); + +test("Ghoul Rush's Frozen Lake shares no hazard, monster, boss, act or tick-state name with another stage's pack (the packs' tables are merged by name)", () => { + for (const key of ["monsters", "bosses", "hazards", "move", "boss", "act", "solid", "harmless", "platform", "kill", "weak", "swoops", "guard", "unseen", "slides", "cause", "land", "horde"]) { + for (const other of [BONES, GRAVEYARD, GROUNDS, CHAPEL, SANATORIUM, VILLAGE, MINE, CART, CARNIVAL, arm.ARMS]) { + for (const name of Object.keys(fz.FROZEN[key] || {})) assert.ok(!(other[key] && name in other[key]), `${key}.${name} is also ${other.id}'s`); + } + } + for (const name of ["shard", "spike", "webGlob", "webPatch", "barrel"]) assert.ok(fz.FROZEN.hazards[name], `${name} is a hazard of the pack`); + assert.ok(arm.ARMS.hazards.armRoadFlare && arm.ARMS.hazards.armRoadFire, "the flare's two hazards are the arms'"); + assert.deepEqual(Object.keys(fz.FROZEN.slides), ["frozen"]); +}); + +/* ------------------------------------------------------------ slippery ice */ + +test("Ghoul Rush's slippery ice: his run eases toward the held direction and, let go, he slides about 8 units; off the ice he runs as ever; a jump keeps what he had; Hot Cocoa turns it off; a wall stops it", () => { + const on = frozenRound("huts"); + standAt(on, 24); + run(on, 100, { right: true }); + assert.ok(on.you.slide > 0 && on.you.slide < ghoul.RUN_SPEED - 10, `eased in (${on.you.slide.toFixed(1)} after 100 ms)`); + assert.equal(on.you.onIce, true); + run(on, 600, { right: true }); + assert.equal(on.you.slide, ghoul.RUN_SPEED, "up to a full run in the end"); + const x0 = on.you.x; + run(on, 40); + assert.ok(on.you.slide > 0, "let go, he is still sliding"); + run(on, 1400); + assert.equal(on.you.slide, 0, "and stopped"); + const slid = on.you.x - x0; + assert.ok(slid > 5 && slid < 10, `about 8 units of slide (${slid.toFixed(1)})`); + // Turning round is braked, not instant. + standAt(on, 60); + run(on, 700, { right: true }); + run(on, 60, { left: true }); + assert.ok(on.you.slide > 0 || on.you.x > 60, "still carried right a moment after turning left"); + run(on, 900, { left: true }); + assert.equal(on.you.slide, -ghoul.RUN_SPEED, "then running left"); + // Off the ice, the plain run at once. + const off = frozenRound("huts"); + standAt(off, 120); + run(off, 16, { right: true }); + assert.equal(off.you.slide, ghoul.RUN_SPEED); + const x1 = off.you.x; + run(off, 100); + assert.ok(Math.abs(off.you.x - x1) < 0.01, "and he stops at once"); + // A jump from the ice keeps the speed: no friction in the air. + const jump = frozenRound("huts"); + standAt(jump, 24); + run(jump, 800, { right: true }); + ghoul.jump(jump); + const xj = jump.you.x; + run(jump, 200); + assert.equal(jump.you.state, "air"); + assert.ok(jump.you.x - xj > 6, `he sails on (${(jump.you.x - xj).toFixed(1)} in 200 ms)`); + assert.equal(jump.you.glide, true); + run(jump, 1000); + assert.equal(jump.you.state, "run"); + assert.equal(jump.you.glide, false, "landed on ice or not, the glide is spent"); + // Hot Cocoa: no sliding. + const cocoa = frozenRound("huts"); + ghoul.applyPower(cocoa, "cocoa"); + standAt(cocoa, 24); + run(cocoa, 16, { right: true }); + assert.equal(cocoa.you.slide, ghoul.RUN_SPEED, "a full run at once"); + const xc = cocoa.you.x; + run(cocoa, 100); + assert.ok(Math.abs(cocoa.you.x - xc) < 0.01, "and he stops at once"); + // The room's end stops a slide. + const end = frozenRound("widow"); + standAt(end, 180); + run(end, 1200, { right: true }); + run(end, 16); + assert.equal(end.you.slide, 0, "against the end of the room it is spent"); + assert.ok(end.you.x <= end.spec.length - 1.5); + // Rooms with no ice are untouched: no easing, the field untouched. + const hall = ghoul.newRound(3); + hall.dice = 0; + hall.phase = "play"; + hall.monsters.length = 0; + run(hall, 16, { right: true }); + assert.equal(hall.you.slide, 0, "nothing eases there"); + const hx = hall.you.x; + run(hall, 100); + assert.ok(Math.abs(hall.you.x - hx) < 0.01, "a hall runs and stops as ever"); +}); + +test("Ghoul Rush's Frozen Ghoul is a zombie that slides: it eases to its pace on ice, carries on when you turn it round, and walks plainly off it", () => { + const round = frozenRound("huts"); + standAt(round, 90); + round.you.safeMs = 1e9; + const m = put(round, "frozen", 40); + assert.ok(ghoul.ZOMBIES.has("frozen"), "a zombie in every way but its death"); + run(round, 200); + assert.ok(m.sv > 0 && m.sv < ghoul.MONSTERS.frozen.speed, `eased in (${m.sv.toFixed(1)})`); + run(round, 1500); + assert.ok(m.sv >= ghoul.MONSTERS.frozen.speed - 0.01 || m.x > 60, "up to its pace"); + // You go round behind it: it keeps sliding the old way a moment, then turns. + standAt(round, 20); + m.sv = 18; + const before = m.x; + run(round, 200); + assert.ok(m.x > before, "it carried on"); + run(round, 2000); + assert.ok(m.sv < 0 && m.x < before + 6, "and then came back"); + // Off the ice, a plain walk: its speed is its pace at once. + const dry = frozenRound("huts"); + standAt(dry, 150); + dry.you.safeMs = 1e9; + const d = put(dry, "frozen", 120); + run(dry, 20); + assert.equal(d.sv, ghoul.MONSTERS.frozen.speed); + // It lurches when you are near, on its level. + const near = frozenRound("huts"); + standAt(near, 90); + const n = put(near, "frozen", 76); + run(near, 1600); + assert.equal(n.lurching, true); +}); + +/* -------------------------------------------------------------- thin ice */ + +test("Ghoul Rush's thin ice: a tile cracks after THIN_WARN_MS of standing on it, breaks at THIN_MS into a pit and costs a life (cause ice), heals when stepped off, and freezes again", () => { + assert.equal(fz.THIN_WARN_MS, 500); + assert.equal(fz.THIN_MS, 1300); + const round = frozenRound("huts"); + const t = tile(round); + assert.deepEqual([t.x0, t.x1], [190, 196]); + assert.equal(t.state, "ok"); + standAt(round, 193); + round.you.safeMs = 0; + run(round, fz.THIN_WARN_MS - 40); + assert.equal(t.state, "ok"); + assert.equal(events(round, "iceCrack").length, 0); + run(round, 80); + assert.equal(t.state, "crack", "a crack shows"); + assert.equal(events(round, "iceCrack")[0]?.by, "you"); + assert.equal(ghoul.groundAt(round.spec, 193), 6, "still a floor"); + // Stepped off before it goes, it heals (at half the rate it grew). + standAt(round, 180); + run(round, 1200); + assert.equal(t.state, "ok"); + assert.equal(t.t, 0); + // Stood on to the end: through the ice. + standAt(round, 193); + round.you.safeMs = 0; + const lives = round.lives; + round.events.length = 0; + run(round, fz.THIN_MS + 40); + assert.equal(t.state, "broken"); + const broke = events(round, "iceBreak")[0]; + assert.ok(broke && broke.under === true, "it broke under him"); + assert.equal(events(round, "lose")[0]?.cause, "ice", "went through the ice"); + assert.equal(round.lives, lives - 1); + assert.equal(round.phase, "crash"); + assert.equal(ghoul.groundAt(round.spec, 193), -Infinity, "a pit where the tile was"); + assert.ok(ghoul.groundAt(round.spec, 189) === 6 && ghoul.groundAt(round.spec, 197) === 6, "floor either side"); + assert.equal(round.spec.base.ground, ghoul.roomFor("huts").ground, "the room's own floor is kept whole"); + // The next life: the ice is whole again. + run(round, ghoul.CRASH_MS + 80); + assert.equal(round.phase, "ready"); + assert.equal(ghoul.groundAt(round.spec, 193), 6, "a life later the floor is back"); + assert.equal(tile(round).state, "ok"); + // It freezes again on its own, after THIN_BACK_MS, when nobody is under it. + const other = frozenRound("huts"); + standAt(other, 100); + other.you.safeMs = 1e9; + const o = tile(other); + fz.crackTile(other, o); + run(other, fz.THIN_MS); + assert.equal(o.state, "broken"); + assert.equal(events(other, "iceBreak")[0].under, false); + assert.equal(ghoul.groundAt(other.spec, 193), -Infinity); + run(other, fz.THIN_BACK_MS - 800); + assert.equal(o.state, "broken"); + run(other, 400); + assert.equal(o.state, "ok"); + assert.equal(events(other, "iceBack").length, 1); + assert.equal(ghoul.groundAt(other.spec, 193), 6); +}); + +test("Ghoul Rush's thin ice: a crack that opens under a walker drops it too, in the air above it he falls in as into a pit, Hot Cocoa halves how fast it cracks, and endless lives spare the fall", () => { + const round = frozenRound("huts"); + standAt(round, 120); + round.you.safeMs = 1e9; + const z = put(round, "zombie", 193, { stunMs: 0 }); + fz.crackTile(round, tile(round)); + tile(round).t = fz.THIN_MS - 60; + z.wait = 0; + round.you.x = 193.3; + round.you.y = 6; + run(round, 100); + assert.equal(tile(round).state, "broken"); + run(round, 600); + assert.ok(z.dead || z.y < 0 || !round.monsters.includes(z), "a walker on it falls through"); + // Over the tile in the air when it breaks: a pit, so the plain fall (wings aside). + const air = frozenRound("huts"); + standAt(air, 193); + air.you.safeMs = 0; + ghoul.jump(air); + run(air, 60); + assert.equal(air.you.state, "air"); + fz.crackTile(air, tile(air)); + tile(air).t = fz.THIN_MS - 20; + run(air, 40); + assert.equal(tile(air).state, "broken"); + assert.equal(events(air, "iceBreak")[0].under, false, "not under him: he was in the air"); + until(air, () => events(air, "lose").length > 0, 1500); + assert.equal(events(air, "lose")[0]?.cause, "pit", "he fell in as into a pit"); + // Cocoa: the same time stands twice as long. + const cocoa = frozenRound("huts"); + ghoul.applyPower(cocoa, "cocoa"); + standAt(cocoa, 193); + run(cocoa, fz.THIN_MS); + assert.equal(tile(cocoa).state, "crack", "still holding at THIN_MS"); + assert.ok(tile(cocoa).t < fz.THIN_MS * 0.55 + 20 && tile(cocoa).t > fz.THIN_MS * 0.45, `half the growth (${tile(cocoa).t})`); + run(cocoa, fz.THIN_MS * 1.2); + assert.equal(tile(cocoa).state, "broken"); + // Endless lives: through the ice costs nothing. + for (const infinite of [false, true]) { + const r = frozenRound("huts"); + r.infinite = infinite; + standAt(r, 193); + r.you.safeMs = 0; + run(r, fz.THIN_MS + 40); + assert.equal(events(r, "lose")[0]?.cause, "ice"); + assert.equal(r.lives, infinite ? 3 : 2, infinite ? "spared" : "costs one"); + } + // A thin tile in another room is not shared: each room has its own tiles. + const lodge = frozenRound("lodge"); + assert.equal(lodge.thin.tiles.length, 3); + assert.deepEqual(lodge.thin.tiles.map((t) => t.x0), [250, 384, 470]); + assert.equal(ghoul.newRound(1).thin, null, "the hall has none"); +}); + +/* ----------------------------------------------------------------- hands */ + +test("Ghoul Rush's Under-Ice Hand tracks you under the ice, warns, then cracks the thin tile over it or, with none, bursts up and grabs; under the ice it is neither solid nor hit", () => { + const round = frozenRound("huts"); + standAt(round, 120); + round.you.safeMs = 0; + const m = put(round, "hand", 100); + assert.equal(m.act, "trail"); + assert.equal(ghoul.solid(m), false, "under the ice it is not there"); + bolt(round, m, m.y + 1.5); + round.shots[0].x = m.x - 3; + run(round, 40); + assert.equal(m.hp, 2, "a bolt goes over it"); + round.shots.length = 0; + const warn = upTo(round, "handWarn", 3000); + assert.ok(warn, "it warns"); + assert.equal(m.act, "warn"); + const t0 = round.clock; + const up = upTo(round, "handUp", 1500); + assert.ok(up, "then it bursts up"); + assert.ok(Math.abs(round.clock - t0 - fz.HAND_WARN_MS) < 40, `warned ${fz.HAND_WARN_MS} ms (${round.clock - t0})`); + assert.equal(m.act, "grab"); + assert.equal(ghoul.solid(m), true, "up, it can be hit"); + assert.equal(events(round, "iceCrack").length, 0, "no tile to crack here"); + // Up, it hurts where it stands. + const hurt = frozenRound("huts"); + standAt(hurt, 112); + put(hurt, "hand", 112, { act: "grab", wait: 1000 }); + run(hurt, 20); + assert.equal(events(hurt, "lose")[0]?.cause, "hand"); + // And it is shot or stomped. + const shot = frozenRound("huts"); + standAt(shot, 90); + const g = put(shot, "hand", 100, { act: "grab", wait: 1000 }); + bolt(shot, g, g.y + 1.5); + run(shot, 60); + assert.ok(g.hp < 2 || g.dead); + // Over a thin tile it cracks it (no grab) and goes down. + const tiled = frozenRound("huts"); + standAt(tiled, 170); + tiled.you.safeMs = 1e9; + const h = put(tiled, "hand", 193, { act: "warn", wait: 30 }); + run(tiled, 80); + assert.equal(events(tiled, "handUp").length, 0, "no grab where there is a tile to crack"); + assert.equal(events(tiled, "iceCrack")[0]?.by, "hand"); + assert.equal(tile(tiled).state, "crack"); + assert.equal(tile(tiled).hand, true); + assert.equal(h.act, "sink"); + // A tile a hand has cracked breaks by itself, with nobody on it. + run(tiled, fz.THIN_MS); + assert.equal(tile(tiled).state, "broken"); + assert.equal(events(tiled, "iceBreak")[0].under, false); + // It trails again after, and never across a pit. + const dry = frozenRound("huts"); + standAt(dry, 270); + const far = put(dry, "hand", 230); + run(dry, 3000); + assert.ok(far.x < 238, "it cannot cross the pit"); +}); + +/* ---------------------------------------------------------------- shades */ + +test("Ghoul Rush's Snow Shade is out of sight (not solid, nothing to shoot) and leaves footprints; a bolt coming at it, its own attack, a flare or Flash Powder show it", () => { + const round = frozenRound("huts"); + standAt(round, 40); + round.you.safeMs = 1e9; + const m = put(round, "shade", 70); + run(round, 16); + assert.equal(m.unseen, true); + assert.equal(ghoul.solid(m), false); + run(round, 2400); + assert.ok(m.x < 70, "it stalks you"); + assert.ok(m.prints.length >= 2, `footprints (${m.prints.length})`); + assert.ok(m.prints.every((p) => p.y === 6 && p.age >= 0)); + assert.ok(m.prints.length <= fz.PRINT_KEEP); + // Touch does nothing while it is unseen. + const touch = frozenRound("huts"); + standAt(touch, 50); + touch.you.safeMs = 0; + const t = put(touch, "shade", 50.5, { act: "rest", wait: 1e9 }); + run(touch, 40); + assert.equal(t.unseen, true); + assert.equal(events(touch, "lose").length, 0, "an unseen shade is harmless to touch"); + // A bolt heading for it shows it, so the next bolt hits. + const shot = frozenRound("huts"); + standAt(shot, 40); + shot.you.safeMs = 1e9; + const s = put(shot, "shade", 70, { act: "rest", wait: 1e9 }); + run(shot, 8); + assert.equal(s.shownMs ?? 0, 0); + shot.shots.push({ x: 56, y: 8.4, vx: 130, vy: 0, gone: 0 }); + run(shot, 8); + assert.ok(events(shot, "shadeShow").length === 1, "shown"); + assert.ok(s.shownMs > 0 && s.shownMs <= fz.SHADE_SHOW_MS); + run(shot, 120); + assert.equal(s.hp, 2, "and the bolt hits it"); + // It stays shown SHADE_SHOW_MS, then fades. + run(shot, fz.SHADE_SHOW_MS + 100); + run(shot, 8); + assert.equal(s.unseen, true); + // A bolt flying away from it, or far off, shows nothing. + const far = frozenRound("huts"); + standAt(far, 40); + const f = put(far, "shade", 100, { act: "rest", wait: 1e9 }); + far.shots.push({ x: 60, y: 8.4, vx: 130, vy: 0, gone: 0 }); + far.shots.push({ x: 90, y: 8.4, vx: -130, vy: 0, gone: 0 }); + run(far, 8); + assert.equal(f.shownMs ?? 0, 0); + // Its attack shows it: a wind-up, a lunge, a rest, and a hit costs a life (cause shade). + const atk = frozenRound("huts"); + standAt(atk, 40); + atk.you.safeMs = 0; + const a = put(atk, "shade", 49); + const wind = upTo(atk, "shadeWind", 1500); + assert.ok(wind, "it winds up within range"); + run(atk, 8); + assert.equal(a.unseen, false, "shown while it attacks"); + assert.ok(upTo(atk, "shadeLunge", 1500)); + until(atk, () => events(atk, "lose").length > 0, 1500); + assert.equal(events(atk, "lose")[0]?.cause, "shade"); + // A flare's light or Flash Powder (m.litMs) shows it too. + const lit = frozenRound("huts"); + standAt(lit, 40); + const l = put(lit, "shade", 90, { act: "rest", wait: 1e9 }); + l.litMs = 500; + run(lit, 16); + assert.equal(l.unseen, false); + assert.equal(ghoul.solid(l), true); +}); + +/* ------------------------------------------------- frozen ghouls shatter */ + +test("Ghoul Rush's Frozen Ghoul shatters into two chest-high shards, one each way, that cross the whole screen, are ducked, and hurt only after a moment; a flare melts it without shards", () => { + const round = frozenRound("huts"); + standAt(round, 100, -1); + round.you.safeMs = 1e9; + const m = put(round, "frozen", 70); + ghoul.hurt(round, m, 99, "shot", () => 1); + const shards = round.hazards.filter((h) => h.kind === "shard"); + assert.equal(shards.length, 2); + assert.equal(events(round, "shatter").length, 1); + assert.ok(shards.every((s) => s.off >= ghoul.DUCK_H + 0.2), "both over a ducked head"); + assert.deepEqual(shards.map((s) => Math.sign(s.vx)).sort(), [-1, 1], "one each way"); + assert.equal(Math.sign(shards.find((s) => s.vx > 0).vx), 1, "one flies at you"); + assert.ok(shards.every((s) => s.warn === fz.SHARD_WARN_MS && s.live === 0 && s.cause === "shard")); + // They hurt only once the warning is over. + const early = frozenRound("huts"); + standAt(early, 74); + early.you.safeMs = 0; + const e = put(early, "frozen", 72); + ghoul.hurt(early, e, 99, "shot", () => 1); + run(early, fz.SHARD_WARN_MS - 40); + assert.equal(events(early, "lose").length, 0, "no hurt while they tinkle"); + run(early, 400); + assert.equal(events(early, "lose")[0]?.cause, "shard", "then a life"); + // They are ducked, from either side. + for (const ducked of [true, false]) { + const d = frozenRound("huts"); + standAt(d, 80); + d.you.safeMs = 0; + const g = put(d, "frozen", 72); + ghoul.hurt(d, g, 99, "shot", () => 1); + d.input.down = ducked; + run(d, 700); + assert.equal(events(d, "lose").length, ducked ? 0 : 1, ducked ? "passes overhead" : "hits standing"); + } + // A shard crosses the whole screen, then is gone. + const far = frozenRound("huts"); + standAt(far, 20); + far.you.safeMs = 1e9; + far.hazards.push({ kind: "shard", x: 24, y: 8.8, off: 2.8, vx: 26, w: 1.8, h: 1.2, warn: 0, life: fz.SHARD_LIFE_MS, live: 1, cause: "shard" }); + run(far, 1500); + const sh = far.hazards.find((h) => h.kind === "shard"); + assert.ok(sh && sh.x > 24 + 26 * 1.4 - 1, `still flying past 17 units (${sh && sh.x})`); + run(far, 4000); + assert.ok(!far.hazards.some((h) => h.kind === "shard"), "gone off the screen"); + // A shard ends at a pit, never rides on, and there are never too many. + const pit = frozenRound("huts"); + standAt(pit, 20); + pit.hazards.push({ kind: "shard", x: 233, y: 6, off: 0, vx: 26, w: 1.8, h: 1.3, warn: 0, life: 2000, live: 1, cause: "shard" }); + run(pit, 700); + assert.equal(pit.hazards.length, 0, "gone at the pit's edge"); + const many = frozenRound("huts"); + standAt(many, 20); + many.you.safeMs = 1e9; + for (let i = 0; i < 6; i++) { + const z = put(many, "frozen", 60 + i * 2); + ghoul.hurt(many, z, 99, "shot", () => 1); + } + assert.ok(many.hazards.filter((h) => h.kind === "shard").length <= fz.SHARD_CAP); + // Burned, it melts: no shards. + const burn = frozenRound("huts"); + standAt(burn, 40); + burn.hazards.push({ kind: "armRoadFire", x: 70, y: 6, life: fl.FLARE_MS, max: fl.FLARE_MS, tick: 0, bossDone: 0, w: fl.FLARE_W, h: fl.FLARE_H, live: 0, cause: "" }); + const b = put(burn, "frozen", 70); + run(burn, 40); + assert.ok(b.dead || !burn.monsters.includes(b), "burned in one tick"); + assert.equal(burn.hazards.filter((h) => h.kind === "shard").length, 0); + assert.equal(events(burn, "shatter").length, 0); + assert.equal(events(burn, "frozenMelt").length, 1); +}); + +/* ------------------------------------------------------------ ice wraiths */ + +test("Ghoul Rush's Ice Wraith swoops (a ducked Planny is passed over), costs a life standing, and its dive leaves you frozen when it has gone past (never under Hot Cocoa); one dives at a time", () => { + assert.ok(fz.FROZEN.swoops.icewraith({ act: "dive" }) && !fz.FROZEN.swoops.icewraith({ act: "hover" })); + const dive = (ducked, over = {}, setup = () => {}) => { + const round = frozenRound("huts"); + round.spec = { ...round.spec, horde: [], spawns: [] }; + standAt(round, 60); + round.input.down = ducked; + setup(round); + const m = put(round, "icewraith", 44, { y: 16, act: "wind", wait: 1, home: 16, ...over }); + round.events.length = 0; + until(round, () => events(round, "lose").length > 0 || events(round, "freezeHit").length > 0, 2500); + return { round, m, lost: events(round, "lose"), froze: events(round, "freezeHit") }; + }; + const stand = dive(false); + assert.equal(stand.lost[0]?.cause, "icewraith", "standing it hits"); + const duck = dive(true); + assert.equal(duck.lost.length, 0, "ducked it passes over"); + assert.equal(duck.froze.length, 1, "and leaves its chill"); + assert.equal(duck.froze[0].immune, false); + assert.ok(duck.round.you.heldMs > 0 && duck.round.you.heldMs <= fz.FREEZE_MS, `frozen ${duck.round.you.heldMs} ms`); + run(duck.round, 16); + assert.equal(duck.round.you.ducking, false, "frozen, he stands"); + // Frozen, no key does anything; then he is free. + duck.round.input.right = true; + const x0 = duck.round.you.x; + run(duck.round, 200, { right: true }); + assert.equal(duck.round.you.x, x0, "no key works while he is frozen"); + run(duck.round, fz.FREEZE_MS + 400, { right: true }); + assert.ok(duck.round.you.x > x0 + 4, "free again"); + // Hot Cocoa is immune. + const cocoa = dive(true, {}, (r) => ghoul.applyPower(r, "cocoa")); + assert.equal(cocoa.froze.length, 1); + assert.equal(cocoa.froze[0].immune, true); + assert.equal(cocoa.round.you.heldMs, 0); + // One dives at a time, and none at a Planny still frozen. + const two = frozenRound("huts"); + standAt(two, 60); + two.you.safeMs = 1e9; + const a = put(two, "icewraith", 90, { y: 16, act: "hover", wait: 0, home: 16 }); + const b = put(two, "icewraith", 95, { y: 16, act: "hover", wait: 0, home: 16 }); + run(two, 120); + assert.equal([a, b].filter((m) => m.act === "wind").length, 1, "only one shrieks"); + const held = frozenRound("huts"); + standAt(held, 60); + held.you.safeMs = 1e9; + held.you.heldMs = 5000; + const c = put(held, "icewraith", 90, { y: 16, act: "hover", wait: 0, home: 16 }); + run(held, 600); + assert.equal(c.act, "hover", "it waits for him to thaw"); + // Walls never stop it, the floor turns it, and it waits unseen till you come. + const idle = frozenRound("huts"); + standAt(idle, 20); + const w = put(idle, "icewraith", 200, { y: 30, home: 30 }); + assert.equal(w.act, "idle"); + assert.equal(ghoul.solid(w), false); + run(idle, 100); + assert.equal(w.act, "idle", "out of range"); + standAt(idle, 150); + run(idle, 100); + assert.equal(w.act, "hover"); + assert.equal(events(idle, "iceWraithWake").length, 1); +}); + +/* ------------------------------------------------------------- the cocoa */ + +test("Ghoul Rush's Hot Cocoa is a stage-only power-up that lasts 10 s, with its own pill word, found nowhere else", () => { + assert.equal(ghoul.POWERS.cocoa.stage, "frozen"); + assert.equal(ghoul.POWERS.cocoa.ms, 10000); + assert.ok(ghoul.TIMED.includes("cocoa")); + assert.equal(PILL_WORDS.cocoa, "COCOA"); + assert.equal(ghoul.powerHere({ dark: true, stage: "frozen" }, "cocoa"), true); + assert.equal(ghoul.powerHere({ dark: true, stage: "manor" }, "cocoa"), false); + assert.equal(ghoul.powerHere({ dark: true, stage: null }, "cocoa"), false); + const rnd = ghoul.seeded(9); + const seen = new Set(); + for (let i = 0; i < 400; i++) { + seen.add(pickPower(rnd, { dark: i % 2 === 0, stage: "frozen" }, "", i % 3 === 0)); + assert.notEqual(pickPower(rnd, { dark: true, stage: "carnival" }, "", true), "cocoa"); + } + assert.ok(seen.has("cocoa"), "it turns up in the lake"); + const round = frozenRound("huts"); + ghoul.applyPower(round, "cocoa"); + assert.equal(round.effects.cocoa, 10000); + run(round, 10100); + assert.equal(round.effects.cocoa, 0); + assert.equal(events(round, "expire")[0]?.kind, "cocoa"); + // A placed one elsewhere is swapped (the placed loot of the Frozen Lake's rooms). + for (const id of ROOM_IDS) { + const r = frozenRound(id); + r.spec.items.forEach(([kind], i) => { + if (kind === "cocoa") assert.equal(r.loot[i], "cocoa", `${id}: the cocoa stays itself in its own stage`); + }); + } +}); + +/* --------------------------------------------------------------- the flare */ + +test("Ghoul Rush's Road Flare is the stage's weapon: thrown ahead (about 16 units), it lands and burns 6 wide for 4 s, burning what stands in it, lighting shades, and never hurting Planny", () => { + assert.equal(STAGE_ARMS.frozen, "flare"); + assert.deepEqual([ghoul.POWERS.flare.arm, ghoul.POWERS.flare.stage, ghoul.POWERS.flare.sticks, ghoul.POWERS.flare.max], [true, "frozen", 2, 4]); + assert.equal(armDrop({ stage: "frozen" }, 0), "flare"); + assert.equal(ghoul.powerHere({ dark: true, stage: "frozen" }, "flare"), true); + assert.equal(ghoul.powerHere({ dark: true, stage: "carnival" }, "flare"), false); + for (const id of ROOM_IDS) { + const weapons = ghoul.roomById(id).items.filter((i) => ghoul.POWERS[i[0]].arm).map((i) => i[0]); + assert.ok(weapons.includes("flare") && weapons.length <= 2, `${id}: ${weapons}`); + } + const round = frozenRound("huts"); + standAt(round, 30); + round.you.safeMs = 0; + ghoul.applyPower(round, "flare"); + assert.equal(round.arms[0].kind, "flare"); + assert.equal(round.arms[0].n, 2); + tapTap(round); + assert.equal(round.arms[0].n, 1); + assert.equal(events(round, "flareThrow").length, 1); + assert.equal(round.hazards.filter((h) => h.kind === "armRoadFlare").length, 1); + until(round, () => round.hazards.some((h) => h.kind === "armRoadFire"), 2000); + const fire = round.hazards.find((h) => h.kind === "armRoadFire"); + assert.ok(fire, "it lands and burns"); + assert.ok(fire.x - 30 > 12 && fire.x - 30 < 22, `about 16 ahead (${(fire.x - 30).toFixed(1)})`); + assert.ok(fire.w === fl.FLARE_W && fire.life > fl.FLARE_MS - 100 && fire.life <= fl.FLARE_MS); + assert.equal(events(round, "flareLand").length, 1); + // It burns what stands in it, a tick at a time (no drops), and the zombie dies after its hp. + const z = put(round, "zombie", fire.x, { stunMs: 1e9 }); + const hp = z.hp; + run(round, 16); + assert.equal(z.hp, hp - fl.FLARE_DMG, "burned the moment it stands in it"); + run(round, fl.FLARE_TICK_MS - 80); + assert.equal(z.hp, hp - fl.FLARE_DMG, "and not again before the next tick"); + run(round, 120); + assert.equal(z.hp, hp - 2 * fl.FLARE_DMG); + run(round, fl.FLARE_TICK_MS * (hp + 1)); + assert.ok(z.dead || !round.monsters.includes(z), "burned down"); + // A zombie running through it takes a burn on the way. + const runner = frozenRound("huts"); + standAt(runner, 90); + runner.you.safeMs = 1e9; + runner.hazards.push({ kind: "armRoadFire", x: 70, y: 6, life: fl.FLARE_MS, max: fl.FLARE_MS, tick: 0, bossDone: 0, w: fl.FLARE_W, h: fl.FLARE_H, live: 0, cause: "" }); + const r = put(runner, "zombie", 56); + run(runner, 1500); + assert.ok(r.hp < r.max || r.dead, "burned in passing"); + assert.equal(round.drops.length, 0, "no drops from an area weapon"); + // It never hurts Planny, standing in it. + standAt(round, fire.x); + round.you.safeMs = 0; + run(round, 500); + assert.equal(events(round, "lose").length, 0); + // Then it is out. + run(round, fl.FLARE_MS + 200); + assert.ok(!round.hazards.some((h) => h.kind === "armRoadFire")); + // Its light shows a shade near it, and burns it. + const lit = frozenRound("huts"); + standAt(lit, 30); + lit.hazards.push({ kind: "armRoadFire", x: 60, y: 6, life: fl.FLARE_MS, max: fl.FLARE_MS, tick: 0, bossDone: 0, w: fl.FLARE_W, h: fl.FLARE_H, live: 0, cause: "" }); + const s = put(lit, "shade", 62, { act: "rest", wait: 1e9 }); + run(lit, 16); + run(lit, 16); + assert.equal(s.unseen, false, "lit"); + run(lit, fl.FLARE_TICK_MS * 4); + assert.ok(s.hp < 3 || s.dead, "and burned once it stands in the fire"); + // A flare that comes to a pit is lost. + const pit = frozenRound("huts"); + standAt(pit, 220); + pit.hazards.push({ kind: "armRoadFlare", x: 238.5, y: 8, vx: 0, vy: -20, spin: 0, rest: false, t: 0, w: 0.8, h: 0.8, live: 0, cause: "" }); + run(pit, 800); + assert.ok(!pit.hazards.some((h) => h.kind === "armRoadFire"), "no fire over a pit"); +}); + +/* -------------------------------------------------------------- the Widow */ + +test("Ghoul Rush's Frost Widow hangs from the roof with her veil up, three fire barrels set out in the arena, guarded from every shot until the veil melts", () => { + const round = widowFight(); + const b = round.boss; + assert.equal(b.kind, "frostwidow"); + assert.equal(b.act, "hang"); + assert.equal(b.y, 6 + fz.HANG_OVER, "hanging from the top of the cavern"); + assert.equal(b.veil, true); + assert.equal(b.hp, 90); + const barrels = round.hazards.filter((h) => h.kind === "barrel"); + assert.deepEqual(barrels.map((h) => h.x), fz.BARREL_SPOTS.map((o) => round.spec.arena + o)); + assert.ok(barrels.every((h) => h.state === "still" && h.y === 6)); + assert.equal(ghoul.roomFor("widow", 7).bossHp, Math.round(90 * (1 + ghoul.BOSS_DEPTH_HP * 7))); + // A shot at her glances off: the veil, and she is off the floor besides. + for (const [act, y] of [["hang", 26], ["low", 6]]) { + Object.assign(b, { act, y, x: 170, wait: 1e9, lowMs: 1e9 }); + round.shots.length = 0; + round.events.length = 0; + round.shots.push({ x: 160, y: act === "low" ? 8.4 : 28, vx: 80, vy: 0, gone: 0 }); + run(round, 160); + assert.equal(b.hp, 90, `${act}: not hurt`); + assert.equal(events(round, "bossBlock").length, 1, `${act}: a guard shows`); + } + // Her touch costs a life, wherever her body is. + const touch = widowFight({ x: 150 }); + touch.you.safeMs = 0; + Object.assign(touch.boss, { act: "low", y: 6, x: 152, wait: 1e9, lowMs: 1e9 }); + run(touch, 20); + assert.equal(events(touch, "lose")[0]?.cause, "frostwidow"); + // Standing on a board at 18 she walks over, up on her roof: no touch. + const high = widowFight({ x: 132 }); + high.you.safeMs = 0; + standAt(high, 132, 1, 18, 1); + Object.assign(high.boss, { act: "hang", y: 26, x: 132, wait: 1e9 }); + run(high, 20); + assert.equal(events(high, "lose").length, 0); +}); + +test("Ghoul Rush's barrels: a bolt kicks a standing one the way it flew, it rolls burning along the floor, hurts monsters, bursts on a wall, and a thrown weapon passes through", () => { + const round = widowFight({ x: 120 }); + const barrel = round.hazards.find((h) => h.kind === "barrel" && h.x === round.spec.arena + 30); + // From the left: it rolls right. + round.shots.push({ x: barrel.x - 4, y: 7.5, vx: 130, vy: 0, gone: 0 }); + run(round, 60); + assert.equal(barrel.state, "roll"); + assert.equal(barrel.vx, fz.BARREL_V); + assert.equal(events(round, "barrelKick").length, 1); + assert.equal(round.shots.length, 0, "the bolt is spent"); + const x0 = barrel.x; + run(round, 300); + assert.ok(barrel.x - x0 > 8 && barrel.y === 6, "rolling along the floor"); + // From the right: it rolls left. + const left = widowFight({ x: 190 }); + const b2 = left.hazards.find((h) => h.kind === "barrel" && h.x === left.spec.arena + 66); + left.shots.push({ x: b2.x + 4, y: 7.5, vx: -130, vy: 0, gone: 0 }); + run(left, 40); + assert.equal(b2.vx, -fz.BARREL_V); + // It hurts what it rolls through, once each. + const hit = widowFight({ x: 120 }); + const b3 = hit.hazards.find((h) => h.kind === "barrel" && h.x === hit.spec.arena + 30); + const z = put(hit, "zombie", b3.x + 8); + hit.shots.push({ x: b3.x - 4, y: 7.5, vx: 130, vy: 0, gone: 0 }); + run(hit, 600); + assert.equal(z.hp, z.max - fz.BARREL_DMG >= 0 ? z.max - fz.BARREL_DMG : z.hp); + assert.ok(z.dead || z.hp < z.max, "burned by the barrel"); + // It bursts on the arena's wall, and it is gone. + const wall = widowFight({ x: 120 }); + const b4 = wall.hazards.find((h) => h.kind === "barrel" && h.x === wall.spec.arena + 66); + wall.boss.x = 120; + wall.shots.push({ x: b4.x - 4, y: 7.5, vx: 130, vy: 0, gone: 0 }); + run(wall, 1500); + assert.ok(!wall.hazards.includes(b4)); + assert.ok(events(wall, "barrelBurst").length >= 1); + // A thrown weapon (a stake) kicks it and flies on. + const arc = widowFight({ x: 120 }); + const b5 = arc.hazards.find((h) => h.kind === "barrel" && h.x === arc.spec.arena + 30); + arc.shots.push({ arm: "stake", x: b5.x - 4, y: 7.5, vx: 96, vy: 0, gone: 0, t: 0, spin: 0, dmg: 4, bossDmg: 4, pierce: true }); + run(arc, 60); + assert.equal(b5.state, "roll"); + assert.equal(arc.shots.length, 1, "the stake flies on"); + // A bolt that misses it (too high) goes by. + const miss = widowFight({ x: 120 }); + const b6 = miss.hazards.find((h) => h.kind === "barrel" && h.x === miss.spec.arena + 30); + miss.shots.push({ x: b6.x - 4, y: 14, vx: 130, vy: 0, gone: 0 }); + run(miss, 60); + assert.equal(b6.state, "still"); +}); + +test("Ghoul Rush's veil melts to a rolling barrel (or a flare's fire) when she is on the floor, stays down VEIL_DOWN_MS while she stays, then grows back and the used barrels are set out again", () => { + const round = widowFight({ x: 125 }); + const b = round.boss; + Object.assign(b, { act: "low", y: 6, x: 160, wait: 0, lowMs: 1e9 }); + const barrel = round.hazards.find((h) => h.kind === "barrel" && h.x === round.spec.arena + 48); + // Shot from the left, 4 away from her: it rolls into her. + barrel.x = 150; + round.shots.push({ x: 146, y: 7.5, vx: 130, vy: 0, gone: 0 }); + until(round, () => !b.veil, 1500); + assert.equal(b.veil, false, "melted"); + const melt = events(round, "veilMelt")[0]; + assert.ok(melt && melt.by === "barrel"); + assert.equal(events(round, "veilDown")[0].ms, fz.VEIL_DOWN_MS); + assert.equal(b.veilMs <= fz.VEIL_DOWN_MS, true); + assert.ok(!round.hazards.includes(barrel), "the barrel is spent"); + assert.equal(round.boss.hp, 90, "melting hurts nothing"); + // Now a shot hurts her: any shot, 1. + round.shots.length = 0; + round.events.length = 0; + round.shots.push({ x: 152, y: 14, vx: 80, vy: 0, gone: 0 }); + run(round, 120); + assert.equal(b.hp, 89); + assert.equal(events(round, "bossHit")[0]?.weak, false); + // She stays on the floor while it is down, however long her low time was. + b.lowMs = 0; + run(round, 1000); + assert.equal(b.act, "low"); + // It grows back after VEIL_DOWN_MS, and the barrel is set out again. + const t0 = round.clock; + const up = upTo(round, "veilUp", fz.VEIL_DOWN_MS + 500); + assert.ok(up, "veilUp"); + assert.equal(b.veil, true); + assert.ok(Math.abs(round.clock - t0 - (fz.VEIL_DOWN_MS - 1120)) < 400, `about ${fz.VEIL_DOWN_MS} ms in all (${round.clock - t0} more after 1.1 s)`); + assert.equal(round.hazards.filter((h) => h.kind === "barrel").length, 3); + assert.equal(events(round, "barrelPlace").length, 1); + // A rolling barrel at her with the veil down hurts her instead (BARREL_BOSS), the veil down already. + const raw = widowFight({ x: 125 }); + Object.assign(raw.boss, { act: "low", y: 6, x: 160, wait: 0, lowMs: 1e9, veil: false, veilMs: 5000 }); + raw.hazards.push({ kind: "barrel", x: 150, y: 6, state: "roll", vx: fz.BARREL_V, roll: 0, life: 4000, hit: [], w: fz.BARREL_W, h: fz.BARREL_H, live: 0, cause: "" }); + run(raw, 600); + assert.equal(raw.boss.hp, 90 - fz.BARREL_BOSS); + // A flare's fire melts it too, and never hurts a veil-less boss more than FLARE_BOSS a tick. + const fire = widowFight({ x: 125 }); + Object.assign(fire.boss, { act: "low", y: 6, x: 160, wait: 0, lowMs: 1e9 }); + fire.hazards.push({ kind: "armRoadFire", x: 156, y: 6, life: fl.FLARE_MS, max: fl.FLARE_MS, tick: 0, bossDone: 0, w: fl.FLARE_W, h: fl.FLARE_H, live: 0, cause: "" }); + run(fire, 120); + assert.equal(fire.boss.veil, false); + assert.equal(events(fire, "veilMelt")[0]?.by, "flare"); + assert.equal(events(fire, "bossBlock").length, 0, "no block spam"); + run(fire, fl.FLARE_TICK_MS * 3 + 60); + assert.ok(fire.boss.hp < 90 && fire.boss.hp >= 90 - 8, `the fire's tick hurts a little (${fire.boss.hp})`); + // In the air (hanging) a barrel or a fire does nothing to the veil. + const hang = widowFight({ x: 125 }); + hang.hazards.push({ kind: "armRoadFire", x: 170, y: 6, life: fl.FLARE_MS, max: fl.FLARE_MS, tick: 0, bossDone: 0, w: fl.FLARE_W, h: fl.FLARE_H, live: 0, cause: "" }); + run(hang, 400); + assert.equal(hang.boss.veil, true); +}); + +test("Ghoul Rush's Frost Widow's heart: with the veil down and her on the floor any shot does 1, and one into her underside while her mouth is open does triple (a weak hit)", () => { + const round = widowFight({ x: 125 }); + const b = round.boss; + Object.assign(b, { act: "low", y: 6, x: 160, wait: 0, lowMs: 1e9, veil: false, veilMs: 1e9, mouth: false }); + round.shots.push({ x: 154.5, y: 18, vx: 80, vy: 0, gone: 0 }); + run(round, 100); + assert.equal(b.hp, 89); + round.events.length = 0; + b.mouth = true; + b.mouthMs = 1e9; + // Up high, mouth or no mouth: 1. + round.shots.push({ x: 154.5, y: 18, vx: 80, vy: 0, gone: 0 }); + run(round, 100); + assert.equal(b.hp, 88); + // Low (where a standing blaster's bolts go): triple. + round.shots.push({ x: 154.5, y: 8.4, vx: 80, vy: 0, gone: 0 }); + run(round, 100); + assert.equal(b.hp, 85); + const hit = events(round, "bossHit").at(-1); + assert.equal(hit.weak, true); + assert.equal(hit.kind, "frostwidow"); + // Closed, the same shot is 1 again. + b.mouth = false; + b.mouthMs = 0; + round.shots.push({ x: 154.5, y: 8.4, vx: 80, vy: 0, gone: 0 }); + run(round, 100); + assert.equal(b.hp, 84); + // Through armBossDamage: a thrown weapon's damage is scaled and capped as for every boss. + const arc = widowFight({ x: 125 }); + Object.assign(arc.boss, { act: "low", y: 6, x: 160, wait: 0, lowMs: 1e9, veil: false, veilMs: 1e9 }); + arc.shots.push({ arm: "stake", x: 154.5, y: 8.4, vx: 96, vy: 0, gone: 0, t: 0, spin: 0, dmg: 4, bossDmg: 4, pierce: true }); + run(arc, 100); + assert.ok(arc.boss.hp < 90 && arc.armBossDmg > 0, "the stake counts toward the share cap"); +}); + +test("Ghoul Rush's Frost Widow's cycle: she hangs, drops on the far side of you, stands LOW_MS (longer while her veil is down), rises and hangs again, her mouth open for each web spit", () => { + const round = widowFight({ x: 125 }); + const b = round.boss; + round.boss.spikeIn = 1e9; + round.boss.spitIn = 1e9; + assert.equal(b.act, "hang"); + b.x = 170; + b.wait = 1; + run(round, 8); + assert.equal(b.act, "drop"); + const drop = events(round, "widowDrop")[0]; + assert.ok(drop, "a drop"); + assert.ok(Math.abs(b.toX - (125 + fz.LAND_AWAY)) < 1.5 || b.toX >= 125 + fz.LAND_AWAY - 1.5, `lands ${fz.LAND_AWAY} from you, on her side (${b.toX})`); + run(round, fz.DROP_MS / 2); + assert.ok(b.y < 26 && b.y > 6, "on the way down"); + run(round, fz.DROP_MS); + assert.equal(b.act, "low"); + assert.equal(b.y, 6); + // She walks at you, stopping LOW_KEEP short. + const gap0 = b.x - round.you.x; + run(round, 3000); + assert.ok(b.x - round.you.x >= fz.LOW_KEEP - 0.5 && b.x - round.you.x < gap0 + 0.01); + // And rises when her time is up (the veil still up). + b.lowMs = 1; + run(round, 16); + assert.equal(b.act, "rise"); + assert.equal(events(round, "widowRise").length, 1); + run(round, fz.RISE_MS + 40); + assert.equal(b.act, "hang"); + assert.equal(b.y, 26); + // The mouth opens for the wind-up of a web spit. + b.spitIn = 1; + run(round, 16); + assert.equal(events(round, "webWind").length, 1); + assert.equal(b.mouth, true); + run(round, fz.SPIT_WIND_MS + 20); + assert.equal(events(round, "webShot").length, 1); + assert.equal(b.mouth, true, "still open a moment"); + run(round, fz.MOUTH_HOLD_MS + 40); + assert.equal(b.mouth, false); +}); + +test("Ghoul Rush's blizzard: a wind warns for a second, then pushes Planny away from her at 22 a second for 3 s (half while he ducks or stands behind a barrel); the push is no damage", () => { + const first = widowFight({ x: 158 }); + first.boss.spikeIn = 1e9; + first.boss.spitIn = 1e9; + first.boss.stunMs = 1e9; + first.boss.x = 118; + first.you.safeMs = 1e9; + const t0 = first.clock; + const warn = upTo(first, "blizzard", fz.BLIZZARD_FIRST_MS + 500); + assert.ok(warn, "the blizzard is called"); + assert.ok(Math.abs(first.clock - t0 - fz.BLIZZARD_FIRST_MS) < 40, `the first one ${fz.BLIZZARD_FIRST_MS} ms in`); + assert.equal(first.twist.wind.state, "warn"); + const x0 = first.you.x; + run(first, fz.BLIZZARD_WARN_MS - 80); + assert.equal(first.you.x, x0, "no wind during the warning"); + const blow = upTo(first, "blizzardBlow", 400); + assert.ok(blow); + assert.equal(first.twist.wind.state, "blow"); + // The wind is away from her. + const side = Math.sign(first.you.x - first.boss.x); + assert.equal(blow.dir, side); + const x1 = first.you.x; + run(first, 500); + assert.ok(Math.abs((first.you.x - x1) * side - fz.BLIZZARD_PUSH / 2) < 2, `11 units in half a second (${((first.you.x - x1) * side).toFixed(1)})`); + assert.ok(first.you.x !== x1 && Math.sign(first.you.x - x1) === side); + // He can run into it: net 14. + const x2 = first.you.x; + run(first, 1000, { [side > 0 ? "left" : "right"]: true }); + assert.ok((first.you.x - x2) * side < -3, `running into it makes headway (${((first.you.x - x2) * side).toFixed(1)})`); + run(first, fz.BLIZZARD_MS); + assert.ok(events(first, "blizzardEnd").length === 1); + assert.equal(first.twist.wind.state, "calm"); + assert.equal(events(first, "lose").length, 0, "no damage"); + // Ducking halves it; so does a barrel between him and her. + const duck = widowFight({ x: 150 }); + Object.assign(duck.twist.wind, { state: "blow", ms: 3000, dir: 1 }); + duck.boss.x = 120; + duck.input.down = true; + ghoul.moveYou(duck, 16); + const d0 = duck.you.x; + run(duck, 1000, { down: true }); + assert.equal(duck.you.ducking, true); + assert.ok(Math.abs(duck.you.x - d0 - fz.BLIZZARD_PUSH * fz.BLIZZARD_COVER) < 3, `half (${(duck.you.x - d0).toFixed(1)})`); + const pushed = (barrelAt) => { + const r = widowFight({ x: 156 }); + Object.assign(r.twist.wind, { state: "blow", ms: 3000, dir: 1 }); + r.boss.x = 120; + r.boss.stunMs = 1e9; + r.hazards.find((h) => h.kind === "barrel" && h.x === r.spec.arena + 48).x = barrelAt; + const x0 = r.you.x; + run(r, 200); + return r.you.x - x0; + }; + const bare = pushed(190); + const covered = pushed(153); + assert.ok(Math.abs(bare - fz.BLIZZARD_PUSH * 0.2) < 0.8, `in the open, 22 a second (${bare.toFixed(2)})`); + assert.ok(Math.abs(covered - bare * fz.BLIZZARD_COVER) < 0.4, `behind a barrel, half (${covered.toFixed(2)} against ${bare.toFixed(2)})`); + // A wall stops it. + const wall = widowFight({ x: 196 }); + Object.assign(wall.twist.wind, { state: "blow", ms: 3000, dir: 1 }); + wall.boss.x = 120; + run(wall, 1000); + assert.ok(wall.you.x <= wall.spec.length - 1.5); + // The first blow is not before the fight: nothing in the intro. + const intro = frozenRound("widow"); + standAt(intro, intro.spec.arena + 12); + intro.you.safeMs = 1e9; + run(intro, 500); + assert.equal(events(intro, "blizzard").length, 0); +}); + +test("Ghoul Rush's ice spikes: a cracking line at your x for 800 ms, then a spike 9.5 high for a second (cause spike): step out, jump it, or stand on a board over it", () => { + const spike = (round, x) => { + round.events.length = 0; + round.boss.spikeIn = 1; + round.boss.spitIn = 1e9; + standAt(round, x ?? round.you.x); + round.you.safeMs = 0; + run(round, 16); + }; + const round = widowFight({ x: 150 }); + spike(round); + const w = events(round, "spikeWarn")[0]; + assert.ok(w && Math.abs(w.x - 150) < 0.5, "at your x"); + const h = round.hazards.find((q) => q.kind === "spike"); + assert.deepEqual([h.w, h.h], [fz.SPIKE_W, fz.SPIKE_H]); + run(round, fz.SPIKE_WARN_MS - 80); + assert.equal(events(round, "lose").length, 0, "nothing while it cracks"); + assert.equal(h.live, 0); + run(round, 120); + assert.equal(events(round, "spikeUp").length, 1); + assert.equal(events(round, "lose")[0]?.cause, "spike"); + // Stepping out in time. + const step = widowFight({ x: 150 }); + spike(step); + run(step, 400, { right: true }); + run(step, fz.SPIKE_WARN_MS + fz.SPIKE_UP_MS); + assert.equal(events(step, "lose").length, 0); + // Jumping it. + const jump = widowFight({ x: 150 }); + spike(jump); + run(jump, fz.SPIKE_WARN_MS - 300); + ghoul.jump(jump); + run(jump, 700, { right: true }); + run(jump, fz.SPIKE_UP_MS); + assert.equal(events(jump, "lose").length, 0, "jumped across it"); + // A board 18 (12 up) is over it. + const board = widowFight({ x: 132 }); + standAt(board, 132, 1, 18, 1); + board.boss.spikeIn = 1; + board.boss.spitIn = 1e9; + board.you.safeMs = 0; + run(board, 16); + const hb = board.hazards.find((q) => q.kind === "spike"); + assert.ok(Math.abs(hb.x - 132) < 0.5); + run(board, fz.SPIKE_WARN_MS + 300); + assert.equal(events(board, "lose").length, 0, "a spike never reaches a board that high"); + // Endless lives spare it. + for (const infinite of [false, true]) { + const r = widowFight({ x: 150 }); + r.infinite = infinite; + spike(r); + until(r, () => events(r, "lose").length > 0, 2000); + assert.equal(events(r, "lose")[0]?.cause, "spike"); + assert.equal(r.lives, infinite ? 3 : 2); + } + // It crushes a monster in its column. + const crush = widowFight({ x: 125 }); + const z = put(crush, "zombie", 160); + crush.hazards.push({ kind: "spike", x: 160, y: 6, w: fz.SPIKE_W, h: fz.SPIKE_H, warn: 20, up: 600, live: 0, cause: "spike" }); + run(crush, 80); + assert.ok(z.dead || !crush.monsters.includes(z)); + // Two at once in a rage. + const rage = widowFight({ x: 150 }); + rage.boss.hp = 40; + run(rage, 16); + spike(rage); + assert.equal(rage.hazards.filter((q) => q.kind === "spike").length, 2, "a second one ahead of you"); +}); + +test("Ghoul Rush's web spit: a slow glob that lands as a patch 5 wide for 6 s, slowing Planny like water and hurting nothing; a bolt shoots a glob down", () => { + const round = widowFight({ x: 150 }); + round.boss.spikeIn = 1e9; + round.boss.spitIn = 1; + round.you.safeMs = 0; + run(round, 16); + assert.equal(events(round, "webWind").length, 1); + run(round, fz.SPIT_WIND_MS + 20); + const glob = round.hazards.find((h) => h.kind === "webGlob"); + assert.ok(glob, "a glob in the air"); + assert.equal(events(round, "webShot").length, 1); + round.boss.spitIn = 1e9; + const land = upTo(round, "webLand", 3000); + assert.ok(land, "it lands"); + const patch = round.hazards.find((h) => h.kind === "webPatch"); + assert.ok(patch && patch.w === fz.WEB_W && patch.life <= fz.WEB_LIFE_MS); + assert.equal(events(round, "lose").length, 0, "it hurts nothing"); + // Standing in it slows him; out of it, he is quick again. + standAt(round, patch.x); + round.you.safeMs = 0; + const x0 = round.you.x; + run(round, 400, { right: true }); + const slowed = round.you.x - x0; + assert.ok(round.you.slowMs > 0); + standAt(round, 120); + const free0 = round.you.x; + run(round, 400, { right: true }); + assert.ok(slowed < (round.you.x - free0) * 0.8, `slower in the web (${slowed.toFixed(1)} against ${(round.you.x - free0).toFixed(1)})`); + assert.equal(events(round, "lose").length, 0); + // It is gone after WEB_LIFE_MS. + run(round, fz.WEB_LIFE_MS + 200); + assert.ok(!round.hazards.some((h) => h.kind === "webPatch")); + // A bolt through a glob in the air shoots it down: no patch. + const shot = widowFight({ x: 150 }); + shot.hazards.push({ kind: "webGlob", x: 160, y: 20, vx: -2, vy: 0, spin: 0, life: 3000, w: 1.6, h: 1.6, live: 0, cause: "" }); + shot.shots.push({ x: 156, y: 20.5, vx: 130, vy: 0, gone: 0 }); + run(shot, 120); + assert.ok(!shot.hazards.some((h) => h.kind === "webGlob" || h.kind === "webPatch"), "shot down"); +}); + +test("Ghoul Rush's Frost Widow's rage at half her hp: the veil grows back sooner, the barrels are set out new, two ice wraiths come (never more than two alive) and she is quicker; endless lives spare her touch", () => { + const round = widowFight({ x: 125 }); + const b = round.boss; + round.hazards = round.hazards.filter((h) => h.kind !== "barrel").concat([{ kind: "barrel", x: 140, y: 6, spot: 99, state: "roll", vx: 5, roll: 0, life: 9999, hit: [], w: 3, h: 3.4, live: 0, cause: "" }]); + b.hp = 45; + round.events.length = 0; + run(round, 16); + assert.equal(b.raged, true); + assert.equal(events(round, "widowRage").length, 1); + const barrels = round.hazards.filter((h) => h.kind === "barrel"); + assert.equal(barrels.length, 3, "a new set of three"); + assert.ok(barrels.every((h) => h.state === "still")); + const wraiths = round.monsters.filter((m) => m.kind === "icewraith"); + assert.equal(wraiths.length, 2); + assert.equal(events(round, "wraithCall").length, 2); + // Never more than two alive, a drop or not. + b.act = "hang"; + b.wait = 1; + b.spikeIn = 1e9; + b.spitIn = 1e9; + run(round, 16); + assert.equal(round.monsters.filter((m) => m.kind === "icewraith").length, 2); + // The veil grows back in VEIL_DOWN_RAGE_MS. + Object.assign(b, { act: "low", y: 6, x: 160, lowMs: 1e9, wait: 0 }); + round.hazards.find((h) => h.kind === "barrel").x = 150; + round.shots.push({ x: 146, y: 7.5, vx: 130, vy: 0, gone: 0 }); + until(round, () => !b.veil, 1500); + assert.equal(events(round, "veilDown").at(-1).ms, fz.VEIL_DOWN_RAGE_MS); + // Quicker waits: a fight at half hp has shorter hangs. + const calm = widowFight({ x: 125 }); + calm.boss.spikeIn = 1e9; + calm.boss.spitIn = 1e9; + calm.boss.act = "low"; + calm.boss.y = 6; + calm.boss.lowMs = 1; + calm.boss.veil = true; + run(calm, 16); + assert.equal(calm.boss.act, "rise"); + run(calm, fz.RISE_MS + 40); + assert.ok(Math.abs(calm.boss.wait - fz.HANG_MS) < 60); + const quick = widowFight({ x: 125 }); + quick.boss.hp = 40; + run(quick, 16); + quick.boss.spikeIn = 1e9; + quick.boss.spitIn = 1e9; + quick.boss.act = "low"; + quick.boss.y = 6; + quick.boss.lowMs = 1; + run(quick, 16); + run(quick, fz.RISE_MS + 40); + assert.ok(Math.abs(quick.boss.wait - fz.HANG_MS * fz.RAGE_QUICK) < 60, `${quick.boss.wait}`); + // Endless lives spare her touch, an ice wraith's dive and a shard. + const costs = (setup, cause) => { + for (const infinite of [false, true]) { + const r = widowFight({ x: 150 }); + r.infinite = infinite; + r.you.safeMs = 0; + r.boss.spikeIn = 1e9; + r.boss.spitIn = 1e9; + setup(r); + until(r, () => events(r, "lose").length > 0, 2500); + assert.equal(events(r, "lose")[0]?.cause, cause, `${cause}: a life is lost`); + assert.equal(r.lives, infinite ? 3 : 2, `${cause}: ${infinite ? "spared" : "costs one"}`); + } + }; + costs((r) => Object.assign(r.boss, { act: "low", y: 6, x: 152, lowMs: 1e9, wait: 0 }), "frostwidow"); + costs((r) => put(r, "icewraith", 134, { y: 16, act: "wind", wait: 1, home: 16 }), "icewraith"); + costs((r) => r.hazards.push({ kind: "shard", x: 150, y: 6, off: 0, vx: 0, w: 1.8, h: 1.3, warn: 0, life: 900, live: 1, cause: "shard" }), "shard"); + costs((r) => put(r, "hand", 150, { act: "grab", wait: 900 }), "hand"); + costs((r) => put(r, "shade", 150.2, { act: "lunge", wait: 900, shownMs: 900 }), "shade"); +}); + +test("Ghoul Rush's Frost Widow can be beaten: a bot that shoots a barrel into her, then her, ducks the wraiths and keeps out of the spikes finishes the fight at depth 0 and depth 7", () => { + const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); + const bot = (round) => { + const { you, boss: b, input: inp, spec } = round; + inp.left = inp.right = inp.down = inp.fire = false; + if (round.phase !== "play" || you.out > 0) return; + const lo = spec.arena + 6; + const hi = spec.length - 6; + let tx = spec.arena + 48; + let face = 0; + let fire = false; + let duck = false; + const spikes = round.hazards.filter((h) => h.kind === "spike" && (h.warn > 0 || h.live > 0)); + const bad = (x) => spikes.some((h) => Math.abs(x - h.x) < 8); + const wraiths = round.monsters.filter((m) => m.kind === "icewraith" && Math.abs(m.x - you.x) < 45 && m.x > round.camX && m.x < round.camX + 96); + const hover = wraiths.find((m) => m.act === "hover" && Math.abs(m.y - you.y) < 14); + if (spikes.some((h) => Math.abs(you.x - h.x) < 12)) { + tx = you.x; + for (let d = 0; d <= 60; d++) { + const x = [you.x + d, you.x - d].find((q) => q > lo && q < hi && !bad(q)); + if (x !== undefined) { + tx = x; + break; + } + } + } else if (wraiths.some((m) => m.act === "wind" || m.act === "dive")) { + duck = true; + tx = you.x; + } else if (b.state !== "fight") tx = spec.arena + 40; + else if (b.act === "low" && b.veil) { + const s = Math.sign(b.x - you.x) || 1; + const barrels = round.hazards.filter((h) => h.kind === "barrel" && h.state === "still" && (b.x - h.x) * s > 4).sort((p, q) => Math.abs(p.x - b.x) - Math.abs(q.x - b.x)); + const best = barrels[0]; + if (best) { + const side = Math.sign(b.x - best.x); + const want = best.x - side * 8; + if ((you.x - best.x) * side < -2 && Math.abs(you.x - want) < 14) { + face = side; + fire = true; + tx = you.x; + } else tx = want; + } else tx = clamp(b.x - s * 22, lo, hi); + } else if (b.act === "low") { + const s = Math.sign(b.x - you.x) || 1; + tx = clamp(b.x - s * 20, lo, hi); + face = s; + fire = Math.abs(b.x - you.x) < 40; + } else if (hover) { + tx = you.x; + face = Math.sign(hover.x - you.x) || 1; + fire = true; + } + if (b.state === "fight" && (b.act === "low" || b.act === "drop") && Math.abs(tx - b.x) < 11) tx = b.x + (you.x >= b.x ? 11 : -11); + const dx = tx - you.x; + if (Math.abs(dx) > 2.5) inp[dx > 0 ? "right" : "left"] = true; + else if (face && you.face !== face) inp[face > 0 ? "right" : "left"] = true; + if (duck) { + inp.left = inp.right = false; + inp.down = true; + } + inp.fire = fire; + }; + const fight = (depth) => { + const round = frozenRound("widow", depth); + standAt(round, round.spec.arena + 12); + round.you.safeMs = 1500; + round.lives = 99; + let ms = 0; + let t0 = null; + while (ms < 300000 && round.boss.state !== "down") { + bot(round); + ghoul.advance(round, 16, steady); + ms += 16; + if (round.boss.state === "fight" && t0 === null) t0 = ms; + round.events.length = 0; + } + return { won: round.boss.state === "down", secs: (ms - t0) / 1000, round }; + }; + for (const depth of [0, 7]) { + const r = fight(depth); + assert.ok(r.won, `depth ${depth}: down in ${r.secs.toFixed(0)} s`); + assert.ok(r.secs > 25, `depth ${depth}: not a pushover (${r.secs.toFixed(0)} s)`); + assert.equal(r.round.hasKey, true, "her fall opens the door"); + assert.ok(r.round.lives >= 1); + } + // Her fall: points, a life, the field cleared. + const down = widowFight({ x: 125 }); + Object.assign(down.boss, { act: "low", y: 6, x: 160, veil: false, veilMs: 1e9, wait: 0, lowMs: 1e9, hp: 1 }); + down.shots.push({ x: 154.5, y: 8.4, vx: 80, vy: 0, gone: 0 }); + const lives = down.lives; + run(down, 100); + assert.equal(down.boss.state, "down"); + assert.equal(events(down, "bossDown")[0]?.kind, "frostwidow"); + assert.equal(down.lives, lives + 1, "a boss always gives a life"); + assert.equal(down.hazards.length, 0, "the field is cleared"); +}); + +/* ------------------------------------------------------- the whole stage */ + +test("Ghoul Rush's Frozen Lake plays the same every time: a seed gives the same fight, and the pack draws no random number", () => { + const trace = () => { + const round = widowFight({ x: 130 }); + const seen = []; + for (let t = 0; t < 40000; t += 16) { + round.input.right = t % 3000 < 1500; + round.input.fire = t % 1000 < 600; + ghoul.advance(round, 16, never); + if (t % 800 === 0) seen.push([round.boss.act, round.boss.x.toFixed(2), round.boss.y.toFixed(2), round.boss.veil, round.boss.hp, round.you.x.toFixed(2), round.hazards.length, round.monsters.length]); + round.you.safeMs = 1e9; + round.events.length = 0; + } + return seen; + }; + assert.deepEqual(trace(), trace()); + // Stepping on the ice, the tiles and the shades draw nothing either (the room's own horde does, not run here). + const round = frozenRound("lodge"); + standAt(round, 60); + round.you.safeMs = 1e9; + put(round, "shade", 120); + put(round, "hand", 80); + put(round, "frozen", 100); + for (let t = 0; t < 6000; t += 16) { + round.input.right = t % 2000 < 1000; + round.input.left = !round.input.right; + ghoul.advance(round, 16, never); + } +}); + +test("Ghoul Rush's every room of the Frozen Lake can be finished with its thin tiles cut out, and every placed thing sits on a surface", () => { + const MARGIN = 0.6; + for (const id of ROOM_IDS) { + const room = ghoul.roomById(id); + const pieces = []; + for (const [x0, x1, y] of room.ground) { + let a = x0; + for (const [t0, t1] of room.thin.filter(([p, q]) => p >= x0 && q <= x1).sort((p, q) => p[0] - q[0])) { + pieces.push({ x0: a, x1: t0, y, ground: true }); + a = t1; + } + pieces.push({ x0: a, x1, y, ground: true }); + } + const list = [...pieces, ...room.shelves.map(([x0, x1, y]) => ({ x0, x1, y, ground: false }))]; + const reaches = (A, B) => { + const dy = B.y - A.y; + if (A.ground && B.ground && (A.x1 === B.x0 || B.x1 === A.x0) && Math.abs(dy) <= ghoul.STEP_UP) return true; + const gap = Math.max(B.x0 - A.x1, A.x0 - B.x1); + if (gap <= 0) return dy < 0 || dy <= ghoul.JUMP_TOP - MARGIN; + return ghoul.jumpHeightAt(gap + MARGIN) >= dy + MARGIN; + }; + const reach = (from) => { + const seen = new Set([from]); + const queue = [from]; + while (queue.length) { + const a = queue.shift(); + for (const b of list) if (!seen.has(b) && reaches(a, b)) (seen.add(b), queue.push(b)); + } + return seen; + }; + const at = (x, y) => list.find((s) => x >= s.x0 && x <= s.x1 && s.y === y); + const start = at(room.start, ghoul.groundAt(room, room.start)); + const door = at(room.door, ghoul.groundAt(room, room.door)); + assert.ok(start && door, `${id}: a start and a door`); + let from = start; + if (room.key) { + const key = at(room.key[0], room.key[1]); + assert.ok(key && reach(start).has(key), `${id}: a route to the key with every tile broken`); + from = key; + } + assert.ok(reach(from).has(door), `${id}: a route on to the door with every tile broken`); + for (const [kind, x, y] of room.items) assert.ok(room.shelves.some(([a, b, top]) => x >= a && x <= b && top === y) || ghoul.groundAt(room, x) === y, `${id}: the ${kind} at ${x} on a surface`); + for (const s of room.spawns) { + if (["frozen", "hand", "shade", "zombie"].includes(s[0])) assert.ok(ghoul.groundAt(room, s[1]) > -Infinity, `${id}: the ${s[0]} at ${s[1]} on the floor`); + if (s[0] === "skel") assert.ok(room.shelves.some(([a, b, top]) => s[1] >= a && s[1] <= b && top === s[2]), `${id}: the skeleton at ${s[1]} on a board`); + if (s[0] === "hand" || s[0] === "shade" || s[0] === "frozen") assert.ok(!room.thin.some(([a, b]) => s[1] >= a - 1 && s[1] <= b + 1) || s[0] === "frozen", `${id}: the ${s[0]} at ${s[1]} not on a thin tile`); + } + assert.equal(ghoul.timeFor(ghoul.roomFor(id)) / 1000 >= 70 || room.boss ? true : false, true, `${id}: a clock`); + } + // The widow's boards: a stair of 12 and 18 each side (18 is over the spikes). + const widow = ghoul.roomById("widow"); + assert.deepEqual(widow.shelves.map((s) => s[2]).sort((a, b) => a - b), [12, 12, 18, 18]); + assert.ok(widow.length - ghoul.FIELD_W > 30); +}); + +test("Ghoul Rush's stage select lists the Frozen Lake and takes you straight into each of its rooms with the flare in the bag", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.stageSelect(); + const r = g.round; + assert.equal(r.phase, "select"); + const at = ghoul.STAGES.findIndex((s) => s.id === "frozen"); + assert.equal(at, ghoul.STAGES.length - 1); + for (let i = 0; i < at; i++) ghoul.steerSelect(r, 1, 0); + for (let i = 0; i < 4; i++) ghoul.steerSelect(r, 0, 1); + assert.equal(r.select.at, at); + assert.equal(r.select.room, 4); + ghoul.takeSelect(r); + assert.equal(r.spec.id, "widow"); + assert.equal(r.stage, "frozen"); + assert.ok(r.arms.some((a) => a.kind === "flare"), "the stage's weapon is in the bag"); + g.tick(16); + // And its rooms draw (no art of its own yet: the foyer's look stands in), with the hands, shades, ghouls and wraiths about. + for (let room = 0; room < 3; room++) { + g.stageSelect(); + for (let i = 0; i < at; i++) ghoul.steerSelect(g.round, 1, 0); + for (let i = 0; i < room; i++) ghoul.steerSelect(g.round, 0, 1); + ghoul.takeSelect(g.round); + g.round.phase = "play"; + for (const kind of ["hand", "shade", "frozen", "icewraith"]) ghoul.spawnMonster(g.round, kind, g.round.you.x + 12, kind === "icewraith" ? 20 : 6, { rise: 0, ...(kind === "icewraith" ? { act: "hover", home: 20 } : {}) }); + assert.doesNotThrow(() => g.tick(16)); + assert.doesNotThrow(() => g.tick(16)); + } +}); + +test("Ghoul Rush's Frozen Lake events are all named strings, and the game takes each one without a fault (the art and the sounds answer them later)", () => { + assert.ok(fz.EVENTS.length >= 30 && new Set(fz.EVENTS).size === fz.EVENTS.length); + const noop = () => {}; + const kit = { tone: noop, burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6 }; + for (const type of fz.EVENTS) assert.doesNotThrow(() => react({ type, x: 10, y: 6, tx: 20, ty: 6, kind: "frostwidow" }, kit), type); +}); + +/* ---------------------------------------------------- voices and drawing */ + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return played; +}; + +test("Ghoul Rush's Frozen Lake: every new kind has a voice for every act, each a real tone, and every event of the pack plays its own sound once (or is silent on purpose)", () => { + const listed = { + hand: ["appear", "warn", "grab", "hurt", "die"], + shade: ["appear", "show", "wind", "lunge", "hurt", "die"], + frozen: ["appear", "shatter", "melt", "hurt", "die"], + icewraith: ["wake", "wind", "dive", "chill", "hurt", "die"], + frostwidow: ["wake", "drop", "rise", "rage", "melt", "up", "gust", "blow", "warn", "spike", "spit", "shot", "land", "call", "kick", "burst", "hurt", "weak", "die"], + ice: ["crack", "break", "back"], + flare: ["throw", "land"], + cocoa: ["active"], + }; + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(listed)) { + assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + } + for (const kind of [...Object.keys(fz.MONSTERS), ...Object.keys(fz.BOSSES)]) assert.ok(VOICES[kind]?.die, `${kind} has a voice and a death`); + for (const type of [...fz.EVENTS, "flareLand", "flareThrow"]) assert.ok(EVENT_VOICE[type] || SILENT.includes(type), `${type} is heard or silent on purpose`); + for (const type of Object.keys(EVENT_VOICE)) assert.ok(fz.EVENTS.includes(type) || type === "flareLand", `${type} is an event of the pack`); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(listed[kind].includes(act), `${type}: ${kind} ${act} is a listed act`); + const played = heard({ type, kind }); + assert.equal(played.filter((n) => n === VOICES[kind][act]).length, 1, `${type}: ${kind}'s ${act} once`); + assert.equal(played.length, 1, `${type}: nothing else`); + } + for (const type of SILENT) assert.deepEqual(heard({ type }), [], `${type} is silent`); + const once = (e, kind, act) => assert.equal(heard(e).filter((n) => n === VOICES[kind][act]).length, 1, `${e.type}: ${kind} ${act} once`); + for (const kind of ["hand", "shade", "frozen"]) once({ type: "spawn", kind }, kind, "appear"); + for (const kind of Object.keys(fz.MONSTERS)) { + once({ type: "hit", kind }, kind, "hurt"); + once({ type: "kill", kind, mult: 1, how: "shot", points: 1 }, kind, "die"); + } + once({ type: "bossWake", kind: "frostwidow" }, "frostwidow", "wake"); + once({ type: "bossHit", kind: "frostwidow", how: "shot" }, "frostwidow", "hurt"); + once({ type: "bossHit", kind: "frostwidow", how: "shot", weak: true }, "frostwidow", "weak"); + once({ type: "bossDown", kind: "frostwidow", points: 1 }, "frostwidow", "die"); + once({ type: "power", kind: "cocoa", points: 50 }, "cocoa", "active"); +}); + +test("Ghoul Rush's Frozen Lake: every new way to die has its words and its own sound", () => { + for (const cause of ["ice", "shard", "spike", "frostwidow", "icewraith", "hand", "frozen", "shade"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Frozen Lake has a look for each room, and a hole in its ice is water drawn over, not a black box", () => { + for (const id of ROOM_IDS) { + assert.ok(LOOKS[id]?.custom && LOOKS[id].pack === "frozen" && LOOKS[id].frozen, `${id} has a custom look`); + assert.equal(LOOKS[id].pit, "rgba(0, 0, 0, 0)", `${id}: the pit is clear`); + } +}); + +test("Ghoul Rush's Frozen Lake draws: every room, the ice and thin ice in each stage, the holes, every monster in every act, the Widow in every pose, the hazards, the flare, Hot Cocoa, the blizzard and Planny in ice, lit and dark, and its card on the stage pick", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["frozen"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { + hand: [{ act: "trail" }, { act: "warn", wait: 200 }, { act: "grab", wait: 700 }, { act: "sink", wait: 150 }], + shade: [{ act: "stalk", prints: [{ x: 30, y: 6, age: 100 }, { x: 33, y: 6, age: 4900 }] }, { act: "stalk", shownMs: 300 }, { act: "wind", wait: 300 }, { act: "lunge", wait: 300 }], + frozen: [{ dir: -1, sv: 0 }, { dir: 1, sv: 12, lurching: true }], + icewraith: [{ act: "idle" }, { act: "hover", y: 18 }, { act: "wind", y: 18 }, { act: "dive", vx: -20, vy: -10, y: 14 }], + }; + for (const id of ROOM_IDS) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + r.hazards.length = 0; + standAt(r, id === "widow" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + ghoul.advance(r, 8, steady); + for (const [kind, list] of Object.entries(acts)) list.forEach((over, i) => put(r, kind, r.you.x + 6 + i * 5, { wait: 1e9, force: true, ...over })); + if (r.thin) { + const states = [{ t: 100 }, { t: 800, state: "crack" }, { t: 1300, state: "broken", back: 900 }, { t: 0, state: "broken", back: 5000 }]; + r.thin.tiles.forEach((tl, i) => Object.assign(tl, states[i % states.length])); + } + for (const h of [{ kind: "shard", x: r.you.x + 20, y: 6, off: 0, vx: 26, w: 1.8, h: 1.3, warn: 100, life: 650 }, { kind: "shard", x: r.you.x + 24, y: 8.8, off: 2.8, vx: -26, w: 1.8, h: 1.2, warn: 0, life: 650 }, { kind: "spike", x: r.you.x + 28, y: 6, w: 4, h: 9.5, warn: 300, up: 1000 }, { kind: "spike", x: r.you.x + 33, y: 6, w: 4, h: 9.5, warn: 0, up: 1000, live: 700 }, { kind: "webGlob", x: r.you.x + 12, y: 14, vx: -10, vy: -3, spin: 1, life: 1500, w: 1.6, h: 1.6 }, { kind: "webPatch", x: r.you.x + 16, y: 6, life: 3000, max: 6000, w: 5, h: 0.8 }, { kind: "barrel", x: r.you.x + 8, y: 6, state: "still", vx: 0, roll: 0, life: 5000, hit: [], w: 3, h: 3.4 }, { kind: "barrel", x: r.you.x + 10, y: 6, state: "roll", vx: 34, roll: 2, life: 5000, hit: [], w: 3, h: 3.4 }, { kind: "armRoadFlare", x: r.you.x + 14, y: 12, vx: 20, vy: 5, spin: 1, rest: false, t: 0, w: 0.8, h: 0.8 }, { kind: "armRoadFire", x: r.you.x + 18, y: 6, life: 3000, max: 4000, tick: 0, bossDone: 0, w: 6, h: 5 }]) r.hazards.push({ cause: "x", live: 0, ...h }); + r.effects.cocoa = 5000; + for (const heldMs of [0, 500, 100]) { + r.you.heldMs = heldMs; + for (const wind of [null, { state: "warn", ms: 500, dir: 1 }, { state: "blow", ms: 1500, dir: -1 }]) { + if (r.twist && wind) r.twist.wind = wind; + assert.doesNotThrow(() => g.tick(16)); + } + } + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + const f = r.boss.floor; + for (const pose of [{ act: "hang", y: f + 20 }, { act: "drop", y: f + 8, toX: r.boss.x - 10, wait: 300 }, { act: "low", y: f }, { act: "low", y: f, veil: false, veilMs: 3000, mouth: true }, { act: "low", y: f, veil: false, veilMs: 400, spitWind: 300 }, { act: "rise", y: f + 10, raged: true }, { act: "low", y: f, hurt: 100 }]) { + Object.assign(r.boss, { wait: 1e9, lowMs: 1e9, ...pose }); + assert.doesNotThrow(() => g.tick(16)); + } + } + r.you.safeMs = 1e9; + } + } + assert.equal(r.spec.id, "widow", "got to the Widow's Web and drew it"); + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["frozen", "carnival"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Frozen Lake's card"); +}); diff --git a/scripts/test-web-console-activities-ghoul-gameover.mjs b/scripts/test-web-console-activities-ghoul-gameover.mjs new file mode 100644 index 0000000..7bcd77d --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-gameover.mjs @@ -0,0 +1,90 @@ +// Web console tests, Ghoul Rush's game over: a lost end plays the mechanical laugh track (and a win does not), and the "G A M E - O V E R" banner drops in letter by letter and draws on a fake canvas. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import { dropAt, gameOverBanner, OVER_WORD } from "../src/web-console/public/activities/ghoul-gameover-draw.js"; +import { toneNames } from "../src/web-console/public/tones.js"; + +function fakeCtx(texts) { + return new Proxy({}, { + get: (t, name) => (name in t ? t[name] : name === "fillText" ? (s) => texts.push(s) : () => {}), + set: (t, name, value) => ((t[name] = value), true), + }); +} + +// Clears every stage the way the main suite does. +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, () => 0.5); +} +function winRun(h) { + const r = h.round; + through(r); + while (!r.over) { + r.phaseMs = 0; + ghoul.pickStage(r); + for (let k = 0; k < 4; k++) through(r); + } +} + +function playTo(end) { + const sounds = []; + const texts = []; + const ctx = fakeCtx(texts); + const h = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, tone: (name) => sounds.push(name) }); + h.resize(900, 900); + h.key("action"); + for (let k = 0; k < 40; k++) h.tick(16); + end(h); + for (let k = 0; k < 300 && h.state === "running"; k++) h.tick(16); + return { h, sounds, texts }; +} + +test("Ghoul Rush: the laugh track is a house tone", () => { + assert.ok(toneNames().includes("ghoulLaughTrack")); +}); + +test("Ghoul Rush: a lost end plays the laugh track, a win does not", () => { + const lost = playTo((h) => { + h.round.dice = 0; + h.round.lives = 1; + ghoul.lose(h.round, "zombie"); + }); + assert.equal(lost.h.state, "over"); + assert.ok(lost.sounds.includes("gameOver") && lost.sounds.includes("ghoulLaughTrack"), "the loss laughs"); + const won = playTo(winRun); + assert.equal(won.h.state, "over"); + assert.ok(won.sounds.includes("victory") && !won.sounds.includes("ghoulLaughTrack"), "a win stays quiet"); +}); + +test("Ghoul Rush: the game over banner is drawn on a loss only, letter by letter", () => { + const lost = playTo((h) => { + h.round.dice = 0; + h.round.lives = 1; + ghoul.lose(h.round, "zombie"); + }); + for (let k = 0; k < 200; k++) lost.h.tick(16); + assert.ok(["ghoulLaughTrack2", "ghoulLaughTrack3"].every((n) => lost.sounds.includes(n)), "the laugh runs on, a second a part"); + assert.equal(lost.sounds.filter((n) => n === "ghoulLaughTrack3").length, 1, "each part plays once"); + lost.texts.length = 0; + lost.h.tick(16); + assert.equal(lost.texts.filter((s) => OVER_WORD.includes(s) && s.length === 1).length, OVER_WORD.length * 2, "every letter drawn, shadow and face"); + const won = playTo(winRun); + won.texts.length = 0; + won.h.tick(16); + assert.ok(!won.texts.includes("G"), "no banner on a win"); +}); + +test("Ghoul Rush: a letter falls, bounces once and rests", () => { + assert.equal(dropAt(-5), 1); + assert.ok(dropAt(100) < 1 && dropAt(100) > 0.5); + assert.equal(dropAt(10000), 0); + let thrown = null; + try { + gameOverBanner({ label() {}, BONE: "#fff", DANGER: "#f00" })(fakeCtx([]), { g: { FIELD_W: 96, FIELD_H: 54 }, overMs: 300, clock: 300 }); + } catch (e) { + thrown = e; + } + assert.equal(thrown, null); +}); diff --git a/scripts/test-web-console-activities-ghoul-graveyard.mjs b/scripts/test-web-console-activities-ghoul-graveyard.mjs new file mode 100644 index 0000000..35b40c0 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-graveyard.mjs @@ -0,0 +1,445 @@ +// Web console tests, Ghoul Rush's Graveyard stage: its four rooms, grasping hands, mourners and their wail, grave robbers, rotters and the legs they leave, carrion crows, the graves rotters climb out of, and Mother Mourning, who can only be hurt while she watches and drops a stone fist on whatever moves. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as gy from "../src/web-console/public/activities/ghoul-graveyard.js"; +import { VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Graveyard's room `id`, reached the way play reaches it, +// nothing woken: every spawner spent, the horde held back. +function graveRound(id) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["graveyard"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.events.length = 0; + return round; +} + +function standAt(round, x) { + Object.assign(round.you, { x, y: ghoul.groundAt(round.spec, x), vx: 0, vy: 0, state: "run", shelf: -1, coyote: 0, drop: -1, out: 0, safeMs: 0, face: 1 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, steady); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +test("Ghoul Rush's Graveyard is a stage of three rooms and Mother Mourning's, its monsters and boss joined to the game's", () => { + const st = ghoul.stageById("graveyard"); + assert.deepEqual(st.rooms, ["lychgate", "graves", "mausoleums", "angel"]); + assert.equal(st.boss, "angel"); + for (const kind of Object.keys(gy.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], gy.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.angel, gy.BOSSES.angel); + assert.ok(ghoul.ZOMBIES.has("rotter"), "a rotter is a zombie in all but its death"); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); +}); + +test("Ghoul Rush's graves let out rotters, a door's fifth entry naming what comes out", () => { + const round = graveRound("lychgate"); + const at = round.spec.spawns.findIndex((s) => s[0] === "door"); + assert.equal(round.spec.spawns[at][4], "rotter"); + round.spawns[at].over = false; + standAt(round, round.spec.spawns[at][1] - 30); + round.you.safeMs = 1e9; + run(round, 1200); + assert.ok(round.monsters.some((m) => m.kind === "rotter" && m.door), "a rotter out of the grave"); +}); + +test("Ghoul Rush's grasping hands lie unseen under the dirt, burst up as you come near, grab, sink, and creep under the ground after you, never across a pit", () => { + const round = graveRound("lychgate"); + standAt(round, 20); + round.you.safeMs = 1e9; + const h = put(round, "hands", 60); + assert.equal(h.act, "lurk"); + assert.equal(ghoul.solid(h), false, "unseen under the dirt"); + run(round, 200); + assert.equal(h.act, "lurk", "nothing while you are far"); + standAt(round, 60 - gy.HANDS_NEAR + 2); + round.you.safeMs = 1e9; + run(round, 8); + assert.equal(h.act, "rise"); + assert.equal(events(round, "grab").length, 1); + assert.equal(ghoul.solid(h), false, "harmless while it comes up"); + run(round, gy.HANDS_RISE_MS); + assert.equal(h.act, "grab"); + assert.equal(ghoul.solid(h), true, "up, it can hurt and be hit"); + run(round, gy.HANDS_UP_MS + gy.HANDS_SINK_MS); + assert.equal(h.act, "creep"); + assert.equal(ghoul.solid(h), false); + const x0 = h.x; + standAt(round, 30); + round.you.safeMs = 1e9; + run(round, 600); + assert.ok(h.x < x0 - 3, `it creeps toward you (${x0} to ${h.x.toFixed(1)})`); + // The Lychgate's first floor ends in a pit at 110: hands creeping after + // you across it stop at its edge. + const r2 = graveRound("lychgate"); + standAt(r2, 130); + r2.you.safeMs = 1e9; + const h2 = put(r2, "hands", 100, { act: "creep", wait: 1e9 }); + run(r2, 3000); + assert.ok(h2.x < 110, `stopped at the pit (${h2.x.toFixed(1)})`); +}); + +test("Ghoul Rush's mourner lifts her veil and wails now and then, slowing you to half speed for a while if you are close", () => { + const round = graveRound("lychgate"); + standAt(round, 30); + round.you.safeMs = 1e9; + const m = put(round, "mourner", 46); + m.throwIn = 10; + run(round, 40); + assert.equal(events(round, "wailWind").length, 1, "the veil lifts"); + run(round, gy.WAIL_WIND_MS); + const wail = events(round, "wail")[0]; + assert.ok(wail && wail.close, "a wail, close"); + assert.ok(round.you.slowMs > gy.SLOW_MS - 100, "you are slowed"); + // Slowed, you run at SLOW_SHARE of your speed. + const r2 = graveRound("lychgate"); + standAt(r2, 20); + r2.you.safeMs = 1e9; + run(r2, 400, { right: true }); + const free = r2.you.x - 20; + standAt(r2, 20); + r2.you.safeMs = 1e9; + r2.you.slowMs = 5000; + run(r2, 400, { right: true }); + const slow = r2.you.x - 20; + assert.ok(Math.abs(slow - free * gy.SLOW_SHARE) < 0.5, `half speed (${slow.toFixed(1)} of ${free.toFixed(1)})`); + // Out of reach, a wail slows nothing. + const r3 = graveRound("lychgate"); + standAt(r3, 20); + r3.you.safeMs = 1e9; + const far = put(r3, "mourner", 20 + gy.WAIL_REACH + 8); + far.throwIn = 10; + far.speed = 0; + run(r3, 40 + gy.WAIL_WIND_MS); + assert.equal(events(r3, "wail")[0]?.close, false); + assert.ok(!(r3.you.slowMs > 0)); +}); + +test("Ghoul Rush's grave robber walks at you, digs in close, and comes up behind you, out of reach of your bolts while under the ground", () => { + const round = graveRound("graves"); + standAt(round, 30); + round.you.safeMs = 1e9; + const m = put(round, "robber", 30 + gy.ROBBER_DIG - 2); + assert.equal(ghoul.solid(m), true, "walking, it can be hit"); + run(round, 20); + assert.equal(m.act, "dig"); + assert.equal(events(round, "dig").length, 1); + assert.equal(ghoul.solid(m), false, "digging in, it cannot"); + run(round, gy.DIG_MS + 2000); + assert.ok(events(round, "unearth").length >= 1, "it comes up"); + const up = events(round, "unearth")[0]; + assert.ok(up.x < round.you.x, `behind you, facing right (${up.x.toFixed(1)} vs ${round.you.x})`); +}); + +test("Ghoul Rush's rotter shot down at the body leaves its legs walking after you; a headshot or a stomp finishes it", () => { + const body = graveRound("lychgate"); + standAt(body, 20); + const r = put(body, "rotter", 40); + ghoul.kill(body, r, "shot", steady); + assert.equal(events(body, "legs").length, 1); + const legs = body.monsters.find((m) => m.kind === "legs"); + assert.ok(legs, "its legs"); + body.you.safeMs = 1e9; + const x0 = legs.x; + run(body, 300); + assert.ok(legs.x < x0 - 3, "walking at you"); + for (const how of ["head", "stomp", "crush"]) { + const round = graveRound("lychgate"); + standAt(round, 20); + ghoul.kill(round, put(round, "rotter", 40), how, steady); + assert.equal(round.monsters.filter((m) => m.kind === "legs").length, 0, `none after a ${how}`); + } +}); + +test("Ghoul Rush's carrion crow waits on its headstone till you come near, then dives at your chest and climbs away to dive again", () => { + const round = graveRound("lychgate"); + standAt(round, 20); + round.you.safeMs = 1e9; + const c = put(round, "crow", 20 + gy.CROW_NEAR + 10, { y: 10 }); + assert.equal(c.act, "perch"); + run(round, 300); + assert.equal(c.act, "perch", "still while you are far"); + standAt(round, c.x - gy.CROW_NEAR + 4); + round.you.safeMs = 1e9; + run(round, 8); + assert.equal(events(round, "caw").length, 1); + run(round, 600); + assert.ok(events(round, "dive").length >= 1); + assert.ok(c.act === "dive" || c.act === "climb"); + const dived = events(round, "dive")[0]; + assert.ok(dived.x > round.you.x, "from ahead of you"); +}); + +/* --------------------------------------------------------- the angel */ + +// The Angel's Rest arena, you in it, Mother Mourning awake. +function angelFight() { + const round = graveRound("angel"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + round.you.safeMs = 0; + round.events.length = 0; + return round; +} + +const shoot = (round) => { + const b = round.boss; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 6, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); +}; + +test("Mother Mourning weeps as stone: shots and stomps glance off her while she weeps (and turns), and she flings headstones", () => { + const round = angelFight(); + const b = round.boss; + assert.equal(b.act, "weep"); + const hp = b.hp; + shoot(round); + assert.equal(b.hp, hp, "no harm while she weeps"); + assert.equal(events(round, "bossBlock").length, 1); + round.you.safeMs = 1e9; + run(round, gy.ANGEL_THROW_MS * 1.5); + assert.ok(events(round, "throw").some((e) => e.kind === "stone" && e.by === "angel"), "a headstone flung"); + // Standing on her head while she weeps does her no harm either. + const r2 = angelFight(); + const b2 = r2.boss; + Object.assign(r2.you, { x: b2.x, y: b2.y + b2.h + 0.3, vy: -20, state: "air", safeMs: 1e9 }); + ghoul.advance(r2, 40, steady); + assert.equal(b2.hp, b2.max); + assert.ok(events(r2, "bossBlock").length >= 1); +}); + +test("Mother Mourning turns and watches: stand still and she can be hurt; move and a stone fist comes down where you are, its shadow first", () => { + const round = angelFight(); + const b = round.boss; + round.you.safeMs = 1e9; + run(round, b.wait + 8); + assert.equal(b.act, "turn"); + assert.equal(events(round, "angelTurn").length, 1); + run(round, gy.ANGEL_TURN_MS + 8); + assert.equal(b.act, "watch"); + round.you.safeMs = 0; + // Still: no fist, and a shot hurts her. + run(round, 300); + assert.equal(round.hazards.length, 0, "standing still is safe"); + const hp = b.hp; + shoot(round); + assert.equal(b.hp, hp - 1, "while she watches, she can be hurt"); + assert.equal(events(round, "bossHit")[0].kind, "angel", "the hit names her"); + // Moving: a fist's shadow where you are, then the fist. + run(round, 40, { right: true }); + assert.equal(events(round, "angelSee").length, 1); + assert.equal(round.hazards.length, 1); + const fist = round.hazards[0]; + assert.ok(Math.abs(fist.x - round.you.x) < 2, "over you"); + assert.ok(fist.warn > 0, "its shadow first"); + run(round, gy.FIST_WARN_MS); + assert.ok(events(round, "fist").length === 1, "down it comes"); + assert.equal(events(round, "lose")[0]?.cause, "fist", "and you were still under it"); +}); + +test("Mother Mourning at half her hp spreads her wings: a shorter weep, the same watch, and a shockwave each way as each weep begins", () => { + const round = angelFight(); + const b = round.boss; + round.you.safeMs = 1e9; + const calmWeep = b.wait; + b.hp = Math.floor(b.max * gy.ANGEL_RAGE); + run(round, 8); + assert.equal(events(round, "angelWings").length, 1); + run(round, b.wait + gy.ANGEL_TURN_MS + 16); + assert.equal(b.act, "watch"); + assert.ok(b.wait <= gy.ANGEL_WATCH_MS, "the watch no longer grows"); + round.waves.length = 0; + run(round, b.wait + 8); + assert.equal(b.act, "weep"); + assert.ok(b.wait < calmWeep, "a shorter weep"); + assert.deepEqual(round.waves.map((w) => w.dir).sort(), [-1, 1], "a shockwave each way"); +}); + +test("Mother Mourning is tougher: more hp, a shorter watch, and a quicker fist (a shorter shadow and gap)", () => { + assert.equal(gy.BOSSES.angel.hp, 85); + assert.equal(angelFight().boss.max, 85); + assert.ok(gy.ANGEL_WATCH_MS <= 1600); + assert.ok(gy.FIST_WARN_MS <= 440 && gy.FIST_GAP_MS <= 570); + const round = angelFight(); + const b = round.boss; + round.you.safeMs = 1e9; + run(round, b.wait + gy.ANGEL_TURN_MS + 16); + assert.equal(b.act, "watch"); + assert.ok(b.wait <= gy.ANGEL_WATCH_MS && b.wait > gy.ANGEL_WATCH_MS - 100, `watches about ${gy.ANGEL_WATCH_MS} ms (${b.wait})`); +}); + +test("Mother Mourning moves when you are not looking: each time she turns back to watch she has blinked a few units nearer, never onto you or out of the arena, with stone dust", () => { + const blinkFrom = (youX, herX) => { + const round = angelFight(); + const b = round.boss; + round.you.safeMs = 1e9; + if (herX !== undefined) b.x = herX; + standAt(round, youX); + round.you.safeMs = 1e9; + Object.assign(b, { act: "turn", wait: 0 }); + const x0 = b.x; + run(round, 8); + return { round, b, x0 }; + }; + const near = blinkFrom(120); + assert.equal(near.b.act, "watch"); + assert.ok(Math.abs(near.b.x - (near.x0 - gy.BLINK_STEP)) < 0.01, `blinked ${gy.BLINK_STEP} nearer (${near.x0} to ${near.b.x})`); + const ev = events(near.round, "angelBlink"); + assert.equal(ev.length, 1); + assert.ok(ev[0].x === near.x0 && ev[0].tx === near.b.x, "the dust at both ends"); + assert.equal(near.b.y, ghoul.groundAt(near.round.spec, near.b.x), "still on the floor"); + // Close to you she stops short of BLINK_KEEP, and never goes past you. + const close = blinkFrom(150, 150 + gy.BLINK_KEEP + 2); + assert.ok(close.b.x - 150 >= gy.BLINK_KEEP - 0.01, `kept her distance (${close.b.x - 150})`); + const on = blinkFrom(150, 150 + gy.BLINK_KEEP - 4); + assert.equal(on.b.x, on.x0, "already too close: she stays"); + assert.equal(events(on.round, "angelBlink").length, 0); + // At the arena's wall she stays inside it. + const wall = blinkFrom(106, 104 + 6 + gy.BOSSES.angel.w / 2 + 0.2); + assert.ok(wall.b.x >= 104 + 6 + gy.BOSSES.angel.w / 2 - 0.01, "inside the arena"); + // Over many turns she creeps nearer but never reaches you, and she never harms you by arriving. + const creep = angelFight(); + creep.you.safeMs = 1e9; + standAt(creep, 110); + creep.you.safeMs = 1e9; + const x0 = creep.boss.x; + for (let i = 0; i < 6; i++) { + Object.assign(creep.boss, { act: "turn", wait: 0 }); + run(creep, 8); + } + assert.ok(creep.boss.x < x0 - 10, "creeping nearer"); + assert.ok(creep.boss.x - creep.you.x >= gy.BLINK_KEEP - 0.01); + // She can still be hurt right after she blinks. + const hurt = angelFight(); + hurt.you.safeMs = 1e9; + Object.assign(hurt.boss, { act: "turn", wait: 0 }); + run(hurt, 8); + const hp = hurt.boss.hp; + shoot(hurt); + assert.equal(hurt.boss.hp, hp - 1); +}); + +test("Mother Mourning in her rage throws two headstones at a time, and while she watches a fist also falls near you now and then even if you stand still, its shadow first", () => { + const throws = (rage) => { + const round = angelFight(); + const b = round.boss; + round.you.safeMs = 1e9; + if (rage) b.hp = Math.floor(b.max * gy.ANGEL_RAGE); + b.throwIn = 1; + run(round, 8); + return events(round, "throw").filter((e) => e.by === "angel").length; + }; + assert.equal(throws(false), 1); + assert.equal(throws(true), 2); + const calm = angelFight(); + calm.you.safeMs = 1e9; + Object.assign(calm.boss, { act: "watch", wait: 1e9, rainIn: 100 }); + run(calm, 3000); + assert.equal(calm.hazards.length, 0, "before her rage, standing still is safe"); + const round = angelFight(); + const b = round.boss; + b.hp = Math.floor(b.max * gy.ANGEL_RAGE); + Object.assign(b, { act: "watch", wait: 1e9, rainIn: 100 }); + round.you.safeMs = 1e9; + run(round, 120); + assert.equal(round.hazards.length, 1, "a fist with nobody moving"); + const fist = round.hazards[0]; + assert.ok(Math.abs(fist.x - round.you.x) <= gy.RAIN_NEAR + 0.01, "near you"); + assert.ok(fist.warn > 0 && fist.live === 0, "its shadow first"); + assert.equal(events(round, "angelSee").length, 0, "you did not move"); + run(round, gy.FIST_WARN_MS + 8); + assert.equal(events(round, "fist").length, 1, "down it comes"); + // It keeps falling about every RAIN_MS, at random spots near you. + const many = angelFight(); + many.boss.hp = Math.floor(many.boss.max * gy.ANGEL_RAGE); + Object.assign(many.boss, { act: "watch", wait: 1e9, rainIn: gy.RAIN_MS }); + many.you.safeMs = 1e9; + let spots = new Set(); + for (let t = 0; t < gy.RAIN_MS * 6; t += 4) { + ghoul.advance(many, 4, () => Math.random()); + for (const h of many.hazards) spots.add(h.x.toFixed(2)); + } + assert.ok(spots.size >= 4 && spots.size <= 7, `about six fists (${spots.size})`); + // Standing under one costs a life, named for the fist. + const under = angelFight(); + under.boss.hp = Math.floor(under.boss.max * gy.ANGEL_RAGE); + Object.assign(under.boss, { act: "watch", wait: 1e9, rainIn: 10 }); + run(under, 20 + gy.FIST_WARN_MS + 40); + assert.equal(events(under, "lose")[0]?.cause, "fist"); + // Endless lives spare it. + const endless = angelFight(); + endless.infinite = true; + endless.boss.hp = Math.floor(endless.boss.max * gy.ANGEL_RAGE); + Object.assign(endless.boss, { act: "watch", wait: 1e9, rainIn: 10 }); + const lives = endless.lives; + run(endless, 20 + gy.FIST_WARN_MS + 40); + assert.equal(endless.lives, lives); +}); + +test("Mother Mourning's blink reads: stone dust and a callout, no picked sound beyond the house boom", () => { + const played = []; + const floats = []; + const bursts = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: (...a) => bursts.push(a), float: (x, y, t) => floats.push(t), ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {} }; + react({ type: "angelBlink", kind: "angel", x: 150, y: 8, tx: 145 }, kit); + assert.equal(bursts.length, 2, "dust at both ends"); + assert.deepEqual(floats, ["She moved"]); + const names = Object.values(VOICES.angel); + assert.equal(played.filter((n) => names.includes(n)).length, 0, "no voice doubled up"); + assert.deepEqual(played, ["boom"]); +}); + +test("Mother Mourning falls: the door opens and every hazard is gone", () => { + const round = angelFight(); + const b = round.boss; + b.act = "watch"; + b.wait = 1e9; + b.hp = 1; + round.hazards.push({ kind: "fist", x: 150, y: 6, w: 6, h: 9, warn: 300, live: 0, cause: "fist" }); + shoot(round); + assert.equal(b.state, "down"); + assert.equal(round.hasKey, true); + assert.equal(round.hazards.length, 0); +}); + +test("Ghoul Rush: a hit on any boss plays that boss's own hurt sound, and the Graveyard's monsters and Mother Mourning each have their own voice for every act", () => { + for (const kind of Object.keys(ghoul.BOSSES)) { + const played = []; + const fx = { clock: 1e6 }; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {} }; + react({ type: "bossHit", kind, x: 0, y: 0, how: "shot" }, kit); + assert.ok(played.includes(VOICES[kind].hurt), `${kind}: ${VOICES[kind].hurt}`); + } + const own = { hands: ["appear", "grab", "hurt", "die"], mourner: ["appear", "wail", "hurt", "die"], robber: ["appear", "dig", "unearth", "hurt", "die"], rotter: ["appear", "climb", "hurt", "die"], legs: ["appear", "die"], crow: ["wake", "dive", "hurt", "die"], angel: ["wake", "weep", "watch", "see", "slam", "wings", "hurt", "die"] }; + for (const [kind, acts] of Object.entries(own)) { + assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + for (const act of acts) assert.match(VOICES[kind][act], new RegExp(`^ghoul${kind[0].toUpperCase()}${kind.slice(1)}`), `${kind}.${act} is its own`); + } +}); diff --git a/scripts/test-web-console-activities-ghoul-grounds.mjs b/scripts/test-web-console-activities-ghoul-grounds.mjs new file mode 100644 index 0000000..9d55046 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-grounds.mjs @@ -0,0 +1,921 @@ +// Web console tests, Ghoul Rush's Grounds stage: its four rooms, topiary beasts that creep only when your back is turned, rootlings under the lawn, lantern moths, mulch crawlers, the Hedge shears (found only here), and the Groundskeeper, whose lantern takes triple damage, whose scythe is jumped, whose fire burns the floor and who mounts a mower at half his hp. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as gr from "../src/web-console/public/activities/ghoul-grounds.js"; +import { LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-grounds-draw.js"; +import { PILL_WORDS } from "../src/web-console/public/activities/ghoul-powers.js"; +import { pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import * as sfxGrounds from "../src/web-console/public/activities/ghoul-sfx-grounds.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Grounds' room `id`, reached the way play reaches it, +// nothing woken: every spawner spent, the horde held back. +function groundsRound(id) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["grounds"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1) { + Object.assign(round.you, { x, y: ghoul.groundAt(round.spec, x), vx: 0, vy: 0, state: "run", shelf: -1, coyote: 0, drop: -1, out: 0, safeMs: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, steady); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +// Runs until `done()` (or `ms` have passed), 4 ms at a time. +function until(round, done, ms = 4000) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, steady); +} + +// A bolt arriving from the left at height `y` on the monster `m`. +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +test("Ghoul Rush's Grounds is a stage of three rooms and the Groundskeeper's, its monsters and boss joined to the game's, with shears and a place for each kind", () => { + const st = ghoul.stageById("grounds"); + assert.deepEqual(st.rooms, ["maze", "topiary", "gazebo", "yard"]); + assert.equal(st.boss, "keeper"); + for (const kind of Object.keys(gr.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], gr.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.keeper, gr.BOSSES.keeper); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [maze, garden, gazebo, yard] = st.rooms.map((id) => ghoul.roomById(id)); + for (const room of [maze, garden, gazebo]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + assert.ok(room.items.some((i) => i[0] === "shears"), `${room.id}: Hedge shears`); + assert.ok(room.spawns.some((s) => s[0] in gr.MONSTERS), `${room.id}: some of the new monsters`); + } + assert.equal(yard.boss, "keeper"); + assert.equal(yard.horde.length, 0); + assert.ok(yard.shelves.length >= 3, "shelves to jump onto"); + // They get harder in order: more haunting, a quicker horde. + assert.ok(maze.spawns.length <= garden.spawns.length && garden.spawns.length <= gazebo.spawns.length); + assert.ok(maze.hordeMs > garden.hordeMs && garden.hordeMs > gazebo.hordeMs); + // The maze's hedges are walls to jump. + assert.ok(maze.ground.some((p, i) => i && p[2] - maze.ground[i - 1][2] > ghoul.STEP_UP), "a hedge higher than a step"); +}); + +test("Ghoul Rush's topiary beast stands frozen while you face it and charges the moment your back is turned, saying so", () => { + const round = groundsRound("maze"); + standAt(round, 30, 1); + round.you.safeMs = 1e9; + const m = put(round, "topiary", 60); + assert.equal(m.act, "still"); + assert.equal(ghoul.solid(m), true, "a frozen hedge still hurts"); + run(round, 400); + assert.equal(m.x, 60, "facing it, it never moves"); + assert.equal(events(round, "rustle").length, 0); + round.you.face = -1; + run(round, 400); + assert.equal(m.act, "creep"); + assert.equal(events(round, "rustle").length, 1); + assert.ok(m.x < 60 - 5, `it charged (${m.x.toFixed(1)})`); + assert.ok(m.x > 60 - 0.4 * gr.MONSTERS.topiary.speed * 1.5, "at its own speed"); + round.you.face = 1; + run(round, 8); + assert.equal(m.act, "still"); + assert.equal(events(round, "freeze").length, 1); + const stopped = m.x; + run(round, 300); + assert.equal(m.x, stopped); + // Far away it stays put even with your back turned; it is no stomp either. + const far = groundsRound("maze"); + standAt(far, 10, -1); + const f = put(far, "topiary", 10 + gr.TOPIARY_NEAR + 20); + run(far, 300); + assert.equal(f.act, "still"); + assert.equal(ghoul.MONSTERS.topiary.stomp, false); + // Right under you it stops rather than flipping about. + const under = groundsRound("maze"); + standAt(under, 20, -1); + under.you.safeMs = 1e9; + const u = put(under, "topiary", 20 + ghoul.UNDER_DX / 2); + run(under, 200); + assert.ok(Math.abs(u.x - (20 + ghoul.UNDER_DX / 2)) < 0.01); +}); + +test("Ghoul Rush's topiary beast is only ever hit while you face it: a bolt goes the way you face", () => { + const round = groundsRound("maze"); + standAt(round, 30, 1); + round.you.safeMs = 1e9; + const m = put(round, "topiary", 50); + round.input.fire = true; + run(round, 400); + assert.ok(m.hp < m.max, "shot while frozen"); + assert.equal(m.act, "still"); + assert.equal(m.x, 50); +}); + +test("Ghoul Rush's rootling is a crack running after you under the lawn, which warns where a root will come up, bursts up (solid, hurting, shot or stomped for a while), sinks and tracks again", () => { + const round = groundsRound("topiary"); + standAt(round, 20); + round.you.safeMs = 1e9; + const r = put(round, "rootling", 20 + gr.ROOT_NEAR - 4); + assert.equal(r.act, "trail"); + assert.equal(ghoul.solid(r), false, "not solid while under"); + const x0 = r.x; + run(round, 400); + assert.ok(r.x < x0 - 4, `the crack runs toward you (${x0} to ${r.x.toFixed(1)})`); + assert.equal(r.act, "trail"); + // It stops tracking and warns, then comes up where it stopped. + until(round, () => r.act === "warn"); + assert.equal(r.act, "warn"); + assert.equal(events(round, "rootWarn").length, 1); + const at = r.x; + run(round, gr.ROOT_WARN_MS - 40); + assert.equal(r.x, at, "the warning does not follow you"); + assert.equal(ghoul.solid(r), false); + run(round, 80); + assert.equal(r.act, "up"); + assert.equal(events(round, "rootUp").length, 1); + assert.equal(ghoul.solid(r), true); + run(round, gr.ROOT_UP_MS + 40); + assert.equal(r.act, "sink"); + assert.equal(ghoul.solid(r), false); + run(round, gr.ROOT_SINK_MS + 40); + assert.ok(["trail", "warn"].includes(r.act) && events(round, "rootWarn").length >= 2, "and round again"); + // Far away on its floor, it lies still. + const far = groundsRound("topiary"); + standAt(far, 10); + const f = put(far, "rootling", 10 + gr.ROOT_NEAR + 10); + run(far, 500); + assert.equal(f.x, 10 + gr.ROOT_NEAR + 10); + // A root that is up hurts, can be stomped, and dies to a bolt. + const hurt = groundsRound("topiary"); + standAt(hurt, 30); + const up = put(hurt, "rootling", 30, { act: "up", wait: gr.ROOT_UP_MS }); + run(hurt, 20); + assert.equal(events(hurt, "lose")[0]?.cause, "rootling"); + assert.equal(ghoul.MONSTERS.rootling.stomp, true); + assert.ok(up); + const shot = groundsRound("topiary"); + standAt(shot, 30); + const t = put(shot, "rootling", 50, { act: "up", wait: 1e9 }); + for (let k = 0; k < t.max; k++) bolt(shot, t, t.y + 2); + ghoul.advance(shot, 4, steady); + assert.ok(t.hp < t.max, "a bolt hurts it"); +}); + +test("Ghoul Rush's lantern moths come as flocks of three and flutter at you, 1.5 times faster in a dark room and faster still, and straight, while you hold the Lantern", () => { + const travel = (setup) => { + const round = groundsRound("gazebo"); + standAt(round, 20); + round.you.safeMs = 1e9; + setup(round); + const m = put(round, "moth", 80, { y: ghoul.groundAt(round.spec, 80) + 1.7, flock: true }); + run(round, 1500); + return { dist: 80 - m.x, m }; + }; + const lit = travel((r) => (r.dark = false)); + const dark = travel((r) => (r.dark = true)); + const lamp = travel((r) => { + r.dark = true; + ghoul.applyPower(r, "lantern"); + }); + assert.ok(dark.dist > lit.dist * 1.25, `dark ${dark.dist.toFixed(1)} vs lit ${lit.dist.toFixed(1)}`); + assert.ok(lamp.dist > dark.dist * 1.25, `the Lantern ${lamp.dist.toFixed(1)}`); + assert.ok(lit.m.dir === -1 && ghoul.MONSTERS.moth.hp === 1); + // A spawn row makes a flock of three, one bolt each; a horde moth comes alone. + const round = groundsRound("gazebo"); + standAt(round, 20); + round.you.safeMs = 1e9; + put(round, "moth", 120, { y: 30 }); + run(round, 8); + const flock = round.monsters.filter((m) => m.kind === "moth"); + assert.equal(flock.length, gr.MOTH_FLOCK); + assert.ok(new Set(flock.map((m) => Math.round(m.x))).size > 1, "spread apart"); + const lone = groundsRound("gazebo"); + standAt(lone, 20); + lone.you.safeMs = 1e9; + put(lone, "moth", 120, { y: 30, horde: true }); + run(lone, 8); + assert.equal(lone.monsters.filter((m) => m.kind === "moth").length, 1); + assert.equal(ghoul.MONSTERS.moth.flies, true, "a horde one comes in high"); +}); + +test("Ghoul Rush's mulch crawler waits unseen in its leaf pile, bursts out as you come near, then crawls at you", () => { + const round = groundsRound("topiary"); + standAt(round, 20); + round.you.safeMs = 1e9; + const m = put(round, "mulch", 20 + gr.MULCH_NEAR + 14); + assert.equal(m.act, "pile"); + assert.equal(ghoul.solid(m), false, "a pile of leaves"); + run(round, 300); + assert.equal(m.act, "pile", "nothing while you are far"); + standAt(round, m.x - gr.MULCH_NEAR + 2); + round.you.safeMs = 1e9; + run(round, 8); + assert.equal(m.act, "burst"); + assert.equal(events(round, "leaves").length, 1); + assert.equal(ghoul.solid(m), false, "harmless while it bursts"); + run(round, gr.MULCH_BURST_MS + 20); + assert.equal(m.act, "crawl"); + assert.equal(ghoul.solid(m), true); + const x0 = m.x; + run(round, 300); + assert.ok(m.x < x0 - 2, "it crawls at you"); + // A horde one is already crawling. + const horde = groundsRound("topiary"); + standAt(horde, 20); + const h = put(horde, "mulch", 90, { horde: true }); + run(horde, 8); + assert.equal(h.act, "crawl"); +}); + +/* ------------------------------------------------------ the shears */ + +test("The Hedge shears are found only in The Grounds: no drop elsewhere ever picks them, a placed one elsewhere is swapped, and one shot kills a topiary beast or a rootling outright", () => { + assert.equal(ghoul.POWERS.shears.stage, "grounds"); + assert.equal(ghoul.POWERS.shears.ms, 10000); + assert.ok(ghoul.TIMED.includes("shears"), "a timed power-up, shown in the pill"); + assert.equal(PILL_WORDS.shears, "SHEARS"); + const home = groundsRound("maze"); + assert.equal(ghoul.powerHere(home, "shears"), true); + assert.ok(home.loot.includes("shears"), "placed ones stay"); + const picked = new Set(); + const random = ghoul.seeded(9); + for (let k = 0; k < 400; k++) picked.add(pickPower(random, home)); + assert.ok(picked.has("shears"), "drops here can be shears"); + // Elsewhere: the hall and the Graveyard never. + const hall = ghoul.newRound(3); + hall.dice = 0; + assert.equal(ghoul.powerHere(hall, "shears"), false); + const away = groundsRound("maze"); + away.stage = "graveyard"; + assert.equal(ghoul.powerHere(away, "shears"), false); + for (let k = 0; k < 400; k++) { + assert.notEqual(pickPower(random, away), "shears"); + assert.notEqual(pickPower(random, hall), "shears"); + } + for (const base of ghoul.ROOMS) if (!["maze", "topiary", "gazebo", "yard"].includes(base.id)) assert.ok(!base.items.some((i) => i[0] === "shears"), `${base.id} places none`); + // A placed one swapped when a room is entered elsewhere. + const swapped = ghoul.newRound(11); + swapped.dice = 0; + swapped.stage = "manor"; + assert.equal(ghoul.powerHere(swapped, "shears"), false); + // With the shears on, a shot kills a beast or a root; without, it takes six. + const kills = (kind, shears, over = {}) => { + const round = groundsRound("maze"); + standAt(round, 20); + round.you.safeMs = 1e9; + if (shears) ghoul.applyPower(round, "shears"); + const m = put(round, kind, 60, over); + bolt(round, m, m.y + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, 4, steady); + return { dead: !round.monsters.includes(m), round }; + }; + assert.equal(kills("topiary", false).dead, false); + const t = kills("topiary", true); + assert.equal(t.dead, true); + assert.equal(events(t.round, "snip").length, 1, "a snip"); + assert.equal(kills("rootling", false, { act: "up", wait: 1e9 }).dead, false); + assert.equal(kills("rootling", true, { act: "up", wait: 1e9 }).dead, true); + assert.equal(kills("mulch", true, { act: "crawl" }).dead, false, "only hedge beasts and roots"); + assert.equal(kills("zombie", true).dead, false); + // It runs out after its time. + const timed = groundsRound("maze"); + ghoul.applyPower(timed, "shears"); + ghoul.advance(timed, ghoul.POWERS.shears.ms + 8, steady); + assert.equal(timed.effects.shears, 0); +}); + +/* ----------------------------------------------------- the keeper */ + +// The yard, you in the arena, the Groundskeeper awake and idle. +function keeperFight() { + const round = groundsRound("yard"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + round.you.safeMs = 0; + round.events.length = 0; + return round; +} + +// Straight to the keeper's next move, as if his rest had run out. +const hurry = (b) => (b.wait = 0); + +test("The Groundskeeper's lantern is a weak spot: a bolt into it, while it swings into the open, does triple damage and says so; a bolt anywhere else, or while it is tucked away, does one", () => { + const round = keeperFight(); + const b = round.boss; + assert.equal(b.kind, "keeper"); + assert.equal(b.dir, -1, "he faces you"); + const open = () => Object.assign(b, { act: "rest", wait: gr.KEEPER_OPEN_MS - 100 }); + open(); + let hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + gr.LANTERN_Y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.hp, hp - gr.LANTERN_MULT, "triple"); + const hit = events(round, "bossHit").at(-1); + assert.deepEqual([hit.kind, hit.how, hit.weak], ["keeper", "weak", true]); + assert.equal(events(round, "lanternOpen").length, 1); + // Over the lantern, or below it, or on his back: plain damage. + for (const y of [b.y + 12, b.y + 0.3]) { + open(); + hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.hp, hp - 1, `one at ${y - b.y}`); + assert.equal(events(round, "bossHit").at(-1).weak, false); + } + open(); + hp = b.hp; + round.shots.push({ x: b.x + b.w / 2 + 0.2, y: b.y + gr.LANTERN_Y, vx: -80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.hp, hp - 1, "not from behind"); + // Tucked away (idle), even the lantern's box is only a hit. + Object.assign(b, { act: "idle", wait: 1e9 }); + hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + gr.LANTERN_Y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.hp, hp - 1, "tucked away"); +}); + +test("The Groundskeeper winds up his scythe and sends a low sweep along the floor toward you: stand in it and a life goes, jump it and nothing does; he rests with his lantern open after", () => { + const stand = keeperFight(); + const b = stand.boss; + hurry(b); + run(stand, 8); + assert.equal(b.act, "wind"); + assert.equal(events(stand, "scytheWind").length, 1); + run(stand, gr.SCYTHE_WIND_MS + 8); + assert.equal(events(stand, "scytheSweep").length, 1); + assert.equal(b.act, "rest"); + assert.equal(b.lit, false, "tucked away through the sweep"); + const wave = stand.waves.find((w) => w.kind === "scythe"); + assert.ok(wave && wave.dir === -1, "toward you"); + run(stand, 2000); + assert.equal(events(stand, "lose")[0]?.cause, "scythe"); + // Jumped, it passes. + const hop = keeperFight(); + const k = hop.boss; + hurry(k); + run(hop, gr.SCYTHE_WIND_MS + 16); + let jumped = false; + for (let t = 0; t < 1400; t += 4) { + const w = hop.waves.find((q) => q.kind === "scythe"); + if (w && !jumped && Math.abs(w.x - hop.you.x) < 8) { + ghoul.jump(hop); + jumped = true; + } + ghoul.advance(hop, 4, steady); + } + assert.ok(jumped); + assert.equal(events(hop, "lose").length, 0, "jumped clean over"); + assert.ok(k.lit || k.act === "idle", "his lantern came open late in the rest"); +}); + +test("The Groundskeeper lobs the lantern's fire to where you stand: it lands after a flight and burns a patch about 6 wide for about 3 s, hurting while it burns, then goes", () => { + const round = keeperFight(); + const b = round.boss; + b.attacks = 1; + hurry(b); + run(round, 8); + assert.equal(b.act, "throwWind"); + assert.equal(events(round, "lanternWind").length, 1); + const x = round.you.x; + run(round, gr.LANTERN_WIND_MS + 8); + const throwEvent = events(round, "lanternThrow")[0]; + assert.ok(throwEvent && Math.abs(throwEvent.tx - x) < 0.5, "to where you stood"); + const patch = round.hazards[0]; + assert.equal(patch.kind, "fire"); + assert.equal(patch.w, gr.FIRE_W); + assert.equal(patch.live, 0, "still in the air"); + // Move away: it burns without hurting you. + round.you.safeMs = 0; + standAt(round, x + 14); + run(round, gr.FIRE_FLIGHT_MS + 100); + assert.equal(events(round, "fireLand").length, 1); + assert.ok(patch.live > 0); + assert.equal(events(round, "lose").length, 0); + // Step into it: a life. + standAt(round, x); + run(round, 20); + assert.equal(events(round, "lose")[0]?.cause, "fire"); + // It burns out. + round.you.safeMs = 1e9; + standAt(round, x + 20); + run(round, gr.FIRE_MS); + assert.equal(round.hazards.filter((h) => h.kind === "fire" && h.live > 0).length, 0); + // Stood in from the first, it was only a hurt after landing. + const wait = keeperFight(); + wait.boss.attacks = 1; + hurry(wait.boss); + run(wait, gr.LANTERN_WIND_MS + 40 + gr.FIRE_FLIGHT_MS - 100); + assert.equal(events(wait, "lose").length, 0, "the flight harms nothing"); +}); + +test("The Groundskeeper at half his hp climbs onto a mower: he revs, charges to the far wall (jump onto a shelf or lose a life), stalls there with no attacks, turns, and comes quicker", () => { + const round = keeperFight(); + const b = round.boss; + const calm = gr.SCYTHE_WIND_MS / round.spec.pace; + b.hp = Math.floor(b.max * gr.KEEPER_RAGE); + hurry(b); + run(round, 8); + assert.equal(events(round, "keeperMower").length, 1); + assert.equal(b.mower, true); + assert.equal(b.w, gr.MOWER_W); + assert.equal(b.act, "mount"); + run(round, gr.KEEPER_MOUNT_MS + 16); + assert.equal(b.act, "idle"); + // His next scythe comes quicker. + b.attacks = 0; + hurry(b); + run(round, 8); + assert.equal(b.act, "wind"); + assert.ok(b.wait < calm, "a quicker wind-up"); + // Two moves later, the charge: the rev first. + b.attacks = 2; + Object.assign(b, { act: "idle", wait: 0 }); + round.waves.length = 0; + round.hazards.length = 0; + const side = b.x; + run(round, 8); + assert.equal(b.act, "rev"); + assert.equal(events(round, "mowerRev").length, 1); + const dir = b.dir; + assert.equal(dir, -1, "toward the far wall"); + // You wait on the middle shelf, over the mower's reach. + Object.assign(round.you, { x: 127, y: 22, shelf: 1, state: "run", vy: 0, safeMs: 0 }); + run(round, gr.MOWER_REV_MS + 16); + assert.equal(b.act, "charge"); + assert.equal(events(round, "mowerCharge").length, 1); + let moved = 0; + for (let t = 0; t < 4000 && b.act === "charge"; t += 4) { + ghoul.advance(round, 4, steady); + moved = side - b.x; + } + assert.equal(b.act, "stall"); + assert.equal(events(round, "mowerStall").length, 1); + assert.ok(moved > 50, `across the arena (${moved.toFixed(1)})`); + assert.equal(events(round, "lose").length, 0, "the shelf was clear"); + // The stall: no attacks, then his lantern opens and he turns to you. + assert.equal(b.lit, false); + run(round, gr.MOWER_STALL_MS - gr.KEEPER_OPEN_MS + 40); + assert.equal(b.lit, true, "open late in the stall"); + assert.equal(b.dir, 1, "turned to you"); + assert.equal(round.waves.length + round.hazards.length, 0, "no attacks while stalled"); + run(round, gr.KEEPER_OPEN_MS); + assert.equal(b.act, "idle"); + // On the floor, in front of the charge, it costs a life, named for the mower. + const flat = keeperFight(); + const m = flat.boss; + m.mower = true; + m.w = gr.MOWER_W; + Object.assign(m, { act: "charge", dir: -1 }); + standAt(flat, m.x - 16); + run(flat, 800); + assert.equal(events(flat, "lose")[0]?.cause, "mower"); +}); + +test("The Groundskeeper's touch is his own, the endless-lives code spares a life from every new way to die, and his fall opens the door and ends the fire", () => { + for (const cause of ["scythe", "fire", "mower", "keeper", "topiary", "rootling", "moth", "mulch"]) { + const round = keeperFight(); + round.infinite = true; + const lives = round.lives; + ghoul.lose(round, cause); + assert.equal(round.lives, lives, `${cause} costs none`); + } + const touch = keeperFight(); + touch.boss.act = "idle"; + touch.boss.wait = 1e9; + Object.assign(touch.you, { x: touch.boss.x - 4 }); + run(touch, 20); + assert.equal(events(touch, "lose")[0]?.cause, "keeper"); + const round = keeperFight(); + const b = round.boss; + b.hp = 1; + round.hazards.push({ kind: "fire", x: 150, y: 6, w: 6, h: 3, warn: 0, live: 2000, cause: "fire" }); + Object.assign(b, { act: "rest", wait: gr.KEEPER_OPEN_MS - 100 }); + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + gr.LANTERN_Y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.state, "down"); + assert.equal(round.hasKey, true); + assert.equal(round.hazards.length, 0); +}); + +/* ------------------------------------------- the keeper, made harder */ + +test("The Groundskeeper is tougher and his lantern is open for less time: more hp, and a lit window about a third shorter", () => { + assert.equal(gr.BOSSES.keeper.hp, 95); + assert.equal(keeperFight().boss.max, 95); + assert.ok(gr.KEEPER_OPEN_MS <= 800 * 0.7, `${gr.KEEPER_OPEN_MS} ms`); + const round = keeperFight(); + const b = round.boss; + Object.assign(b, { act: "rest", wait: gr.KEEPER_OPEN_MS + 60 }); + run(round, 20); + assert.equal(b.lit, false, "still tucked away a moment before the window"); + run(round, 100); + assert.equal(b.lit, true); +}); + +test("The Groundskeeper's first swing is a low sweep, and later swings are low or high, a high one wound up with the scythe raised and named", () => { + const first = keeperFight(); + hurry(first.boss); + run(first, 8); + assert.equal(events(first, "scytheWind")[0].high, false, "the first is low"); + run(first, gr.SCYTHE_WIND_MS + 8); + assert.ok(first.waves.some((w) => w.kind === "scythe")); + assert.equal(first.hazards.filter((h) => h.kind === "sweep").length, 0); + // Later, a low one is followed by a high one at the usual odds (steady 0.5 is under SWEEP_HIGH), a high one by a low one (0.5 is over SWEEP_REPEAT). + const round = keeperFight(); + const b = round.boss; + b.swings = 1; + b.high = false; + hurry(b); + run(round, 8); + assert.equal(b.act, "wind"); + assert.equal(b.high, true); + const wind = events(round, "scytheWind")[0]; + assert.equal(wind.high, true, "the wind-up says high"); + run(round, gr.SCYTHE_WIND_MS + 8); + assert.equal(events(round, "scytheSweep")[0].high, true); + assert.equal(round.waves.length, 0, "no wave along the floor"); + assert.equal(round.hazards.filter((h) => h.kind === "sweep").length, 1); + const next = keeperFight(); + Object.assign(next.boss, { swings: 2, high: true }); + hurry(next.boss); + run(next, 8); + assert.equal(next.boss.high, false, "a high one is followed by a low one"); + // Drawn: the sweep, in its wind-up and in flight. + assert.ok(round.hazards[0].dir === -1 && round.hazards[0].live === 0, "the generic hazard hit never fires for it"); +}); + +test("The Groundskeeper's high sweep passes over a body on the ground and hurts one in the air; a low sweep is still jumped", () => { + // Standing on the floor: it passes clean over, then leaves the field. + const stand = keeperFight(); + Object.assign(stand.boss, { swings: 1, high: false }); + hurry(stand.boss); + run(stand, gr.SCYTHE_WIND_MS + 16); + assert.equal(stand.hazards.filter((h) => h.kind === "sweep").length, 1); + run(stand, 3000); + assert.equal(events(stand, "lose").length, 0, "standing on the floor is safe"); + assert.equal(stand.hazards.filter((h) => h.kind === "sweep").length, 0, "gone past the arena"); + // Jumping into it costs a life, named for the scythe. + const hop = keeperFight(); + Object.assign(hop.boss, { swings: 1, high: false }); + hurry(hop.boss); + run(hop, gr.SCYTHE_WIND_MS + 16); + let jumped = false; + for (let t = 0; t < 2400 && !events(hop, "lose").length; t += 4) { + const h = hop.hazards.find((q) => q.kind === "sweep"); + if (h && !jumped && Math.abs(h.x - hop.you.x) < 9) { + ghoul.jump(hop); + jumped = true; + } + ghoul.advance(hop, 4, steady); + } + assert.ok(jumped); + assert.equal(events(hop, "lose")[0]?.cause, "scythe"); + // Endless lives spare the life. + const endless = keeperFight(); + endless.infinite = true; + const lives = endless.lives; + Object.assign(endless.boss, { swings: 1, high: false }); + hurry(endless.boss); + run(endless, gr.SCYTHE_WIND_MS + 16); + let up = false; + for (let t = 0; t < 2400; t += 4) { + const h = endless.hazards.find((q) => q.kind === "sweep"); + if (h && !up && Math.abs(h.x - endless.you.x) < 9) { + ghoul.jump(endless); + up = true; + } + ghoul.advance(endless, 4, steady); + } + assert.ok(up); + assert.equal(endless.lives, lives, "no life lost"); + // A low sweep is still jumped (the Groundskeeper test above), and a body well above the box passes over a high one. + const above = keeperFight(); + Object.assign(above.boss, { swings: 1, high: false }); + hurry(above.boss); + run(above, gr.SCYTHE_WIND_MS + 16); + Object.assign(above.you, { y: 20, vy: 0, state: "air" }); + above.you.safeMs = 0; + const h = above.hazards.find((q) => q.kind === "sweep"); + h.x = above.you.x + 4; + for (let t = 0; t < 400; t += 4) { + above.you.y = 20; + above.you.vy = 0; + ghoul.advance(above, 4, steady); + } + assert.equal(events(above, "lose").length, 0, "a high shelf is clear of it"); +}); + +test("The Groundskeeper's lantern throw on the mower lands a second patch where you are heading, and on foot only the one", () => { + const foot = keeperFight(); + foot.boss.attacks = 1; + hurry(foot.boss); + run(foot, gr.LANTERN_WIND_MS + 40); + assert.equal(foot.hazards.filter((h) => h.kind === "fire").length, 1); + assert.equal(events(foot, "lanternThrow")[0].tx2, undefined); + const mounted = keeperFight(); + const b = mounted.boss; + b.mower = true; + b.w = gr.MOWER_W; + b.attacks = 1; + hurry(b); + standAt(mounted, 150); + mounted.you.vx = -6; + const x = mounted.you.x; + run(mounted, gr.LANTERN_WIND_MS + 40); + const fires = mounted.hazards.filter((h) => h.kind === "fire"); + assert.equal(fires.length, 2); + const ev = events(mounted, "lanternThrow")[0]; + assert.ok(Math.abs(ev.tx - x) < 0.5 && Math.abs(ev.tx2 - (x - gr.FIRE_LEAD)) < 0.5, `on you and ahead of you (${ev.tx.toFixed(1)}, ${ev.tx2.toFixed(1)})`); + assert.ok(Math.abs(fires[0].x - fires[1].x) >= gr.FIRE_W, "two patches, not one"); + // Both land and burn; endless lives spare the life. + mounted.you.safeMs = 1e9; + standAt(mounted, x + 30); + mounted.you.safeMs = 1e9; + run(mounted, gr.FIRE_FLIGHT_MS + 100); + assert.equal(events(mounted, "fireLand").length, 2); + assert.ok(fires.every((f) => f.live > 0)); + // Running the other way, the patch is on that side. + const right = keeperFight(); + Object.assign(right.boss, { mower: true, w: gr.MOWER_W, attacks: 1 }); + hurry(right.boss); + standAt(right, 130); + right.you.vx = 6; + run(right, gr.LANTERN_WIND_MS + 40); + assert.ok(events(right, "lanternThrow")[0].tx2 > right.you.x + 5); +}); + +test("The Groundskeeper's lantern, opening on the mower, calls two or three moths toward it, never more than four alive", () => { + const open = (round) => Object.assign(round.boss, { act: "rest", wait: gr.KEEPER_OPEN_MS + 40 }); + const foot = keeperFight(); + open(foot); + run(foot, 120); + assert.equal(foot.boss.lit, true); + assert.equal(foot.monsters.filter((m) => m.kind === "moth").length, 0, "on foot, no moths"); + const round = keeperFight(); + Object.assign(round.boss, { mower: true, w: gr.MOWER_W }); + open(round); + run(round, 120); + const moths = () => round.monsters.filter((m) => m.kind === "moth" && !m.dead); + assert.equal(moths().length, gr.MOTH_CALL, "two (steady is under one half... one more only when the draw is low)"); + assert.equal(events(round, "mothCall").length, 1); + assert.ok(moths().every((m) => m.lure > 0), "called to the lantern"); + // They head for the lantern, not for you, for the first moments. + const b = round.boss; + const lx = () => b.x + b.dir * (b.w / 2 - gr.LANTERN_BACK); + const before = moths().map((m) => Math.abs(m.x - lx())); + round.you.safeMs = 1e9; + run(round, 400); + const after = moths().map((m) => Math.abs(m.x - lx())); + assert.ok(after.every((d, i) => d < before[i] - 1), `closer to the lantern (${before.map((d) => d.toFixed(0))} to ${after.map((d) => d.toFixed(0))})`); + // A lucky draw calls one more. + const lucky = keeperFight(); + Object.assign(lucky.boss, { mower: true, w: gr.MOWER_W }); + open(lucky); + for (let t = 0; t < 120; t += 4) ghoul.advance(lucky, 4, () => 0.1); + assert.equal(lucky.monsters.filter((m) => m.kind === "moth").length, gr.MOTH_CALL + 1); + // The cap: with three already flying, only one more comes; with four, none and no call. + for (const [have, added] of [[3, 1], [4, 0]]) { + const capped = keeperFight(); + Object.assign(capped.boss, { mower: true, w: gr.MOWER_W }); + capped.you.safeMs = 1e9; + for (let i = 0; i < have; i++) put(capped, "moth", 150 + i * 3, { y: 20, flock: true }); + open(capped); + for (let t = 0; t < 120; t += 4) ghoul.advance(capped, 4, () => 0.1); + const alive = capped.monsters.filter((m) => m.kind === "moth" && !m.dead).length; + assert.equal(alive, have + added, `${have} flying, ${alive} after`); + assert.equal(events(capped, "mothCall").length, added ? 1 : 0); + assert.ok(alive <= gr.MOTH_CAP); + } +}); + +test("The Groundskeeper's mower charges come a bit more often: the move before the third is sometimes a charge, never two in a row from it", () => { + const mounted = (random) => { + const round = keeperFight(); + Object.assign(round.boss, { mower: true, w: gr.MOWER_W, attacks: 1 }); + hurry(round.boss); + for (let t = 0; t < 12; t += 4) ghoul.advance(round, 4, random); + return round; + }; + assert.equal(mounted(steady).boss.act, "throwWind", "the usual draw: still the lantern"); + const early = mounted(() => 0.1); + assert.equal(early.boss.act, "rev", "a low draw: an early charge"); + assert.equal(events(early, "mowerRev").length, 1); + // The very next move is not another charge. + Object.assign(early.boss, { act: "idle", wait: 0 }); + for (let t = 0; t < 12; t += 4) ghoul.advance(early, 4, () => 0.1); + assert.notEqual(early.boss.act, "rev"); + assert.equal(early.boss.attacks, 3); + // On foot, never. + const foot = keeperFight(); + foot.boss.attacks = 1; + hurry(foot.boss); + for (let t = 0; t < 12; t += 4) ghoul.advance(foot, 4, () => 0.1); + assert.notEqual(foot.boss.act, "rev"); +}); + +test("Ghoul Rush's Grounds: the high sweep and the moth call have their reactions, the two fire patches share one sound, and the sweep draws", () => { + const names = Object.values(VOICES).flatMap((v) => Object.values(v)); + const heard = (e, fx = { clock: 1e6 }, extra = {}) => { + const played = []; + const noop = () => {}; + const floats = []; + const kit = { tone: (name) => played.push(name), burst: noop, float: (x, y, text) => floats.push(text), ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react(e, kit); + return { played, floats }; + }; + const at = { x: 10, y: 6, tx: 20, ty: 6 }; + const wind = heard({ ...at, type: "scytheWind", kind: "keeper", high: true }); + assert.deepEqual(wind.floats, ["Stay low!"]); + assert.deepEqual(wind.played.filter((n) => names.includes(n)), [VOICES.keeper.scytheWind], "one sound"); + assert.deepEqual(heard({ ...at, type: "scytheWind", kind: "keeper", high: false }).floats, []); + const sweep = heard({ ...at, type: "scytheSweep", kind: "keeper", high: true }); + assert.deepEqual(sweep.played.filter((n) => names.includes(n)), [VOICES.keeper.scytheSweep], "one sound"); + const call = heard({ ...at, type: "mothCall", kind: "keeper", n: 2 }); + assert.deepEqual(call.floats, ["Moths!"]); + assert.equal(call.played.filter((n) => names.includes(n)).length, 0, "the moths' own spawn sounds speak"); + // Two patches landing together: one fire sound. + const fx = { clock: 1e6 }; + const first = heard({ ...at, type: "fireLand" }, fx).played.filter((n) => names.includes(n)); + const second = heard({ ...at, type: "fireLand", x: 30 }, fx).played.filter((n) => names.includes(n)); + assert.equal(first.length + second.length, 1, "one sound for two patches"); + assert.equal(heard({ ...at, type: "lanternThrow", kind: "keeper", tx2: 31, ty2: 6 }).played.filter((n) => names.includes(n)).length, 1); + // A scythe is still the cause, with its words and sound. + assert.ok(LOSE_WORDS.scythe && LOSE_SOUNDS.scythe); +}); + +/* ------------------------------------------------------ voices etc. */ + +test("Ghoul Rush's Grounds: every new kind has a voice for every act and every new event plays exactly one; endless lives skip every new loss, and his fall puts out the fire", () => { + const own = { topiary: ["appear", "rustle", "freeze", "hurt", "die"], rootling: ["appear", "warn", "up", "hurt", "die"], moth: ["appear", "hurt", "die"], mulch: ["appear", "leaves", "hurt", "die"], keeper: ["wake", "scytheWind", "scytheSweep", "lanternWind", "lanternThrow", "fire", "lanternOpen", "mower", "rev", "charge", "stall", "hurt", "weak", "die"], shears: ["snip"] }; + for (const [kind, acts] of Object.entries(own)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const heard = (e) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6 }; + react(e, kit); + return played; + }; + const at = { x: 10, y: 6, tx: 20, ty: 6 }; + const cases = [ + [{ type: "rustle", kind: "topiary" }, "topiary", "rustle"], + [{ type: "rootWarn", kind: "rootling" }, "rootling", "warn"], + [{ type: "rootUp", kind: "rootling" }, "rootling", "up"], + [{ type: "leaves", kind: "mulch" }, "mulch", "leaves"], + [{ type: "scytheWind", kind: "keeper" }, "keeper", "scytheWind"], + [{ type: "lanternWind", kind: "keeper" }, "keeper", "lanternWind"], + [{ type: "scytheSweep", kind: "keeper" }, "keeper", "scytheSweep"], + [{ type: "lanternThrow", kind: "keeper" }, "keeper", "lanternThrow"], + [{ type: "keeperMower", kind: "keeper" }, "keeper", "mower"], + [{ type: "mowerRev", kind: "keeper" }, "keeper", "rev"], + [{ type: "mowerCharge", kind: "keeper" }, "keeper", "charge"], + [{ type: "mowerStall", kind: "keeper" }, "keeper", "stall"], + [{ type: "bossWake", kind: "keeper" }, "keeper", "wake"], + [{ type: "bossHit", kind: "keeper", how: "shot" }, "keeper", "hurt"], + [{ type: "bossHit", kind: "keeper", how: "weak", weak: true }, "keeper", "weak"], + [{ type: "fireLand" }, "keeper", "fire"], + [{ type: "lanternOpen", kind: "keeper" }, "keeper", "lanternOpen"], + [{ type: "freeze", kind: "topiary" }, "topiary", "freeze"], + [{ type: "snip", kind: "topiary" }, "shears", "snip"], + [{ type: "snip", kind: "rootling" }, "shears", "snip"], + [{ type: "bossDown", kind: "keeper", points: 1 }, "keeper", "die"], + [{ type: "hit", kind: "topiary" }, "topiary", "hurt"], + [{ type: "kill", kind: "moth", mult: 1, how: "shot", points: 1 }, "moth", "die"], + [{ type: "spawn", kind: "moth" }, "moth", "appear"], + ]; + for (const [e, kind, act] of cases) assert.ok(heard({ ...at, ...e }).includes(VOICES[kind][act]), `${e.type}: ${kind} ${act}`); + // Each picked sound plays once, and the weak spot's and the shears' replace the sounds beside them. + const keeperHit = (e) => heard({ ...at, type: "bossHit", kind: "keeper", ...e }); + assert.equal(keeperHit({ how: "weak", weak: true }).includes(VOICES.keeper.hurt), false, "weak replaces hurt"); + assert.equal(keeperHit({ how: "shot" }).includes(VOICES.keeper.weak), false, "a plain shot is not weak"); + for (const e of cases.map((c) => c[0])) { + const names = Object.values(VOICES).flatMap((v) => Object.values(v)); + const picked = heard({ ...at, ...e }).filter((n) => names.includes(n)); + assert.equal(picked.length, 1, `${e.type} plays exactly one picked sound`); + } + const shearsKill = heard({ ...at, type: "kill", kind: "topiary", mult: 1, how: "shears", points: 1 }); + assert.equal(shearsKill.includes(VOICES.topiary.die), false, "a shears kill is not also a dying cry"); + // Every picked tone exists in the merged tones, and the stage keeps them in its own file. + const merged = ghoulSfx.default.tones; + for (const kind of Object.keys(own)) { + for (const [act, name] of Object.entries(VOICES[kind])) { + assert.ok(merged[name]?.layers?.length, `${kind}.${act}: ${name} is in the merged tones`); + assert.ok(sfxGrounds.GROUNDS_SFX.tones[name], `${name} lives in ghoul-sfx-grounds.js`); + assert.equal(name, `ghoul${kind === "keeper" ? "Keeper" : kind[0].toUpperCase() + kind.slice(1)}${act[0].toUpperCase()}${act.slice(1)}`, "named by kind and act"); + } + } + for (const cause of ["scythe", "fire", "mower", "keeper", "topiary", "rootling", "moth", "mulch"]) { + const round = keeperFight(); + round.infinite = true; + const lives = round.lives; + ghoul.lose(round, cause); + assert.equal(round.lives, lives, `${cause} costs none`); + } + const touch = keeperFight(); + touch.boss.act = "idle"; + touch.boss.wait = 1e9; + Object.assign(touch.you, { x: touch.boss.x - 4 }); + run(touch, 20); + assert.equal(events(touch, "lose")[0]?.cause, "keeper"); + const round = keeperFight(); + const b = round.boss; + b.hp = 1; + round.hazards.push({ kind: "fire", x: 150, y: 6, w: 6, h: 3, warn: 0, live: 2000, cause: "fire" }); + Object.assign(b, { act: "rest", wait: gr.KEEPER_OPEN_MS - 100 }); + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + gr.LANTERN_Y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.state, "down"); + assert.equal(round.hasKey, true); + assert.equal(round.hazards.length, 0); +}); + +/* ------------------------------------------------------ voices etc. */ + +test("Ghoul Rush's Grounds: every new way to die has its words and its own sound", () => { + const heard = (e) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6 }; + react(e, kit); + return played; + }; + for (const cause of ["scythe", "fire", "mower", "keeper", "topiary", "rootling", "moth", "mulch"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ x: 10, y: 6, type: "lose", cause, lives: 2 }).includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Grounds draws: every room, every monster in every act, the Groundskeeper in each move on foot and mounted, the scythe's sweep and the lantern's fire, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["grounds"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { topiary: ["still", "creep"], rootling: ["trail", "warn", "up", "sink"], mulch: ["pile", "burst", "crawl"], moth: [""] }; + for (const id of ["maze", "topiary", "gazebo", "yard"]) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + standAt(r, id === "yard" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + for (const [kind, list] of Object.entries(acts)) { + list.forEach((act, i) => put(r, kind, r.you.x + 6 + i * 5, { act, wait: 300, y: kind === "moth" ? 12 : undefined })); + } + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const mower of [false, true]) { + Object.assign(r.boss, { mower, w: mower ? gr.MOWER_W : gr.BOSSES.keeper.w }); + for (const act of ["idle", "wind", "rest", "throwWind", "rev", "charge", "stall", "mount"]) { + Object.assign(r.boss, { act, wait: 400, dir: -1, lit: act === "rest" }); + g.tick(16); + } + } + r.hazards.push({ kind: "fire", x: r.you.x + 10, y: 6, w: 6, h: 3, warn: 400, live: 0, cause: "fire", sx: r.boss.x, sy: 9 }, { kind: "fire", x: r.you.x + 20, y: 6, w: 6, h: 3, warn: 0, live: 1500, cause: "fire" }); + r.waves.push({ x: r.you.x + 8, y: 6, dir: -1, life: 6000, kind: "scythe", cause: "scythe" }); + } + for (let k = 0; k < 20; k++) g.tick(16); + r.you.safeMs = 1e9; + } + } + assert.ok(r.spec.id === "yard", "got to the yard and drew it"); +}); diff --git a/scripts/test-web-console-activities-ghoul-mine.mjs b/scripts/test-web-console-activities-ghoul-mine.mjs new file mode 100644 index 0000000..766c10b --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-mine.mjs @@ -0,0 +1,1569 @@ +// Web console tests, Ghoul Rush's Deep Seam Mine stage: its four rooms (always dark, the cage lifts, the water, the rockfall), rocks that fall after a dust warning and crush monsters and cost a life, the knocker imp that steals your light but never a life, the canary ghost whose scream brings three rocks down, the dead miner that digs out of the wall, the blind crawler that hunts by sound, the cage you can ride, the Hard Hat and Dynamite (found only here), and the Tommyknocker, who knocks, sweeps his hammer, puts the lights out, sinks into the seam and bursts out dazed, and rages at half his hp. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as mn from "../src/web-console/public/activities/ghoul-mine.js"; +import * as arm from "../src/web-console/public/activities/ghoul-arms.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-mine-draw.js"; +import { PILL_WORDS, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import { BONES } from "../src/web-console/public/activities/ghoul-bones.js"; +import { GRAVEYARD } from "../src/web-console/public/activities/ghoul-graveyard.js"; +import { GROUNDS } from "../src/web-console/public/activities/ghoul-grounds.js"; +import { CHAPEL } from "../src/web-console/public/activities/ghoul-chapel.js"; +import { SANATORIUM } from "../src/web-console/public/activities/ghoul-sanatorium.js"; +import { VILLAGE } from "../src/web-console/public/activities/ghoul-village.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the mine drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); +// Fire tapped twice, as the keys do it. +const tapTap = (round) => { + ghoul.pressFire(round); + ghoul.releaseFire(round); + ghoul.pressFire(round); + ghoul.releaseFire(round); +}; +// Sticks in the bag. +const sticks = (round, n) => { + round.arms = [{ kind: "dyn", n }]; +}; +// The four rooms walked, and the stage's five (the Runaway Cart, a ride, has its own suite). +const ROOM_IDS = ["shaft", "tunnels", "collapse", "seam"]; +const STAGE_ROOMS = ["shaft", "tunnels", "collapse", "cart", "seam"]; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// The twist as a room that has just begun would hold it, with no rock due for +// ages (set `next` for one that is). +const calm = () => ({ next: 1e12, quiet: 0, noise: false, reach: 0, wade: 0 }); + +// A round in the Mine's room `id`, reached the way play reaches it, nothing +// woken: every spawner spent, the horde held back, no rock due (pass `rocks` +// to leave the room's own clock running). +function mineRound(id, { rocks = false } = {}) { + const round = ghoul.newRound(5); + round.lives = 3; + round.dice = 0; + through(round); + round.offer = ["mine"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.bonus = 1e9; + round.twist = rocks ? { ...calm(), next: round.spec.rocks * mn.ROCK_FIRST } : calm(); + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +function until(round, done, ms = 4000, random = steady) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); +} + +// Runs `ms`, returning each event of `type` as [ms since the start, event]. +function log(round, ms, type, random = steady) { + const got = []; + round.events.length = 0; + const t0 = round.clock; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + for (const e of round.events) if (e.type === type) got.push([round.clock - t0, e]); + round.events.length = 0; + } + return got; +} + +// Runs until an event of `type` is on the field (leaving it there, and the round +// as it stood that slice) or `ms` pass; the event, or null. +function upTo(round, type, ms = 4000, random = steady) { + round.events.length = 0; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + const e = round.events.find((x) => x.type === type); + if (e) return e; + } + return null; +} + +// A bolt arriving from the left at height `y` on the thing `m` (a monster or the boss). +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +// A rock hazard as the pack makes one. +const rockAt = (x, over = {}) => ({ kind: "rock", state: "warn", x, y: 44, w: mn.ROCK_W, h: mn.ROCK_H, vy: 0, warn: mn.ROCK_WARN_MS, total: mn.ROCK_WARN_MS, floor: 6, live: 0, cause: "rock", ...over }); + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played }; +}; + +test("Ghoul Rush's Deep Seam Mine is a stage of three rooms and the Seam, always dark, its monsters and boss joined to the game's, with a place for each kind, cage lifts, water and rockfall", () => { + const st = ghoul.stageById("mine"); + assert.deepEqual(st.rooms, STAGE_ROOMS); + assert.deepEqual(mn.MINE_ROOMS, STAGE_ROOMS); + assert.equal(st.boss, "tommy"); + assert.equal(st.title, "The Deep Seam Mine"); + assert.equal(st.sub, "They are still knocking"); + assert.equal(ghoul.STAGES.at(-3), st, "the last stage in the list but the Carnival and the Frozen Lake"); + for (const kind of Object.keys(mn.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], mn.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.tommy, mn.BOSSES.tommy); + assert.equal(mn.BOSSES.tommy.sub, "Follow the knocking, not the light"); + assert.equal(ghoul.BOSSES.tommy.hp, 120); + assert.ok(ghoul.MONSTERS.imp.hp === 2 && ghoul.MONSTERS.canary.hp === 1 && ghoul.MONSTERS.miner.hp === 4 && ghoul.MONSTERS.blind.hp === 3); + assert.ok(ghoul.ZOMBIES.has("miner"), "a dead miner is a zombie variant"); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [shaft, tunnels, collapse, seam] = ROOM_IDS.map((id) => ghoul.roomById(id)); + assert.deepEqual([shaft.title, tunnels.title, collapse.title, seam.title], ["Mine Shaft", "Flooded Tunnels", "The Collapse", "The Mother Seam"]); + assert.deepEqual([shaft.sub, tunnels.sub, collapse.sub, seam.sub], ["The cage only goes down", "The pumps stopped in 1891", "They are still knocking", "Follow the knocking, not the light"]); + for (const room of [shaft, tunnels, collapse, seam]) assert.equal(room.dark, true, `${room.id}: always dark`); + const returning = ["zombie", "bat", "crawl"]; + for (const room of [shaft, tunnels, collapse]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + assert.ok(room.items.some((i) => i[0] === "hat") && room.items.some((i) => i[0] === "dyn"), `${room.id}: the Hard Hat and Dynamite`); + assert.ok(room.spawns.some((s) => s[0] in mn.MONSTERS), `${room.id}: some of the new monsters`); + assert.ok(room.spawns.some((s) => returning.includes(s[0])), `${room.id}: some returning ones`); + // The key shelf has a board right under it, so a run at the key climbs it. + assert.ok(room.shelves.some(([a, b, y]) => y === 15 && a <= room.key[0] && b >= room.key[0]), `${room.id}: a step under the key shelf`); + } + assert.ok(seam.items.some((i) => i[0] === "hat") && seam.items.some((i) => i[0] === "dyn"), "the boss room has both too"); + assert.equal(seam.boss, "tommy"); + assert.equal(seam.horde.length, 0); + assert.ok(seam.shelves.some((s) => s[2] === 12) && seam.shelves.some((s) => s[2] === 17.5), "a gallery of boards each side"); + // The shaft's cages, the tunnels' water, the rocks. + const cages = shaft.spawns.filter((s) => s[0] === "cage"); + assert.ok(cages.length >= 2 && cages.length <= 3, "two or three cage lifts"); + for (const [, x, lo, hi] of cages) { + assert.ok(hi > lo + 8, `the cage at ${x} has a track`); + const top = hi + mn.CAGE_H; + assert.ok(shaft.shelves.some(([a, b, y]) => Math.abs(y - top) < 0.05 && x + 4 >= a && x - 4 <= b), `the cage at ${x} meets a landing at ${top}`); + assert.ok(Math.abs(ghoul.groundAt(shaft, x) - lo) < 1, `the cage at ${x} starts at the floor`); + } + assert.equal(shaft.water.length + collapse.water.length + seam.water.length, 0, "water only in the tunnels"); + assert.ok(tunnels.water.length >= 3); + for (const [a, b] of tunnels.water) { + assert.ok(b > a && ghoul.groundAt(tunnels, a) === 6 && ghoul.groundAt(tunnels, b) === 6 && ghoul.groundAt(tunnels, (a + b) / 2) === 6, `the water ${a} to ${b} lies on the flat floor`); + for (let x = a; x <= b; x += 4) assert.equal(ghoul.groundAt(tunnels, x), 6, `no pit or step in the water at ${x}`); + } + assert.ok(shaft.rocks > tunnels.rocks && tunnels.rocks > collapse.rocks && collapse.rocks > 0 && seam.rocks === 0, "more rockfall in order, none in the seam of its own"); + assert.deepEqual([shaft.rocks, tunnels.rocks, collapse.rocks], [30000, 12000, 7000]); + // The new room fields pass through the room builder. + assert.equal(ghoul.roomFor("tunnels").rocks, 12000); + assert.deepEqual(ghoul.roomFor("tunnels").water, tunnels.water); + assert.deepEqual(ghoul.roomFor("hall").water, []); + assert.equal(ghoul.roomFor("hall").rocks, 0); + // Harder in order, and the first room is easy: a gentle horde and few kinds at once. + assert.ok(shaft.spawns.length <= tunnels.spawns.length && tunnels.spawns.length <= collapse.spawns.length); + assert.ok(shaft.hordeMs > tunnels.hordeMs && tunnels.hordeMs > collapse.hordeMs, "the horde quickens"); + assert.equal(shaft.hordeMs, 3200, "about 3200 ms between horde spawns in the first room"); + assert.ok(shaft.horde.length <= 2 && !shaft.horde.includes("miner"), "the first room's horde is gentle"); + assert.ok(!shaft.spawns.some((s) => s[0] === "blind" || s[0] === "canary"), "no blind crawlers or canaries in the first room"); + assert.ok(tunnels.spawns.some((s) => s[0] === "blind") && tunnels.spawns.some((s) => s[0] === "canary") && tunnels.spawns.some((s) => s[0] === "miner")); + assert.ok(collapse.spawns.some((s) => s[0] === "imp") && collapse.spawns.some((s) => s[0] === "canary")); + assert.ok(shaft.spawns.some((s) => s[0] === "imp") && collapse.spawns.some((s) => s[0] === "imp"), "imps in the shaft and the collapse"); + // Canaries fly where a tilted bolt reaches (no higher than 20 over the floor under them). + for (const room of [tunnels, collapse]) for (const [, x, y] of room.spawns.filter((s) => s[0] === "canary")) assert.ok(y - ghoul.groundAt(room, x) <= 9 && y - ghoul.groundAt(room, x) >= 8, `${room.id}: the canary at ${x} flies within a bolt's reach`); + // The stage is a card of its own and a place in the stage select. + assert.ok(LOOKS.shaft.custom && LOOKS.shaft.pack === "mine" && LOOKS.seam.mine); +}); + +test("Ghoul Rush's Mine shares no hazard, monster, boss, act or tick-state name with another stage's pack (the packs' tables are merged by name)", () => { + for (const key of ["monsters", "bosses", "hazards", "move", "boss", "act", "solid", "harmless", "platform", "kill", "weak"]) { + for (const other of [BONES, GRAVEYARD, GROUNDS, CHAPEL, SANATORIUM, VILLAGE]) { + for (const name of Object.keys(mn.MINE[key] || {})) assert.ok(!(other[key] && name in other[key]), `${key}.${name} is also ${other.id}'s`); + } + } + assert.ok(mn.MINE.hazards.hammer && !mn.MINE.hazards.sweep, "the Groundskeeper keeps its sweep"); + assert.equal(typeof GROUNDS.hazards.sweep, "function"); + assert.equal(mn.MINE.fire, undefined, "Dynamite is a secondary weapon now, no hook on the blaster"); +}); + +/* --------------------------------------------------------------- rockfall */ + +test("Ghoul Rush's rockfall: the first rock comes at 0.9 of a period, after 700 ms of dust, and falls to lie as rubble for 4.5 s", () => { + const round = mineRound("tunnels", { rocks: true }); + standAt(round, 60); + round.you.safeMs = 1e9; + const t0 = round.clock; + const warn = upTo(round, "rockWarn", 12000); + assert.ok(warn, "a warning"); + const warnedAt = round.clock - t0; + assert.ok(Math.abs(warnedAt - 10800) < 20, `at 0.9 of 12 s (${warnedAt})`); + assert.ok(Math.abs(warn.x - 60) < 1e-9, "over you when you stand still"); + assert.equal(warn.ms, 700); + assert.equal(warn.y, 6); + const rock = round.hazards.find((h) => h.kind === "rock"); + assert.ok(rock && rock.state === "warn" && rock.live === 0, "dust first, and a rock that waits hurts nothing"); + assert.equal(events(round, "rockFall").length, 0); + const fall = upTo(round, "rockFall", 1000); + assert.ok(fall, "then it falls"); + assert.ok(Math.abs(round.clock - t0 - warnedAt - mn.ROCK_WARN_MS) < 20, `700 ms after the warning (${round.clock - t0 - warnedAt})`); + assert.ok(rock.state === "fall" && rock.live > 0, "falling, it can hurt"); + const fellAt = round.clock; + assert.ok(upTo(round, "rockLand", 1200), "it lands"); + assert.ok(round.clock - fellAt > 450 && round.clock - fellAt < 650, `about half a second down (${round.clock - fellAt})`); + assert.ok(rock.state === "rubble" && rock.live === 0 && rock.h === mn.ROCK_RUBBLE_H, "rubble, harmless"); + assert.equal(rock.y, 6); + // Rubble lies about 4.5 s, then is gone. + const l0 = round.clock; + for (let t = 0; t < 6000 && round.hazards.includes(rock); t += 4) ghoul.advance(round, 4, steady); + assert.ok(!round.hazards.includes(rock), "gone"); + assert.ok(Math.abs(round.clock - l0 - mn.ROCK_RUBBLE_MS) < 40, `lay ${mn.ROCK_RUBBLE_MS} ms (${round.clock - l0})`); +}); + +test("Ghoul Rush's rockfall is aimed 9 ahead of the way you run, never in the first 14 of a room, never twice in one spot, and a deeper stage lets them go sooner", () => { + const run1 = mineRound("collapse", { rocks: true }); + standAt(run1, 80); + run1.you.safeMs = 1e9; + run1.twist.next = 0; + run(run1, 8, { right: true }); + const a = events(run1, "rockWarn"); + assert.equal(a.length, 1); + assert.ok(Math.abs(a[0].x - (run1.you.x + mn.ROCK_LEAD)) < 2, `ahead of a runner (${a[0].x} for ${run1.you.x})`); + const left = mineRound("collapse", { rocks: true }); + standAt(left, 80, -1); + left.you.safeMs = 1e9; + left.twist.next = 0; + run(left, 8, { left: true }); + assert.ok(Math.abs(events(left, "rockWarn")[0].x - (left.you.x - mn.ROCK_LEAD)) < 2, "and behind one who runs left"); + // At a room's start: not yet. + const early = mineRound("collapse", { rocks: true }); + standAt(early, early.spec.start + 2); + early.you.safeMs = 1e9; + early.twist.next = 0; + run(early, 40); + assert.equal(events(early, "rockWarn").length, 0, "none in the first 14"); + assert.ok(early.twist.next > 1000 && early.twist.next < 1600, "it tries again soon"); + // Never twice in one spot. + const dup = mineRound("collapse", { rocks: true }); + standAt(dup, 80); + dup.you.safeMs = 1e9; + dup.hazards.push(rockAt(81)); + dup.twist.next = 0; + run(dup, 40); + assert.equal(dup.hazards.filter((h) => h.kind === "rock").length, 1, "a rock already due over you: no second"); + // Never over a pit: the spot is refused (the next try is a period away). + const pit = mineRound("collapse", { rocks: true }); + standAt(pit, 80); + pit.you.safeMs = 1e9; + pit.twist.next = 0; + run(pit, 8, { right: true }); + assert.equal(pit.hazards.filter((h) => h.kind === "rock").length, 1); + assert.equal(ghoul.groundAt(pit.spec, 234), -Infinity, "(a pit lies at 230 to 238)"); + const over = mineRound("collapse", { rocks: true }); + standAt(over, 226, 1); + over.you.safeMs = 1e9; + over.twist.next = 0; + run(over, 8, { right: true }); + const aimed = over.hazards.filter((h) => h.kind === "rock"); + assert.ok(aimed.every((h) => ghoul.groundAt(over.spec, h.x) > -Infinity), "never over a pit"); + // A deeper stage lets them go sooner (after the first, which keeps its 0.9 of a period). + const deep = ghoul.roomFor("collapse", 6); + assert.ok(deep.every < 0.8); + const sooner = mineRound("collapse", { rocks: true }); + sooner.spec = deep; + sooner.twist = null; + standAt(sooner, 80); + sooner.you.safeMs = 1e9; + const two = log(sooner, 7000 * 0.9 + 7000 * deep.every + 900, "rockWarn"); + assert.equal(two.length, 2); + assert.ok(Math.abs(two[1][0] - two[0][0] - 7000 * deep.every) < 40, `a period apart (${two[1][0] - two[0][0]})`); + assert.ok(Math.abs(two[0][0] - 7000 * 0.9) < 40, `the first at 0.9 of a period (${two[0][0]})`); +}); + +test("Ghoul Rush's rock crushes the monsters under it (flattened, double points) and costs a life if it lands on you (the cause rock); beside it, or jumping clear, you are safe", () => { + const round = mineRound("collapse"); + standAt(round, 40); + round.you.safeMs = 1e9; + const z = put(round, "zombie", 90, { act: "walk" }); + const g = put(round, "imp", 93.5); + round.hazards.push(rockAt(91.5, { state: "fall", y: 16, vy: -40, live: 1 })); + const score0 = round.score; + const kills = log(round, 600, "kill"); + assert.equal(kills.length, 2); + assert.ok(kills.every(([, e]) => e.how === "crush"), "crushed"); + assert.ok(round.score - score0 >= 100 * 2, "double points"); + assert.ok(z.dead && g.dead); + assert.equal(round.monsters.length, 0); + assert.ok(round.hazards.some((h) => h.kind === "rock" && h.state === "rubble")); + // On you. + const hit = mineRound("collapse"); + standAt(hit, 60); + hit.hazards.push(rockAt(60)); + until(hit, () => events(hit, "lose").length > 0, 2500); + assert.equal(events(hit, "lose")[0]?.cause, "rock"); + // Beside it: nothing. + const beside = mineRound("collapse"); + standAt(beside, 66); + beside.hazards.push(rockAt(60)); + run(beside, 2500); + assert.equal(events(beside, "lose").length, 0); + assert.equal(events(beside, "rockLand").length, 1); + // A rock still waiting (dust only) does not hurt you. + const dust = mineRound("collapse"); + standAt(dust, 60); + dust.hazards.push(rockAt(60, { warn: 1e9, total: 1e9 })); + run(dust, 1500); + assert.equal(events(dust, "lose").length, 0, "dust costs nothing"); + // A rock that has landed lies harmless: you can stand in the rubble. + const rub = mineRound("collapse"); + standAt(rub, 60); + rub.hazards.push(rockAt(60, { state: "rubble", live: 0, y: 6, h: mn.ROCK_RUBBLE_H, rub: 3000 })); + run(rub, 1500); + assert.equal(events(rub, "lose").length, 0); + // Only so much rubble at once. + const heap = mineRound("collapse"); + standAt(heap, 20); + heap.you.safeMs = 1e9; + for (let i = 0; i < mn.RUBBLE_CAP + 3; i++) heap.hazards.push(rockAt(60 + i * 10, { vy: -60, y: 8 })); + run(heap, 600); + assert.ok(heap.hazards.filter((h) => h.state === "rubble").length <= mn.RUBBLE_CAP); +}); + +test("Ghoul Rush's Hard Hat is found only in the Mine, is worn till used (shown as a pill, kept from room to room in the Mine, gone out of it), and makes one rock bounce off you into rubble beside you instead of costing a life", () => { + assert.equal(ghoul.POWERS.hat.stage, "mine"); + assert.equal(ghoul.POWERS.hat.ms, undefined, "worn, not timed"); + assert.equal(PILL_WORDS.hat, "HARD HAT"); + assert.ok(!ghoul.TIMED.includes("hat")); + assert.equal(ghoul.powerHere({ dark: true, stage: "manor" }, "hat"), false); + assert.equal(ghoul.powerHere({ dark: false, stage: null }, "hat"), false); + assert.equal(ghoul.powerHere({ dark: false, stage: "village" }, "hat"), false); + assert.equal(ghoul.powerHere({ dark: true, stage: "mine" }, "hat"), true); + const rnd = ghoul.seeded(17); + for (const stage of [null, "manor", "wing", "graveyard", "grounds", "chapel", "sanatorium", "village"]) { + for (let i = 0; i < 400; i++) { + for (const dropping of [false, true]) { + const got = pickPower(rnd, { dark: i % 2 === 0, stage }, "", dropping); + assert.ok(got !== "hat" && got !== "dyn", `${stage}: never picked`); + } + } + } + const seen = new Set(); + for (let i = 0; i < 400; i++) seen.add(pickPower(rnd, { dark: true, stage: "mine" })); + assert.ok(seen.has("hat") && !seen.has("dyn"), "the hat turns up in the Mine; Dynamite comes from the weapons' own drop band"); + for (const room of ghoul.ROOMS) { + for (const kind of ["hat"]) { + const placed = [...room.items, ...room.sky].some((i) => i[0] === kind); + assert.equal(placed, STAGE_ROOMS.includes(room.id), `${room.id}: ${kind} ${placed ? "placed" : "absent"}`); + } + } + // A placed one in a Mine room stays; picked up it is worn, with no timer, and shows as a pill. + const round = mineRound("collapse"); + assert.equal(round.loot[round.spec.items.findIndex((i) => i[0] === "hat")], "hat"); + standAt(round, round.spec.items.find((i) => i[0] === "hat")[1]); + round.items.fill(false); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + assert.equal(round.you.hat, true); + run(round, 20000); + assert.equal(round.you.hat, true, "still worn long after"); + assert.ok(!events(round, "expire").some((e) => e.kind === "hat")); + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + assert.ok(!g.hud.effects.some((e) => e.text === "HARD HAT")); + g.round.you.hat = true; + const pill = g.hud.effects.find((e) => e.text === "HARD HAT"); + assert.equal(pill?.color, ghoul.POWERS.hat.color); + // Kept into the next Mine room; gone in a room out of the Mine. + through(round); + assert.equal(round.you.hat, true, "kept into the next Mine room"); + const out = ghoul.newRound(3); + out.dice = 0; + out.you.hat = true; + ghoul.advance(out, 50, steady); + assert.equal(out.you.hat, false, "never worn out of the Mine"); + // Under it, a rock bounces, and the hat is used up. + const hat = mineRound("collapse"); + standAt(hat, 60); + hat.you.hat = true; + hat.hazards.push(rockAt(60)); + run(hat, 2000); + assert.equal(events(hat, "lose").length, 0); + const bounce = events(hat, "rockBounce"); + assert.equal(bounce.length, 1); + assert.equal(hat.you.hat, false, "used up"); + assert.equal(events(hat, "rockLand").length, 0, "it did not land on you"); + const lying = hat.hazards.find((h) => h.kind === "rock"); + assert.ok(lying && lying.state === "rubble" && Math.abs(lying.x - 60) >= mn.ROCK_W - 0.01, "rubble beside you"); +}); + +/* ------------------------------------------------------------------- imps */ + +test("Ghoul Rush's knocker imp skitters at you and hops after you onto a board; touching it costs no life but steals your light for 5 s, and it runs off with the spark", () => { + const round = mineRound("shaft"); + standAt(round, 40); + const imp = put(round, "imp", 80); + assert.equal(imp.act, "skitter"); + assert.ok(ghoul.MONSTERS.imp.w === 2 && ghoul.MONSTERS.imp.h === 2.4 && ghoul.MONSTERS.imp.speed > ghoul.MONSTERS.zombie.speed * 2); + round.you.safeMs = 1e9; + const x0 = imp.x; + run(round, 500); + assert.ok(x0 - imp.x > 8, `fast (${x0 - imp.x} in 500 ms)`); + // It hops up onto the board you stand on. + const hop = mineRound("shaft"); + standAt(hop, 63, 1, 15, 1); + hop.you.safeMs = 1e9; + const h = put(hop, "imp", 57); + until(hop, () => h.y > 14.9, 1500); + assert.ok(h.y >= 14.9 && h.x > 55, `up on the board (${h.x}, ${h.y})`); + // Touching it: no life, the light dims, it flees. + const steal = mineRound("shaft"); + standAt(steal, 40); + const s = put(steal, "imp", 40.5); + assert.equal(ghoul.solid(s), true); + ghoul.advance(steal, 8, steady); + assert.equal(events(steal, "lose").length, 0, "no life"); + assert.equal(steal.lives, 3); + assert.equal(steal.phase, "play"); + assert.ok(steal.you.dimMs > 4900 && steal.you.dimMs <= mn.IMP_DIM_MS, `5 s of dim (${steal.you.dimMs})`); + assert.equal(steal.you.dimBy, s.id); + assert.equal(s.stole, true); + assert.equal(s.act, "flee"); + const ev = events(steal, "impSteal"); + assert.equal(ev.length, 1); + assert.equal(ev[0].id, s.id); + assert.equal(ev[0].ms, 5000); + const x1 = s.x; + standAt(steal, 40); + run(steal, 400); + assert.ok(Math.abs(s.x - x1) > 5, "off with it"); + assert.ok(s.x > 40 === (x1 > 40), "away from you"); + // The light is back after 5 s, the imp skitters again. + run(steal, 5200); + assert.equal(steal.you.dimMs, 0); + assert.equal(s.stole, false); + assert.equal(s.act, "skitter"); + assert.equal(events(steal, "impDrop").length, 0, "time gives it back quietly"); + // A bolt to the thief ends the dim at once (and says so); an imp that did not steal it changes nothing. + const shot = mineRound("shaft"); + standAt(shot, 40); + const t = put(shot, "imp", 40.5); + ghoul.advance(shot, 8, steady); + assert.ok(shot.you.dimMs > 0); + Object.assign(t, { x: 60, hp: 1, max: 1 }); + bolt(shot, t, t.y + 1); + const other = put(shot, "imp", 120, { hp: 1, max: 1 }); + ghoul.advance(shot, 8, steady); + assert.ok(t.dead, "the thief is shot"); + assert.equal(shot.you.dimMs, 0, "the light is back at once"); + assert.equal(events(shot, "impDrop").length, 1); + assert.ok(!other.dead); + // Another imp's death does not give it back. + const decoy = mineRound("shaft"); + standAt(decoy, 40); + const th = put(decoy, "imp", 40.5); + ghoul.advance(decoy, 8, steady); + const other2 = put(decoy, "imp", 70, { hp: 1, max: 1 }); + bolt(decoy, other2, other2.y + 1); + ghoul.advance(decoy, 8, steady); + assert.ok(other2.dead && !th.dead); + assert.ok(decoy.you.dimMs > 4000, "still dim"); + assert.equal(events(decoy, "impDrop").length, 0); + // Stomped, too. + const stomp = mineRound("shaft"); + standAt(stomp, 40); + const st = put(stomp, "imp", 40.5); + ghoul.advance(stomp, 8, steady); + assert.ok(stomp.you.dimMs > 0); + standAt(stomp, st.x, 1, st.y + st.h + 0.02); + Object.assign(stomp.you, { state: "air", vy: -10 }); + ghoul.advance(stomp, 4, steady); + assert.ok(st.dead || stomp.monsters.every((m) => m !== st), "stomped"); + assert.equal(stomp.you.dimMs, 0, "a stomp gives it back too"); +}); + +test("Ghoul Rush's Hard Hat keeps an imp from stealing your light once (knocked off, the imp thrown back), and a safe moment (just back from a life lost) does too", () => { + const round = mineRound("shaft"); + standAt(round, 40); + round.you.hat = true; + const imp = put(round, "imp", 40.5); + ghoul.advance(round, 16, steady); + assert.equal(round.you.dimMs, 0); + assert.equal(imp.stole, undefined); + assert.equal(events(round, "impSteal").length, 0); + assert.equal(events(round, "hatKnock").length, 1, "the hat is knocked off"); + assert.equal(round.you.hat, false); + assert.ok(Math.abs(imp.x - 40) >= mn.HAT_KNOCK - 0.5, "the imp is thrown back"); + assert.equal(events(round, "lose").length, 0); + const safe = mineRound("shaft"); + standAt(safe, 40); + safe.you.safeMs = 1000; + put(safe, "imp", 40.5); + run(safe, 300); + assert.equal(safe.you.dimMs, 0); + // Without it, the same imp does steal (the control). + const bare = mineRound("shaft"); + standAt(bare, 40); + put(bare, "imp", 40.5); + run(bare, 40); + assert.ok(bare.you.dimMs > 0); +}); + +/* ---------------------------------------------------------------- canary */ + +test("Ghoul Rush's canary ghost flits toward you near the ceiling, never hurts by touch, screams once within 20 of you (three rocks, over you and 6 either side, 900 ms of dust), then flees and rests", () => { + const round = mineRound("tunnels"); + standAt(round, 40); + round.you.safeMs = 1e9; + const c = put(round, "canary", 100, { y: 14.5 }); + assert.equal(c.act, "flit"); + assert.equal(ghoul.MONSTERS.canary.hp, 1); + run(round, 600); + assert.ok(c.x < 100 - 4, "it flits toward you"); + assert.equal(events(round, "canaryScream").length, 0, "far off: no scream"); + Object.assign(c, { x: 58 }); + const cry = log(round, 40, "canaryScream"); + assert.equal(cry.length, 1); + assert.equal(cry[0][1].n, 3); + assert.equal(c.act, "scream"); + const rocks = round.hazards.filter((h) => h.kind === "rock"); + assert.equal(rocks.length, 3); + assert.deepEqual(rocks.map((h) => Math.round(h.x)).sort((a, b) => a - b), [34, 40, 46]); + assert.ok(rocks.every((h) => h.state === "warn" && Math.abs(h.warn - 900) < 60), "900 ms of dust"); + const fell = log(round, 1100, "rockFall"); + assert.equal(fell.length, 3); + assert.ok(fell.every(([ms]) => ms > 800 - 60 && ms < 900 + 60), "all three together, 900 ms on"); + // It flees, then flits again, and cannot scream again for about 4.5 s. + assert.equal(c.act === "flee" || c.act === "flit", true); + Object.assign(c, { x: 56, act: "flit" }); + run(round, 600); + assert.equal(events(round, "canaryScream").length, 0, "resting"); + c.cool = 0; + Object.assign(c, { x: 56 }); + run(round, 60); + assert.ok(events(round, "canaryScream").length >= 1 || c.act === "scream", "after its rest, again"); + // Touching it costs nothing. + const touch = mineRound("tunnels"); + standAt(touch, 40); + put(touch, "canary", 40, { y: 7, cool: 1e9 }); + run(touch, 400); + assert.equal(events(touch, "lose").length, 0); + // A bolt brings it down before it screams. + const shot = mineRound("tunnels"); + standAt(shot, 40); + shot.you.safeMs = 1e9; + const s = put(shot, "canary", 80, { y: 14.5 }); + bolt(shot, s, 15.4); + run(shot, 8); + assert.ok(s.dead || !shot.monsters.includes(s), "one bolt"); + run(shot, 800); + assert.equal(events(shot, "canaryScream").length, 0); + assert.equal(shot.hazards.filter((h) => h.kind === "rock").length, 0); + // Not in view, it keeps quiet. + const away = mineRound("tunnels"); + standAt(away, 40); + const far = put(away, "canary", 140, { y: 14.5 }); + Object.assign(far, { cool: 0 }); + away.camX = 0; + Object.assign(away.you, { x: 40 }); + run(away, 200); + assert.equal(events(away, "canaryScream").length, 0); +}); + +/* ---------------------------------------------------------------- miners */ + +test("Ghoul Rush's dead miner lies buried in the wall (not solid) till you come within 44, digs out over 650 ms in a spray of rubble, then walks at you", () => { + const round = mineRound("shaft"); + standAt(round, 40); + round.you.safeMs = 1e9; + const m = put(round, "miner", 140); + assert.equal(m.act, "buried"); + assert.equal(ghoul.solid(m), false, "buried: not solid"); + bolt(round, m, m.y + 2); + run(round, 120); + assert.equal(m.hp, 4, "a bolt goes through the wall"); + assert.equal(events(round, "minerDig").length, 0, "100 away: nothing"); + standAt(round, 100); + round.you.safeMs = 1e9; + const dig = log(round, 8, "minerDig"); + assert.equal(dig.length, 1); + assert.equal(m.act, "dig"); + assert.equal(ghoul.solid(m), false, "digging: not solid"); + assert.equal(dig[0][1].ms, 650); + const up = log(round, 800, "minerDig"); + assert.equal(up.length, 0, "once"); + assert.equal(m.act, "walk"); + assert.equal(ghoul.solid(m), true); + const x0 = m.x; + standAt(round, 100); + run(round, 600); + assert.ok(x0 - m.x > 3, "walking at you"); + // A lurch of 8 a second, hit by 4 bolts. + assert.equal(ghoul.MONSTERS.miner.speed, 8); + // Further than 44 it stays buried. + const far = mineRound("shaft"); + standAt(far, 40); + const f = put(far, "miner", 120); + run(far, 300); + assert.equal(f.act, "buried"); + // Out of view it stays buried. + const hid = mineRound("shaft"); + standAt(hid, 40); + const h = put(hid, "miner", 50); + hid.camX = 400; + run(hid, 100); + assert.equal(h.act, "buried", "not in view"); +}); + +test("Ghoul Rush's dead miner winds up its pickaxe 400 ms within 5 of you, swings (a hazard 5 long, live 200 ms, the cause pickaxe), rests 900 ms, and touching it hurts too", () => { + const round = mineRound("tunnels"); + standAt(round, 46); + round.you.safeMs = 1e9; + const m = put(round, "miner", 52, { act: "walk" }); + const wind = log(round, 8, "pickWind"); + assert.equal(wind.length, 1); + assert.equal(m.act, "wind"); + const w0 = round.clock; + const swung = upTo(round, "pickSwing", 600); + assert.ok(swung, "a swing"); + assert.ok(Math.abs(round.clock - w0 - mn.PICK_WIND_MS) < 40, `400 ms of wind-up (${round.clock - w0})`); + const pick = round.hazards.find((h) => h.kind === "pick"); + assert.ok(pick && pick.cause === "pickaxe" && pick.w === mn.PICK_REACH && pick.live > 150 && pick.live <= mn.PICK_LIVE_MS); + assert.ok(pick.x < m.x, "in front of it"); + assert.equal(m.act, "rest"); + run(round, 300); + assert.ok(!round.hazards.includes(pick), "gone after 200 ms"); + const r0 = round.clock; + assert.ok(upTo(round, "pickWind", 1500), "after its 900 ms rest, again"); + assert.ok(Math.abs(round.clock - r0 - (mn.PICK_REST_MS - 300)) < 60, `rested 900 ms from the swing (${round.clock - r0})`); + // The swing costs a life in front of it; out of its reach it costs none. + const hit = mineRound("tunnels"); + standAt(hit, 46); + put(hit, "miner", 52, { act: "walk" }); + until(hit, () => events(hit, "lose").length > 0, 1200); + assert.equal(events(hit, "lose")[0]?.cause, "pickaxe"); + const clear = mineRound("tunnels"); + standAt(clear, 46); + put(clear, "miner", 52, { act: "walk" }); + until(clear, () => events(clear, "pickWind").length > 0, 200); + standAt(clear, 30); + run(clear, 900); + assert.equal(events(clear, "lose").length, 0, "stepped back out of reach"); + // Jumping over it. + const over = mineRound("tunnels"); + standAt(over, 46); + put(over, "miner", 52, { act: "walk" }); + assert.ok(upTo(over, "pickWind", 100)); + run(over, 200); + over.input.up = true; + ghoul.jump(over); + assert.ok(upTo(over, "pickSwing", 600), "it swings under you"); + run(over, 700); + assert.equal(events(over, "lose").length, 0, "jumped it"); + // Touching it: the cause miner. + const touch = mineRound("tunnels"); + standAt(touch, 50); + put(touch, "miner", 50.5, { act: "walk" }); + ghoul.advance(touch, 8, steady); + assert.equal(events(touch, "lose")[0]?.cause, "miner"); +}); + +/* ---------------------------------------------------------------- blind */ + +test("Ghoul Rush's blind crawler hunts by sound: fast while you run, jump or shoot, lost after 600 ms of quiet (blindLost), then it wanders slowly until a noise within 44 of it finds you again (blindHear)", () => { + const round = mineRound("shaft"); + standAt(round, 40); + round.you.safeMs = 1e9; + const b = put(round, "blind", 80); + assert.equal(b.act, "lost"); + assert.equal(ghoul.MONSTERS.blind.hp, 3); + // Quiet: it wanders and does not come. + run(round, 1500); + assert.equal(events(round, "blindHear").length, 0); + assert.ok(Math.abs(b.x - 80) < 6.5, "feeling about"); + // You run: it hears you (it is within 44) and comes fast. + round.input.right = true; + const heard1 = log(round, 40, "blindHear"); + round.input.right = false; + assert.equal(heard1.length, 1); + assert.equal(b.act, "hunt"); + // Run on the spot to keep making noise: it closes at the hunt speed. + const hunt = mineRound("shaft"); + standAt(hunt, 40); + hunt.you.safeMs = 1e9; + const c = put(hunt, "blind", 80, { act: "hunt" }); + const start = c.x; + Object.assign(hunt.input, { left: true }); + for (let t = 0; t < 500; t += 4) { + ghoul.advance(hunt, 4, steady); + standAt(hunt, 40, -1); + hunt.input.left = true; + } + hunt.input.left = false; + assert.ok(start - c.x > mn.BLIND_HUNT_V * 0.5 * 0.8, `fast while you run (${start - c.x})`); + // Still for 600 ms: it loses you, once. + const lost = log(hunt, 1200, "blindLost"); + assert.equal(lost.length, 1); + assert.ok(lost[0][0] >= mn.BLIND_LOSE_MS - 40 - 100 && lost[0][0] <= mn.BLIND_LOSE_MS + 60, `after 600 ms of quiet (${lost[0][0]})`); + assert.equal(c.act, "lost"); + const at = c.x; + run(hunt, 1000); + assert.ok(Math.abs(c.x - at) <= mn.BLIND_WANDER_V * 1 + 0.5, `wandering slowly (${Math.abs(c.x - at)})`); + assert.equal(events(hunt, "blindHear").length, 0, "silence: still lost"); + // A shot is a noise. + hunt.input.fire = true; + const again = log(hunt, 60, "blindHear"); + hunt.input.fire = false; + assert.equal(again.length, 1, "heard again"); + assert.equal(c.act, "hunt"); + // A jump is a noise, and so is the landing's air. + const jumper = mineRound("shaft"); + standAt(jumper, 40); + jumper.you.safeMs = 1e9; + const d = put(jumper, "blind", 70, { act: "lost" }); + ghoul.jump(jumper); + ghoul.advance(jumper, 8, steady); + assert.equal(d.act, "hunt", "a jump"); + assert.equal(jumper.twist.noise, true); + // Standing still, no noise. + const still = mineRound("shaft"); + standAt(still, 40); + still.you.safeMs = 1e9; + const e = put(still, "blind", 70, { act: "lost" }); + run(still, 800); + assert.equal(still.twist.noise, false); + assert.ok(still.twist.quiet >= 600); + assert.equal(e.act, "lost"); + // Too far to hear a dry run (44), near enough to hear a wading one (70). + const dry = mineRound("shaft"); + standAt(dry, 30); + dry.you.safeMs = 1e9; + const far = put(dry, "blind", 86, { act: "lost" }); + run(dry, 200, { right: true }); + assert.equal(far.act, "lost", "56 away on dry floor: not heard"); + assert.equal(dry.twist.reach, mn.HEAR_DRY); + const wet = mineRound("tunnels"); + standAt(wet, 20); + wet.you.safeMs = 1e9; + const far2 = put(wet, "blind", 76, { act: "lost" }); + Object.assign(wet.input, { right: true }); + for (let t = 0; t < 100; t += 4) { + ghoul.advance(wet, 4, steady); + standAt(wet, 20); + wet.input.right = true; + } + wet.input.right = false; + assert.equal(far2.act, "hunt", "56 away through the water: heard"); + assert.equal(wet.twist.reach, mn.HEAR_WET); + // It hurts by touch. + const bite = mineRound("shaft"); + standAt(bite, 40); + put(bite, "blind", 40.5); + ghoul.advance(bite, 8, steady); + assert.equal(events(bite, "lose")[0]?.cause, "blind"); +}); + +/* ----------------------------------------------------------------- water */ + +test("Ghoul Rush's knee-deep water slows you to 0.65 of your speed and lowers a jump a little, only on the floor in a span, and each step splashes", () => { + const wet = mineRound("tunnels"); + standAt(wet, 20); + wet.you.safeMs = 1e9; + const x0 = wet.you.x; + run(wet, 1000, { right: true }); + const d = wet.you.x - x0; + assert.ok(Math.abs(d - ghoul.RUN_SPEED * ghoul.WATER_SPEED) < 1, `0.65 of 36 (${d})`); + assert.equal(ghoul.WATER_SPEED, 0.65); + assert.equal(wet.you.wet, true); + const dry = mineRound("tunnels"); + standAt(dry, 120); + dry.you.safeMs = 1e9; + const y0 = dry.you.x; + run(dry, 500, { right: true }); + assert.ok(Math.abs(dry.you.x - y0 - 18) < 1, "full speed on dry floor"); + assert.equal(dry.you.wet, false); + // The jump: a little lower in it. + const jw = mineRound("tunnels"); + standAt(jw, 40); + jw.you.safeMs = 1e9; + ghoul.advance(jw, 4, steady); + ghoul.jump(jw); + assert.ok(Math.abs(jw.you.vy - ghoul.JUMP_V * ghoul.WATER_JUMP) < 1e-9); + assert.ok(ghoul.WATER_JUMP < 1 && ghoul.WATER_JUMP > 0.85, "a little"); + const jd = mineRound("tunnels"); + standAt(jd, 120); + ghoul.advance(jd, 4, steady); + ghoul.jump(jd); + assert.equal(jd.you.vy, ghoul.JUMP_V); + // On a board over the water, or in the air, you are not wet. + const board = mineRound("tunnels"); + standAt(board, 60, 1, 15, 1); + ghoul.advance(board, 4, steady); + assert.equal(board.you.wet, false); + const air = mineRound("tunnels"); + standAt(air, 60); + ghoul.jump(air); + ghoul.advance(air, 20, steady); + assert.equal(air.you.wet, false, "in the air"); + // Splashes while you wade, about every 320 ms; none standing still or dry. + const splash = mineRound("tunnels"); + standAt(splash, 20); + splash.you.safeMs = 1e9; + Object.assign(splash.input, { right: true }); + const w = log(splash, 1700, "wade"); + splash.input.right = false; + assert.ok(w.length >= 4 && w.length <= 6, `about every 320 ms (${w.length})`); + const gaps = w.slice(1).map((s, i) => s[0] - w[i][0]); + assert.ok(gaps.every((g) => Math.abs(g - mn.WADE_MS) < 20), `320 ms apart (${gaps})`); + assert.equal(log(splash, 800, "wade").length, 0, "standing still in water: quiet"); + const dryWalk = mineRound("tunnels"); + standAt(dryWalk, 120); + assert.equal(log(dryWalk, 800, "wade").length, 0); + run(dryWalk, 600, { right: true }); + assert.equal(events(dryWalk, "wade").length, 0, "dry: no splash"); + // Rooms without water never slow you. + const none = mineRound("shaft"); + standAt(none, 20); + none.you.safeMs = 1e9; + run(none, 500, { right: true }); + assert.ok(Math.abs(none.you.x - 20 - 18) < 1); + // The finishing routes still hold in the water: a jump from the water reaches the step under the key shelf. + const jump = mineRound("tunnels"); + standAt(jump, 312); + jump.you.safeMs = 1e9; + ghoul.advance(jump, 4, steady); + jump.input.up = true; + jump.input.jump = ghoul.JUMP_BUFFER_MS; + until(jump, () => jump.you.state === "run" && jump.you.y > 14, 1200); + assert.ok(jump.you.y >= 15 - 1e-9 && jump.you.shelf >= 0, `up on the 15 board from the water (${jump.you.y})`); +}); + +/* ----------------------------------------------------------------- cages */ + +test("Ghoul Rush's cage lift rides its track at 7 a second, rests 1.5 s at each end, carries Planny standing on it, and is no monster: not hit by bolts, never hurts, never dies", () => { + const round = mineRound("shaft"); + const cg = put(round, "cage", 210, { y: 6.2, lo: 6.2, hi: 17.8, v: 7, rest: 0 }); + assert.equal(cg.act, "ride"); + assert.equal(ghoul.solid(cg), false); + standAt(round, 210, 1, 7.4); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + assert.ok(Math.abs(round.you.y - 7.4) < 0.1, "standing on its board"); + run(round, 1000); + assert.ok(Math.abs(cg.y - (6.2 + 7)) < 0.15, `up 7 in a second (${cg.y})`); + assert.ok(Math.abs(round.you.y - (cg.y + 1.2)) < 0.15, `carried (${round.you.y} on ${cg.y})`); + assert.equal(round.you.state, "run"); + // At the top it rests 1.5 s, then comes back down with him. + until(round, () => cg.rest > 0, 1700); + const topAt = round.clock; + assert.equal(cg.y, 17.8); + run(round, 1400); + assert.equal(cg.y, 17.8, "resting"); + assert.ok(Math.abs(round.you.y - 19) < 0.01); + until(round, () => cg.y < 17.7, 400); + assert.ok(round.clock - topAt >= 1450 && round.clock - topAt <= 1600, `1.5 s at the top (${round.clock - topAt})`); + run(round, 800); + assert.ok(cg.y < 14, "back down"); + assert.ok(Math.abs(round.you.y - (cg.y + 1.2)) < 0.15, "carried down"); + // At the bottom it rests, too, and rises again. + until(round, () => cg.y <= 6.2, 2500); + assert.equal(cg.y, 6.2); + assert.equal(cg.v, mn.CAGE_V); + // A bolt passes through it, a stomp does not bounce you, and nothing hurts. + const solo = mineRound("shaft"); + const c2 = put(solo, "cage", 230, { y: 6.2, lo: 6.2, hi: 17.8, v: 7, rest: 1e9 }); + standAt(solo, 210); + solo.you.safeMs = 1e9; + solo.shots.push({ x: 216, y: 7.2, vx: 80, vy: 0, gone: 0 }); + run(solo, 300); + assert.equal(c2.hp, 9999, "a bolt does not touch it"); + assert.ok(solo.shots.length === 0 || solo.shots[0].x > 234, "and goes through"); + assert.equal(ghoul.MONSTERS.cage.hp, 9999); + assert.equal(ghoul.hurt(solo, c2, 5, "shot", steady) === false, true, "hurt cannot kill it"); + assert.ok(c2.hp > 9000); + // Beside it, in it, even under it: no life lost. + const bump = mineRound("shaft"); + put(bump, "cage", 230, { y: 6.2, lo: 6.2, hi: 17.8, v: 0, rest: 1e9 }); + standAt(bump, 230, 1, 6); + Object.assign(bump.you, { y: 6, state: "run" }); + run(bump, 600); + assert.equal(events(bump, "lose").length, 0); + // Walking off its high end onto the landing. + const off = mineRound("shaft"); + put(off, "cage", 100, { y: 17.8, lo: 6.2, hi: 17.8, v: -7, rest: 1000 }); + standAt(off, 100, -1, 19); + off.you.safeMs = 1e9; + run(off, 100, { left: true }); + run(off, 400, { left: true }); + assert.ok(off.you.x < 96, "walked off the cage's end"); + assert.ok(Math.abs(off.you.y - 19) < 0.01 && off.you.shelf >= 0, `onto the landing at 19 (${off.you.y})`); + // The track starts from its row when only the row says so. + const track = mineRound("shaft"); + const row = track.spec.spawns.find((s) => s[0] === "cage"); + const fromRow = ghoul.spawnMonster(track, "cage", row[1], row[2], { rise: 0 }); + standAt(track, 20); + run(track, 40); + assert.equal(fromRow.lo, row[2]); + assert.equal(fromRow.hi, row[3]); +}); + +/* ------------------------------------------------------------- dynamite */ + +test("Ghoul Rush's Dynamite is the Mine's own secondary weapon: every Mine room has it, a pickup there gives 3 sticks (2 elsewhere, never over 6), and a double tap throws one with no bolt spent", () => { + assert.equal(ghoul.POWERS.dyn.arm, true); + assert.equal(ghoul.POWERS.dyn.ms, undefined, "sticks, not a timer"); + assert.ok(!ghoul.TIMED.includes("dyn")); + assert.equal(ghoul.powerHere({ dark: false, stage: "village" }, "dyn"), true, "common, anywhere"); + const round = mineRound("collapse"); + assert.deepEqual(round.arms, []); + ghoul.applyPower(round, "dyn"); + assert.deepEqual(round.arms, [{ kind: "dyn", n: 3 }]); + ghoul.applyPower(round, "dyn"); + ghoul.applyPower(round, "dyn"); + assert.equal(round.arms[0].n, ghoul.POWERS.dyn.max, "no more than 6"); + sticks(round, 3); + // Held fire throws nothing: only the double tap does. + standAt(round, 40); + round.you.safeMs = 1e9; + run(round, 300, { fire: true }); + assert.equal(round.hazards.filter((h) => h.kind === "stick").length, 0); + assert.ok(round.stats.shots > 0); + run(round, 400); + const shots = round.stats.shots; + round.events.length = 0; + tapTap(round); + assert.equal(round.hazards.filter((h) => h.kind === "stick").length, 1); + assert.equal(round.arms[0].n, 2); + assert.equal(events(round, "dynThrow").length, 1); + assert.equal(round.stats.shots, shots, "a throw is no bolt"); + const stick = round.hazards.find((h) => h.kind === "stick"); + assert.ok(stick.vx === arm.DYN_VX && stick.vy === arm.DYN_VY && stick.fuse === arm.DYN_FUSE_MS); + // Facing left, it flies left. + const left = mineRound("collapse"); + standAt(left, 80, -1); + sticks(left, 1); + left.you.safeMs = 1e9; + tapTap(left); + assert.ok(left.hazards.find((h) => h.kind === "stick").vx < 0); + assert.deepEqual(left.arms, [], "the last one gone"); + // What you hold comes with you into the next room. + sticks(left, 2); + through(left); + assert.deepEqual(left.arms, [{ kind: "dyn", n: 2 }], "a new room, the same sticks"); +}); + +test("Ghoul Rush's thrown stick flies in an arc, lands on the ground or a board, and 1 s after the throw blows up: every solid monster within 11 across dies (no drops), the boss takes 8, you take nothing", () => { + const round = mineRound("collapse"); + standAt(round, 40); + round.you.safeMs = 1e9; + sticks(round, 1); + const t0 = round.clock; + tapTap(round); + run(round, 8); + const stick = round.hazards.find((h) => h.kind === "stick"); + assert.ok(stick); + until(round, () => stick.rest, 1000); + assert.ok(stick.rest && stick.y === 6, "landed on the floor"); + assert.ok(stick.x > 55 && stick.x < 70, `about 24 ahead (${stick.x})`); + const sx = stick.x; + // Monsters: one in the blast, one just out of it, one behind you, one buried in the wall. + const inside = put(round, "zombie", sx + 8, { act: "walk" }); + const edge = put(round, "zombie", sx + 25); + const grave = put(round, "miner", sx - 4); + const lost = put(round, "imp", 10); + const score0 = round.score; + const rolls = []; + const blasts = []; + until(round, () => { + if (events(round, "dynBlast").length) blasts.push(round.clock - t0); + return round.hazards.some((h) => h.kind === "blast"); + }, 1200, () => (rolls.push(1), 0.5)); + assert.ok(round.hazards.some((h) => h.kind === "blast"), "it blew"); + assert.ok(Math.abs(round.clock - t0 - arm.DYN_FUSE_MS) < 60, `1 s after the throw (${round.clock - t0})`); + assert.ok(inside.dead || !round.monsters.includes(inside), "caught in the blast"); + assert.ok(!edge.dead, "out of it"); + assert.ok(!grave.dead, "buried in the wall: not solid, not caught"); + assert.ok(!lost.dead); + assert.equal(round.lives, 3); + assert.equal(events(round, "lose").length, 0, "you take nothing"); + assert.ok(round.score > score0); + assert.equal(round.drops.length, 0, "no drops"); + const blast = round.hazards.find((h) => h.kind === "blast"); + assert.equal(blast.w, arm.BLAST_W); + assert.equal(blast.live, 0, "it never hurts you"); + run(round, 500); + assert.ok(!round.hazards.some((h) => h.kind === "blast"), "the flash is gone after 450 ms"); + // A stick landing on a board sits on it; one against a wall stops. + const board = mineRound("collapse"); + standAt(board, 30, 1, 11, 0); + board.you.safeMs = 1e9; + sticks(board, 1); + tapTap(board); + run(board, 8); + const bs = board.hazards.find((h) => h.kind === "stick"); + until(board, () => bs.rest, 1000); + assert.ok(bs.rest); + // A stick lost down a pit never blows. + const pit = mineRound("collapse"); + const lostStick = { kind: "stick", x: 234, y: 7, vx: 0, vy: 0, fuse: 800, max: 1000, spin: 0, rest: false, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }; + pit.hazards.push(lostStick); + standAt(pit, 10); + run(pit, 1200); + assert.equal(events(pit, "dynBlast").length, 0); + assert.ok(!pit.hazards.includes(lostStick)); + // The blast hurts the boss (8, double while he is dazed) only where he stands and is not hidden. + const fight = seamFight(); + const b = fight.boss; + const hp0 = b.hp; + fight.hazards.push({ kind: "stick", x: b.x - 4, y: 6, vx: 0, vy: 0, fuse: 8, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(fight, 40); + assert.equal(b.hp, hp0 - arm.DYN_BOSS_DMG, "8 off the boss"); + b.dazed = 1000; + fight.hazards.push({ kind: "stick", x: b.x - 4, y: 6, vx: 0, vy: 0, fuse: 8, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(fight, 40); + assert.equal(b.hp, hp0 - arm.DYN_BOSS_DMG * 3, "and 16 while dazed"); + const far = seamFight(); + far.hazards.push({ kind: "stick", x: far.boss.x - 30, y: 6, vx: 0, vy: 0, fuse: 8, max: 1000, spin: 0, rest: true, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }); + run(far, 40); + assert.equal(far.boss.hp, far.boss.max, "too far from him"); +}); + +/* ------------------------------------------------------------ the boss */ + +function seamFight() { + const round = mineRound("seam"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + ghoul.advance(round, 8, steady); + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +// The boss about to choose its `n`th move. +function choose(round, n) { + Object.assign(round.boss, { act: "idle", wait: 0, moves: n - 1 }); +} + +// A bolt at the boss's chest, from the left. +const bossBolt = (round) => round.shots.push({ x: round.boss.x - round.boss.w / 2 - 0.3, y: round.boss.y + 8, vx: 80, vy: 0, gone: 0 }); + +test("Ghoul Rush's Tommyknocker waits at the end of the seam, then knocks: four beats 380 ms apart, a rock with 700 ms of dust at each (the first ahead of you, two 14 either side, the fourth between), then rests 0.7 s", () => { + const round = seamFight(); + const b = round.boss; + assert.equal(b.kind, "tommy"); + assert.equal(b.max, 120); + assert.equal(ghoul.roomFor("seam", 0).bossHp, 120); + assert.deepEqual([b.w, b.h], [10, 15]); + assert.equal(round.blackout, false); + choose(round, 1); + const t0 = round.clock; + const seen = []; + for (let t = 0; t < 1900; t += 4) { + ghoul.advance(round, 4, steady); + for (const e of round.events) if (e.type === "tommyKnock" || e.type === "rockWarn") seen.push([e.type, round.clock - t0, e]); + round.events.length = 0; + } + const knocks = seen.filter((s) => s[0] === "tommyKnock"); + const warns = seen.filter((s) => s[0] === "rockWarn"); + assert.equal(knocks.length, 4); + assert.deepEqual(knocks.map((k) => k[2].n), [1, 2, 3, 4]); + assert.ok(Math.abs(knocks[1][1] - knocks[0][1] - mn.KNOCK_BEAT_MS) < 20 && Math.abs(knocks[2][1] - knocks[1][1] - mn.KNOCK_BEAT_MS) < 20 && Math.abs(knocks[3][1] - knocks[2][1] - mn.KNOCK_BEAT_MS) < 20, "380 ms apart"); + assert.equal(warns.length, 4, "a rock at each beat"); + assert.ok(warns.every(([, ms], i) => Math.abs(ms - knocks[i][1]) < 20), "with the beat"); + const spec = round.spec; + const xs = warns.map((w) => w[2].x); + assert.ok(Math.abs(xs[0] - round.you.x) < 1e-6, "the first over you"); + assert.ok(Math.abs(xs[2] - (round.you.x + mn.KNOCK_SPREAD)) < 1e-6 && xs[1] === spec.arena + 3, "and either side (the left clamped to the arena's wall)"); + assert.ok(warns.every((w) => w[2].ms === 700)); + assert.ok(b.act === "rest", "then he rests"); + // A second of rest after the last beat, then he waits before the next move. + until(round, () => b.act === "idle", 1500); + assert.ok(Math.abs(round.clock - t0 - knocks[3][1] - mn.KNOCK_REST_MS) < 30, `0.7 s of rest (${round.clock - t0 - knocks[3][1]})`); + // Under his knocks you move to be safe: a rock over you costs a life. + const hit = seamFight(); + hit.you.safeMs = 0; + choose(hit, 1); + until(hit, () => events(hit, "lose").length > 0, 3000); + assert.equal(events(hit, "lose")[0]?.cause, "rock"); + // And a hard hat bounces the one that comes down on you, used up. + const hat = seamFight(); + hat.you.hat = true; + hat.you.safeMs = 0; + choose(hat, 1); + run(hat, 3000); + assert.equal(events(hat, "lose").length, 0); + assert.equal(events(hat, "rockBounce").length, 1); + assert.equal(hat.you.hat, false); +}); + +test("Ghoul Rush's Tommyknocker winds up his hammer 500 ms when you are close, then sweeps low along the floor (15 long, 2.6 high, live 260 ms, the cause hammer): jump it", () => { + const round = seamFight(); + const b = round.boss; + standAt(round, b.x - b.w / 2 - 4); + round.you.safeMs = 1e9; + choose(round, 2); + const wind = log(round, 8, "sweepWind"); + assert.equal(wind.length, 1); + assert.equal(b.act, "sweepWind"); + const s0 = round.clock; + assert.ok(upTo(round, "tommySweep", 700), "the sweep"); + assert.ok(Math.abs(round.clock - s0 - mn.SWEEP_WIND_MS) < 20, `500 ms (${round.clock - s0})`); + const hz = round.hazards.find((h) => h.kind === "hammer"); + assert.ok(hz && hz.w === 15 && hz.h === 2.6 && hz.cause === "hammer" && hz.live > 200 && hz.dir === -1); + assert.ok(hz.x < b.x - b.w / 2, "in front of him"); + assert.equal(b.act, "rest"); + run(round, 300); + assert.ok(!round.hazards.some((h) => h.kind === "hammer"), "gone in 260 ms"); + // Standing in it costs a life; in the air above 2.6 does not; out of reach does not. + const hit = seamFight(); + standAt(hit, hit.boss.x - hit.boss.w / 2 - 4); + hit.you.safeMs = 0; + choose(hit, 2); + until(hit, () => events(hit, "lose").length > 0, 1500); + assert.equal(events(hit, "lose")[0]?.cause, "hammer"); + const jump = seamFight(); + standAt(jump, jump.boss.x - jump.boss.w / 2 - 4); + jump.you.safeMs = 0; + choose(jump, 2); + assert.ok(upTo(jump, "sweepWind", 100)); + run(jump, 300); + jump.input.up = true; + ghoul.jump(jump); + assert.ok(upTo(jump, "tommySweep", 600), "it sweeps under you"); + run(jump, 700); + assert.equal(events(jump, "lose").length, 0, "jumped it"); + // Not twice within 1.8 s: the next close move is not a sweep. + const twice = seamFight(); + const tb = twice.boss; + standAt(twice, tb.x - tb.w / 2 - 4); + twice.you.safeMs = 1e9; + choose(twice, 2); + until(twice, () => events(twice, "tommySweep").length > 0, 800); + choose(twice, 4); + tb.swingCool = 1000; + run(twice, 40); + assert.equal(events(twice, "sweepWind").length, 1, "no second sweep so soon"); + assert.ok(tb.act === "knock", "a knock instead"); +}); + +test("Ghoul Rush's Tommyknocker puts the lights out: the room goes dark, he sinks (nothing can hit him), a decoy imp carries his lantern, the real knocking trickles from where he will burst out, and after 4 s he bursts out there", () => { + const round = seamFight(); + const b = round.boss; + choose(round, 3); + const dark = log(round, 8, "tommyDark"); + assert.equal(dark.length, 1); + assert.equal(round.blackout, true, "the lamps are out"); + assert.equal(b.darkOn, true); + assert.equal(b.act, "dark"); + assert.equal(b.hidden, false); + const sink = log(round, 800, "tommySink"); + assert.equal(sink.length, 1); + assert.ok(Math.abs(sink[0][0] - mn.TOMMY_SINK_MS) < 30, `600 ms (${sink[0][0]})`); + assert.equal(b.hidden, true); + assert.equal(b.y, mn.HIDE_Y); + assert.equal(b.act, "hidden"); + assert.equal(round.blackout, true); + // Nothing hits him down there: no bolt, no stomp, no touch. + const hp0 = b.hp; + round.shots.push({ x: b.x - 6, y: 8, vx: 80, vy: 0, gone: 0 }); + standAt(round, b.x, 1, 6); + round.you.safeMs = 0; + run(round, 120); + assert.equal(b.hp, hp0); + assert.equal(events(round, "lose").length, 0); + // The decoy: an imp with his lantern, at the side opposite where he will burst out. + const decoy = round.monsters.find((m) => m.decoy); + assert.ok(decoy && decoy.kind === "imp"); + const lo = 104 + 6 + 5; + const hi = 200 - 6 - 5; + assert.ok(Math.abs(b.burstX - (lo + (hi - lo) * 0.25)) < 1e-9, `he bursts out at a quarter across (${b.burstX})`); + assert.ok(Math.abs(b.decoyX - (lo + (hi - lo) * 0.75)) < 1e-9); + run(round, 400); + assert.ok(Math.abs(decoy.x - b.decoyX) < 8, "it keeps to its spot"); + assert.equal(decoy.act, "pace"); + assert.equal(round.you.dimMs, 0, "the decoy steals nothing"); + // Knocking from the burst spot every 700 ms. + const t0 = round.clock; + const knocks = log(round, 2000, "tommyKnockDark"); + assert.ok(knocks.length >= 2 && knocks.every(([, e]) => e.x === b.burstX), "dust where he will come out"); + assert.ok(Math.abs(knocks[1][0] - knocks[0][0] - mn.KNOCK_DARK_MS) < 20); + // Out after 4 s of dark, dazed, the lamps back on. + const burst = upTo(round, "tommyBurst", 4400); + assert.ok(burst, "he bursts out"); + assert.equal(burst.x, b.burstX); + assert.equal(b.hidden, false); + assert.equal(b.x, b.burstX); + assert.equal(b.y, 6); + assert.equal(round.blackout, false); + assert.equal(b.darkOn, false); + assert.equal(b.dazed > 1300 && b.dazed <= mn.DAZE_MS, true); + assert.equal(b.act, "dazed"); + assert.ok(round.monsters.every((m) => !m.decoy), "the lantern is out"); + // The whole dark was about 4 s from the sink. + const total = mineDarkLength(false); + assert.ok(Math.abs(total - (mn.TOMMY_SINK_MS + mn.DARK_MS)) < 60, `${mn.DARK_MS} ms in the seam (${total})`); +}); + +// Milliseconds from the lights going out to the burst, for a fight at full hp or raged. +function mineDarkLength(raged) { + const round = seamFight(); + if (raged) round.boss.hp = Math.floor(round.boss.max / 2); + choose(round, 3); + ghoul.advance(round, 8, steady); + const t0 = round.clock; + let burst = -1; + for (let t = 0; t < 9000 && burst < 0; t += 4) { + ghoul.advance(round, 4, steady); + if (events(round, "tommyBurst").length) burst = round.clock - t0; + round.events.length = 0; + } + return burst; +} + +test("Ghoul Rush's Tommyknocker is dazed 1.5 s after bursting out and takes double damage then (a bolt does 2, the hit says weak), only then", () => { + const round = seamFight(); + const b = round.boss; + choose(round, 3); + until(round, () => events(round, "tommyBurst").length > 0, 6000); + assert.ok(b.dazed > 1400); + round.events.length = 0; + const hp0 = b.hp; + bossBolt(round); + ghoul.advance(round, 8, steady); + assert.equal(hp0 - b.hp, 2, "double"); + const hit = events(round, "bossHit")[0]; + assert.equal(hit.how, "weak"); + assert.equal(hit.weak, true); + assert.equal(hit.kind, "tommy"); + // He does not attack while dazed, and stands where he came out. + const x0 = b.x; + run(round, 1200); + assert.equal(b.x, x0); + assert.equal(b.act, "dazed"); + // After the 1.5 s: normal damage. + until(round, () => b.dazed <= 0, 1500); + assert.equal(b.dazed, 0); + round.events.length = 0; + const hp1 = b.hp; + bossBolt(round); + ghoul.advance(round, 8, steady); + assert.equal(hp1 - b.hp, 1, "single again"); + assert.equal(events(round, "bossHit")[0].weak, false); + // Never before he has burst out. + const fresh = seamFight(); + const hp2 = fresh.boss.hp; + bossBolt(fresh); + ghoul.advance(fresh, 8, steady); + assert.equal(hp2 - fresh.boss.hp, 1); + // Bursting out where you stand hurts: he is no ghost. + const ambush = seamFight(); + choose(ambush, 3); + ghoul.advance(ambush, 8, steady); + until(ambush, () => ambush.boss.hidden, 1000); + ambush.you.safeMs = 0; + standAt(ambush, ambush.boss.burstX); + until(ambush, () => events(ambush, "lose").length > 0, 6000); + assert.ok(["tommy", "hammer"].includes(events(ambush, "lose")[0]?.cause), "the eruption or his touch"); +}); + +test("Ghoul Rush's Tommyknocker rages at half his hp: every wait 0.7 as long, the dark lasts 6 s, and each lights-out sends 3 imps, never more than 5 alive", () => { + const round = seamFight(); + const b = round.boss; + b.hp = Math.floor(b.max / 2); + const rage = log(round, 40, "tommyRage"); + assert.equal(rage.length, 1); + assert.equal(b.raged, true); + assert.equal(log(round, 200, "tommyRage").length, 0, "once"); + // The dark is 6 s. + const calm1 = mineDarkLength(false); + const raged = mineDarkLength(true); + assert.ok(Math.abs(raged - (mn.TOMMY_SINK_MS * mn.TOMMY_QUICK + mn.DARK_RAGE_MS)) < 80, `6 s of dark (${raged})`); + assert.ok(raged > calm1 + 1500); + // Each lights-out sends three imps. + const imps = seamFight(); + imps.boss.hp = Math.floor(imps.boss.max / 2); + choose(imps, 3); + ghoul.advance(imps, 8, steady); + assert.equal(imps.monsters.filter((m) => m.kind === "imp").length, 3, "three imps"); + assert.ok(imps.monsters.every((m) => m.kind !== "imp" || !m.decoy)); + until(imps, () => imps.boss.hidden, 1000); + assert.equal(imps.monsters.filter((m) => m.kind === "imp").length, 4, "and the decoy"); + // Never more than five alive. + const cap = seamFight(); + cap.boss.hp = Math.floor(cap.boss.max / 2); + for (let i = 0; i < 4; i++) put(cap, "imp", 150 + i * 3); + choose(cap, 3); + ghoul.advance(cap, 8, steady); + assert.equal(cap.monsters.filter((m) => m.kind === "imp").length, 5, "capped at five"); + const quiet = seamFight(); + choose(quiet, 3); + ghoul.advance(quiet, 8, steady); + assert.equal(quiet.monsters.filter((m) => m.kind === "imp").length, 0, "no imps before the rage"); + // Waits are 0.7 as long: the idle between moves. + const fast = seamFight(); + fast.boss.hp = Math.floor(fast.boss.max / 2); + run(fast, 40); + Object.assign(fast.boss, { act: "rest", wait: 1 }); + run(fast, 8); + assert.ok(Math.abs(fast.boss.wait - mn.TOMMY_IDLE_MS * mn.TOMMY_QUICK) < 20, `idle ${fast.boss.wait}`); +}); + +test("Ghoul Rush's Tommyknocker draws no random number in any move, and neither do the rocks, the imps, the miners, the crawlers or the cages", () => { + const fight = seamFight(); + fight.boss.hp = fight.boss.max; + for (let n = 1; n <= 7; n++) { + choose(fight, n); + fight.boss.hp = n > 4 ? Math.floor(fight.boss.max / 2) : fight.boss.hp; + standAt(fight, n % 2 ? fight.spec.arena + 12 : fight.boss.x - fight.boss.w / 2 - 4); + fight.you.safeMs = 1e9; + run(fight, 6200, {}, never); + } + for (const type of ["tommyKnock", "sweepWind", "tommySweep", "tommyDark", "tommySink", "tommyKnockDark", "tommyBurst", "tommyRage"]) assert.ok(events(fight, type).length > 0, `${type} happened without a random draw`); + const tun = mineRound("tunnels", { rocks: true }); + standAt(tun, 60); + tun.you.safeMs = 1e9; + put(tun, "blind", 100); + put(tun, "miner", 120); + put(tun, "canary", 90, { y: 14.5 }); + tun.twist.next = 0; + run(tun, 4000, { right: true }, never); + assert.ok(events(tun, "rockWarn").length >= 1 && events(tun, "canaryScream").length >= 0); + const sh = mineRound("shaft", { rocks: true }); + standAt(sh, 60); + sh.you.safeMs = 1e9; + // The imp behind you, out of the way of the bolts (a bolt's kill may drop loot). + put(sh, "imp", 20); + put(sh, "cage", 100, { y: 6.2, lo: 6.2, hi: 17.8, v: 7, rest: 0 }); + sticks(sh, 2); + tapTap(sh); + run(sh, 3000, { fire: true }, never); + assert.ok(events(sh, "dynBlast").length >= 1); +}); + +/* -------------------------------------------------------------- endless */ + +test("Ghoul Rush's endless lives (round.infinite) spare every new way to lose a life: a rock, a pickaxe, a hammer sweep, a miner, a blind crawler and the Tommyknocker himself", () => { + const costs = (id, setup, cause, { fight = false } = {}) => { + for (const infinite of [false, true]) { + const round = fight ? seamFight() : mineRound(id); + round.infinite = infinite; + round.you.safeMs = 0; + setup(round); + until(round, () => events(round, "lose").length > 0, 3000); + const e = events(round, "lose")[0]; + assert.equal(e?.cause, cause, `${cause}: a life is lost`); + assert.equal(round.lives, infinite ? 3 : 2, `${cause}: ${infinite ? "spared" : "costs one"}`); + } + }; + costs("collapse", (r) => (standAt(r, 60), r.hazards.push(rockAt(60))), "rock"); + costs("tunnels", (r) => (standAt(r, 46), put(r, "miner", 52, { act: "walk" })), "pickaxe"); + costs("tunnels", (r) => (standAt(r, 50), put(r, "miner", 50.5, { act: "walk" })), "miner"); + costs("shaft", (r) => (standAt(r, 40), put(r, "blind", 40.5)), "blind"); + costs("seam", (r) => (standAt(r, r.boss.x - r.boss.w / 2 - 4), choose(r, 2)), "hammer", { fight: true }); + costs("seam", (r) => standAt(r, r.boss.x - 3), "tommy", { fight: true }); + // The imp, the canary and the cage never cost one at all, endless or not. + const round = mineRound("shaft"); + standAt(round, 40); + put(round, "imp", 40.5); + put(round, "canary", 40, { y: 7 }); + put(round, "cage", 40, { y: 6.2, lo: 6.2, hi: 6.2, v: 0, rest: 1e9 }); + run(round, 600); + assert.equal(events(round, "lose").length, 0); +}); + +/* ---------------------------------------------------- voices and drawing */ + +test("Ghoul Rush's Mine: every new kind has a voice for every act, each a real tone, and every event of the pack plays its own sound exactly once", () => { + const listed = { + imp: ["appear", "steal", "drop", "hurt", "die"], + canary: ["appear", "scream", "hurt", "die"], + miner: ["appear", "dig", "wind", "swing", "hurt", "die"], + blind: ["appear", "lost", "hear", "hurt", "die"], + cage: ["appear", "die"], + tommy: ["wake", "knock", "sweepWind", "sweep", "dark", "sink", "knockDark", "burst", "rage", "hurt", "weak", "die"], + rock: ["warn", "fall", "land", "bounce"], + water: ["wade"], + hat: ["active"], + dyn: ["active", "throw", "blast"], + }; + for (const [kind, acts] of Object.entries(listed)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + for (const kind of [...Object.keys(mn.MONSTERS), ...Object.keys(mn.BOSSES)]) assert.ok(VOICES[kind] && VOICES[kind].die, `${kind} has a voice and a death`); + // Every event the pack emits is answered by one act, played once and nothing else (a splash is gated). + for (const type of mn.EVENTS) assert.ok(EVENT_VOICE[type], `${type} is heard`); + for (const type of Object.keys(EVENT_VOICE)) assert.ok(mn.EVENTS.includes(type), `${type} is an event of the pack`); + assert.equal(new Set(mn.EVENTS).size, mn.EVENTS.length); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(listed[kind].includes(act), `${type}: ${kind} ${act} is a listed act`); + assert.deepEqual(heard({ type, kind }).played, [VOICES[kind][act]], `${type}: ${kind} ${act}, once`); + } + // Each listed act is the voice of some event (or the game's own play of it). + const reached = new Set(Object.values(EVENT_VOICE).map(([kind, act]) => `${kind}.${act}`)); + const theGames = ["imp.appear", "imp.hurt", "imp.die", "canary.appear", "canary.hurt", "canary.die", "miner.appear", "miner.hurt", "miner.die", "blind.appear", "blind.hurt", "blind.die", "cage.appear", "cage.die", "tommy.wake", "tommy.hurt", "tommy.weak", "tommy.die", "hat.active", "dyn.active"]; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(reached.has(`${kind}.${act}`) || theGames.includes(`${kind}.${act}`), `${kind}.${act} is played by something`); + const once = (e, kind, act) => { + const played = heard(e).played; + assert.equal(played.filter((n) => n === VOICES[kind][act]).length, 1, `${e.type}: ${kind} ${act} once`); + }; + once({ type: "spawn", kind: "imp" }, "imp", "appear"); + once({ type: "spawn", kind: "canary" }, "canary", "appear"); + once({ type: "spawn", kind: "miner" }, "miner", "appear"); + once({ type: "spawn", kind: "blind" }, "blind", "appear"); + once({ type: "spawn", kind: "cage" }, "cage", "appear"); + once({ type: "bossWake", kind: "tommy" }, "tommy", "wake"); + once({ type: "bossHit", kind: "tommy", how: "shot" }, "tommy", "hurt"); + once({ type: "bossHit", kind: "tommy", how: "weak", weak: true }, "tommy", "weak"); + once({ type: "bossDown", kind: "tommy", points: 1 }, "tommy", "die"); + once({ type: "hit", kind: "imp" }, "imp", "hurt"); + once({ type: "kill", kind: "blind", mult: 1, how: "shot", points: 1 }, "blind", "die"); + once({ type: "kill", kind: "miner", mult: 1, how: "shot", points: 1 }, "miner", "die"); + const words = []; + heard({ type: "bossHit", kind: "tommy", how: "weak", weak: true }, { float: (x, y, text) => words.push(text) }); + assert.ok(words.includes("Double!"), "a weak hit says Double!"); + for (const kind of ["hat", "dyn"]) { + const played = heard({ type: "power", kind, points: 50 }).played; + assert.ok(played.includes(VOICES[kind].active) && !played.includes("powerUp"), `${kind}: the pickup is its own sound`); + } +}); + +test("Ghoul Rush's Mine: every new way to die has its words and its own sound", () => { + for (const cause of ["rock", "miner", "pickaxe", "blind", "tommy", "hammer"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Mine draws: every room, every monster in every act, the rocks in each state, the stick and its blast, the swings, the water, the Tommyknocker in each move hidden or not, the lights out, a dimmed light, both badges, and the stage's card, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["mine"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { + imp: [{ act: "skitter" }, { act: "flee", stole: true }, { act: "pace", decoy: true }], + canary: [{ act: "flit", y: 14 }, { act: "scream", y: 14 }, { act: "flee", y: 14 }], + miner: [{ act: "buried" }, { act: "dig", wait: 300 }, { act: "walk" }, { act: "wind", wait: 200 }, { act: "rest" }], + blind: [{ act: "lost" }, { act: "hunt" }], + cage: [{ act: "ride", y: 8, lo: 6.2, hi: 17.8, rest: 0 }, { act: "ride", y: 17.8, lo: 6.2, hi: 17.8, rest: 800 }], + }; + for (const id of ROOM_IDS) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + for (const dim of [0, 3000]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + r.twist = calm(); + standAt(r, id === "seam" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + r.you.dimMs = dim; + r.dyn = 2; + for (const [kind, list] of Object.entries(acts)) list.forEach((over, i) => put(r, kind, r.you.x + 6 + i * 5, { wait: 1e9, ...over })); + r.hazards.push( + rockAt(r.you.x + 8), + rockAt(r.you.x + 12, { state: "fall", y: 20, live: 1 }), + rockAt(r.you.x + 16, { state: "rubble", y: 6, h: 1.4, live: 0, rub: 2000 }), + { kind: "stick", x: r.you.x + 20, y: 9, vx: 10, vy: 0, fuse: 500, max: 1000, spin: 1, rest: false, w: 0.8, h: 0.8, live: 0, cause: "dynamite" }, + { kind: "blast", x: r.you.x + 26, y: 6, w: 22, h: 12, boom: 200, max: 450, live: 0, cause: "dynamite" }, + { kind: "pick", x: r.you.x + 30, y: 6, w: 5, h: 4.2, dir: 1, live: 100, max: 200, cause: "pickaxe" }, + { kind: "hammer", x: r.you.x + 34, y: 6, w: 15, h: 2.6, dir: -1, live: 100, max: 260, cause: "hammer" }, + ); + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const act of ["idle", "knock", "sweepWind", "rest", "dark", "hidden", "dazed"]) { + Object.assign(r.boss, { act, wait: 1e9, knockIn: 200, beat: 1, dir: -1, hidden: act === "hidden", darkOn: act === "dark" || act === "hidden", dazed: act === "dazed" ? 1000 : 0, burstX: 150, decoyX: 180, y: act === "hidden" ? mn.HIDE_Y : 6 }); + r.blackout = r.boss.darkOn; + g.tick(16); + } + Object.assign(r.boss, { hidden: false, y: 6, darkOn: false }); + r.boss.raged = true; + } + r.blackout = false; + for (let k = 0; k < 20; k++) g.tick(16); + r.blackout = true; + g.tick(16); + r.blackout = false; + r.you.safeMs = 1e9; + } + } + } + assert.ok(r.spec.id === "seam", "got to the seam and drew it"); + // A sleeping Tommyknocker, the boss bar, and the badges as they sit in a room. + for (const kind of ["hat", "dyn"]) { + const p = mineRound("shaft"); + p.drops.push({ id: 1, kind, x: 30, y: 8, vx: 0, vy: 0, life: 9000, rest: true }); + g.tick(16); + ghoul.applyPower(p, kind); + } + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["mine", "village"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Mine's card"); + // And the dark sees what is lit: the blackout and the dim raise the dark and shrink the glow. + assert.equal(LOOKS.shaft.pack, "mine"); +}); + +test("Ghoul Rush's stage select lists the Mine and takes you straight into each of its rooms", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.stageSelect(); + const r = g.round; + assert.equal(r.phase, "select"); + const at = ghoul.STAGES.findIndex((s) => s.id === "mine"); + assert.equal(at, ghoul.STAGES.length - 3); + for (let i = 0; i < at; i++) ghoul.steerSelect(r, 1, 0); + for (let i = 0; i < 4; i++) ghoul.steerSelect(r, 0, 1); + assert.equal(r.select.at, at); + assert.equal(r.select.room, 4); + ghoul.takeSelect(r); + assert.equal(r.spec.id, "seam"); + assert.equal(r.stage, "mine"); + assert.equal(r.dark, true, "always dark"); + g.tick(16); +}); diff --git a/scripts/test-web-console-activities-ghoul-retry.mjs b/scripts/test-web-console-activities-ghoul-retry.mjs new file mode 100644 index 0000000..84235b1 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-retry.mjs @@ -0,0 +1,318 @@ +// Web console tests, Ghoul Rush's retry mercy: after a loss in a room, each restart of it sets one power-up a few steps ahead of Planny (never the first attempt, never in a ride or bonus room), the kind from its own hash so no shared roll shifts, on a firm surface, replacing the last one uncollected, reset when the room is cleared. +// Run with: node --test scripts/test-web-console-activities-ghoul-retry.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import { MERCY_FAR, MERCY_NEAR, mercyKind, mercySpot, mix3 } from "../src/web-console/public/activities/ghoul-powers.js"; + +const steady = () => 0.5; +const mercies = (round) => round.drops.filter((d) => d.mercy); +const events = (round, type) => round.events.filter((e) => e.type === type); +// What ghoul.js hands the spot finder, through the real footing(). +const SPOT_KIT = Object.freeze({ footing: ghoul.footing, leftEdge: () => 1.5, rightEdge: (r) => r.spec.length - 1.5 }); + +function stubCanvas() { + const calls = { count: 0 }; + const ctx = new Proxy({}, { + get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }), + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls }; +} + +// Every spawner spent and the horde held back, so nothing else wakes. +function quiet(round) { + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + return round; +} + +// A round standing at the start of room `ri` of stage `si` (the hall when `si` is -1), in play. +function inRoom(si, ri, seed = 5) { + const round = ghoul.newRound(seed); + round.dice = 0; + if (si >= 0) { + round.phase = "select"; + round.select = { at: si, room: ri }; + assert.ok(ghoul.takeSelect(round)); + } + round.phase = "play"; + round.events.length = 0; + round.lives = 99; + return quiet(round); +} + +// A life lost (`cause`), then on through the crash and the "Ready?" hold to play again. +function die(round, cause = "zombie") { + round.phase = "play"; + round.you.out = 0; + round.you.safeMs = 0; + assert.ok(ghoul.lose(round, cause)); + for (let ms = 0; ms < 20000 && round.phase !== "play" && !round.over; ms += 50) ghoul.advance(round, 50, steady); + return quiet(round); +} + +const everyRoom = () => ghoul.STAGES.flatMap((st, si) => st.rooms.map((id, ri) => ({ st, si, ri, id }))); +const special = (round) => Boolean(round.spec.ride || round.spec.bonus || round.bonusRound); + +test("Ghoul Rush retry mercy: the first attempt of a room spawns nothing, the second exactly one power-up a few steps ahead of Planny on the floor", () => { + const round = inRoom(-1, 0); + assert.equal(mercies(round).length, 0); + assert.equal(events(round, "retry").length, 0); + assert.deepEqual(round.retries, { room: round.room, n: 0 }); + die(round); + const m = mercies(round); + assert.equal(m.length, 1, "exactly one"); + assert.equal(events(round, "retry").length, 1); + assert.deepEqual(round.retries, { room: round.room, n: 1 }); + const dx = m[0].x - round.you.x; + assert.ok(dx >= MERCY_NEAR && dx <= MERCY_FAR, `ahead by ${dx}`); + assert.equal(dx, MERCY_FAR, "the far end of the range when the floor allows"); + assert.ok(ghoul.groundAt(round.spec, m[0].x) > -Infinity, "over a floor"); + assert.equal(m[0].y - 1, ghoul.groundAt(round.spec, m[0].x), "resting on its surface"); + assert.ok(m[0].rest); + assert.ok(!["life", "die"].includes(m[0].kind) && !ghoul.POWERS[m[0].kind].arm, `no 1UP, die or weapon (${m[0].kind})`); + assert.ok(ghoul.powerHere(round, m[0].kind)); +}); + +test("Ghoul Rush retry mercy: a third attempt gets a fresh pickup and the uncollected one is gone, never more than one alive", () => { + const round = inRoom(-1, 0); + die(round); + const first = mercies(round)[0]; + die(round); + const second = mercies(round); + assert.equal(second.length, 1); + assert.notEqual(second[0], first, "a new object"); + assert.equal(round.retries.n, 2); + assert.deepEqual(events(round, "retry").map((e) => e.n), [1, 2]); + for (let i = 0; i < 4; i++) die(round); + assert.equal(mercies(round).length, 1); + assert.equal(round.retries.n, 6); +}); + +test("Ghoul Rush retry mercy: walking into it takes it like any power-up, and the next loss sets out another", () => { + const round = inRoom(-1, 0); + die(round); + const [m] = mercies(round); + Object.assign(round.you, { x: m.x, y: ghoul.groundAt(round.spec, m.x), vx: 0, vy: 0, state: "run", shelf: -1 }); + round.events.length = 0; + ghoul.advance(round, 8, steady); + assert.deepEqual(events(round, "power").map((e) => e.kind), [m.kind]); + assert.equal(mercies(round).length, 0); + die(round); + assert.equal(mercies(round).length, 1); +}); + +test("Ghoul Rush retry mercy: clearing the room resets the count, the next room's first attempt spawns nothing, and its second does", () => { + const round = inRoom(0, 0); + die(round); + die(round); + assert.equal(round.retries.n, 2); + assert.equal(mercies(round).length, 1); + // Through the door the way play does it. + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); + assert.equal(round.spec.id, ghoul.STAGES[0].rooms[1]); + assert.equal(round.retries.n, 0, "reset for the new room"); + assert.equal(mercies(round).length, 0, "the old pickup is gone with the room"); + round.phase = "play"; + quiet(round); + die(round); + assert.equal(round.retries.n, 1); + assert.equal(mercies(round).length, 1); +}); + +test("Ghoul Rush retry mercy: a boss room (from its start, or locked in the arena) gets one too", () => { + const si = 0; + const ri = ghoul.STAGES[si].rooms.length - 1; + const round = inRoom(si, ri); + assert.ok(round.spec.boss); + die(round); + assert.equal(mercies(round).length, 1, "from the start"); + const arena = inRoom(si, ri); + arena.lockX = arena.spec.arena; + arena.boss.state = "fight"; + die(arena); + const m = mercies(arena); + assert.equal(m.length, 1, "in the arena"); + assert.ok(m[0].x > arena.spec.arena && m[0].x < arena.spec.length, "inside the arena"); +}); + +test("Ghoul Rush retry mercy: a ride or bonus room never gets one, every other room of every stage does", () => { + let rides = 0; + let plain = 0; + for (const { si, ri, id } of everyRoom()) { + const round = inRoom(si, ri); + round.lives = 9; + if (round.bonusRound) round.bonusRound.hearts = 5; + round.you.out = 0; + round.you.safeMs = 0; + ghoul.lose(round, "zombie"); + for (let ms = 0; ms < 20000 && round.phase !== "play" && !round.over; ms += 50) ghoul.advance(round, 50, steady); + if (special(round)) { + rides++; + assert.equal(mercies(round).length, 0, `${id}: none in a ride or bonus room`); + assert.equal(events(round, "retry").length, 0, id); + } else { + plain++; + assert.equal(mercies(round).length, 1, `${id}: one`); + } + } + assert.ok(rides >= 1 && plain >= 20, `${rides} special rooms, ${plain} others`); +}); + +test("Ghoul Rush retry mercy: over every stage's rooms, dark and lit, many retries, only what powerHere allows turns up, never a 1UP, die or weapon", () => { + const seen = new Set(); + for (const { st, si, ri, id } of everyRoom()) { + for (const dark of [true, false]) { + const round = inRoom(si, ri, 11 + ri); + if (special(round)) continue; + round.dark = dark; + for (let n = 1; n <= 12; n++) { + const kind = mercyKind(round, n, { seeded: ghoul.seeded }); + assert.ok(ghoul.powerHere(round, kind), `${id}: ${kind} here`); + assert.ok(!["life", "die"].includes(kind) && !ghoul.POWERS[kind].arm, `${id}: ${kind} is a plain power-up`); + if (ghoul.POWERS[kind].stage) assert.equal(ghoul.POWERS[kind].stage, st.id, `${id}: ${kind} only in its stage`); + if (ghoul.POWERS[kind].dark) assert.ok(dark, `${id}: the Lantern only in the dark`); + if (kind === "hourglass") assert.ok(round.timeMs > 0, `${id}: no Hourglass where there is no clock`); + seen.add(kind); + } + } + } + assert.ok(seen.size >= 6, `variety: ${[...seen].join(", ")}`); +}); + +test("Ghoul Rush retry mercy: the spot is firm ground within reach, facing either way, never a pit, a wall, a belt or water, and found at every room's start", () => { + for (const { id, si, ri } of everyRoom()) { + const round = inRoom(si, ri); + if (special(round)) continue; + const spec = round.spec; + const open = [...(spec.belts || []), ...(spec.water || [])]; + assert.ok(mercySpot(round, SPOT_KIT), `${id}: a spot at the start`); + for (let x = 3; x < spec.length - 3; x += 1.7) { + const g = ghoul.groundAt(spec, x); + if (g === -Infinity) continue; + for (const face of [1, -1]) { + Object.assign(round.you, { x, y: g, face, shelf: -1 }); + const s = mercySpot(round, SPOT_KIT); + if (!s) continue; + const d = (s.x - x) * face; + assert.ok(d >= MERCY_NEAR - 1e-9 && d <= MERCY_FAR + 1e-9, `${id}@${x}: ${d} ahead`); + for (const px of [s.x - 1, s.x, s.x + 1]) assert.ok(ghoul.footing(round, px, g), `${id}@${x}: firm at ${px}, not a pit or a wall`); + assert.ok(Math.abs(s.y - g) <= ghoul.STEP_UP, `${id}@${x}: a step or less`); + assert.ok(open.every(([a, b]) => s.x < a - 1 || s.x > b + 1), `${id}@${x}: clear of belts and water`); + } + } + } +}); + +test("Ghoul Rush retry mercy: the kind is a pure hash of (seed, room, retry), the shared rng is never touched, and a run with a mercy spawn rolls the same monsters afterwards as one without", () => { + const kit = { seeded: ghoul.seeded }; + const round = inRoom(0, 1, 9); + assert.equal(mercyKind(round, 3, kit), mercyKind(round, 3, kit)); + assert.equal(mix3(1, 2, 3), mix3(1, 2, 3)); + assert.notEqual(mix3(1, 2, 3), mix3(1, 2, 4)); + const kinds = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((n) => mercyKind(round, n, kit))); + assert.ok(kinds.size >= 3, "the retries vary"); + // The pick asks for a fresh stream of its own; the round's rng is never an input. + let made = 0; + mercyKind(round, 1, { seeded: (s) => { made++; return ghoul.seeded(s); } }); + assert.equal(made, 1); + // Same seed, same loss; one lets the mercy spawn, the other has it switched off (a bonus spec while the crash ends). Both then play on with an identical rng. + const play = (withMercy) => { + const r = ghoul.newRound(21); + r.dice = 0; + r.phase = "play"; + let calls = 0; + const base = ghoul.seeded(77); + const rng = () => { + calls++; + return base(); + }; + r.you.out = 0; + r.you.safeMs = 0; + const real = r.spec; + ghoul.lose(r, "zombie"); + if (!withMercy) r.spec = { ...real, bonus: true }; + for (let ms = 0; ms < 20000 && r.phase !== "play"; ms += 50) { + ghoul.advance(r, 50, rng); + if (r.phase === "ready") r.spec = real; + } + r.spec = real; + const spawned = mercies(r).length; + r.drops.length = 0; + const before = calls; + // Stand still and let the hall wake. + for (let ms = 0; ms < 12000 && !r.over; ms += 16) { + r.you.safeMs = 1e6; + ghoul.advance(r, 16, rng); + } + return { spawned, calls: calls - before, shape: JSON.stringify(r.monsters.map((m) => [m.kind, +m.x.toFixed(3), +m.y.toFixed(3)])), n: r.monsters.length }; + }; + const a = play(true); + const b = play(false); + assert.equal(a.spawned, 1); + assert.equal(b.spawned, 0); + assert.ok(a.n > 0, "monsters came"); + assert.deepEqual([a.calls, a.shape], [b.calls, b.shape], "the same monsters, the same draws"); +}); + +test("Ghoul Rush retry mercy: a clock run out restarts the room and counts, and so does a death with the endless-lives code on", () => { + const timed = inRoom(0, 0); + assert.ok(timed.timeMs > 0); + timed.timeMs = 20; + const lives = timed.lives; + for (let ms = 0; ms < 20000 && timed.phase !== "ready"; ms += 4) ghoul.advance(timed, 4, steady); + assert.equal(events(timed, "timeUp").length, 1); + assert.equal(timed.lives, lives - 1); + assert.equal(timed.retries.n, 1); + assert.equal(mercies(timed).length, 1); + const endless = inRoom(0, 0); + endless.infinite = true; + die(endless); + die(endless); + assert.equal(endless.lives, 99, "no life lost"); + assert.equal(endless.retries.n, 2); + assert.equal(mercies(endless).length, 1); +}); + +test("Ghoul Rush retry mercy: no pickup when the run is over, and a practice round's first attempt spawns nothing like any other", () => { + const spent = inRoom(-1, 0); + spent.lives = 1; + die(spent); + assert.ok(spent.over); + assert.equal(mercies(spent).length, 0); + const practice = inRoom(0, 1); + practice.practice = true; + assert.equal(mercies(practice).length, 0); + die(practice); + assert.equal(mercies(practice).length, 1); +}); + +test("Ghoul Rush retry mercy: the game draws the pickup, its shimmer and its words in dark and lit rooms without error", () => { + for (const dark of [true, false]) { + const { canvas, calls } = stubCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.round.dice = 0; + for (let ms = 0; ms < 4000; ms += 16) g.tick(16); + const r = g.round; + r.dark = dark; + r.lives = 9; + r.you.safeMs = 0; + r.you.out = 0; + ghoul.lose(r, "zombie"); + const before = calls.count; + let seen = 0; + for (let ms = 0; ms < 8000; ms += 16) { + g.tick(16); + seen = Math.max(seen, mercies(r).length); + } + assert.equal(seen, 1, `a pickup in the ${dark ? "dark" : "light"}`); + assert.ok(calls.count > before); + } +}); diff --git a/scripts/test-web-console-activities-ghoul-ride.mjs b/scripts/test-web-console-activities-ghoul-ride.mjs new file mode 100644 index 0000000..0fae3d8 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-ride.mjs @@ -0,0 +1,935 @@ +// Web console tests, Ghoul Rush's dark ride (the Midnight Carnival's bonus round): its place (between the funhouse and the Big Top), the bonus round's five hearts and the flow on to the boss, the dice rule, the controls (arrows, Space, the mouse, the duck zone), aim assist, the mini-bosses, the Exit's twist, a bot that rides it all and one that does nothing, the endless-lives code, and every event voiced. +// Run with: node --test scripts/test-web-console-activities-ghoul-ride.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as rt from "../src/web-console/public/activities/ghoul-ride.js"; +import { SCENES, END_P } from "../src/web-console/public/activities/ghoul-ride-scenes.js"; +import { CAR_X, DUCK_OFF, DUCK_ON, bindG } from "../src/web-console/public/activities/ghoul-ride-core.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, LOOKS as RIDE_LOOKS, VOICES as RIDE_VOICES } from "../src/web-console/public/activities/ghoul-ride-voices.js"; +import { CARNIVAL_ROOMS } from "../src/web-console/public/activities/ghoul-carnival.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES } from "../src/web-console/public/activities/ghoul-draw.js"; +import { endBonus } from "../src/web-console/public/activities/ghoul-bonus.js"; +import { rideArt } from "../src/web-console/public/activities/ghoul-ride-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the dark ride reached the way play reaches it, the intro done. +function rideRound() { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["carnival"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "darkride") through(round); + return round; +} +function playing() { + const round = rideRound(); + round.phase = "play"; + round.timeMs = 1e9; + round.events.length = 0; + return round; +} +const step = (round, n = 1) => { + for (let i = 0; i < n && round.phase === "play"; i++) ghoul.advance(round, 16, steady); +}; +// The ride's own clock in seconds. +const G = (round) => { + bindG(round.gallery); + return round.gallery; +}; + +/* ----------------------------------------------------------------- bots */ + +// Every point a shot at (x, y) would hit something worth shooting. +function targetAt(g, round) { + bindG(g); + for (let y = 6; y <= 40; y += 3) { + for (let x = 6; x <= 92; x += 3) { + for (const e of g.ents) { + if (!e.alive || e.k === "inno" || e.k === "mir" || e.k === "door" || !rt.K[e.k].hit) continue; + if (rt.K[e.k].hit(e, x, y)) return { x, y }; + } + } + } + return null; +} +// A bot that aims at anything shootable, ducks at a warning, and never fires at a guest. +function aimbot(round) { + const g = round.gallery; + bindG(g); + const inp = round.input; + inp.left = inp.right = inp.up = inp.down = false; + if (g.duckWarn > 0.15) { + g.ret.y = 46; + inp.fire = false; + return; + } + const t = targetAt(g, round); + if (t) { + g.ret.x = t.x; + g.ret.y = t.y; + inp.fire = true; + } else { + g.ret.x = 62; + g.ret.y = 26; + inp.fire = false; + } +} +function ridden(round, bot, maxSeconds = 140) { + const seen = new Set(); + let ms = 0; + while (round.phase === "play" && ms < maxSeconds * 1000) { + if (bot) bot(round); + ghoul.advance(round, 16, steady); + ms += 16; + if (round.gallery) seen.add(round.gallery.zi); + } + return { seconds: ms / 1000, seen }; +} + +/* ------------------------------------------------------------ the place */ + +test("Ghoul Rush ride: the dark ride is the Carnival's bonus round between the funhouse and the Big Top", () => { + assert.deepEqual([...CARNIVAL_ROOMS], ["midway", "mirrors", "funhouse", "darkride", "bigtop"]); + const stage = ghoul.STAGES.find((s) => s.id === "carnival"); + assert.deepEqual([...stage.rooms], [...CARNIVAL_ROOMS]); + const spec = ghoul.roomById("darkride"); + assert.equal(spec.bonus, true); + assert.equal(spec.ride.gallery, true); + assert.equal(spec.boss, null); + assert.equal(spec.key, null); + assert.equal(spec.dark, false, "the ride ignores the dark roll"); + assert.ok(spec.ride.time >= 95000 && spec.ride.time <= 105000, "about a hundred seconds on the game's clock"); + assert.equal(ghoul.timeFor(spec), spec.ride.time); + assert.match(spec.ride.how, /Mouse: move to aim, click or hold to fire/); + assert.equal(RIDE_LOOKS.darkride.pack, "ride"); + assert.ok(LOOKS.darkride); + assert.equal(ghoul.ROOM_MUSIC.darkride, "ghoulRideTheme"); +}); + +test("Ghoul Rush ride: the scene table has 12 rooms in order with the prototype's lengths, about 92 seconds at a clean ride", () => { + assert.deepEqual(SCENES.map((s) => s.id), ["bay", "wax", "torture", "carousel", "mirrors", "tunnel", "web", "lift", "tent", "exit", "dark", "barker"]); + assert.deepEqual(SCENES.map((s) => s.len), [40, 108, 150, 124, 104, 170, 150, 110, 140, 74, 24, 122]); + assert.equal(END_P, SCENES.reduce((a, s) => a + s.len, 0)); + let at = 0; + for (const s of SCENES) { + assert.equal(s.a, at, `${s.id} starts where the last ended`); + at += s.len; + assert.ok(s.name && s.tag, `${s.id} has a plaque`); + } +}); + +test("Ghoul Rush ride: entering sets the ride up (five hearts, the intro, a banner naming the mouse), and no other room has a ride", () => { + const round = rideRound(); + assert.ok(round.gallery, "the ride is made"); + assert.equal(round.gallery.hp, 5); + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.phase, "ready"); + assert.equal(round.phaseMs, ghoul.roomById("darkride").ride.ready); + const start = events(round, "bonusStart")[0]; + assert.ok(start, "the bonus round announces itself"); + assert.match(start.how, /Mouse: move to aim, click or hold to fire/); + ghoul.advance(round, 6000, steady); + assert.equal(round.phase, "ready", "it waits for a press"); + assert.equal(rt.startRide(round), true); + ghoul.advance(round, 16, steady); + assert.equal(round.phase, "play"); + assert.equal(events(round, "go").length, 1); + const other = ghoul.newRound(5); + other.dice = 0; + assert.equal(other.gallery ?? null, null); + through(other); + assert.equal(other.gallery ?? null, null, "a plain room has none"); +}); + +/* ------------------------------------------------------------- hearts */ + +test("Ghoul Rush ride: a hit costs a heart, not a life, and protects for 2.2 seconds; the ride plays on", () => { + const round = playing(); + step(round, 3); + const lives = round.lives; + const g = G(round); + g.mode = "ride"; + rt.stepRide(0.016); + const hit = (cause) => ghoul.lose(round, cause); + assert.equal(hit("ridegrab"), true); + assert.equal(round.bonusRound.hearts, 4); + assert.equal(round.lives, lives, "no life is touched"); + assert.equal(round.phase, "play", "no crash: the ride goes on"); + assert.equal(events(round, "lose").at(-1).hearts, 4); + // The ride's own hurt (with the safe moment) is the one the rules use. + const before = round.bonusRound.hearts; + g.inv = 0; + RIDE_HURT(round, "ridecrash"); + assert.equal(round.bonusRound.hearts, before - 1); + RIDE_HURT(round, "ridecrash"); + assert.equal(round.bonusRound.hearts, before - 1, "2.2 seconds of safety"); + assert.ok(g.inv > 2.1 && g.inv <= rt.INVULN); +}); + +// A heart lost the way the rules lose one (the hurt helper is private): a pop reaching the car. +function RIDE_HURT(round, cause) { + const g = round.gallery; + bindG(g); + g.mode = "ride"; + if (g.inv > 0) { + // Same gate as the rules: nothing while safe. + return; + } + g.inv = rt.INVULN; + ghoul.lose(round, cause); + g.hp = round.bonusRound.hearts; +} + +test("Ghoul Rush ride: a real hit from the field costs a heart through the bonus round (a lunging ghoul reaches the car)", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.inv = 0; + const e = { k: "pop", t: "ghoul", x: 10, y: 40, hp: 1, maxhp: 1, boss: null, ph: "lunge", pt: 99, age: 0, trig: 56, wait: 1, L: 0.1, rel: true, rx: 20, ry: 41, sc: 1.6, sc0: 1, flinch: 0, alive: true, dying: 0, sx0: 40, sy0: 40, swings: 0, atk: 0 }; + g.ents.push(e); + step(round, 3); + assert.equal(round.bonusRound.hearts, 4); + assert.equal(events(round, "lose").at(-1).cause, "ridegrab"); + assert.equal(round.phase, "play"); +}); + +test("Ghoul Rush ride: the fifth heart ends the bonus with no dice, the run's lives and dice are untouched, and play moves on to the boss", () => { + const round = playing(); + round.dice = 3; + const lives = round.lives; + const g = G(round); + g.mode = "ride"; + for (let i = 0; i < 4; i++) { + g.inv = 0; + RIDE_HURT(round, "ridegrab"); + assert.equal(round.phase, "play"); + } + assert.equal(round.bonusRound.hearts, 1); + g.inv = 0; + RIDE_HURT(round, "ridegrab"); + assert.equal(round.bonusRound.hearts, 0); + assert.equal(round.phase, "crash"); + ghoul.advance(round, 3000, steady); + assert.equal(round.phase, "clear", "the lost card"); + assert.equal(round.bonusRound.won, false); + assert.deepEqual(round.bonusRound.result, { won: false, dice: 0, gained: 0 }); + assert.equal(round.dice, 3, "dice in hand kept"); + assert.equal(round.lives, lives); + assert.equal(round.over, false); + ghoul.advance(round, 3000, steady); + assert.equal(round.spec.id, "bigtop", "on to the boss"); + assert.equal(round.gallery ?? null, null); +}); + +test("Ghoul Rush ride: under the endless-lives code a hit costs nothing", () => { + const round = playing(); + round.infinite = true; + const g = G(round); + g.mode = "ride"; + for (let i = 0; i < 8; i++) { + g.inv = 0; + RIDE_HURT(round, "ridegrab"); + } + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.phase, "play"); + assert.equal(round.lives, ghoul.START_LIVES); +}); + +/* ---------------------------------------------------------------- dice */ + +test("Ghoul Rush ride: the dice rule is 5 to 9 by performance, a perfect ride is 9, and the bonus adds them under the cap of 9", () => { + const base = { shots: 100, hits: 100, kills: 50, missed: 0, hp: 5, ducksOK: 4, best: 20, innoHits: 0 }; + assert.equal(rt.gradeOf(base).dice, 9); + assert.equal(rt.gradeOf(base).grade, "S"); + const worst = { shots: 100, hits: 0, kills: 0, missed: 50, hp: 1, ducksOK: 0, best: 0, innoHits: 9 }; + assert.equal(rt.gradeOf(worst).dice, 5); + assert.equal(rt.RIDE_FLOOR, 5); + for (let hp = 1; hp <= 5; hp++) for (const acc of [0, 0.4, 0.7, 1]) { + const d = rt.gradeOf({ ...base, hp, hits: Math.round(100 * acc) }).dice; + assert.ok(d >= 5 && d <= 9, `${hp} hearts at ${acc}: ${d}`); + } + // Fewer hearts never earn more. + assert.ok(rt.gradeOf({ ...base, hp: 1 }).dice <= rt.gradeOf({ ...base, hp: 5 }).dice); + // A guest shot costs. + assert.ok(rt.gradeOf({ ...base, innoHits: 10 }).perf < rt.gradeOf(base).perf); + // The bonus uses the ride's own number and caps the dice in hand at 9. + const round = playing(); + round.dice = 6; + round.bonusRound.perf.dice = 8; + round.bonusRound.perf.cardMs = 7000; + endBonus(round, true, { award: (r, p) => (r.score += p), ROOM_POINTS: 100 }); + assert.equal(round.bonusRound.dice, 8); + assert.equal(round.bonusRound.gained, 3, "6 + 8 caps at 9"); + assert.equal(round.dice, 9); + assert.equal(round.bonusRound.cardMs, 7000); +}); + +/* ------------------------------------------------------------- controls */ + +test("Ghoul Rush ride: the arrows move the reticle with acceleration, Space fires, and a tap too short for a step still fires", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.ret.x = 50; + g.ret.y = 20; + round.input.right = true; + step(round, 5); + const slow = g.ret.x - 50; + step(round, 20); + const next = g.ret.x - 50 - slow; + assert.ok(slow > 0 && next / 20 > slow / 5, "it speeds up while held"); + round.input.right = false; + round.input.up = true; + const y0 = g.ret.y; + step(round, 10); + assert.ok(g.ret.y < y0, "up raises it"); + round.input.up = false; + const shots = g.shots; + round.input.fire = true; + step(round, 40); + round.input.fire = false; + assert.ok(g.shots - shots >= 4 && g.shots - shots <= 6, `held fire shoots every ${rt.FIRE_GAP}s: ${g.shots - shots}`); + const s2 = g.shots; + g.fireCd = 0; + g.trigger = true; + step(round, 1); + assert.equal(g.shots, s2 + 1, "a tap fires"); + assert.equal(round.shots.length, 0, "the blaster's bolts never fly in the ride"); +}); + +test("Ghoul Rush ride: the mouse aims and a press or hold fires, and a let-go or a pause stops it", () => { + const round = playing(); + step(round, 2); + const g = G(round); + const [pointer] = rt.RIDE.pointer; + assert.equal(pointer(round, "move", 70, 30), true); + assert.deepEqual([g.ret.x, g.ret.y], [70, 30]); + pointer(round, "move", 500, -20); + assert.deepEqual([g.ret.x, g.ret.y], [92, 3], "clamped to the field"); + pointer(round, "move", 60, 25); + const shots = g.shots; + pointer(round, "down", 60, 25); + step(round, 40); + assert.ok(g.shots - shots >= 3, "held press keeps firing"); + pointer(round, "up", 0, 0); + const after = g.shots; + step(round, 30); + assert.equal(g.shots, after); + pointer(round, "down", 60, 25); + pointer(round, "cancel", 0, 0); + assert.equal(g.ptrDown, false); + // Out of the room the pack takes nothing. + assert.equal(pointer({ gallery: null, spec: { ride: null }, phase: "play" }, "move", 1, 1), false); +}); + +test("Ghoul Rush ride: the game takes pointer events, starts a round with a press and hands the ride the field's units", () => { + const fake = { width: 0, height: 0, style: {}, getContext: () => null }; + const game = ghoul.default.create({ canvas: fake, onScore: () => {} }); + assert.equal(typeof game.pointer, "function"); + assert.equal(game.pointer("move", 5, 5), false, "nothing before a round"); + assert.equal(game.pointer("down", 5, 5), true, "a press starts it"); + assert.equal(game.state, "running"); + game.resize(960, 600); + // Into the ride the way the stage select does. + game.stageSelect(); + const round = game.round; + round.select = null; + round.phase = "ready"; + assert.ok(round); +}); + +test("Ghoul Rush ride: the duck zone is a place, with a dead band and hysteresis, and a ducked Planny cannot fire", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.ret.y = DUCK_ON - 0.5; + step(round, 1); + assert.equal(g.ducked, false, "inside the dead band"); + g.ret.y = DUCK_ON + 0.2; + step(round, 1); + assert.equal(g.ducked, true); + g.ret.y = DUCK_OFF + 0.5; + step(round, 1); + assert.equal(g.ducked, true, "stays ducked until it comes back above the lower line"); + g.ret.y = DUCK_OFF - 0.5; + step(round, 1); + assert.equal(g.ducked, false); + assert.ok(DUCK_ON - DUCK_OFF >= 1 && DUCK_ON > 41.5); + g.ret.y = 46; + step(round, 1); + const shots = g.shots; + g.fireCd = 0; + g.trigger = true; + step(round, 1); + assert.equal(g.shots, shots, "no firing while ducked"); +}); + +test("Ghoul Rush ride: Space in the ride neither fires the blaster nor uses a weapon from the bag", () => { + const round = playing(); + round.bag = ["stake"]; + const game = ghoul.default.create({ canvas: { width: 0, height: 0, style: {}, getContext: () => null }, onScore: () => {} }); + assert.ok(game); + round.input.fire = true; + step(round, 30); + assert.equal(round.shots.length, 0); + assert.equal(round.heat, 0); +}); + +/* ------------------------------------------------------------ aim assist */ + +test("Ghoul Rush ride: aim assist pulls a near miss onto a target but never onto a guest or a decoy mirror", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.ents.length = 0; + g.fireCd = 0; + // A lit skull lantern: a shot 3 units off still hits it. + const lantern = { k: "lant", x: g.p + 40, y: 20, v: "skull", lit: true, lt: 0, hp: 1, delay: 0, alive: true, dying: 0, age: 0, sway: 0 }; + g.ents.push(lantern); + const cx = CAR_X + 40; + g.ret.x = cx + 3.5; + g.ret.y = 22; + g.trigger = true; + g.fireCd = 0; + step(round, 1); + assert.equal(g.hits, 1, "assist found the lantern"); + g.ents.length = 0; + // A guest next to the reticle, nothing else: no hit, no OOPS. + const guest = { k: "inno", x: g.p + 40, y: 40, v: "kid", bad: false, hp: 1, alive: true, dying: 0, age: 0 }; + g.ents.push(guest); + g.ret.x = cx + 5; + g.ret.y = 36; + g.fireCd = 0; + g.trigger = true; + step(round, 1); + assert.equal(g.innoHits, 0, "assist never hits a guest"); + assert.equal(guest.dying, 0); + g.ents.length = 0; + const mir = { k: "mir", x: g.p + 40, n: 3, reals: [1], pops: [], cracked: [false, false, false], hp: 99, alive: true, age: 0, spawned: true, done: false, shat: 0, pick: 0 }; + g.ents.push(mir); + const r = rt.mirRect(mir, 0); + g.ret.x = r.cx + 6; + g.ret.y = r.y + 10; + const hitsBefore = g.hits; + g.fireCd = 0; + g.trigger = true; + step(round, 1); + assert.equal(mir.cracked[0], false, "assist never cracks a decoy"); + assert.equal(g.hits, hitsBefore); +}); + +/* ---------------------------------------------------------- mini-bosses */ + +test("Ghoul Rush ride: the mini-bosses have their hit points and phases, and a kill gives a heart back (never above five)", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.ents.length = 0; + const swan = rt.K.mini && null; + assert.equal(swan, null); + // Make them through the scene table's own rows. + const rows = SCENES.flatMap((s) => s.spawn.filter((r) => r[0] === "mini").map((r) => r[1])); + assert.deepEqual(rows, ["swan", "spider"]); + const mkSwan = SCENES.find((s) => s.id === "tunnel").spawn.find((r) => r[0] === "mini"); + g.p = SCENES.find((s) => s.id === "tunnel").a; + g.zi = SCENES.findIndex((s) => s.id === "tunnel"); + g.sp[g.zi] = false; + rt.stepRide(0.016); + const swanE = g.ents.find((e) => e.k === "mini" && e.id === "swan"); + assert.ok(swanE, `the swan spawns with its scene (${mkSwan[2]})`); + assert.equal(rt.miniHp(swanE), 10); + assert.equal(swanE.spots.length, 1); + g.sp[SCENES.findIndex((s) => s.id === "web")] = false; + g.p = SCENES.find((s) => s.id === "web").a; + g.zi = SCENES.findIndex((s) => s.id === "web"); + rt.stepRide(0.016); + const spider = g.ents.find((e) => e.k === "mini" && e.id === "spider"); + assert.deepEqual(spider.spots.map((s) => s.hp), [7, 4]); + // Killing one gives a heart back, never above five. + round.bonusRound.hearts = 3; + for (const s of swanE.spots) s.hp = 1; + swanE.active = true; + swanE.pick = 0; + swanE.spots[0].x = 50; + swanE.spots[0].y = 20; + rt.K.mini.onHit(swanE, 50, 20); + assert.equal(round.bonusRound.hearts, 4, "a mini-boss kill heals one"); + round.bonusRound.hearts = 5; + const sp2 = g.ents.find((e) => e.k === "mini" && e.id === "spider"); + sp2.spots.forEach((s) => (s.hp = 1)); + sp2.active = true; + sp2.pick = 0; + rt.K.mini.onHit(sp2, 50, 20); + sp2.pick = 1; + rt.K.mini.onHit(sp2, 50, 20); + assert.equal(round.bonusRound.hearts, 5, "never above five"); +}); + +/* ------------------------------------------------------------ the Exit */ + +test("Ghoul Rush ride: the Exit tells first (flicker and growl, red halos), then only the red guests turn", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.ents.length = 0; + const zi = SCENES.findIndex((s) => s.id === "exit"); + const s = SCENES[zi]; + g.zi = zi; + g.p = s.a; + g.sp[zi] = false; + rt.stepRide(0.016); + const guests = g.ents.filter((e) => e.k === "inno"); + assert.ok(guests.length >= 8, "a crowd"); + const bad = guests.filter((e) => e.bad); + const good = guests.filter((e) => !e.bad); + assert.ok(bad.length > 0 && good.length > 0, "both kinds in the crowd"); + assert.equal(g.st.exit.tell, false); + g.p = s.a + 30 - s.skip + 1; + rt.stepRide(0.016); + assert.equal(g.st.exit.tell, true, "the tell"); + assert.ok(round.events.some((e) => e.type === "rideGrowl")); + assert.ok(g.floats.some((f) => /RED HALO/.test(f.s))); + assert.equal(g.st.exit.turned, false); + assert.ok(g.ents.filter((e) => e.k === "inno").length === guests.length, "nobody has turned yet"); + const ghouls = g.ents.filter((e) => e.k === "pop" && e.t === "ghoul").length; + g.p = s.a + 44 - s.skip + 1; + rt.stepRide(0.016); + assert.equal(g.st.exit.turned, true); + for (const b of bad) assert.equal(b.alive, false, "the red ones turned"); + for (const gd of good) assert.equal(gd.alive, true, "green ones never turn"); + const turned = g.ents.filter((e) => e.k === "pop" && e.t === "ghoul"); + assert.equal(turned.length - ghouls, bad.length); +}); + +/* ------------------------------------------------------ whole rides */ + +test("Ghoul Rush ride: a bot rides all twelve rooms alive in about 85 to 100 seconds and the bonus pays 5 to 9 dice", () => { + const round = playing(); + round.dice = 0; + const lives = round.lives; + const { seconds, seen } = ridden(round, aimbot); + assert.deepEqual([...seen].sort((a, b) => a - b), SCENES.map((_, i) => i), "every room is reached"); + assert.equal(round.phase, "clear", `finished (${seconds}s)`); + assert.ok(round.bonusRound.won, "alive at the end"); + assert.ok(seconds >= 85 && seconds <= 100, `${seconds}s`); + assert.ok(round.bonusRound.dice >= 5 && round.bonusRound.dice <= 9, `${round.bonusRound.dice} dice`); + assert.equal(round.dice, round.bonusRound.dice); + assert.equal(round.lives, lives); + assert.equal(round.bonusRound.result.won, true); + if (process.env.RIDE_LOG) console.log("ride", seconds, round.bonusRound.hearts, round.bonusRound.dice, round.gallery.grade, round.gallery.score); + assert.ok(round.bonusRound.cardMs >= 4000, "the cascade has its time"); + ghoul.advance(round, round.bonusRound.cardMs + 100, steady); + assert.equal(round.spec.id, "bigtop", "on to the boss"); +}); + +test("Ghoul Rush ride: a bot that does nothing dies early with no dice and the run goes on to the boss", () => { + const round = playing(); + round.dice = 2; + const lives = round.lives; + const { seconds } = ridden(round, (r) => { + r.input.fire = false; + }); + assert.ok(round.phase === "crash" || round.phase === "clear", "the hearts ran out"); + assert.ok(seconds < 60, `${seconds}s`); + ghoul.advance(round, 3000, steady); + assert.equal(round.bonusRound.hearts, 0); + assert.deepEqual(round.bonusRound.result, { won: false, dice: 0, gained: 0 }); + assert.equal(round.dice, 2); + assert.equal(round.lives, lives); + assert.equal(round.over, false); + ghoul.advance(round, 3000, steady); + assert.equal(round.spec.id, "bigtop"); +}); + +test("Ghoul Rush ride: the ride's time never costs a heart and the room clock follows it", () => { + const round = playing(); + round.timeMs = ghoul.timeFor(round.spec); + ridden(round, (r) => { + r.input.fire = false; + r.gallery.inv = 1e9; + }); + assert.ok(round.bonusRound.hearts === 5 || round.phase !== "play"); + assert.ok(round.timeMs >= 1000, "the clock holds above zero"); +}); + +test("Ghoul Rush ride: the ride draws no number from Math.random", () => { + const real = Math.random; + Math.random = () => { + throw new Error("the ride drew a random number"); + }; + try { + const round = playing(); + ridden(round, aimbot, 30); + } finally { + Math.random = real; + } +}); + +/* ------------------------------------------------------- events, voices */ + +test("Ghoul Rush ride: every event is voiced, every voice is a tone, and every cause of a lost heart has words and a sound", () => { + assert.equal(rt.EVENTS.length, rt.SOUNDS.length); + for (const type of rt.EVENTS) assert.ok(EVENT_VOICE[type], `${type} is voiced`); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(rt.EVENTS.includes(type), `${type} is the ride's`); + assert.ok(RIDE_VOICES[kind][act], `${type} has a voice`); + assert.ok(VOICES.ride[act], `${type} reaches the game's VOICES`); + } + const tones = ghoulSfx.tones || ghoulSfx.default?.tones || {}; + for (const name of Object.values(RIDE_VOICES.ride)) assert.ok(tones[name], `${name} is defined`); + for (const cause of rt.CAUSES) { + assert.ok(LOSE_WORDS[cause], `${cause} has words`); + assert.ok(LOSE_SOUNDS[cause], `${cause} has a sound`); + assert.ok(tones[LOSE_SOUNDS[cause][0]], `${cause}'s sound is defined`); + } + // Every event a ride puts on the field is one of the ride's or the game's. + const round = playing(); + ridden(round, aimbot, 40); + const known = new Set([...rt.EVENTS, "lose", "go", "room", "bonusStart", "bonusEnd", "clear", "fire", "kill", "hit", "candy", "respawn"]); + for (const e of round.events) assert.ok(known.has(e.type), `${e.type} is known`); + const causes = new Set(events(round, "lose").map((e) => e.cause)); + for (const c of causes) assert.ok(rt.CAUSES.includes(c), `${c} is a ride cause`); +}); + +test("Ghoul Rush ride: older rooms are untouched (the cart is not confused by a ride room, a plain room has no ride)", () => { + const round = ghoul.newRound(5); + round.dice = 0; + assert.equal(round.gallery ?? null, null); + for (const hook of rt.RIDE.ride) assert.equal(hook(round, 4, {}), false); +}); + +test("Ghoul Rush ride: the Barker's scene switches the music to the finale loop once, no other scene does, and it ends with the room", () => { + const music = ghoulSfx.default?.music || ghoulSfx.music || {}; + for (const name of [ghoul.ROOM_MUSIC.darkride, "ghoulBarker"]) assert.ok(music[name], `${name} is a defined track`); + const round = playing(); + assert.equal(round.gallery.track, undefined, "the ride opens on the room's own track"); + assert.equal(ghoul.dread(round), 0.7); + const switches = []; + let last; + let ms = 0; + while (round.phase === "play" && ms < 140000) { + aimbot(round); + ghoul.advance(round, 16, steady); + ms += 16; + const g = round.gallery; + if (g.track !== last) { + switches.push({ track: g.track, scene: SCENES[g.zi].id }); + last = g.track; + } + } + assert.deepEqual(switches, [{ track: "ghoulBarker", scene: "barker" }], "one switch, at the Barker"); + assert.equal(round.gallery.track, "ghoulBarker", "the end card keeps the finale"); + assert.equal(ghoul.dread(round), 0.9); + // On to the boss room: no gallery, no stray track, the room's own music. + ghoul.advance(round, round.bonusRound.cardMs + 100, steady); + assert.equal(round.spec.id, "bigtop"); + assert.ok(!round.gallery, "nothing of the ride is left"); + assert.ok(ghoul.ROOM_MUSIC.bigtop && ghoul.ROOM_MUSIC.bigtop !== "ghoulBarker"); + assert.ok(ghoul.dread(round) <= 0.9 + 1e-9 && ghoul.dread(round) >= 0.7); +}); + +test("Ghoul Rush ride: a ride lost before the Barker never plays the finale, and the next room starts clean", () => { + const round = playing(); + ridden(round, null, 140); + assert.equal(round.phase === "play", false); + assert.ok(!round.gallery?.track, "no finale was reached"); + assert.equal(ghoul.dread(round), 0.7); +}); + +/* ------------------------------------------- the picked sounds (wire-ride-sounds.cjs) */ + +// The 31 acts that had a tone but nothing playing it until the hooks went in. +const NEW_SOUNDS = [ + "carDrop", "carJump", "blasterMiss", "blasterAssist", "hurtDuck", "hurtFlicker", "waxMelt", "horseGallop", "mirrorGhoul", "jarCrack", "swanPeck", "swanSpit", "swanDie", + "bubblesRise", "bubblesHands", "widowFang", "widowDie", "spiderlingSkitter", "spiderlingDie", "batFlap", "clownHoop", "exitGate", "stallEyes", "stallJaws", + "barkerEye", "barkerSpit", "barkerBite", "barkerDie", "endCard", "endCount", "endLost", +]; +const capName = (s) => s[0].toUpperCase() + s.slice(1); +const sfxTones = () => ghoulSfx.tones || ghoulSfx.default?.tones || {}; + +// A ride played to the end: every event counted by the second of the ride it came in, and the clocks of each. +function listened(round, bot, maxSeconds = 140) { + const perSec = {}; + const at = {}; + let seen = round.events.length; + let ms = 0; + while (round.phase === "play" && ms < maxSeconds * 1000) { + if (bot) bot(round); + ghoul.advance(round, 16, steady); + ms += 16; + const clock = round.gallery ? round.gallery.clock : 0; + for (; seen < round.events.length; seen++) { + const type = round.events[seen].type; + const bucket = (perSec[type] ||= {}); + bucket[Math.floor(clock)] = (bucket[Math.floor(clock)] || 0) + 1; + (at[type] ||= []).push(clock); + } + } + return { perSec, at, seconds: ms / 1000 }; +} +// Never fires, ducks at a warning: it is hurt (the endless-lives code spares the hearts) and so sees what a perfect shot never lets happen. +function duckbot(round) { + const g = round.gallery; + round.input.fire = false; + g.ret.y = g.duckWarn > 0.15 ? 46 : 26; +} + +test("Ghoul Rush ride: all 61 picked ride sounds are real tones, and every sound name has a voice", () => { + const tones = sfxTones(); + const names = new Set(); + const overrides = []; + for (const n of rt.SOUNDS) { + const voice = RIDE_VOICES.ride[n]; + assert.ok(voice, `${n} has a voice`); + assert.ok(tones[voice], `${voice} is defined`); + if (voice !== `ghoulRide${capName(n)}`) overrides.push(n); + names.add(voice); + } + assert.equal(overrides.length, 30, "30 sounds the ride already played now play a pick"); + for (const n of NEW_SOUNDS) { + assert.ok(rt.SOUNDS.includes(n), `${n} is one of the ride's sounds`); + assert.equal(RIDE_VOICES.ride[n], `ghoulRide${capName(n)}`, `${n} plays its own tone`); + } + assert.equal(NEW_SOUNDS.length, 31); + assert.equal(new Set(rt.SOUNDS).size, rt.SOUNDS.length, "no sound is listed twice"); + assert.equal(names.size, rt.SOUNDS.length, "no two sounds share a tone"); + const picked = [...overrides.map((n) => RIDE_VOICES.ride[n]), ...NEW_SOUNDS.map((n) => RIDE_VOICES.ride[n])]; + assert.equal(new Set(picked).size, 61, "61 picked tones"); + for (const k of picked) { + const t = tones[k]; + assert.ok(Array.isArray(t.layers) && t.layers.length > 0, `${k} has layers`); + for (const l of t.layers) { + assert.equal(typeof l.type, "string", `${k} layer type`); + assert.ok(l.gain > 0 && l.gain <= 1, `${k} layer gain ${l.gain}`); + } + } +}); + +test("Ghoul Rush ride: a perfect bot and a bot that is hurt between them play every new sound, each at a sane rate", () => { + const perfect = listened(playing(), aimbot); + assert.ok(perfect.seconds >= 85 && perfect.seconds <= 100, `the perfect ride still takes ${perfect.seconds}s`); + const hurtRound = playing(); + hurtRound.infinite = true; + const hurt = listened(hurtRound, duckbot); + const played = (type) => !!(perfect.perSec[type] || hurt.perSec[type]); + // Not reachable by a bot: the jar (no scene hangs one yet, tested below) and the result cards (their own tick, tested below). + const apart = new Set(["jarCrack", "endCard", "endCount", "endLost"]); + for (const n of NEW_SOUNDS) if (!apart.has(n)) assert.ok(played(`ride${capName(n)}`), `${n} plays in a ride`); + const fresh = new Set(NEW_SOUNDS.map((n) => `ride${capName(n)}`)); + for (const run of [perfect, hurt]) { + for (const [type, buckets] of Object.entries(run.perSec)) { + if (!rt.EVENTS.includes(type)) continue; + const most = Math.max(...Object.values(buckets)); + assert.ok(most <= 14, `${type} plays ${most} times in one second`); + if (fresh.has(type)) assert.ok(most <= 6, `${type} plays ${most} times in one second`); + } + } + // The bursty ones keep their gap, so a held trigger or a wave never machine-guns. + for (const [name, gap] of [["blasterMiss", 0.12], ["bubblesRise", 0.25], ["spiderlingSkitter", 0.15], ["batFlap", 0.12]]) { + for (const run of [perfect, hurt]) { + const ts = run.at[`ride${capName(name)}`] || []; + for (let i = 1; i < ts.length; i++) assert.ok(ts[i] - ts[i - 1] >= gap - 1e-6, `${name} twice within ${gap}s`); + } + } + // Once per moment: one drop, one jump over the crest, one gate, one jaws, one boss death, two eyes. + for (const n of ["carDrop", "carJump", "exitGate", "stallJaws", "barkerDie"]) { + for (const run of [perfect, hurt]) assert.ok((run.at[`ride${capName(n)}`] || []).length <= 1, `${n} plays once`); + } + assert.equal((perfect.at.rideBarkerEye || []).length, 2, "the Barker opens his two eyes"); + assert.ok((perfect.at.rideBlasterMiss || []).length > 0 && (perfect.at.rideBlasterAssist || []).length > 0); + assert.equal((hurt.at.rideHurtFlicker || []).length, (hurt.at.rideHurt || []).length, "the flicker starts with each hit"); +}); + +test("Ghoul Rush ride: a jar plays its crack and not the generic splat, and sounds never change the game", () => { + const round = playing(); + step(round, 2); + const g = G(round); + round.events.length = 0; + const jar = { k: "lant", x: g.p + 30, y: 20, v: "jar", lit: true, lt: 0, hp: 1, alive: true, dying: 0, age: 0, delay: 0, sway: 0 }; + g.ents.push(jar); + rt.K.lant.onHit(jar, 30, 20); + assert.equal(events(round, "rideJarCrack").length, 1); + assert.equal(events(round, "rideSplat").length, 0); + // Two seeded rides play the same (the sound hooks draw nothing from the ride's stream and read no time of their own). + const run = () => { + const r = playing(); + const out = ridden(r, aimbot); + return { seconds: out.seconds, score: r.gallery.score, kills: r.gallery.kills, hearts: r.bonusRound.hearts, dice: r.bonusRound.dice }; + }; + assert.deepEqual(run(), run()); +}); + +test("Ghoul Rush ride: the title screen holds until a key or a click, however long, and that press neither fires nor steers", () => { + const game = () => { + const g = ghoul.default.create({ canvas: { width: 0, height: 0, style: {}, getContext: () => null }, onScore: () => {} }); + g.start(); + g.resize(960, 600); + g.stageSelect(); + const at = ghoul.STAGES.findIndex((s) => s.id === "carnival"); + for (let i = 0; i < at; i++) ghoul.steerSelect(g.round, 1, 0); + for (let i = 0; i < ghoul.STAGES[at].rooms.indexOf("darkride"); i++) ghoul.steerSelect(g.round, 0, 1); + ghoul.takeSelect(g.round); + return g; + }; + const started = (g) => { + g.tick(16); + assert.equal(g.round.phase, "play", "the ride is off"); + assert.equal(g.round.gallery.waiting, false); + }; + const held = (g) => { + for (let i = 0; i < 100; i++) g.tick(100); + assert.equal(g.round.phase, "ready", "still on the title after ten seconds"); + assert.equal(g.round.gallery.p, 0); + }; + // A game key, no shot from it. + const space = game(); + held(space); + space.key("action", true); + held(space); + assert.equal(space.key("action"), true); + assert.equal(space.round.input.fire, false); + assert.equal(space.round.gallery.trigger, false); + started(space); + assert.equal(space.round.gallery.shots, 0); + // An arrow, no step from it. + const arrow = game(); + held(arrow); + arrow.key("left"); + assert.equal(arrow.round.input.left, false); + started(arrow); + // Any other key the window passes on, and only while it waits. + const other = game(); + held(other); + assert.equal(other.anyKey(), true); + started(other); + assert.equal(other.anyKey(), false, "nothing to start now"); + // A click: moving only moves the aim; the press starts it, the aim where it was, no shot. + const click = game(); + held(click); + click.pointer("move", 96, 200); + held(click); + assert.ok(click.pointer("down", 480, 200)); + started(click); + assert.equal(click.round.gallery.ptrDown, false); + assert.equal(click.round.gallery.trigger, false); + assert.equal(click.round.gallery.shots, 0); + assert.ok(click.round.gallery.ret.x > 40, "the reticle is at the click"); +}); + +test("Ghoul Rush ride: the title screen names the mouse, how to duck and how to start", () => { + const round = rideRound(); + const said = []; + const noop = () => {}; + const gradient = { addColorStop: noop }; + const ctx = new Proxy({}, { + get(_, name) { + if (name === "fillText") return (text) => said.push(text); + if (name.startsWith?.("create")) return () => gradient; + if (name === "measureText") return () => ({ width: 1 }); + return noop; + }, + set: () => true, + }); + rideArt({}, noop).field(ctx, { round, g: { W: ghoul.W, HUD_H: ghoul.HUD_H, CRASH_MS: ghoul.CRASH_MS } }); + assert.ok(said.includes("TIP: USE YOUR MOUSE FOR THE BEST RESULTS")); + assert.ok(said.some((t) => /aim cursor below the dashed line/.test(t))); + assert.ok(said.includes("PRESS ANY KEY OR CLICK TO START")); + assert.ok(!said.includes("GET READY")); +}); + +test("Ghoul Rush ride: the ride photo is taken of the painted scene, not the bare board, and before its own flash goes over it", () => { + const round = playing(); + step(round, 2); + const g = G(round); + g.photoWant = true; + g.flash = 1; + g.flashCol = "#abcdef"; + let drawn = 0; + let flashed = false; + let shot = null; + const noop = () => {}; + const gradient = { addColorStop: noop }; + const canvas = { width: 960, height: 600 }; + const ctx = new Proxy({}, { + get(_, name) { + if (name === "canvas") return canvas; + if (name.startsWith?.("create")) return () => gradient; + if (name === "measureText") return () => ({ width: 1 }); + if (name === "fill" || name === "fillRect" || name === "stroke") return () => { drawn++; }; + return noop; + }, + set(_, name, value) { + if (name === "fillStyle" && value === "#abcdef") flashed = true; + return true; + }, + }); + const real = globalThis.document; + globalThis.document = { + createElement: () => ({ getContext: () => ({ drawImage: (from) => { shot = { from, drawn, flashed }; } }) }), + }; + try { + rideArt({}, {}).field(ctx, { round, g: { W: ghoul.W, HUD_H: ghoul.HUD_H, CRASH_MS: ghoul.CRASH_MS } }); + } finally { + if (real === undefined) delete globalThis.document; + else globalThis.document = real; + } + assert.ok(shot, "a photo was taken"); + assert.equal(shot.from, canvas); + assert.ok(shot.drawn > 100, `the scene was painted first (${shot.drawn} marks)`); + assert.equal(shot.flashed, false, "the flash is not in it"); + assert.equal(flashed, true, "it goes over the scene after"); + assert.equal(g.photoWant, false, "one photo"); + assert.ok(g.photo, "and it is kept for the card"); +}); + +test("Ghoul Rush ride: the result card plays its sounds once each through the picked voices, the lost card its own", () => { + const V = RIDE_VOICES.ride; + const art = rideArt({}, {}); + const heard = []; + const kit = { fx: {}, tone: (name) => heard.push(name) }; + const round = playing(); + ridden(round, aimbot); + assert.equal(round.phase, "clear"); + const b = round.bonusRound; + assert.equal(events(round, "bonusEnd")[0].ride, true, "the bonus tells the art it is the ride's"); + while (round.phase === "clear" && round.spec.id === "darkride") { + ghoul.advance(round, 16, steady); + art.tick(round, kit); + } + const count = (list, name) => list.filter((h) => h === name).length; + assert.equal(count(heard, V.endCard), 1, "the card plays once as it appears"); + assert.equal(count(heard, V.endCount), b.dice, "one counter tick for each die that lands"); + assert.equal(count(heard, V.diceLand), b.dice); + assert.equal(count(heard, V.fan), 1); + assert.equal(count(heard, V.stab), 1); + assert.equal(count(heard, V.endLost), 0); + // Lost: the hearts run out, the BONUS LOST card plays its sound once and nothing of the cleared card. + const lost = playing(); + const heard2 = []; + const kit2 = { fx: {}, tone: (name) => heard2.push(name) }; + while (lost.phase === "play") { + lost.input.fire = false; + ghoul.advance(lost, 16, steady); + art.tick(lost, kit2); + } + for (let i = 0; i < 600 && lost.spec.id === "darkride"; i++) { + ghoul.advance(lost, 16, steady); + art.tick(lost, kit2); + } + assert.equal(events(lost, "bonusEnd")[0].won, false); + assert.equal(events(lost, "bonusEnd")[0].ride, true); + assert.equal(count(heard2, V.endLost), 1); + assert.equal(count(heard2, V.endCard) + count(heard2, V.fan), 0); +}); diff --git a/scripts/test-web-console-activities-ghoul-sanatorium.mjs b/scripts/test-web-console-activities-ghoul-sanatorium.mjs new file mode 100644 index 0000000..a56cc1e --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-sanatorium.mjs @@ -0,0 +1,1341 @@ +// Web console tests, Ghoul Rush's Blackmoor Sanatorium stage: its four rooms, orderlies that grab and throw you (and cost no life), gurneys that park, rattle and roll, flickers you can only hit and be hurt by when the lamps go out, specimen bloaters and their formaldehyde, the lamps' flicker, Smelling Salts and the Bone Saw (found only here), and the Night Matron, whose lantern cone builds heat, is stopped by the medicine cabinets and cannot reach the boards, with her syringes, arms and rage. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as sn from "../src/web-console/public/activities/ghoul-sanatorium.js"; +import { LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-sanatorium-draw.js"; +import { PILL_WORDS, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +const events = (round, type) => round.events.filter((e) => e.type === type); +const ROOM_IDS = ["admissions", "baths", "theater", "ward"]; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Sanatorium's room `id`, reached the way play reaches it, +// nothing woken: every spawner spent, the horde held back, the lamps far off. +function sanRound(id) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["sanatorium"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.dark = false; + if (round.twist) round.twist.next = 1e9; + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, steady); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +function until(round, done, ms = 4000) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, steady); +} + +// Runs `ms`, returning each event of `type` as [the round's clock, event]. +function log(round, ms, type, random = steady) { + const got = []; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + for (const e of round.events) if (e.type === type) got.push([round.clock, e]); + round.events.length = 0; + } + return got; +} + +// A bolt arriving from the left at height `y` on the monster `m`. +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +const heard = (e, extra = {}) => { + const played = []; + const floats = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: (x, y, text) => floats.push(text), ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played, floats }; +}; + +test("Ghoul Rush's Blackmoor Sanatorium is a stage of three rooms and the Night Ward, its monsters and boss joined to the game's, with two power-ups of its own and a place for each kind", () => { + const st = ghoul.stageById("sanatorium"); + assert.deepEqual(st.rooms, ROOM_IDS); + assert.equal(st.boss, "matron"); + assert.equal(st.title, "Blackmoor Sanatorium"); + assert.equal(st.sub, "Visiting hours ended in 1912"); + for (const kind of Object.keys(sn.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], sn.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.matron, sn.BOSSES.matron); + assert.equal(sn.BOSSES.matron.sub, "Stay out of her lantern light"); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [admissions, baths, theater, ward] = st.rooms.map((id) => ghoul.roomById(id)); + const returning = ["zombie", "crawl", "ghost", "spitter"]; + for (const room of [admissions, baths, theater]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + assert.ok(room.items.some((i) => i[0] === "salts") && room.items.some((i) => i[0] === "saw"), `${room.id}: both power-ups of the stage`); + assert.ok(room.spawns.some((s) => s[0] in sn.MONSTERS), `${room.id}: some of the new monsters`); + assert.ok(room.spawns.some((s) => returning.includes(s[0])), `${room.id}: some returning ones`); + } + assert.ok(admissions.spawns.some((s) => s[0] === "orderly") && admissions.spawns.some((s) => s[0] === "gurney"), "orderlies and gurneys first met in Admissions"); + assert.ok(baths.spawns.some((s) => s[0] === "specimen") && baths.spawns.some((s) => s[0] === "flicker"), "specimens and flickers in the Baths"); + for (const kind of Object.keys(sn.MONSTERS)) assert.ok(theater.spawns.some((s) => s[0] === kind), `the Theater has ${kind}`); + assert.equal(ward.boss, "matron"); + assert.equal(ward.horde.length, 0); + // Tubs as low pits to hop; the Baths and the Theater flicker, the Theater more often. + assert.ok(baths.ground.some((g, i) => i && g[0] - baths.ground[i - 1][1] > 0), "pits"); + assert.deepEqual([admissions.flicker, baths.flicker, theater.flicker, ward.flicker], [0, 9000, 6500, 0]); + assert.ok(admissions.spawns.length <= baths.spawns.length && baths.spawns.length <= theater.spawns.length); + assert.ok(admissions.hordeMs > baths.hordeMs && baths.hordeMs > theater.hordeMs, "harder in order"); + // The ward: two raised floor blocks (the cabinets) and boards above the beam's reach. + const cabinets = ward.ground.filter((g) => g[2] > 6); + assert.equal(cabinets.length, 2); + const lantern = 6 + sn.BEAM_ORIGIN_Y; + const reach = lantern + Math.tan(sn.BEAM_HALF - sn.DEP_MIN) * sn.BEAM_RANGE; + assert.ok(ward.shelves.some((s) => s[2] + ghoul.HIT_H / 2 > reach + 2), "boards above the beam's reach"); + assert.ok(ghoul.MONSTERS.orderly.hp === 10 && ghoul.MONSTERS.gurney.hp === 5 && ghoul.MONSTERS.flicker.hp === 2); +}); + +/* ---------------------------------------------------------- the orderly */ + +test("Ghoul Rush's orderly walks at you, reaches within 3 of its edge for 450 ms, grabs for 600 ms and throws you 14 back and up, and the throw costs no life", () => { + const round = sanRound("admissions"); + standAt(round, 40); + const o = put(round, "orderly", 60); + assert.equal(o.act, "walk"); + assert.equal(ghoul.MONSTERS.orderly.stomp, false); + run(round, 400); + assert.ok(o.x < 60, "it walks at you"); + assert.equal(events(round, "orderlyReach").length, 0); + // Close: it reaches. + Object.assign(o, { x: 44, act: "walk" }); + run(round, 8); + assert.equal(o.act, "reach"); + assert.equal(events(round, "orderlyReach").length, 1); + const lives = round.lives; + const reached = round.clock; + until(round, () => o.act === "hold", 800); + assert.ok(Math.abs(round.clock - reached - sn.ORDERLY_REACH_MS) < 60, `450 ms of reach (${round.clock - reached})`); + assert.equal(events(round, "orderlyGrab").length, 1); + // Held: no key moves you. + const held = round.clock; + round.input.right = true; + round.input.jump = ghoul.JUMP_BUFFER_MS; + run(round, 300); + assert.equal(round.you.x, 40, "you cannot move"); + assert.equal(round.you.y, 6); + round.input.right = false; + until(round, () => events(round, "orderlyThrow").length > 0, 1000); + assert.ok(Math.abs(round.clock - held - sn.ORDERLY_HOLD_MS) < 60, `600 ms of hold (${round.clock - held})`); + // Thrown back (away from it) and up. + let top = 6; + until(round, () => { + top = Math.max(top, round.you.y); + return round.you.y <= 6 && round.you.state === "run"; + }, 1200); + until(round, () => round.you.state === "run", 1200); + assert.ok(top > 12, `up (${top.toFixed(1)})`); + assert.ok(Math.abs(round.you.x - (40 - sn.ORDERLY_THROW_BACK)) < 1.5, `about 14 back (${round.you.x.toFixed(1)})`); + assert.equal(events(round, "lose").length, 0, "no life lost"); + assert.equal(round.lives, lives); + assert.equal(round.you.out, 0); + // It rests, then walks at you again. + assert.equal(o.act, "rest"); + until(round, () => o.act === "walk", 2000); + assert.equal(o.act, "walk"); +}); + +test("Ghoul Rush's orderly never hurts by touch, can be shot (10 bolts), and a jump out of its reach escapes the grab", () => { + const round = sanRound("admissions"); + standAt(round, 40); + const o = put(round, "orderly", 40, { act: "rest", wait: 1e9 }); + run(round, 400); + assert.equal(events(round, "lose").length, 0, "standing inside it costs nothing"); + assert.equal(ghoul.solid(o), true, "it can be hit"); + for (let k = 0; k < 4; k++) { + bolt(round, o, 8); + ghoul.advance(round, 4, steady); + } + assert.equal(o.hp, 6, "four bolts, four hp"); + // In the air when the reach ends, you are out of its grasp. + const air = sanRound("admissions"); + standAt(air, 40); + const a = put(air, "orderly", 46, { act: "reach", wait: 12, dir: -1 }); + Object.assign(air.you, { y: 13, state: "air", vy: 0 }); + run(air, 16); + assert.equal(a.act, "rest", "it missed"); + assert.equal(events(air, "orderlyGrab").length, 0); + // Out of its grasp's width, too. + const far = sanRound("admissions"); + standAt(far, 20); + const f = put(far, "orderly", 33, { act: "reach", wait: 12, dir: -1 }); + run(far, 16); + assert.equal(f.act, "rest"); + // On a bench above it, it does not even reach. + const bench = sanRound("admissions"); + standAt(bench, 44, 1, 11, 0); + const b = put(bench, "orderly", 48); + run(bench, 100); + assert.equal(b.act, "walk"); +}); + +test("Ghoul Rush's throw costs no life, but where you land can: a pit does", () => { + const round = sanRound("baths"); + standAt(round, 116); + put(round, "orderly", 121, { act: "reach", wait: 4, dir: -1 }); + const lives = round.lives; + until(round, () => events(round, "lose").length > 0, 3000); + assert.equal(events(round, "orderlyThrow").length, 1); + assert.equal(events(round, "lose")[0]?.cause, "pit", "the pit took it"); + assert.equal(round.lives, lives - 1); +}); + +test("Smelling Salts break an orderly's grab at once: no throw, you are free, and it staggers", () => { + const round = sanRound("admissions"); + standAt(round, 40); + const o = put(round, "orderly", 44, { act: "reach", wait: 4, dir: -1 }); + until(round, () => o.act === "hold", 100); + assert.equal(o.act, "hold"); + ghoul.applyPower(round, "salts"); + run(round, 8); + assert.equal(o.act, "rest"); + assert.equal(events(round, "saltsBreak").length, 1); + assert.equal(events(round, "orderlyThrow").length, 0, "no throw"); + assert.equal(round.you.heldMs <= 0, true, "free"); + round.input.right = true; + run(round, 100); + round.input.right = false; + assert.ok(round.you.x > 42, "you run again"); + // With the Salts already in hand, the grab breaks as soon as it is made. + const hold = sanRound("admissions"); + standAt(hold, 40); + ghoul.applyPower(hold, "salts"); + const p = put(hold, "orderly", 44, { act: "reach", wait: 4, dir: -1 }); + run(hold, 40); + assert.equal(p.act, "rest"); + assert.equal(events(hold, "orderlyThrow").length, 0); +}); + +/* ----------------------------------------------------------- the gurney */ + +test("Ghoul Rush's gurney: parked it is harmless and a floor; within 18 it rattles 500 ms, then rolls at you fast to a wall, rests 1.5 s and rolls back", () => { + const round = sanRound("admissions"); + standAt(round, 20); + const g = put(round, "gurney", 120); + run(round, 100); + assert.equal(g.act, "parked", "far off"); + assert.equal(events(round, "gurneyRattle").length, 0); + // Standing on top of it: the highest floor under you. + assert.equal(g.act, "parked"); + assert.equal(ghoul.solid(g), true, "solid to bolts"); + standAt(round, 120, 1, 6 + g.h + 0.6); + round.you.safeMs = 0; + Object.assign(round.you, { state: "air", vy: -10 }); + until(round, () => round.you.state === "run", 400); + assert.equal(round.you.y, 6 + g.h, "you stand on its top"); + assert.equal(events(round, "lose").length, 0, "a parked gurney hurts nothing"); + // Within 18 it rattles. + assert.equal(g.act, "rattle"); + assert.equal(events(round, "gurneyRattle").length, 1); + const rattled = round.clock; + until(round, () => g.act === "roll", 800); + assert.ok(Math.abs(round.clock - rattled - sn.GURNEY_RATTLE_MS) < 60, `500 ms of rattle (${round.clock - rattled})`); + assert.equal(events(round, "gurneyRoll").length, 1); + // Rolling it is no floor: you come down to the real one. + round.you.safeMs = 1e9; + run(round, 20); + assert.equal(round.you.y, 6, "back on the floor"); + assert.equal(events(round, "lose").length, 0); + // It rolls fast at you (the way you were when it started) to the wall. + const x0 = g.x; + standAt(round, 20); + round.you.safeMs = 1e9; + const dir = g.dir; + run(round, 500); + assert.ok(Math.abs(g.x - x0) > 20, `fast (${(g.x - x0).toFixed(1)} in 0.5 s)`); + assert.equal(Math.sign(g.x - x0), dir); + until(round, () => g.act === "rest", 3000); + assert.equal(g.act, "rest", "stopped at the wall"); + assert.equal(events(round, "gurneyRest").length, 1); + assert.ok(g.x > 3 && g.x < 8, `against the room's end (${g.x.toFixed(1)})`); + // After 1.5 s it rolls back at you, with you in range. + const rested = round.clock; + standAt(round, 20); + round.you.safeMs = 1e9; + round.events.length = 0; + until(round, () => g.act === "roll", 2500); + assert.ok(Math.abs(round.clock - rested - sn.GURNEY_REST_MS) < 80, `rests 1.5 s (${round.clock - rested})`); + assert.equal(g.dir, 1, "back at you"); + assert.equal(events(round, "gurneyRoll").length, 1); +}); + +test("Ghoul Rush's gurney hurts only while rolling, parks again when you are far off, stops at an edge, and a rolling one is no floor", () => { + const roll = sanRound("admissions"); + standAt(roll, 110); + const g = put(roll, "gurney", 120, { act: "roll", dir: -1 }); + run(roll, 200); + assert.equal(events(roll, "lose")[0]?.cause, "gurney"); + const rest = sanRound("admissions"); + standAt(rest, 120); + put(rest, "gurney", 120, { act: "rest", wait: 1e9 }); + run(rest, 300); + assert.equal(events(rest, "lose").length, 0, "resting is harmless"); + const rattle = sanRound("admissions"); + standAt(rattle, 120); + put(rattle, "gurney", 120, { act: "rattle", wait: 1e9 }); + run(rattle, 300); + assert.equal(events(rattle, "lose").length, 0, "rattling is harmless"); + // Far from you after its rest, it parks again. + const park = sanRound("admissions"); + standAt(park, 20); + const p = put(park, "gurney", 120, { act: "rest", wait: 4 }); + run(park, 40); + assert.equal(p.act, "parked"); + // An edge stops it: the Baths' tubs. + const edge = sanRound("baths"); + standAt(edge, 110); + edge.you.safeMs = 1e9; + const e = put(edge, "gurney", 60, { act: "roll", dir: 1 }); + until(edge, () => e.act === "rest", 3000); + assert.equal(e.act, "rest"); + assert.ok(e.x + e.w / 2 <= 100.01 && e.x > 90, `at the tub's edge (${e.x.toFixed(1)})`); + // A rolling gurney is no floor to land on. + const air = sanRound("admissions"); + const r = put(air, "gurney", 120, { act: "roll", dir: 1 }); + standAt(air, 120, 1, 6 + r.h + 3); + Object.assign(air.you, { state: "air", vy: -10, safeMs: 1e9 }); + until(air, () => air.you.state === "run", 800); + assert.equal(air.you.y, 6); +}); + +test("Ghoul Rush's gurney takes 5 bolts, or one under the Bone Saw", () => { + const round = sanRound("admissions"); + standAt(round, 20); + round.you.safeMs = 1e9; + const g = put(round, "gurney", 60); + for (let k = 0; k < 4; k++) { + bolt(round, g, 7.5); + ghoul.advance(round, 4, steady); + } + assert.equal(g.hp, 1); + bolt(round, g, 7.5); + ghoul.advance(round, 4, steady); + assert.equal(g.dead, true); + const saw = sanRound("admissions"); + standAt(saw, 20); + saw.you.safeMs = 1e9; + ghoul.applyPower(saw, "saw"); + const h = put(saw, "gurney", 60); + bolt(saw, h, 7.5); + ghoul.advance(saw, 4, steady); + ghoul.advance(saw, 4, steady); + assert.equal(h.dead, true, "one hit"); + assert.equal(events(saw, "kill").length, 1); + assert.equal(events(saw, "kill")[0].how, "saw"); + assert.equal(events(saw, "kill")[0].kind, "gurney"); +}); + +/* ---------------------------------------------------------- the flicker */ + +test("Ghoul Rush's flicker is unseen with the lamps on: bolts go through it, stomps and touch do nothing, and it creeps slowly at you", () => { + const round = sanRound("baths"); + standAt(round, 20); + round.you.safeMs = 0; + const f = put(round, "flicker", 60); + run(round, 8); + assert.equal(f.unseen, true); + assert.equal(ghoul.solid(f), false); + assert.equal(f.act, "creep"); + bolt(round, f, 8); + run(round, 40); + assert.equal(f.hp, f.max, "the bolt went through"); + const x0 = f.x; + run(round, 1000); + assert.ok(x0 - f.x > 4 && x0 - f.x < 12, `creeps slowly (${(x0 - f.x).toFixed(1)} in a second)`); + // On top of you, it does nothing; landing on it is no stomp. + Object.assign(f, { x: round.you.x }); + run(round, 300); + assert.equal(events(round, "lose").length, 0); + standAt(round, 20, 1, 20); + Object.assign(round.you, { state: "air", vy: -20 }); + Object.assign(f, { x: 20, y: 6 }); + until(round, () => round.you.y <= 6.5, 800); + assert.equal(events(round, "stomp").length, 0); + assert.equal(f.dead, undefined); +}); + +test("Ghoul Rush's flicker shows in a blackout: it can be shot (2 bolts), stomped and hurts, lunging fast", () => { + const round = sanRound("baths"); + standAt(round, 20); + round.you.safeMs = 1e9; + const f = put(round, "flicker", 80); + round.blackout = true; + run(round, 8); + assert.equal(f.unseen, false); + assert.equal(ghoul.solid(f), true); + assert.equal(f.act, "lunge"); + assert.equal(events(round, "flickerShow").length, 1, "told once as it shows"); + const x0 = f.x; + run(round, 400); + // FLICKER_LUNGE (22 a second) is three times its unseen creep (7). + assert.ok(x0 - f.x > 6, `lunges fast (${(x0 - f.x).toFixed(1)} in 0.4 s)`); + assert.equal(events(round, "flickerShow").length, 1); + Object.assign(f, { x: 60 }); + bolt(round, f, 8); + run(round, 12); + assert.equal(f.hp, 1); + // It hurts you now. + round.you.safeMs = 0; + Object.assign(f, { x: round.you.x + 1, hp: 2 }); + run(round, 12); + assert.equal(events(round, "lose")[0]?.cause, "flicker"); + // Stomped from above. + const top = sanRound("baths"); + top.blackout = true; + const s = put(top, "flicker", 60); + standAt(top, 60, 1, 6 + s.h + 3); + Object.assign(top.you, { state: "air", vy: -20, safeMs: 1e9 }); + until(top, () => events(top, "stomp").length > 0, 600); + assert.equal(events(top, "stomp").length, 1); + assert.equal(s.dead, true); +}); + +test("Ghoul Rush's flicker shows in the Lantern's light (34) and the Salts' glow (22), where a bolt does double", () => { + const lit = (power, d) => { + const round = sanRound("baths"); + standAt(round, 20); + round.you.safeMs = 1e9; + if (power) ghoul.applyPower(round, power); + const f = put(round, "flicker", 20 + d); + run(round, 8); + return { round, f }; + }; + assert.equal(lit("lantern", sn.LANTERN_LIGHT - 2).f.unseen, false, "in the Lantern's light"); + assert.equal(lit("lantern", sn.LANTERN_LIGHT + 4).f.unseen, true, "beyond it"); + assert.equal(lit("salts", sn.SALTS_GLOW - 2).f.unseen, false, "in the Salts' glow"); + assert.equal(lit("salts", sn.SALTS_GLOW + 4).f.unseen, true, "beyond it"); + assert.equal(lit(null, 5).f.unseen, true, "lit but unaided"); + const { round, f } = lit("salts", 15); + bolt(round, f, 8); + run(round, 12); + assert.equal(f.dead, true, "double damage kills a 2 hp flicker with one bolt"); + const plain = lit("lantern", 15); + bolt(plain.round, plain.f, 8); + run(plain.round, 12); + assert.equal(plain.f.hp, 1, "one without the Salts"); +}); + +/* ------------------------------------------------------------- the lamps */ + +test("Ghoul Rush's lamps stutter for 700 ms, go out for 1.8 s and come on again: the first at 0.6 of a period, then every period; only the flicker rooms do", () => { + for (const [id, period] of [["baths", 9000], ["theater", 6500]]) { + const round = sanRound(id); + round.twist = null; + standAt(round, 20); + round.you.safeMs = 1e9; + const warns = []; + const outs = []; + const ons = []; + for (let t = 0; t < period * 2.3; t += 4) { + ghoul.advance(round, 4, steady); + round.you.safeMs = 1e9; + for (const e of round.events) { + if (e.type === "flickerWarn") warns.push(round.clock); + if (e.type === "lightsOut") outs.push(round.clock); + if (e.type === "lightsOn") ons.push(round.clock); + } + round.events.length = 0; + // The blackout flag is on exactly between lightsOut and lightsOn. + assert.equal(round.blackout, outs.length > ons.length, `${id}: blackout between out and on`); + round.monsters.length = 0; + } + assert.ok(Math.abs(warns[0] - period * sn.FLICKER_FIRST) < 60, `${id}: first stutter at ${warns[0]}`); + assert.ok(Math.abs(warns[1] - warns[0] - period) < 60, `${id}: then every ${period} (${warns[1] - warns[0]})`); + assert.ok(Math.abs(outs[0] - warns[0] - sn.STUTTER_MS) < 60, `${id}: out after the stutter`); + assert.ok(Math.abs(ons[0] - outs[0] - sn.BLACKOUT_MS) < 60, `${id}: out for 1.8 s`); + assert.equal(sn.STUTTER_MS, 700); + assert.equal(sn.BLACKOUT_MS, 1800); + assert.ok(round.twist && ["calm", "stutter", "out"].includes(round.twist.stage)); + } + for (const id of ["admissions"]) { + const round = sanRound(id); + standAt(round, 20); + round.you.safeMs = 1e9; + run(round, 14000); + assert.equal(round.blackout, false, `${id}: no lamps`); + assert.equal(events(round, "lightsOut").length, 0); + assert.equal(round.twist, null); + } + // The stutter alone leaves the lights on and flickers unseen; a new life starts the lamps over. + const round = sanRound("baths"); + round.twist = null; + standAt(round, 20); + round.you.safeMs = 1e9; + const f = put(round, "flicker", 60); + until(round, () => round.twist?.stage === "stutter", 7000); + assert.equal(round.blackout, false); + assert.equal(f.unseen, true); + until(round, () => round.blackout, 1000); + run(round, 8); + assert.equal(f.unseen, false, "shown in the blackout"); + ghoul.lose(round, "zombie"); + run(round, ghoul.CRASH_MS + ghoul.READY_MS + 40); + assert.equal(round.blackout, false); + assert.ok(round.twist.stage === "calm" && round.twist.next > 9000 * sn.FLICKER_FIRST - 200, "the lamps start over with the room"); +}); + +/* ---------------------------------------------------------- the specimen */ + +test("Ghoul Rush's specimen bloater swells, lobs a jar that breaks into a small puddle of formaldehyde (live 2.5 s, jumped it is harmless), and the puddle burns you", () => { + const round = sanRound("baths"); + standAt(round, 20); + round.you.safeMs = 1e9; + const s = put(round, "specimen", 60, { throwIn: 0 }); + run(round, 8); + assert.equal(events(round, "jarWind").length, 1); + assert.equal(round.bones.length, 0, "it swells first"); + run(round, sn.JAR_WIND_MS + 8); + const jar = round.bones.find((b) => b.kind === "jar"); + assert.ok(jar, "a jar in the air"); + assert.equal(jar.cause, "formaldehyde"); + assert.ok(s.x <= 60); + until(round, () => events(round, "jarBreak").length > 0, 3000); + assert.equal(events(round, "jarBreak").length, 1); + const puddle = round.hazards.find((h) => h.kind === "formaldehyde"); + assert.ok(puddle, "a puddle"); + assert.equal(puddle.w, sn.FORMALDEHYDE_W); + assert.ok(puddle.live > sn.FORMALDEHYDE_MS - 200 && puddle.live <= sn.FORMALDEHYDE_MS); + assert.equal(round.bones.length, 0); + // It burns you where you stand; jumped, it does not; and it is gone after 2.5 s. + const jumped = sanRound("baths"); + jumped.hazards.push({ ...puddle }); + standAt(jumped, puddle.x, 1, puddle.y + 2); + Object.assign(jumped.you, { state: "air", vy: 0 }); + jumped.you.safeMs = 0; + run(jumped, 12); + assert.equal(events(jumped, "lose").length, 0, "over it, you are safe"); + const burned = sanRound("baths"); + burned.hazards.push({ ...puddle }); + standAt(burned, puddle.x); + run(burned, 12); + assert.equal(events(burned, "lose")[0]?.cause, "formaldehyde"); + const gone = sanRound("baths"); + gone.hazards.push({ ...puddle }); + run(gone, sn.FORMALDEHYDE_MS - 100); + assert.equal(gone.hazards.length, 1); + run(gone, 140); + assert.equal(gone.hazards.length, 0); + // A jar that lands on you in the air is a hit too, and one shot down breaks nothing. + const hit = sanRound("baths"); + standAt(hit, 40); + const b = hit.bones; + b.push({ id: 9e9, kind: "jar", cause: "formaldehyde", x: 40, y: 8, vx: 0, vy: 0, spin: 0, life: 4000 }); + run(hit, 12); + assert.equal(events(hit, "lose")[0]?.cause, "formaldehyde"); + const shot = sanRound("baths"); + standAt(shot, 20); + shot.bones.push({ id: 9e9 + 1, kind: "jar", cause: "formaldehyde", x: 40, y: 8.4, vx: 0, vy: 20, spin: 0, life: 4000 }); + shot.shots.push({ x: 36, y: 8.4, vx: 80, vy: 0, gone: 0 }); + run(shot, 40); + assert.equal(shot.bones.length, 0); + assert.equal(events(shot, "bone")[0]?.kind, "jar"); + assert.equal(events(shot, "jarBreak").length, 0); + // Never more than FORMALDEHYDE_CAP about; shot to nothing it breaks its own jar. + const many = sanRound("baths"); + for (let k = 0; k < 8; k++) many.bones.push({ id: 9e9 + 10 + k, kind: "jar", x: 50 + k * 6, y: 6, vx: 0, vy: -5, spin: 0, life: 4000 }); + run(many, 40); + assert.ok(many.hazards.filter((h) => h.kind === "formaldehyde").length <= sn.FORMALDEHYDE_CAP); + const die = sanRound("baths"); + standAt(die, 20); + die.you.safeMs = 1e9; + const sp = put(die, "specimen", 60, { throwIn: 1e9 }); + sp.hp = 1; + bolt(die, sp, 8); + run(die, 12); + assert.equal(sp.dead, true); + assert.equal(events(die, "jarBreak")[0]?.how, "death"); + assert.equal(die.hazards.filter((h) => h.kind === "formaldehyde").length, 1); +}); + +/* ------------------------------------------------------------- power-ups */ + +test("Smelling Salts and the Bone Saw are found only in the Sanatorium: no drop elsewhere ever picks them, a placed one elsewhere is swapped, and each lasts 10 s", () => { + for (const kind of ["salts", "saw"]) { + assert.equal(ghoul.POWERS[kind].stage, "sanatorium"); + assert.equal(ghoul.POWERS[kind].ms, 10000); + assert.ok(ghoul.TIMED.includes(kind), "a timed power-up, shown in the pill"); + const home = sanRound("admissions"); + assert.equal(ghoul.powerHere(home, kind), true); + assert.ok(home.loot.includes(kind), "placed ones stay"); + const hall = ghoul.newRound(3); + hall.dice = 0; + assert.equal(ghoul.powerHere(hall, kind), false); + const away = sanRound("admissions"); + away.stage = "chapel"; + assert.equal(ghoul.powerHere(away, kind), false); + const random = ghoul.seeded(9); + const picked = new Set(); + for (let k = 0; k < 400; k++) { + picked.add(pickPower(random, home)); + assert.notEqual(pickPower(random, away), kind); + assert.notEqual(pickPower(random, hall), kind); + assert.notEqual(pickPower(random, hall, "", true), kind); + } + assert.ok(picked.has(kind), "drops here can be it"); + for (const base of ghoul.ROOMS) if (!ROOM_IDS.includes(base.id)) assert.ok(!base.items.some((i) => i[0] === kind), `${base.id} places none`); + const timed = sanRound("admissions"); + ghoul.applyPower(timed, kind); + assert.equal(timed.effects[kind], 10000); + ghoul.advance(timed, ghoul.POWERS[kind].ms + 8, steady); + assert.equal(timed.effects[kind], 0); + } + assert.equal(PILL_WORDS.salts, "SALTS"); + assert.equal(PILL_WORDS.saw, "SAW"); + // A placed one in a room elsewhere would be swapped out for another power-up. + const elsewhere = ghoul.newRound(3); + elsewhere.dice = 0; + assert.ok(!elsewhere.loot.includes("salts") && !elsewhere.loot.includes("saw")); +}); + +test("The Bone Saw's bolts pierce every monster in a line", () => { + const line = (saw) => { + const round = sanRound("admissions"); + standAt(round, 20); + round.you.safeMs = 1e9; + if (saw) ghoul.applyPower(round, "saw"); + const zs = [50, 56, 62].map((x) => put(round, "zombie", x)); + bolt(round, zs[0], 8.4); + run(round, 300); + return zs.map((z) => z.max - z.hp); + }; + assert.deepEqual(line(false), [1, 0, 0], "one bolt, one zombie"); + assert.deepEqual(line(true), [1, 1, 1], "one bolt, all three"); +}); + +/* ------------------------------------------------------------ the Matron */ + +// The ward, you in the arena, the Matron awake and at her place: her attacks +// held off, her beam still. +function wardFight() { + const round = sanRound("ward"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + ghoul.advance(round, 8, steady); + round.you.safeMs = 1e9; + round.events.length = 0; + const home = round.spec.length - sn.HOME_FROM_END; + until(round, () => round.boss.x === home, 4000); + hold(round); + return round; +} + +function hold(round) { + const b = round.boss; + b.act = "idle"; + b.wait = 1e9; +} + +// Points the beam's axis at the depression `dep` below level (sweeping stops being the question). +const aim = (round, dep) => { + const b = round.boss; + dep = Math.min(sn.DEP_MAX, Math.max(sn.DEP_MIN, dep)); + b.phase = Math.asin((dep - (sn.DEP_MIN + sn.DEP_MAX) / 2) / ((sn.DEP_MAX - sn.DEP_MIN) / 2)); +}; +// The depression of the line from the lantern to Planny's middle at x. +const depTo = (round, x) => { + const b = round.boss; + const beam = b.beam; + return Math.atan2(beam.y - (round.you.y + ghoul.HIT_H / 2), beam.x - x); +}; +// Runs `ms` with the beam held on the depression for Planny at x. +function hotRun(round, ms, dep) { + const got = []; + for (let t = 0; t < ms && round.phase === "play"; t += 4) { + aim(round, dep); + ghoul.advance(round, 4, steady); + for (const e of round.events) got.push(e); + round.events.length = 0; + hold(round); + } + return got; +} + +test("The Night Matron walks to her place and holds her lantern: a cone sweeping down across the ward and back, 0.17 either side of its axis, 76 long", () => { + const round = sanRound("ward"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + const b = round.boss; + assert.equal(b.kind, "matron"); + assert.equal(b.state, "intro"); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(b.state, "fight"); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + const home = round.spec.length - sn.HOME_FROM_END; + assert.notEqual(b.x, home, "she is not there yet"); + until(round, () => b.x === home, 4000); + assert.equal(b.x, home); + assert.equal(b.dir, -1, "facing you"); + assert.equal(sn.BOSSES.matron.hp, 100); + assert.equal(sn.BOSSES.matron.points, 3500); + hold(round); + ghoul.advance(round, 4, steady); + // The beam: where it starts and how it points. + const beam = b.beam; + assert.ok(Math.abs(beam.x - (b.x - sn.BEAM_ORIGIN_X)) < 1e-9 && Math.abs(beam.y - (b.y + sn.BEAM_ORIGIN_Y)) < 1e-9, "from her lantern"); + assert.equal(beam.half, sn.BEAM_HALF); + assert.equal(beam.range, sn.BEAM_RANGE); + // Over a sweep it goes from nearly level to steep and back, down and ahead (left) always. + let lo = 9; + let hi = 0; + const sweeps = []; + for (let t = 0; t < sn.BEAM_SWEEP_MS * 1.1; t += 4) { + ghoul.advance(round, 4, steady); + hold(round); + round.you.safeMs = 1e9; + lo = Math.min(lo, beam.dep); + hi = Math.max(hi, beam.dep); + assert.ok(Math.cos(beam.angle) < 0 && Math.sin(beam.angle) < 0, "down and to the left"); + assert.ok(Math.abs(beam.angle - (Math.PI + beam.dep)) < 1e-9); + if (t % 500 === 0) sweeps.push(beam.dep); + } + assert.ok(lo < sn.DEP_MIN + 0.02 && hi > sn.DEP_MAX - 0.02, `a full sweep (${lo.toFixed(2)} to ${hi.toFixed(2)})`); + assert.ok(sweeps.some((d) => d > 0.7) && sweeps.some((d) => d < 0.3)); + // It points at the floor around her feet when steep and far down the ward when shallow. + assert.equal(sn.inBeam({ x: 0, y: 10, angle: Math.PI + 0.5, half: 0.17, range: 76 }, -8, 6), true); + assert.equal(sn.inBeam({ x: 0, y: 10, angle: Math.PI + 0.5, half: 0.17, range: 76 }, -8, 8), false); + assert.equal(sn.inBeam({ x: 0, y: 10, angle: Math.PI + 0.5, half: 0.17, range: 76 }, 8, 6), false, "behind her"); + assert.equal(sn.inBeam({ x: 0, y: 10, angle: Math.PI + 0.5, half: 0.17, range: 5 }, -8, 6), false, "out of range"); +}); + +test("The Matron's lantern heats you in its light: 600 ms of it costs a life (cause lantern), Planny's heat shows on the boss and cools out of it", () => { + const round = wardFight(); + const b = round.boss; + const x = 176; + standAt(round, x); + round.you.safeMs = 0; + const dep = depTo(round, x); + aim(round, dep); + const got = hotRun(round, 300, dep); + assert.equal(b.beam.on, true, "in the cone"); + assert.ok(b.heat > 0.4 && b.heat < 0.6, `half hot after half the time (${b.heat.toFixed(2)})`); + assert.equal(got.filter((e) => e.type === "lose").length, 0); + // Out of the light it cools, in a second. + aim(round, sn.DEP_MAX); + const cool = b.heat; + hotRun(round, 400, sn.DEP_MAX + 0.0); + assert.equal(b.beam.on, false); + assert.ok(b.heat < cool - 0.3, `cooling (${b.heat.toFixed(2)})`); + hotRun(round, 700, sn.DEP_MAX); + assert.equal(b.heat, 0); + // In it for 600 ms: a life. + const t0 = round.clock; + const lost = hotRun(round, 1000, dep).filter((e) => e.type === "lose"); + assert.equal(lost.length, 1); + assert.equal(lost[0].cause, "lantern"); + assert.ok(round.clock - t0 >= sn.HEAT_MS - 12 && round.clock - t0 <= sn.HEAT_MS + 100, `${round.clock - t0} ms`); + assert.equal(sn.HEAT_MS, 600); +}); + +test("A medicine cabinet between her lantern and you is cover: no heat, and a safe jump over it is not", () => { + const round = wardFight(); + const b = round.boss; + const cabinets = round.spec.ground.filter((g) => g[2] > 6); + assert.deepEqual(b.cabinets, cabinets.map((c) => [c[0], c[1], c[2]]), "the boss shows them to the art"); + // Right behind the near cabinet (to its left), the cone cannot reach you however it points. + const near = cabinets[1]; + const hide = near[0] - 5; + standAt(round, hide); + round.you.safeMs = 0; + const dep = depTo(round, hide); + const got = hotRun(round, 1500, dep); + assert.equal(b.beam.blocked, true, "in the cone's direction, but blocked"); + assert.equal(b.beam.on, false); + assert.equal(b.heat, 0); + assert.equal(got.filter((e) => e.type === "lose").length, 0); + // Step out from behind it, where the cabinet is no longer between you, and it costs a life. + const open = near[1] + 6; + standAt(round, open); + const out = hotRun(round, 1000, depTo(round, open)).filter((e) => e.type === "lose"); + assert.equal(out[0]?.cause, "lantern"); + // Each cabinet has a pocket behind it that no point of the sweep lights. + for (const cab of cabinets) { + const x = cab[0] - 3; + const r = wardFight(); + standAt(r, x); + r.you.safeMs = 0; + let heat = 0; + for (let t = 0; t < sn.BEAM_SWEEP_MS * 1.2; t += 4) { + ghoul.advance(r, 4, steady); + hold(r); + r.you.safeMs = 0; + heat = Math.max(heat, r.boss.heat); + } + assert.equal(heat, 0, `behind the cabinet at ${cab[0]}: cool all sweep`); + } + // And in the open the same sweep does light you. + const r = wardFight(); + standAt(r, r.spec.length - 14); + let lit = 0; + for (let t = 0; t < sn.BEAM_SWEEP_MS * 1.2 && r.phase === "play"; t += 4) { + ghoul.advance(r, 4, steady); + hold(r); + lit = Math.max(lit, r.boss.heat); + } + assert.ok(lit > 0 || events(r, "lose").length > 0, "the open floor is lit by a sweep"); +}); + +test("The boards above the beam's reach are never lit, and the lower ones can be", () => { + const round = wardFight(); + const b = round.boss; + const high = round.spec.shelves.filter((s) => s[2] >= 17); + const low = round.spec.shelves.filter((s) => s[2] < 17); + assert.ok(high.length >= 2 && low.length >= 1); + for (const shelf of high) { + const [x0, x1, y] = shelf; + const i = round.spec.shelves.indexOf(shelf); + for (const x of [x0 + 1, (x0 + x1) / 2, x1 - 1]) { + standAt(round, x, 1, y, i); + round.you.safeMs = 0; + let heat = 0; + for (let t = 0; t < sn.BEAM_SWEEP_MS; t += 20) { + for (let k = 0; k < 5; k++) { + ghoul.advance(round, 4, steady); + hold(round); + round.you.safeMs = 0; + } + heat = Math.max(heat, b.heat); + standAt(round, x, 1, y, i); + } + assert.equal(heat, 0, `on the board at ${y}, x ${x}: never lit`); + } + } + // A low board is in the beam's reach for some of the sweep. + const [x0, x1, y] = low[0]; + standAt(round, (x0 + x1) / 2, 1, y, round.spec.shelves.indexOf(low[0])); + round.you.safeMs = 0; + const dep = depTo(round, (x0 + x1) / 2); + assert.ok(dep < sn.DEP_MAX + sn.BEAM_HALF && dep > -0.2); + const lost = hotRun(round, 1000, dep).filter((e) => e.type === "lose"); + assert.equal(lost[0]?.cause, "lantern", "lit on a low board"); +}); + +test("The Matron winds up 500 ms, then throws a fan of three syringes that land 9 apart around you; stand still and one hits (cause syringe)", () => { + const round = wardFight(); + const b = round.boss; + standAt(round, 150); + round.you.safeMs = 0; + Object.assign(b, { act: "idle", wait: 0, turn: 0 }); + aim(round, sn.DEP_MAX); + const wind = log(round, 12, "syringeWind"); + assert.equal(wind.length, 1); + assert.equal(round.bones.length, 0); + const t0 = round.clock; + until(round, () => events(round, "syringes").length > 0 || round.bones.length > 0, 700); + assert.ok(Math.abs(round.clock - t0 - sn.SYRINGE_WIND_MS) < 60, `${round.clock - t0}`); + const fan = round.bones.filter((s) => s.kind === "syringe"); + assert.equal(fan.length, 3); + assert.ok(fan.every((s) => s.cause === "syringe")); + // Each comes down through chest height at one of three places 9 apart. + const lands = fan.map((s) => { + const chest = round.you.y + ghoul.SHOT_Y; + const disc = s.vy * s.vy + 2 * ghoul.BONE_G * (s.y - chest); + const t = (s.vy + Math.sqrt(disc)) / ghoul.BONE_G; + return s.x + s.vx * t; + }).sort((p, q) => p - q); + assert.ok(Math.abs(lands[0] - (150 - sn.SYRINGE_SPREAD)) < 1 && Math.abs(lands[1] - 150) < 1 && Math.abs(lands[2] - (150 + sn.SYRINGE_SPREAD)) < 1, `${lands.map((v) => v.toFixed(1))}`); + // Standing still costs a life; they can be shot down (25 points). + hold(round); + b.beam.on = false; + const lost = []; + for (let t = 0; t < 2000 && !lost.length; t += 4) { + ghoul.advance(round, 4, steady); + hold(round); + aim(round, sn.DEP_MAX); + for (const e of round.events) if (e.type === "lose") lost.push(e); + round.events.length = 0; + } + assert.equal(lost[0]?.cause, "syringe"); + // Out of the way of all three: nothing. + const clear = wardFight(); + standAt(clear, 150); + clear.you.safeMs = 0; + Object.assign(clear.boss, { act: "idle", wait: 0, turn: 0 }); + let hit = false; + for (let t = 0; t < 2200; t += 4) { + ghoul.advance(clear, 4, steady); + hold(clear); + aim(clear, sn.DEP_MAX); + clear.boss.heat = 0; + if (clear.bones.length && clear.you.x === 150) standAt(clear, 150 - 4.5); + for (const e of clear.events) if (e.type === "lose") hit = true; + clear.events.length = 0; + } + assert.equal(hit, false, "between the second and third syringe, nothing lands"); +}); + +test("The Matron's arm: a crack of light at your height for 700 ms, then an arm shoots across the ward from the far wall (cause arm); jumping out of it or dropping works", () => { + const round = wardFight(); + const b = round.boss; + const spec = round.spec; + standAt(round, 120); + round.you.safeMs = 0; + Object.assign(b, { act: "idle", wait: 0, turn: 1 }); + aim(round, sn.DEP_MAX); + const warn = log(round, 12, "armWarn"); + assert.equal(warn.length, 1); + assert.equal(warn[0][1].x, spec.length, "from the far wall (you are in the left half)"); + assert.ok(Math.abs(warn[0][1].y - (6 + 1.5)) < 1.5, "at your height"); + const arm = round.hazards.find((h) => h.kind === "arm"); + assert.ok(arm && arm.live === 0, "a crack, nothing yet"); + assert.equal(arm.y, 5.8); + assert.equal(arm.h, sn.ARM_H); + const t0 = round.clock; + const reach = []; + while (round.clock - t0 < 900 && !reach.length) { + ghoul.advance(round, 4, steady); + hold(round); + aim(round, sn.DEP_MAX); + for (const e of round.events) if (e.type === "armReach") reach.push([round.clock, e]); + round.events.length = 0; + } + assert.ok(Math.abs(reach[0][0] - t0 - sn.ARM_WARN_MS) < 60, `700 ms of warning (${reach[0][0] - t0})`); + // The arm grows from the wall at ARM_V. + const len0 = arm.len; + run(round, 100); + assert.ok(Math.abs(arm.len - len0 - sn.ARM_V * 0.1) < 8, "shooting across"); + assert.ok(arm.x < spec.length && Math.abs(arm.x + arm.w / 2 - spec.length) < 1e-6, "its root at the wall"); + // Standing in its band costs a life. + const stand = []; + for (let t = 0; t < 1500 && !stand.length; t += 4) { + ghoul.advance(round, 4, steady); + hold(round); + aim(round, sn.DEP_MAX); + round.boss.heat = 0; + for (const e of round.events) if (e.type === "lose") stand.push(e); + round.events.length = 0; + } + assert.equal(stand[0]?.cause, "arm"); + // A jump as it reaches takes you over it. + const jumper = wardFight(); + standAt(jumper, 120); + jumper.you.safeMs = 0; + Object.assign(jumper.boss, { act: "idle", wait: 0, turn: 1 }); + let jumped = false; + let lostJump = 0; + for (let t = 0; t < 2600; t += 4) { + ghoul.advance(jumper, 4, steady); + hold(jumper); + aim(jumper, sn.DEP_MAX); + jumper.boss.heat = 0; + const live = jumper.hazards.find((h) => h.kind === "arm"); + if (live && live.live > 0 && !jumped) { + jumped = true; + jumper.input.up = true; + jumper.input.jump = ghoul.JUMP_BUFFER_MS; + } + for (const e of jumper.events) if (e.type === "lose") lostJump++; + jumper.events.length = 0; + } + assert.ok(jumped, "the arm came"); + assert.equal(lostJump, 0, "a jump timed to its reach clears it"); + // Dropping to the floor from a board works too: the arm is at the board's height. + const dropper = wardFight(); + const board = dropper.spec.shelves.findIndex((s) => s[2] === 17); + const [bx0, bx1, by] = dropper.spec.shelves[board]; + standAt(dropper, (bx0 + bx1) / 2, 1, by, board); + dropper.you.safeMs = 0; + Object.assign(dropper.boss, { act: "idle", wait: 0, turn: 1 }); + let down = false; + let lostDrop = 0; + for (let t = 0; t < 2600; t += 4) { + ghoul.advance(dropper, 4, steady); + hold(dropper); + aim(dropper, sn.DEP_MAX); + dropper.boss.heat = 0; + if (!down && dropper.hazards.some((h) => h.kind === "arm" && h.warn === 0)) { + down = true; + dropper.input.down = true; + } + if (dropper.you.state === "air" || dropper.you.shelf < 0) dropper.input.down = false; + for (const e of dropper.events) if (e.type === "lose") lostDrop++; + dropper.events.length = 0; + } + assert.ok(down); + assert.equal(lostDrop, 0, "dropping out of its band works"); +}); + +test("The Matron alternates syringes and arms, each rest in turn, with no draws from the random source", () => { + const round = wardFight(); + const b = round.boss; + standAt(round, 150); + round.you.safeMs = 1e9; + Object.assign(b, { act: "idle", wait: 0, turn: 0 }); + let draws = 0; + const counting = () => { + draws++; + return 0.5; + }; + const seq = []; + for (let t = 0; t < 14000; t += 4) { + ghoul.advance(round, 4, counting); + round.you.safeMs = 1e9; + for (const e of round.events) if (["syringes", "armWarn"].includes(e.type)) seq.push(e.type); + round.events.length = 0; + round.monsters.length = 0; + round.bones.length = 0; + round.hazards.length = 0; + } + assert.deepEqual(seq.slice(0, 4), ["syringes", "armWarn", "syringes", "armWarn"]); + assert.equal(draws, 0); +}); + +test("The Matron's rage at half her hp: it is told, blackouts start so her cone is the only light, arms come from both walls, the fan is five, her waits shorter and the beam quicker", () => { + const round = wardFight(); + const b = round.boss; + standAt(round, 150); + round.you.safeMs = 1e9; + // Before the rage the lamps stay on all through the fight. + run(round, 12000); + assert.equal(events(round, "lightsOut").length, 0); + assert.equal(round.blackout, false); + hold(round); + b.hp = b.max * 0.5 + 1; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + run(round, 20); + assert.equal(b.hp, b.max * 0.5); + assert.equal(events(round, "matronRage").length, 1); + assert.equal(b.raged, true); + const outs = []; + const ons = []; + for (let t = 0; t < 12000; t += 4) { + ghoul.advance(round, 4, steady); + round.you.safeMs = 1e9; + for (const e of round.events) { + if (e.type === "lightsOut") outs.push(round.clock); + if (e.type === "lightsOn") ons.push(round.clock); + } + round.events.length = 0; + hold(round); + } + assert.ok(outs.length >= 1, "blackouts in the ward"); + assert.ok(Math.abs(ons[0] - outs[0] - sn.BLACKOUT_MS) < 60); + // Her sweep is quicker. + const w0 = b.phase; + run(round, 100); + assert.ok(Math.abs(b.phase - w0 - (Math.PI * 2 * 100) / sn.BEAM_SWEEP_RAGE_MS) < 0.01); + // Arms from both walls. + standAt(round, 120); + Object.assign(b, { act: "idle", wait: 0, turn: 1 }); + const warns = log(round, 12, "armWarn"); + assert.equal(warns.length, 2); + assert.deepEqual(warns.map((w) => w[1].x).sort((p, q) => p - q), [round.spec.arena, round.spec.length]); + assert.equal(round.hazards.filter((h) => h.kind === "arm").length, 2); + // A fan of five. + const fan = wardFight(); + fan.boss.hp = fan.boss.max * 0.4; + fan.boss.raged = true; + standAt(fan, 150); + fan.you.safeMs = 1e9; + Object.assign(fan.boss, { act: "idle", wait: 0, turn: 0 }); + until(fan, () => fan.bones.length > 0, 1000); + assert.equal(fan.bones.filter((s) => s.kind === "syringe").length, 5); + assert.equal(events(fan, "syringes")[0]?.n, 5); + // Her waits are 3/4. + assert.ok(Math.abs(fan.boss.wait - sn.SYRINGE_REST_MS * sn.RAGE_QUICK) < 20); +}); + +test("The Matron's touch is her own, a hit on her carries her kind, a stomp does 3, and her fall puts every arm and blackout away", () => { + const round = wardFight(); + const b = round.boss; + standAt(round, b.x - 3); + round.you.safeMs = 0; + aim(round, sn.DEP_MAX); + run(round, 20); + assert.equal(events(round, "lose")[0]?.cause, "matron"); + const fight = wardFight(); + const m = fight.boss; + const hp = m.hp; + fight.shots.push({ x: m.x - m.w / 2 - 0.2, y: m.y + 5, vx: 80, vy: 0, gone: 0 }); + run(fight, 20); + assert.equal(m.hp, hp - 1); + assert.equal(events(fight, "bossHit")[0]?.kind, "matron"); + standAt(fight, m.x, 1, m.y + m.h + 0.5); + Object.assign(fight.you, { state: "air", vy: -10, safeMs: 1e9, shelf: -1 }); + until(fight, () => events(fight, "stomp").length > 0, 400); + assert.equal(m.hp, hp - 1 - ghoul.STOMP_DAMAGE); + fight.blackout = true; + fight.hazards.push({ kind: "arm", x: 150, y: 6, w: 4, h: 3, side: 1, wall: 200, dirx: -1, span: 96, len: 4, warn: 0, hold: 100, live: 1, cause: "arm" }); + m.hp = 1; + fight.shots.push({ x: m.x - m.w / 2 - 0.2, y: m.y + 5, vx: 80, vy: 0, gone: 0 }); + run(fight, 20); + assert.equal(m.state, "down"); + assert.equal(fight.hazards.length, 0); + run(fight, 8); + assert.equal(fight.blackout, false, "the lights come back"); + assert.equal(fight.hasKey, true); + // Tougher deeper into a run, and the cabinets are ground. + assert.ok(ghoul.roomFor("ward", 3).bossHp > sn.BOSSES.matron.hp); + assert.equal([sn.BOSSES.matron.w, sn.BOSSES.matron.h].join("x"), "8x16"); +}); + +/* ---------------------------------------------------- endless lives, etc. */ + +test("The endless-lives code spares a life from every new way to die, however it is reached", () => { + const causes = ["orderly", "gurney", "flicker", "specimen", "formaldehyde", "matron", "lantern", "arm", "syringe"]; + for (const cause of causes) { + const round = wardFight(); + round.infinite = true; + const lives = round.lives; + ghoul.lose(round, cause); + assert.equal(round.lives, lives, `${cause} costs none`); + } + // Through the real thing. + const real = (setup, cause) => { + const round = sanRound("baths"); + round.infinite = true; + const lives = round.lives; + standAt(round, 60); + round.you.safeMs = 0; + setup(round); + run(round, 700); + assert.equal(events(round, "lose")[0]?.cause, cause, cause); + assert.equal(round.lives, lives, `${cause}: endless lives`); + }; + real((r) => put(r, "gurney", 62, { act: "roll", dir: 1 }), "gurney"); + real((r) => { + r.blackout = true; + put(r, "flicker", 61); + }, "flicker"); + real((r) => r.hazards.push({ kind: "formaldehyde", x: 60, y: 6, w: 3.2, h: 0.9, live: 2500, max: 2500, cause: "formaldehyde" }), "formaldehyde"); + real((r) => r.bones.push({ id: 9e9, kind: "syringe", cause: "syringe", x: 60, y: 8, vx: 0, vy: 0, spin: 0, life: 4000 }), "syringe"); + real((r) => r.bones.push({ id: 9e9 + 2, kind: "jar", cause: "formaldehyde", x: 60, y: 8, vx: 0, vy: 0, spin: 0, life: 4000 }), "formaldehyde"); + // The arm and the lantern in the ward. + const arm = wardFight(); + arm.infinite = true; + standAt(arm, 150); + arm.you.safeMs = 0; + arm.hazards.push({ kind: "arm", x: 150, y: 5.8, w: 8, h: 3.4, side: 1, wall: 200, dirx: -1, span: 96, len: 50, warn: 0, hold: 500, live: 1, cause: "arm" }); + const lives = arm.lives; + run(arm, 20); + assert.equal(events(arm, "lose")[0]?.cause, "arm"); + assert.equal(arm.lives, lives); + const lamp = wardFight(); + lamp.infinite = true; + standAt(lamp, 176); + lamp.you.safeMs = 0; + const dep = depTo(lamp, 176); + const lostLamp = hotRun(lamp, 1000, dep).filter((e) => e.type === "lose"); + assert.equal(lostLamp[0]?.cause, "lantern"); + assert.equal(lamp.lives, lives); +}); + +/* ---------------------------------------------------- voices and drawing */ + +test("Ghoul Rush's Sanatorium: every new kind has a voice for every act and every new event plays exactly one picked sound", () => { + const own = { + orderly: ["appear", "reach", "grab", "throw", "hurt", "die"], + gurney: ["appear", "rattle", "roll", "hurt", "die"], + flicker: ["appear", "lunge", "show", "hurt", "die"], + specimen: ["appear", "wind", "jar", "hurt", "die"], + lights: ["warn", "out", "on"], + salts: ["break", "active"], + saw: ["cut", "active"], + matron: ["wake", "beam", "heat", "syringeWind", "syringes", "armWarn", "armReach", "rage", "hurt", "die"], + }; + for (const [kind, acts] of Object.entries(own)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(own)) for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + const names = Object.values(VOICES).flatMap((v) => Object.values(v)); + const cases = [ + [{ type: "orderlyReach", kind: "orderly" }, "orderly", "reach"], + [{ type: "orderlyGrab", kind: "orderly" }, "orderly", "grab"], + [{ type: "orderlyThrow", kind: "orderly" }, "orderly", "throw"], + [{ type: "saltsBreak", kind: "orderly" }, "salts", "break"], + [{ type: "gurneyRattle", kind: "gurney" }, "gurney", "rattle"], + [{ type: "gurneyRoll", kind: "gurney" }, "gurney", "roll"], + [{ type: "flickerShow", kind: "flicker" }, "flicker", "show"], + [{ type: "jarWind", kind: "specimen" }, "specimen", "wind"], + [{ type: "jarBreak", kind: "specimen" }, "specimen", "jar"], + [{ type: "flickerWarn", ms: 700 }, "lights", "warn"], + [{ type: "lightsOut", ms: 1800 }, "lights", "out"], + [{ type: "lightsOn" }, "lights", "on"], + [{ type: "syringeWind", kind: "matron" }, "matron", "syringeWind"], + [{ type: "syringes", kind: "matron", n: 3 }, "matron", "syringes"], + [{ type: "armWarn", kind: "matron" }, "matron", "armWarn"], + [{ type: "armReach", kind: "matron" }, "matron", "armReach"], + [{ type: "matronRage", kind: "matron" }, "matron", "rage"], + [{ type: "flickerLunge", kind: "flicker" }, "flicker", "lunge"], + [{ type: "matronBeam", kind: "matron" }, "matron", "beam"], + [{ type: "matronHeat", kind: "matron" }, "matron", "heat"], + [{ type: "sawCut", kind: "orderly" }, "saw", "cut"], + [{ type: "power", kind: "salts" }, "salts", "active"], + [{ type: "power", kind: "saw" }, "saw", "active"], + [{ type: "spawn", kind: "gurney" }, "gurney", "appear"], + [{ type: "bossWake", kind: "matron" }, "matron", "wake"], + [{ type: "bossHit", kind: "matron", how: "shot" }, "matron", "hurt"], + [{ type: "bossDown", kind: "matron", points: 1 }, "matron", "die"], + [{ type: "hit", kind: "orderly" }, "orderly", "hurt"], + [{ type: "kill", kind: "gurney", mult: 1, how: "saw", points: 1 }, "gurney", "die"], + [{ type: "kill", kind: "flicker", mult: 1, how: "shot", points: 1 }, "flicker", "die"], + [{ type: "spawn", kind: "specimen" }, "specimen", "appear"], + [{ type: "spawn", kind: "orderly" }, "orderly", "appear"], + ]; + for (const [e, kind, act] of cases) { + const played = heard(e).played; + assert.ok(played.includes(VOICES[kind][act]), `${e.type}: ${kind} ${act}`); + assert.equal(played.filter((n) => names.includes(n)).length, 1, `${e.type} plays exactly one picked sound`); + } + // The quiet ones: a gurney coming to rest is not told. + assert.equal(heard({ type: "gurneyRest", kind: "gurney" }).played.filter((n) => names.includes(n)).length, 0); + // Every kind in the game has a voice with a death, new ones included. + for (const kind of Object.keys(sn.MONSTERS)) assert.ok(VOICES[kind].die); + assert.ok(VOICES.matron.die); +}); + +test("Ghoul Rush's Sanatorium: every new way to die has its words and its own sound", () => { + for (const cause of ["orderly", "gurney", "flicker", "specimen", "formaldehyde", "matron", "lantern", "arm", "syringe"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Sanatorium draws: every room, every monster in every act, a blackout, the Matron in each move with her cone and cabinets, the jar, the syringes, the puddle and the arm, and the stage's card, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["sanatorium"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { orderly: ["walk", "reach", "hold", "rest"], gurney: ["parked", "rattle", "roll", "rest"], flicker: ["creep", "lunge"], specimen: [""] }; + for (const id of ROOM_IDS) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + for (const blackout of [false, true]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + standAt(r, id === "ward" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + r.blackout = blackout; + for (const [kind, list] of Object.entries(acts)) list.forEach((act, i) => put(r, kind, r.you.x + 6 + i * 5, { act: act || undefined, windup: kind === "specimen" ? 200 : 0, wait: 1e9, unseen: kind === "flicker" && !blackout })); + r.twist = { next: 1e9, stage: blackout ? "out" : "stutter", left: 500 }; + r.hazards.push({ kind: "formaldehyde", x: r.you.x + 8, y: 6, w: 3.2, h: 0.9, live: 2000, max: 2500, cause: "formaldehyde" }, { kind: "arm", x: r.you.x + 20, y: 6, w: 20, h: 3.4, side: 1, wall: r.you.x + 30, dirx: -1, span: 96, len: 20, warn: 0, hold: 5000, live: 1, cause: "arm" }, { kind: "arm", x: r.you.x + 20, y: 6, w: 0, h: 3.4, side: -1, wall: r.you.x - 10, dirx: 1, span: 96, len: 0, warn: 5000, hold: 5000, live: 0, cause: "arm" }); + r.bones.push({ id: 9e9, kind: "jar", x: r.you.x + 12, y: 14, vx: 0, vy: 0, spin: 0, life: 4000 }, { id: 9e9 + 1, kind: "syringe", cause: "syringe", x: r.you.x + 14, y: 14, vx: 0, vy: 0, spin: 0, life: 4000 }); + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const act of ["walk", "idle", "syringeWind", "rest"]) { + Object.assign(r.boss, { act, wait: 1e9, dir: -1 }); + for (const heat of [0, 0.7]) { + r.boss.heat = heat; + g.tick(16); + } + } + } + for (let k = 0; k < 20; k++) g.tick(16); + r.you.safeMs = 1e9; + } + } + } + assert.ok(r.spec.id === "ward", "got to the ward and drew it"); + for (const kind of ["salts", "saw"]) { + const p = sanRound("admissions"); + p.drops.push({ id: 1, kind, x: 30, y: 8, vx: 0, vy: 0, life: 9000, rest: true }); + p.sky.fill(false); + g.tick(16); + ghoul.applyPower(p, kind); + } + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["sanatorium", "chapel"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Sanatorium's card"); +}); + +/* ------------------------------------------- events for the picked sounds */ + +test("A flicker that shows tells flickerLunge once, as it switches to lunge", () => { + const round = sanRound("baths"); + standAt(round, 100); + round.you.safeMs = 1e9; + const f = put(round, "flicker", 118); + round.twist = { next: 1e9, stage: "calm", left: 0 }; + assert.equal(log(round, 200, "flickerLunge").length, 0, "unseen, it creeps"); + round.blackout = true; + const got = log(round, 400, "flickerLunge"); + assert.equal(got.length, 1); + assert.equal(f.act, "lunge"); +}); + +test("A Bone Saw bolt tells sawCut for each monster it pierces, and only while the Saw is held", () => { + const round = sanRound("admissions"); + standAt(round, 60); + round.you.safeMs = 1e9; + const o = put(round, "orderly", 70); + o.act = "rest"; + o.wait = 1e9; + bolt(round, o, o.y + 3); + assert.equal(log(round, 40, "sawCut").length, 0, "no Saw, no cut"); + round.effects.saw = 5000; + bolt(round, o, o.y + 3); + const got = log(round, 40, "sawCut"); + assert.equal(got.length, 1); + assert.equal(got[0][1].kind, "orderly"); +}); + +test("The Matron tells matronBeam at the start of each sweep and matronHeat once as your heat starts to rise", () => { + const round = wardFight(); + const b = round.boss; + assert.equal(b.sweep, 0, "the first sweep was announced"); + b.phase = Math.PI * 2 - 0.01; + const beams = log(round, 100, "matronBeam"); + assert.equal(beams.length, 1, "one cue as the sweep comes round"); + const x = 176; + standAt(round, x); + round.you.safeMs = 0; + const dep = depTo(round, x); + aim(round, dep); + const heat = hotRun(round, 400, dep).filter((e) => e.type === "matronHeat"); + assert.equal(heat.length, 1, "once, not every frame"); +}); diff --git a/scripts/test-web-console-activities-ghoul-sled.mjs b/scripts/test-web-console-activities-ghoul-sled.mjs new file mode 100644 index 0000000..5563512 --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-sled.mjs @@ -0,0 +1,933 @@ +// Web console tests, Ghoul Rush's Coffin Sled (the Frozen Lake's bonus round, between the Black Ice and the Widow's Web): its shape (every crack clears with a jump and swallows a sled that does not jump, every low can be ducked, spacing, checkpoints, the clock), the sled's speed on slopes, its jump, ducking, a headstone, a drift, a branch, a hand in the snow, the ghoul that pops up and the icicles (bolts that follow the hill), a fall into a crack, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole hill (one that dodges well, one that never does). +// Run with: node --test scripts/test-web-console-activities-ghoul-sled.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as sl from "../src/web-console/public/activities/ghoul-sled.js"; +import * as ct from "../src/web-console/public/activities/ghoul-cart.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, LOOKS as SLED_LOOKS, VOICES as SLED_VOICES, telegraphMarks, telegraphs } from "../src/web-console/public/activities/ghoul-sled-draw.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES, bonusTick, react } from "../src/web-console/public/activities/ghoul-draw.js"; +import { BONUS_FLOOR, diceFor, endBonus, makeBonus } from "../src/web-console/public/activities/ghoul-bonus.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the sled drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Coffin Sled reached the way play reaches it, nothing woken, the clocks long, +// the bonus round on (five hearts). +function sledRound(seed = 5) { + const round = ghoul.newRound(seed); + round.lives = 3; + round.dice = 0; + through(round); + round.offer = ["frozen"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "sled") through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.timeMs = 1e9; + round.bonus = 1e9; + round.events.length = 0; + return round; +} + +const NONE = { sled: true, time: 1e9, finish: 1e6, track: [], stones: [], drifts: [], lows: [], hands: [], icicles: [], pops: [], checks: [] }; +// The same round over a ride of its own (a plain track to measure the sled on). +function synth(ride) { + const round = sledRound(); + round.spec = { ...round.spec, start: 10, ground: [[0, 5, 0]], ride: { ...NONE, ...ride } }; + sl.SLED.place[0](round, {}); + return round; +} +const FLAT = [[[0, 20], [4000, 20]]]; +const DOWN = [[[0, 40], [4000, 40 - 0.15 * 4000]]]; +const UP = [[[0, 0], [4000, 0.3 * 4000]]]; + +// The sled on line `line` of the ride at `x`, at speed `v`. +function sledAt(round, x, line, { v = sl.SLED_V, safe = false } = {}) { + const y = ct.trackY(round.spec.ride, line, x); + assert.ok(y !== null, `line ${line} runs under ${x}`); + Object.assign(round.you, { x, y, vy: 0, state: "run", shelf: -1, face: 1, out: 0, safeMs: safe ? 1e9 : 0, ducking: false }); + Object.assign(round.sled, { line, v, coyote: 0 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 24)); +} + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = typeof keys[k] === "number" ? 0 : false; +} + +function until(round, done, ms = 6000, random = steady) { + let t = 0; + for (; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); + return t; +} + +const press = (round) => { + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = true; +}; + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played }; +}; + +const ROOM = ghoul.roomById("sled"); +const R = ROOM.ride; +const lines = ct.linesOf(R); +const floorOf = (x) => ghoul.groundAt(ROOM, x); +const slopeAtLine = (L, i) => (L.pts[i + 1][1] - L.pts[i][1]) / (L.pts[i + 1][0] - L.pts[i][0]); + +/* -------------------------------------------------------------- the room */ + +test("Ghoul Rush's Coffin Sled is the Frozen Lake's fourth room, between the Black Ice and the Widow's Web: lit, no key, no boss, a ride about 60 to 70 seconds long, a bonus round that plays its own picked track", () => { + const st = ghoul.stageById("frozen"); + assert.deepEqual(st.rooms, ["huts", "lodge", "blackice", "sled", "widow"]); + assert.equal(st.boss, "frostwidow"); + assert.equal(ghoul.STAGES.at(-1), st, "still the last stage in the list"); + assert.deepEqual([ROOM.title, ROOM.sub], ["Coffin Sled", "Hold on. The hill is longer than it looks"]); + assert.equal(ROOM.dark, false, "a moonlit night, always lit"); + assert.equal(ROOM.key, null); + assert.equal(ROOM.boss, null); + assert.equal(ROOM.bonus, true, "a bonus round"); + assert.equal(R.sled, true); + assert.ok(ROOM.length >= 2400 && ROOM.length <= 3000, `${ROOM.length} units long`); + assert.equal(ghoul.ROOM_MUSIC.sled, "ghoulSledRide"); + assert.ok(ghoulSfx.default.music.ghoulSledRide, "its own picked track"); + assert.deepEqual(Object.keys(sl.SLED.monsters), [], "no new monster kinds"); + assert.equal(LOOKS.sled, SLED_LOOKS.sled); + assert.equal(LOOKS.sled.pack, "sled"); + assert.ok(Object.isFrozen(R) && Object.isFrozen(R.track) && Object.isFrozen(R.track[0][0]), "frozen all the way down"); + assert.ok(ROOM.horde.length === 0 && ROOM.spawns.length === 0, "no monsters: the things on the hill are the pack's own"); + // The ground is the hilltop at the start and the snowbank at the end only. + assert.equal(ROOM.ground.length, 2); + assert.ok(ROOM.ground[0][1] < 60 && ROOM.ground[1][0] > ROOM.length - 100, "floor only at the ends"); + assert.equal(ROOM.ground[1][0], R.finish); + assert.ok(ROOM.door > R.finish && ROOM.door > ROOM.length - 14, "the door at the room's end, past the snowbank's start"); + assert.ok(floorOf(ROOM.door - 2) > -Infinity, "floor to walk out on"); + // Lines run left to right, their points rising in x; the first starts under the sled. + for (const L of lines) for (let i = 0; i + 1 < L.pts.length; i++) assert.ok(L.pts[i + 1][0] > L.pts[i][0], "x rises"); + assert.ok(ct.trackY(R, 0, ROOM.start) > floorOf(ROOM.start), "the sled starts on the ice over the hilltop"); + // The ride, at the sled's speed, takes 60 to 70 seconds. + const secs = (lines.at(-1).x1 - ROOM.start) / sl.SLED_V; + assert.ok(secs >= 58 && secs <= 72, `${secs.toFixed(1)} s at SLED_V`); + // The hill: descents that fall about 0.11 to 0.13 and short climbs at about 0.3, never steeper. + let down = 0; + let total = 0; + for (const L of lines) { + for (let i = 0; i + 1 < L.pts.length; i++) { + const s = slopeAtLine(L, i); + const len = L.pts[i + 1][0] - L.pts[i][0]; + assert.ok(s >= -0.2 && s <= 0.32, `a slope of ${s.toFixed(3)}`); + total += len; + if (s < 0) down += len; + } + } + assert.ok(down / total > 0.6, `${((100 * down) / total).toFixed(0)}% of the hill goes down`); + // The camera has room: the ice stays between the floor and the roof, with a clear head over it. + for (const L of lines) for (const [, y] of L.pts) assert.ok(y > sl.DERAIL_Y + 5 && y < 40, `an ice height of ${y}`); + // The clock covers the ride comfortably (and respawns refill it). + assert.equal(ghoul.timeFor(ghoul.roomFor("sled")), R.time); + assert.ok(R.time >= 1.5 * secs * 1000, `a ${R.time} ms clock for a ${secs.toFixed(0)} s ride`); + // The lip ends the hill rising, so it launches by itself, over a gap the launch alone clears. + const lip = lines.at(-1); + assert.ok(ct.slopeOf(R, lines.length - 1, lip.x1) >= sl.RAMP_SLOPE, "the lip launches"); + const gone = sl.flight(R, lip.x1, lip.pts.at(-1)[1], ct.slopeOf(R, lines.length - 1, lip.x1) * 38 + sl.RAMP_POP, 38); + assert.equal(gone, null, "(the unit's own landing check sees only the ice; the bank is the ground)"); +}); + +test("Ghoul Rush's Coffin Sled: the lip's launch alone carries the sled onto the snowbank at any speed it can have there, landing 10 to 40 past its start", () => { + const lip = lines.at(-1); + const end = lip.pts.at(-1); + const rise = ct.slopeOf(R, lines.length - 1, lip.x1); + const bank = floorOf(R.finish + 1); + for (const v of [sl.SLED_MIN, 34, sl.SLED_V, 55, sl.SLED_MAX]) { + let vy = rise * v + sl.RAMP_POP; + let x = end[0]; + let y = end[1]; + for (let t = 0; t < 3; t += 0.002) { + vy -= sl.SLED_G * 0.002; + x += v * 0.002; + y += vy * 0.002; + if (vy < 0 && y <= bank) break; + } + assert.ok(x >= R.finish + 2, `at ${v} it lands ${x - R.finish} past the bank's start`); + assert.ok(x <= R.finish + 40, `at ${v} it lands ${x - R.finish} past the bank's start`); + } +}); + +test("Ghoul Rush's Coffin Sled: every crack clears with a jump at the edge or a few units early, and a sled that never jumps drops into it", () => { + assert.equal(lines.length - 1, 7, "seven cracks"); + for (let i = 0; i + 1 < lines.length - 1; i++) { + const a = lines[i]; + const b = lines[i + 1]; + const gap = b.x0 - a.x1; + assert.ok(gap >= 9 && gap <= 18, `crack ${i} is ${gap} wide`); + const end = a.pts.at(-1); + const slope = ct.slopeOf(R, i, a.x1); + assert.ok(slope < 0, "cracks lie on descents (no ramp launch)"); + for (const v of [40, 45, 50, 55]) { + assert.equal(sl.flight(R, a.x1, end[1], slope * v, v), null, `crack ${i}, no jump, at ${v}`); + for (const early of [0, 4]) { + const x = a.x1 - early; + const y = ct.trackY(R, i, x); + const s = sl.flight(R, x, y, sl.SLED_JUMP_V + ct.slopeOf(R, i, x) * v, v); + assert.ok(s, `crack ${i}: a jump ${early} early at ${v} lands`); + assert.equal(s.line, i + 1, `crack ${i} cleared, at ${v}, ${early} early`); + } + } + } +}); + +test("Ghoul Rush's Coffin Sled: every thing is on a line, off the ends, spaced for a player (22 between jumps and 38 between a jump and a duck), a low's underside between a ducked box and a standing one", () => { + const jumps = []; + for (const [x, line] of [...R.stones, ...R.drifts, ...R.hands]) { + assert.ok(ct.trackY(R, line, x) !== null, `a thing at ${x} stands on line ${line}`); + jumps.push([x - 2, x + 2]); + } + for (let i = 0; i + 1 < lines.length; i++) jumps.push([lines[i].x1, lines[i + 1].x0]); + const ducks = R.lows.map(([x0, x1]) => [x0, x1]); + // Away from the ends of a line (a thing right at a crack would be a jump into a jump). + for (const [x, line] of [...R.stones, ...R.drifts, ...R.hands, ...R.icicles, ...R.pops]) { + assert.ok(x - lines[line].x0 > 8 && lines[line].x1 - x > 14, `a thing at ${x} well inside its line`); + } + jumps.sort((a, b) => a[0] - b[0]); + for (let i = 0; i + 1 < jumps.length; i++) assert.ok(jumps[i + 1][0] - jumps[i][1] >= 22, `jumps at ${jumps[i][1]} and ${jumps[i + 1][0]}`); + for (const [d0, d1] of ducks) { + for (const [j0, j1] of jumps) assert.ok(j0 - d1 >= 38 || d0 - j1 >= 38, `a jump at ${j0} and a duck at ${d0}`); + } + for (let i = 0; i < ducks.length; i++) { + const [x0, x1, y, kind] = R.lows[i]; + assert.ok(kind === 0 || kind === 1); + let hi = 0; + let lo = 99; + for (let x = x0 - k().HIT_W / 2; x <= x1 + k().HIT_W / 2; x += 0.25) { + const g = ct.linesAt(R, x)[0]; + assert.ok(g, "ice under a low"); + hi = Math.max(hi, g[1]); + lo = Math.min(lo, g[1]); + } + assert.ok(hi + k().DUCK_H < y, `a ducked box clears the low at ${x0}`); + assert.ok(lo + k().HIT_H > y, `a standing box hits the low at ${x0}`); + for (const [j0, j1] of ducks) if (j0 !== x0) assert.ok(j0 - x1 > 20 || x0 - j1 > 20); + } + assert.deepEqual([R.stones.length, R.drifts.length, R.lows.length, R.hands.length], [7, 5, 8, 6]); + assert.ok(R.icicles.length >= 12 && R.pops.length >= 8, "plenty to shoot"); + // Checkpoints every 300 to 400 units, each on the ice and clear of a thing. + const cs = R.checks; + for (let i = 0; i < cs.length; i++) { + assert.ok(ct.linesAt(R, cs[i]).length, `checkpoint ${i} on the ice`); + if (i) assert.ok(cs[i] - cs[i - 1] >= 300 && cs[i] - cs[i - 1] <= 400, `${cs[i] - cs[i - 1]} between checkpoints`); + for (const [j0, j1] of jumps) assert.ok(j0 - cs[i] > 20 || cs[i] - j1 > 4, `a thing at ${j0} near checkpoint ${i}`); + } + assert.ok(cs[0] < 450 && R.finish - cs.at(-1) > 300); +}); + +// The kit's numbers the room is built to (a getter, so the file can read it where needed). +function k() { + return { HIT_W: ghoul.HIT_W, HIT_H: ghoul.HIT_H, DUCK_H: ghoul.DUCK_H }; +} + +/* ------------------------------------------------------------ the sled */ + +test("Ghoul Rush's Coffin Sled rolls at SLED_V on the flat, faster down a slope and slower up one, never past SLED_MIN or SLED_MAX, and no key changes it", () => { + const flat = synth({ track: FLAT }); + assert.equal(flat.sled.v, sl.SLED_V); + run(flat, 2000); + assert.ok(Math.abs(flat.sled.v - sl.SLED_V) < 0.01); + run(flat, 1500, { right: true }); + run(flat, 1500, { left: true }); + assert.ok(Math.abs(flat.sled.v - sl.SLED_V) < 0.01, "right and left do nothing"); + assert.ok(Math.abs(flat.you.x - (10 + (2000 + 1500 + 1500) / 1000 * sl.SLED_V)) < 1, "rides on at SLED_V"); + const down = synth({ track: DOWN }); + run(down, 3000); + assert.ok(Math.abs(down.sled.v - (sl.SLED_V + (sl.SLOPE_G * 0.15) / sl.RELAX)) < 0.2, `${down.sled.v} down a 0.15 slope`); + assert.ok(down.sled.v <= sl.SLED_MAX); + const up = synth({ track: UP }); + run(up, 3000); + assert.ok(Math.abs(up.sled.v - (sl.SLED_V - (sl.SLOPE_G * 0.3) / sl.RELAX)) < 0.2, `${up.sled.v} up a 0.3 slope`); + assert.ok(up.sled.v >= sl.SLED_MIN); + const steep = synth({ track: [[[0, 10000], [4000, 6000]]] }); + run(steep, 3000); + assert.equal(steep.sled.v, sl.SLED_MAX); + const wall = synth({ track: [[[0, 0], [4000, 4000]]] }); + run(wall, 3000); + assert.equal(wall.sled.v, sl.SLED_MIN); + // Planny rides facing right, on the ice, never walking. + assert.equal(flat.you.face, 1); + assert.equal(flat.you.state, "run"); + assert.equal(flat.you.y, 20); +}); + +test("Ghoul Rush's Coffin Sled jumps about 13 high for about three quarters of a second (a crack of about 34 at SLED_V), a press saved for a landing jumps on it, one just after a line's end still jumps", () => { + const round = synth({ track: FLAT }); + let top = 0; + press(round); + const t = until(round, () => { + top = Math.max(top, round.you.y - 20); + return round.you.state === "run" && round.you.y === 20 && round.you.vy === 0 && top > 1; + }, 3000); + assert.ok(Math.abs(top - (sl.SLED_JUMP_V * sl.SLED_JUMP_V) / (2 * sl.SLED_G)) < 0.4, `${top.toFixed(1)} high`); + assert.ok(t > 650 && t < 850, `${t} ms in the air`); + assert.equal(events(round, "sledJump").length, 1); + assert.equal(events(round, "sledLand").length, 1); + const across = round.you.x - 10; + assert.ok(across > 31 && across < 37, `${across.toFixed(1)} across`); + // A press in the air waits for the landing. + const buf = synth({ track: FLAT }); + press(buf); + run(buf, 640); + press(buf); + until(buf, () => events(buf, "sledJump").length >= 2, 1500); + assert.equal(events(buf, "sledJump").length, 2, "the saved press jumped again at the landing"); + // Off the end of a line, a press within COYOTE_MS still jumps. + const edge = synth({ track: [[[0, 20], [60, 20]], [[100, 20], [300, 20]]] }); + sledAt(edge, 58.5, 0); + run(edge, 80); + assert.equal(edge.sled.line, -1, "off the end"); + press(edge); + run(edge, 4); + assert.equal(events(edge, "sledJump").length, 1, "coyote"); + // Too late and it is a fall. + const late = synth({ track: [[[0, 20], [60, 20]], [[100, 20], [300, 20]]] }); + sledAt(late, 58.5, 0); + run(late, 80 + sl.COYOTE_MS); + press(late); + run(late, 4); + assert.equal(events(late, "sledJump").length, 0); +}); + +test("Ghoul Rush's Coffin Sled: down ducks (and a press of up jumps instead of ducking), a ducked Planny passes under a low and a standing one hits it (cause branch), at the cost of a heart", () => { + const round = synth({ track: FLAT, lows: [[60, 66, 23.0, 0]] }); + const you = round.you; + assert.equal(you.ducking, false); + run(round, 20, { down: true }); + assert.equal(events(round, "sledDuck").length, 1); + // Held down through the low: nothing is lost. + round.input.down = true; + until(round, () => you.x > 75, 3000); + round.input.down = false; + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.lives, 3); + // Standing, it hits: a heart, the sled rolls on, Planny blinks safe. + const hit = synth({ track: FLAT, lows: [[60, 66, 23.0, 0]] }); + until(hit, () => hit.bonusRound.hearts < 5, 3000); + assert.equal(hit.bonusRound.hearts, 4); + assert.equal(hit.lives, 3, "not a life"); + assert.equal(events(hit, "lose")[0].cause, "branch"); + assert.equal(events(hit, "sledCrash")[0].what, "low"); + assert.equal(hit.phase, "play", "the ride plays on"); + assert.ok(hit.you.safeMs > 0, "blinking safe"); + assert.deepEqual(hit.bonusRound.perf.hits, ["l0"]); + run(hit, 1000); + assert.equal(hit.bonusRound.hearts, 4, "the same branch costs nothing twice"); + // Jumping into it hits too (a lintel to the roof). + const jump = synth({ track: FLAT, lows: [[60, 66, 23.0, 0]] }); + sledAt(jump, 40, 0); + press(jump); + until(jump, () => jump.bonusRound.hearts < 5 || jump.you.x > 80, 3000); + assert.equal(jump.bonusRound.hearts, 4, "a jump does not clear a low"); + // Up beats down: a press jumps even with down held. + const both = synth({ track: FLAT }); + both.input.down = true; + press(both); + run(both, 20); + assert.equal(both.you.ducking, false); + assert.equal(events(both, "sledJump").length, 1); +}); + +test("Ghoul Rush's Coffin Sled: a headstone and a snowdrift are cleared by a jump and cost a heart otherwise (causes tomb and drift), each only once", () => { + for (const [key, cause, what, jumpAt] of [["stones", "tomb", "stone", 50], ["drifts", "drift", "drift", 48]]) { + const hit = synth({ track: FLAT, [key]: [[60, 0]] }); + until(hit, () => hit.bonusRound.hearts < 5, 3000); + assert.equal(hit.bonusRound.hearts, 4, `${cause} costs a heart`); + assert.equal(events(hit, "lose")[0].cause, cause); + assert.equal(events(hit, "sledCrash")[0].what, what); + assert.equal(hit.lives, 3); + assert.deepEqual(hit.bonusRound.perf.hits, [key === "stones" ? "s0" : "d0"]); + run(hit, 500); + assert.equal(hit.bonusRound.hearts, 4); + // Jumped from anywhere from 8 to 27 short of it, it is cleared. + for (const from of [jumpAt + 4, 60 - 26, 60 - 14, 60 - 9]) { + const clear = synth({ track: FLAT, [key]: [[60, 0]] }); + sledAt(clear, from, 0); + press(clear); + until(clear, () => clear.you.x > 80, 3000); + assert.equal(clear.bonusRound.hearts, 5, `${cause} jumped from ${from}`); + } + } +}); + +test("Ghoul Rush's Coffin Sled: a hand in the snow stirs when the sled is HAND_NEAR short, shivers, reaches up for HAND_UP_MS, grabs (cause grasp) if you meet it, and sinks; a jump clears it", () => { + const hit = synth({ track: FLAT, hands: [[200, 0]] }); + sledAt(hit, 150, 0); + assert.equal(hit.sled.hands[0].state, "snow"); + run(hit, 100); + assert.equal(hit.sled.hands[0].state, "snow", "far off: asleep"); + until(hit, () => hit.sled.hands[0].state === "warn", 2000); + assert.ok(200 - hit.you.x <= sl.HAND_NEAR + 0.5 && 200 - hit.you.x > sl.HAND_NEAR - 1, "wakes at HAND_NEAR"); + assert.equal(events(hit, "sledHandWarn").length, 1); + assert.equal(hit.bonusRound.hearts, 5, "a shiver hurts nothing"); + until(hit, () => hit.sled.hands[0].state === "up", 2000); + assert.equal(events(hit, "sledHandUp").length, 1); + assert.ok(200 - hit.you.x > 8 && 200 - hit.you.x < 20, `up ${200 - hit.you.x} ahead: time to see it`); + until(hit, () => hit.bonusRound.hearts < 5, 2000); + assert.equal(events(hit, "lose")[0].cause, "grasp"); + assert.equal(events(hit, "sledCrash")[0].what, "hand"); + assert.equal(hit.sled.hands[0].state, "sink"); + until(hit, () => hit.sled.hands[0].state === "spent", 1000); + assert.deepEqual(hit.bonusRound.perf.hits, ["h0"]); + // A jump over it. + const jump = synth({ track: FLAT, hands: [[200, 0]] }); + sledAt(jump, 150, 0); + until(jump, () => jump.sled.hands[0].state === "up", 2000); + press(jump); + until(jump, () => jump.you.x > 230, 3000); + assert.equal(jump.bonusRound.hearts, 5); + // It is up for HAND_UP_MS and then sinks away on its own. + const left = synth({ track: FLAT, hands: [[600, 0]] }); + sledAt(left, 580, 0); + left.sled.hands[0] = { state: "up", t: sl.HAND_UP_MS, hp: 2 }; + left.you.safeMs = 1e9; + run(left, 100); + const stay = until(left, () => left.sled.hands[0].state === "sink" || left.sled.hands[0].state === "spent", 5000); + assert.ok(stay > sl.HAND_UP_MS - 400 - 100 && stay < sl.HAND_UP_MS + 100, `up ${stay} ms more`); +}); + +test("Ghoul Rush's Coffin Sled: bolts follow the hill, so one shot breaks an icicle, shoots a popped-up ghoul (150 points) and takes HAND_HP bolts off a hand (100 points), each for the grade's acts", () => { + const round = synth({ track: DOWN, icicles: [[60, 0]], pops: [[120, 0]], hands: [[180, 0]] }); + sledAt(round, 20, 0); + round.you.safeMs = 1e9; + const start = round.score; + // The icicle: a bolt from the sled, 40 away and 6 down the hill, still meets it. + round.input.fire = true; + until(round, () => round.sled.icicles[0], 1500); + assert.equal(round.sled.icicles[0], true); + assert.equal(events(round, "sledIcicle").length, 1); + assert.equal(events(round, "sledIcicle")[0].points, sl.ICICLE_POINTS); + assert.equal(round.bonusRound.perf.acts, 1); + // The ghoul pops up when POP_NEAR short of it, rises, and one bolt takes it. + assert.equal(round.sled.pops[0].state === "up" || round.sled.pops[0].state === "down", true); + until(round, () => round.sled.pops[0].state === "broken", 3000); + assert.equal(round.sled.pops[0].state, "broken"); + assert.equal(events(round, "sledPopUp").length, 1); + assert.equal(events(round, "sledPopHit")[0].points, sl.POP_POINTS); + // The hand: HAND_HP bolts. + until(round, () => round.sled.hands[0].state === "broken", 4000); + assert.equal(round.sled.hands[0].state, "broken"); + assert.equal(events(round, "sledHandHit").length, sl.HAND_HP - 1); + assert.equal(events(round, "sledHandBreak")[0].points, sl.HAND_POINTS); + round.input.fire = false; + assert.equal(round.bonusRound.perf.acts, 3); + assert.ok(round.score - start >= sl.ICICLE_POINTS + sl.POP_POINTS + sl.HAND_POINTS); + assert.equal(round.bonusRound.hearts, 5, "a hand shot dead never grabs"); + // A bolt was never level: it flew along the slope. + const probe = synth({ track: DOWN }); + probe.input.fire = true; + run(probe, 300); + probe.input.fire = false; + assert.ok(probe.shots.length > 0); + for (const s of probe.shots) { + const aboveSled = s.y - (40 - 0.15 * s.x); + assert.ok(Math.abs(aboveSled - (ghoul.SHOT_Y)) < 0.5, `a bolt ${aboveSled.toFixed(2)} over the ice`); + } + // A bolt shot and missed leaves nothing behind (an icicle not in the way). + assert.equal(probe.bonusRound.perf.acts, 0); +}); + +test("Ghoul Rush's Coffin Sled: a ghoul that pops up stays POP_UP_MS and ducks down again (not worth anything then), and what is shot stays shot after a restart", () => { + const round = synth({ track: FLAT, pops: [[100, 0]] }); + sledAt(round, 30, 0); + round.you.safeMs = 1e9; + until(round, () => round.sled.pops[0].state === "up", 2000); + const at = round.you.x; + assert.ok(100 - at <= sl.POP_NEAR + 0.5 && 100 - at > sl.POP_NEAR - 1); + const stay = until(round, () => round.sled.pops[0].state === "hid", 4000); + assert.ok(stay >= sl.POP_UP_MS - 60 && stay <= sl.POP_UP_MS + 60, `${stay} ms up`); + // Too soon (still rising) a bolt passes through. + const early = synth({ track: FLAT, pops: [[100, 0]] }); + sledAt(early, 30, 0); + until(early, () => early.sled.pops[0].state === "up", 2000); + early.sled.pops[0].t = sl.POP_UP_MS - 100; + early.shots.push({ x: 99, y: 22, vx: 130, vy: 0, gone: 0 }); + assert.equal(sl.SLED.target(early, early.shots[0]), false, "still rising"); + early.sled.pops[0].t = sl.POP_UP_MS - sl.POP_RISE_MS - 10; + assert.equal(sl.SLED.target(early, early.shots[0]), true, "risen"); + assert.equal(early.sled.pops[0].state, "broken"); + // A restart keeps what was broken, and sets the hands asleep again. + early.sled.hands = [{ state: "broken", t: 0, hp: 0 }, { state: "up", t: 5, hp: 1 }]; + early.spec = { ...early.spec, ride: { ...early.spec.ride, hands: [[300, 0], [400, 0]] } }; + early.sled.icicles = [true]; + early.spec = { ...early.spec, ride: { ...early.spec.ride, icicles: [[200, 0]] } }; + sl.SLED.place[0](early, {}); + assert.deepEqual(early.sled.hands.map((h) => h.state), ["broken", "snow"]); + assert.deepEqual(early.sled.pops.map((p) => p.state), ["broken"]); + assert.deepEqual(early.sled.icicles, [true]); +}); + +/* ---------------------------------------------------------- cracks and hearts */ + +test("Ghoul Rush's Coffin Sled: a crack with no jump is a heart (cause crevasse), the sled goes back on the ice ahead at SLED_V and rolls on; a jump over it costs nothing", () => { + const ride = { track: [[[0, 20], [60, 20]], [[75, 20], [400, 20]]] }; + const fall = synth(ride); + sledAt(fall, 30, 0); + until(fall, () => fall.bonusRound.hearts < 5, 3000); + assert.equal(fall.bonusRound.hearts, 4); + assert.equal(fall.lives, 3, "not a life"); + assert.equal(events(fall, "lose")[0].cause, "crevasse"); + assert.equal(fall.phase, "play"); + assert.equal(fall.sled.line, 1, "on the ice beyond the crack"); + assert.ok(fall.you.x >= 75 && fall.you.x < 80); + assert.equal(fall.you.y, 20); + assert.equal(fall.sled.v, sl.SLED_V); + assert.ok(fall.you.safeMs > 0); + assert.deepEqual(fall.bonusRound.perf.hits, ["k0"]); + run(fall, 600); + assert.equal(fall.sled.line, 1); + assert.equal(fall.bonusRound.hearts, 4); + // Jumped. + const hop = synth(ride); + sledAt(hop, 54, 0); + press(hop); + until(hop, () => hop.you.x > 100, 3000); + assert.equal(hop.bonusRound.hearts, 5); + assert.equal(hop.sled.line, 1); +}); + +test("Ghoul Rush's Coffin Sled: the last heart gone ends the round with nothing at once (no life lost, the dice in hand kept) and the run goes on to the Widow's Web", () => { + const round = sledRound(); + round.dice = 2; + const score = round.score; + round.bonusRound.hearts = 1; + sledAt(round, lines[0].x1 - 6, 0); + round.you.safeMs = 0; + const heartsBefore = round.bonusRound.hearts; + until(round, () => round.phase === "clear", 6000); + assert.equal(heartsBefore, 1); + assert.equal(round.bonusRound.hearts, 0); + assert.equal(round.bonusRound.over, true); + assert.equal(round.bonusRound.won, false); + const end = events(round, "bonusEnd"); + assert.equal(end.length, 1); + assert.equal(end[0].won, false); + assert.equal(end[0].dice, 0); + assert.equal(round.over, false, "no game over"); + assert.equal(round.lives, 3); + assert.equal(round.dice, 2); + assert.ok(round.score >= score); + assert.equal(round.phase, "clear"); + run(round, ghoul.CARD_LOST_MS + 100); + assert.equal(round.spec.id, "widow"); + assert.equal(round.bonusRound, null); + assert.equal(round.sled, null); + assert.equal(round.lives, 3); + assert.equal(round.dice, 2); + assert.equal(round.phase, "ready"); +}); + +test("Ghoul Rush's Coffin Sled: the checkpoints are passed in order (an event each) and the ride goes back to the last one after the last heart", () => { + const round = sledRound(); + const seen = []; + sledAt(round, R.checks[0] - 6, ct.linesAt(R, R.checks[0] - 6)[0][0]); + round.you.safeMs = 1e9; + until(round, () => round.sled.check >= 1, 4000); + for (const e of events(round, "sledCheck")) seen.push(e.n); + assert.deepEqual(seen.slice(0, 1), [1]); + assert.ok(round.sled.check >= 0); + // The place hook puts him back at the last one passed, at SLED_V. + const c0 = round.sled.check; + round.you.x = 1; + sl.SLED.place[0](round, {}); + assert.equal(round.you.x, R.checks[c0]); + assert.equal(round.sled.v, sl.SLED_V); + assert.equal(round.sled.check, c0); + assert.equal(round.camLead, sl.CAM_AHEAD); + // And at the start in a fresh room. + const fresh = sledRound(); + assert.equal(fresh.you.x, ROOM.start); + assert.equal(fresh.sled.check, -1); +}); + +test("Ghoul Rush's Coffin Sled: off the lip the sled launches, lands on the snowbank and stops (sledFinish), the door opens, and walking out ends the round with 3 to 9 Lucky dice", () => { + const round = sledRound(); + round.dice = 1; + const last = lines.length - 1; + sledAt(round, lines[last].x1 - 12, last, { safe: true }); + until(round, () => round.sled.done, 4000); + assert.equal(round.sled.done, true); + assert.equal(events(round, "sledLaunch").length, 1); + assert.equal(events(round, "sledLaunch")[0].last, true); + const fin = events(round, "sledFinish"); + assert.equal(fin.length, 1); + assert.ok(round.you.x > R.finish + 4 && round.you.x < R.finish + 40, `${round.you.x} landed`); + assert.equal(round.you.y, floorOf(round.you.x)); + assert.equal(round.hasKey, true, "the door opens"); + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.phase, "play"); + // He walks out to the door. + round.input.right = true; + until(round, () => round.phase === "clear", 20000); + round.input.right = false; + assert.equal(round.phase, "clear"); + const end = events(round, "bonusEnd"); + assert.equal(end.length, 1); + assert.equal(end[0].won, true); + assert.ok(end[0].dice >= BONUS_FLOOR && end[0].dice <= ghoul.MAX_DICE, `${end[0].dice} dice`); + assert.equal(round.dice, Math.min(ghoul.MAX_DICE, 1 + end[0].dice)); + assert.equal(round.lives, 3); + run(round, ghoul.CARD_MS + 100); + assert.equal(round.spec.id, "widow"); + assert.equal(round.sled, null); +}); + +test("Ghoul Rush's Coffin Sled: no random number is drawn in the room (a ride of 20 seconds, jumping and shooting, on a draw that throws)", () => { + const round = sledRound(); + sledAt(round, 120, 0, { safe: true }); + round.input.fire = true; + for (let t = 0; t < 20000; t += 4) { + if (t % 1500 === 0) press(round); + ghoul.advance(round, 4, never); + round.events.length = 0; + round.you.safeMs = 1e9; + if (round.phase !== "play") break; + } + assert.ok(round.you.x > 600); +}); + +/* ----------------------------------------------------------- the grade */ + +test("Ghoul Rush's Coffin Sled's grade: the dice formula, shooting 12 things for the die, and the sweet tooth die (souls taken, Hot Cocoa drunk)", () => { + const round = sledRound(); + const b = round.bonusRound; + assert.equal(b.perf.goal, sl.ACTS_GOAL); + assert.equal(b.perf.total, R.stones.length + R.drifts.length + R.lows.length + R.hands.length + lines.length - 1); + assert.equal(b.perf.steady, false, "no sweets yet"); + const mk = (perf) => { + const x = makeBonus({ stats: { kills: 0 } }); + Object.assign(x.perf, { total: b.perf.total, goal: sl.ACTS_GOAL }, perf); + return x; + }; + assert.equal(diceFor(mk({ hits: [], acts: 12, steady: true })), 9, "a perfect ride"); + assert.equal(diceFor(mk({ hits: [], acts: 11, steady: true })), 8); + assert.equal(diceFor(mk({ hits: [], acts: 12, steady: false })), 8); + // Souls: 45% of the room's, or less with cocoa. + const goal = Math.ceil(sl.SWEET_SHARE * round.candy.length); + sledAt(round, 60, 0, { safe: true }); + for (let i = 0; i < goal - 1; i++) round.candy[i] = true; + run(round, 500); + assert.equal(b.perf.steady, false, "one soul short"); + round.candy[goal - 1] = true; + run(round, 500); + assert.equal(b.perf.steady, true, "enough souls"); + // Cocoa counts as SWEET_COCOA souls. + const cocoa = sledRound(); + sledAt(cocoa, 60, 0, { safe: true }); + const idx = cocoa.spec.items.findIndex(([kind]) => kind === "cocoa"); + assert.ok(idx >= 0, "the room has Hot Cocoa"); + cocoa.items[idx] = true; + cocoa.loot[idx] = "cocoa"; + for (let i = 0; i < goal - sl.SWEET_COCOA; i++) cocoa.candy[i] = true; + run(cocoa, 500); + assert.equal(cocoa.bonusRound.perf.steady, true, "cocoa and fewer souls"); + assert.equal(R.checks.length >= 3, true); + assert.equal(cocoa.spec.items.filter(([kind]) => kind === "cocoa").length, 3, "three Hot Cocoas"); + assert.ok(cocoa.spec.items.some(([kind]) => kind === "garlic"), "and a Garlic shield"); +}); + +test("Ghoul Rush's Coffin Sled: endless lives (round.infinite) spare the hearts for every cause, through the same lose path", () => { + const round = sledRound(); + round.infinite = true; + const tries = [ + { stones: [[60, 0]] }, { drifts: [[60, 0]] }, { lows: [[56, 62, 23.0, 0]] }, { hands: [[60, 0]] }, + ]; + for (const t of tries) { + const r = synth({ track: FLAT, ...t }); + r.infinite = true; + if (t.hands) sledAt(r, 20, 0); + until(r, () => events(r, "lose").length > 0, 3000); + assert.equal(r.bonusRound.hearts, 5, JSON.stringify(Object.keys(t))); + assert.equal(r.lives, 3); + } + const crack = synth({ track: [[[0, 20], [60, 20]], [[75, 20], [400, 20]]] }); + crack.infinite = true; + sledAt(crack, 30, 0); + until(crack, () => events(crack, "lose").length > 0, 3000); + assert.equal(crack.bonusRound.hearts, 5); + assert.equal(crack.lives, 3); +}); + +test("Ghoul Rush's Coffin Sled: the Garlic shield takes a hit instead of a heart", () => { + const round = synth({ track: FLAT, stones: [[60, 0]] }); + round.you.garlic = true; + until(round, () => round.you.x > 70, 3000); + assert.equal(round.bonusRound.hearts, 5); + assert.equal(round.you.garlic, false, "spent"); +}); + +/* ------------------------------------------------------ sounds and words */ + +test("Ghoul Rush's Coffin Sled: every event has a voice that plays, every cause has words and a sound, and the voices borrow tones that exist", () => { + assert.deepEqual(Object.keys(EVENT_VOICE).sort(), [...sl.EVENTS].sort(), "a voice for every event and no more"); + const tones = new Set(Object.keys(ghoulSfx.default.tones)); + for (const [event, [kind, act]] of Object.entries(EVENT_VOICE)) { + const name = SLED_VOICES[kind] && SLED_VOICES[kind][act]; + assert.ok(name, `${event} has a ${kind}.${act} voice`); + assert.ok(tones.has(name) || ghoulSfx.default.tones[name], `${name} exists`); + assert.equal(VOICES[kind][act], name, "joined to the game's voices"); + const played = heard({ type: event, what: "stone", points: 50 }).played; + assert.ok(played.includes(name), `${event} plays ${name}`); + } + for (const cause of ["tomb", "drift", "branch", "grasp", "crevasse"]) { + assert.ok(LOSE_WORDS[cause], `${cause} has words`); + assert.ok(LOSE_SOUNDS[cause] && LOSE_SOUNDS[cause].length === 3, `${cause} has a sound`); + assert.ok(heard({ type: "lose", cause, hearts: 3 }).played.length > 0, `${cause} sounds`); + } + // Each plays once (a throttled duck is quiet the second time within its beat). + assert.equal(heard({ type: "sledJump" }).played.length, 1); + assert.equal(heard({ type: "sledIcicle", points: 50 }).played.length, 1); +}); + +test("Ghoul Rush's Coffin Sled: the room's own names do not collide with the game's (hazards, events, kinds)", () => { + for (const e of sl.EVENTS) assert.ok(e.startsWith("sled"), e); + const other = new Set(); + for (const pack of [ct]) for (const e of pack.EVENTS || []) other.add(e); + for (const e of sl.EVENTS) assert.ok(!other.has(e), `${e} is the sled's alone`); + assert.deepEqual(Object.keys(sl.SLED).filter((key) => ["hazards", "bosses", "boss"].includes(key)), []); + assert.equal(ghoul.ROOM_MUSIC.sled && typeof ghoul.ROOM_MUSIC.sled, "string"); +}); + +/* --------------------------------------------------------------- drawing */ + +test("Ghoul Rush's Coffin Sled draws: the room in a lit and a dark one, the sled on the ice, in the air and ducking, each thing (stones, drifts, branches, arches, hands in each state, ghouls in each, icicles whole and broken), a crash, the finish and the cards", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["frozen"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + while (r.spec.id !== "sled") through(r); + r.lives = 99; + const spots = [ROOM.start + 40, R.stones[0][0] - 10, R.lows[0][0] - 5, R.lows[1][0] - 5, R.hands[0][0] - 10, R.pops[0][0] - 20, R.checks[0], lines[0].x1 - 10, R.finish - 40]; + for (const dark of [true, false]) { + for (const x of spots) { + r.dark = dark; + r.phase = "play"; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + const top = ct.linesAt(R, x)[0] || [lines.length - 1, 20]; + sledAt(r, x, top[0], { safe: true }); + r.sled.hands = r.sled.hands.map((h, i) => ({ ...h, state: ["snow", "warn", "up", "sink", "broken", "spent"][i % 6], t: 600 })); + r.sled.pops = r.sled.pops.map((p, i) => ({ ...p, state: ["down", "up", "hid", "broken"][i % 4], t: 1500 })); + r.sled.icicles = r.sled.icicles.map((_, i) => i % 3 === 0); + for (const air of [false, true]) { + if (air) Object.assign(r.you, { state: "air", vy: 20, y: r.you.y + 4 }); + if (air) r.sled.line = -1; + r.you.ducking = x === R.lows[0][0] - 5 && !air; + r.shots.push({ x: x + 6, y: r.you.y + 2.4, vx: 130, vy: -10, gone: 0 }); + for (let k = 0; k < 4; k++) g.tick(16); + r.monsters.length = 0; + r.you.safeMs = 1e9; + sledAt(r, x, top[0], { safe: true }); + } + } + } + assert.equal(r.spec.id, "sled"); + // A crash, the lip and the stop, the lost and won cards. + r.you.safeMs = 0; + sledAt(r, R.stones[0][0] - 3, R.stones[0][1]); + for (let k = 0; k < 30; k++) g.tick(16); + assert.ok(r.bonusRound.hearts < r.bonusRound.max || r.phase !== "play", "the crash draws too"); + const done = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + done.resize(900, 900); + done.key("action"); + done.tick(16); + const d = done.round; + through(d); + d.offer = ["frozen"]; + d.phaseMs = 0; + ghoul.pickStage(d, 0); + while (d.spec.id !== "sled") through(d); + d.phase = "play"; + d.sled.done = true; + d.sled.restX = R.finish + 20; + Object.assign(d.you, { x: R.finish + 30, y: 10, state: "run" }); + d.camX = R.finish - 40; + for (let k = 0; k < 10; k++) done.tick(16); + for (const won of [true, false]) { + endBonus(d, won, { ROOM_POINTS: 300, award: (rd, pts) => (rd.score += pts) }); + d.bonusRound.over = true; + for (let k = 0; k < 10; k++) { + done.tick(16); + bonusTick(d, { tone() {}, fx: {} }); + } + d.bonusRound.over = false; + } + // The stage select goes straight into it. + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.stageSelect(); + const p = pick.round; + const at = ghoul.STAGES.findIndex((s) => s.id === "frozen"); + for (let i = 0; i < at; i++) ghoul.steerSelect(p, 1, 0); + for (let i = 0; i < 3; i++) ghoul.steerSelect(p, 0, 1); + assert.equal(p.select.room, 3); + pick.tick(16); + ghoul.takeSelect(p); + assert.equal(p.spec.id, "sled"); + assert.equal(p.sled.line, 0); + assert.equal(p.you.y, ct.trackY(R, 0, ROOM.start)); + pick.tick(16); +}); + +/* ----------------------------------------------------------- the bots */ + +// A bot that dodges well: it jumps at the end of a line (not the lip), 9 to 15 short of a headstone, a drift or a +// hand, ducks under every low, and holds the blaster. `miss` is the share of things it fails to dodge (by a hash). +const mix = (a, b) => { + let h = Math.imul(a + 0x9e37, 0x85ebca6b) ^ Math.imul(b + 0x7f4a, 0xc2b2ae35); + h ^= h >>> 13; + h = Math.imul(h, 0x5bd1e995); + h ^= h >>> 15; + return (h >>> 0) / 4294967296; +}; +function goodBot(round, seed, miss = 0.04) { + const { you, sled: c, input: inp } = round; + inp.left = inp.right = inp.down = false; + inp.fire = true; + if (round.phase !== "play" || !c || c.done) { + inp.up = false; + return; + } + const ok = (x) => mix(seed, Math.round(x)) >= miss; + const look = 9 + (seed % 7); + let jump = false; + if (c.line >= 0) { + const last = c.line === lines.length - 1; + if (!last && lines[c.line].x1 - you.x < 2.2 && ok(lines[c.line].x1)) jump = true; + const ahead = (x) => x - you.x > 6 && x - you.x < look; + for (const [x] of [...R.stones, ...R.drifts]) if (ahead(x) && ok(x)) jump = true; + R.hands.forEach(([x], i) => { + if (c.hands[i].state !== "broken" && ahead(x) && ok(x)) jump = true; + }); + for (const [x0, x1] of R.lows) if (you.x > x0 - 10 && you.x < x1 + 3 && ok(x0)) inp.down = true; + } + if (jump && !inp.down) press(round); + else inp.up = false; +} +function idleBot(round) { + const inp = round.input; + inp.left = inp.right = inp.down = false; + inp.up = false; + inp.fire = true; +} +function rideWith(seed, bot, limit = 100000) { + const round = sledRound(seed); + const lost = []; + let t = 0; + for (; t < limit && round.phase !== "clear" && !round.over; t += 16) { + bot(round); + if (round.sled && round.sled.done && round.phase === "play") round.input.right = true; + ghoul.advance(round, 16, steady); + for (const e of round.events) if (e.type === "lose") lost.push(e.cause); + if (round.sled && !round.sled.done) { + const off = round.you.x - round.camX; + assert.ok(off > 4 && off < 70, `the sled stays in view (${off.toFixed(1)} from the left edge at ${round.you.x.toFixed(0)})`); + } + round.events.length = 0; + } + return { round, lost, ms: t }; +} + +test("Ghoul Rush's Coffin Sled: a bot that dodges well finishes the whole hill in 60 to 75 seconds, 7 to 9 dice, a few hearts lost at most, past every checkpoint", () => { + const dice = []; + for (let seed = 1; seed <= 12; seed++) { + const { round, lost, ms } = rideWith(seed, (r) => goodBot(r, seed)); + const b = round.bonusRound; + assert.equal(b.won, true, `seed ${seed} finished (lost ${lost.join(",")})`); + assert.ok(ms > 60000 && ms < 76000, `${ms} ms`); + assert.ok(b.dice >= 6 && b.dice <= ghoul.MAX_DICE, `${b.dice} dice`); + assert.equal(round.lives, 3, "never a run life"); + assert.equal(round.sled.check, R.checks.length - 1, "past every checkpoint"); + dice.push(b.dice); + } + assert.ok(dice.reduce((a, b) => a + b, 0) / dice.length >= 7, `${dice.join(",")}`); +}); + +test("Ghoul Rush's Coffin Sled: a bot that never dodges (holding fire) loses all five hearts before the first third, ends with 0 dice and the run goes on", () => { + for (let seed = 1; seed <= 6; seed++) { + const { round, lost } = rideWith(seed, idleBot); + const b = round.bonusRound; + assert.equal(b.won, false, "never finishes"); + assert.equal(b.dice, 0); + assert.equal(b.hearts, 0); + assert.equal(lost.length, 5); + assert.ok(round.you.x < ROOM.length * 0.4, `out at ${round.you.x}`); + assert.equal(round.lives, 3); + assert.equal(round.over, false); + } +}); + +/* ------------------------------------------------------------ telegraphs */ + +test("Ghoul Rush's Coffin Sled telegraphs: DUCK over branches and arches, JUMP over cracks, headstones and drifts, none for hands, icicles or ghouls, words only on the first three of each kind, the same every time", () => { + const marks = telegraphMarks(R); + const answers = { crack: "JUMP", stone: "JUMP", drift: "JUMP", branch: "DUCK", arch: "DUCK" }; + assert.equal(marks.length, (R.track.length - 1) + R.stones.length + R.drifts.length + R.lows.length, "one per jumped or ducked obstacle, none for hands, icicles or ghouls"); + for (const m of marks) assert.equal(m.answer, answers[m.kind], m.kind); + R.lows.forEach(([x0, x1, y, kind]) => { + const m = marks.find((q) => q.x === (x0 + x1) / 2); + assert.equal(m.kind, kind ? "arch" : "branch"); + assert.equal(m.answer, "DUCK"); + }); + const first = R.lows.find((l) => !l[3]); + const m = marks.find((q) => q.x === (first[0] + first[1]) / 2); + const xs = [m.lead - 45, m.lead - 41, m.lead - 36, m.lead - 30, m.lead - 10, m.lead, m.lead + 3, m.lead + 7]; + const alphaOf = (x) => (telegraphs(R, x).find((t) => t.kind === "branch" && t.lead === m.lead) || { alpha: 0 }).alpha; + const a = xs.map(alphaOf); + assert.equal(a[0], 0, "not yet in view"); + assert.ok(a[2] > 0 && a[2] < 1, "fading in 40 to 30 ahead"); + assert.equal(a[3], 1); + assert.equal(a[4], 1); + assert.ok(a[6] > 0 && a[6] < 1, "fading as it passes"); + assert.equal(a[7], 0, "gone once passed"); + assert.deepEqual(telegraphs(R, m.lead - 33), telegraphs(R, m.lead - 33), "deterministic"); + assert.deepEqual(JSON.parse(JSON.stringify(telegraphs(R, 100))), JSON.parse(JSON.stringify(telegraphs(R, 100)))); + for (const kind of ["crack", "stone", "drift", "branch", "arch"]) { + const of = marks.filter((q) => q.kind === kind).sort((p, q) => p.lead - q.lead); + assert.ok(of.length > 3, kind); + of.forEach((q, i) => { + assert.equal(q.n, i); + const shown = telegraphs(R, q.lead - 32).find((t) => t.lead === q.lead); + assert.equal(shown.words, i < 3, `${kind} ${i}`); + }); + } + const words = telegraphs(R, R.stones[0][0] - 33); + assert.ok(words.some((t) => t.kind === "stone" && t.answer === "JUMP" && t.words)); +}); + +test("Ghoul Rush's Coffin Sled's intro banner says the controls plainly", () => { + assert.match(R.how, /UP to jump, DOWN to duck/); +}); diff --git a/scripts/test-web-console-activities-ghoul-village.mjs b/scripts/test-web-console-activities-ghoul-village.mjs new file mode 100644 index 0000000..9e3810b --- /dev/null +++ b/scripts/test-web-console-activities-ghoul-village.mjs @@ -0,0 +1,1091 @@ +// Web console tests, Ghoul Rush's Hollow End Village stage: its four rooms, the moonrise (a moon that climbs over each room and, at full, turns the villagers into wolf-men and makes the moonhounds grow), torch mob villagers that lob fire, hanged men that drop on their ropes, shutter ghouls that can be hit only while out, moonhounds, Wolfsbane (found only here), and the Beast of Hollow End, which clings to the wall for double damage, pounces under a shadow, swipes, howls for hounds and rages at half its hp. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import * as vl from "../src/web-console/public/activities/ghoul-village.js"; +import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS } from "../src/web-console/public/activities/ghoul-village-draw.js"; +import { PILL_WORDS, pickPower } from "../src/web-console/public/activities/ghoul-powers.js"; +import * as ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LOOKS, VOICES, react } from "../src/web-console/public/activities/ghoul-draw.js"; + +const steady = () => 0.5; +// The pack draws no random number: a run on this fails on the first draw. +const never = () => { + throw new Error("the village drew a random number"); +}; +const events = (round, type) => round.events.filter((e) => e.type === type); +const ROOM_IDS = ["street", "inn", "square", "green"]; + +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the Village's room `id`, reached the way play reaches it, nothing +// woken: every spawner spent, the horde held back, the moon far from rising +// (set `full` for a full one). +function vilRound(id, { full = false } = {}) { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + round.offer = ["village"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + round.items.fill(true); + round.candy.fill(true); + round.sky.fill(true); + round.timeMs = 1e9; + round.bonus = 1e9; + round.dark = false; + if (!round.spec.boss) round.twist = { moon: full ? 1 : 0, full, ms: full ? 1e9 : -1e12 }; + round.events.length = 0; + return round; +} + +function standAt(round, x, face = 1, y = ghoul.groundAt(round.spec, x), shelf = -1) { + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, out: 0, safeMs: 0, face }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +const put = (round, kind, x, over = {}) => ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, ...over }); + +function run(round, ms, keys = {}, random = steady) { + Object.assign(round.input, keys); + for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random); + for (const k of Object.keys(keys)) round.input[k] = false; +} + +function until(round, done, ms = 4000, random = steady) { + for (let t = 0; t < ms && !done(); t += 4) ghoul.advance(round, 4, random); +} + +// Runs `ms`, returning each event of `type` as [the round's clock, event]. +function log(round, ms, type, random = steady) { + const got = []; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, random); + for (const e of round.events) if (e.type === type) got.push([round.clock, e]); + round.events.length = 0; + } + return got; +} + +// A bolt arriving from the left at height `y` on the monster `m`. +const bolt = (round, m, y) => round.shots.push({ x: m.x - m.w / 2 - 0.3, y, vx: 80, vy: 0, gone: 0 }); + +const heard = (e, extra = {}) => { + const played = []; + const noop = () => {}; + const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra }; + react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit); + return { played }; +}; + +test("Ghoul Rush's Hollow End Village is a stage of three rooms and the Green, its monsters and boss joined to the game's, with a power-up of its own, a moon that rises and a place for each kind", () => { + const st = ghoul.stageById("village"); + assert.deepEqual(st.rooms, ROOM_IDS); + assert.equal(st.boss, "beast"); + assert.equal(st.title, "Hollow End Village"); + assert.equal(st.sub, "Every curtain twitches as you pass"); + for (const kind of Object.keys(vl.MONSTERS)) assert.equal(ghoul.MONSTERS[kind], vl.MONSTERS[kind], `${kind} is a monster`); + assert.equal(ghoul.BOSSES.beast, vl.BOSSES.beast); + assert.equal(vl.BOSSES.beast.sub, "Shoot it while it clings to the wall"); + assert.ok(ghoul.MONSTERS.villager.hp === 3 && ghoul.MONSTERS.hanged.hp === 3 && ghoul.MONSTERS.shutter.hp === 2 && ghoul.BOSSES.beast.hp === 110); + for (const id of st.rooms) assert.ok(ghoul.ROOM_MUSIC[id], `${id} has music`); + const [street, inn, square, green] = st.rooms.map((id) => ghoul.roomById(id)); + const returning = ["zombie", "bat", "crow", "hound", "ghost"]; + for (const room of [street, inn, square]) { + assert.ok(room.key, `${room.id}: a key`); + assert.ok(room.sky.length && room.candy.length && room.items.length && room.horde.length, `${room.id}: sky treasures, candy, items and a horde`); + const wings = room.items.find((i) => i[0] === "wings"); + assert.ok(wings && wings[1] < room.key[0], `${room.id}: wings on the way to the sky`); + assert.ok(room.items.some((i) => i[0] === "bane"), `${room.id}: Wolfsbane`); + assert.ok(room.spawns.some((s) => s[0] in vl.MONSTERS), `${room.id}: some of the new monsters`); + assert.ok(room.spawns.some((s) => returning.includes(s[0])), `${room.id}: some returning ones`); + assert.ok(room.moon > 0, `${room.id}: a moon`); + } + assert.deepEqual([street.moon, inn.moon, square.moon, green.moon], [45000, 40000, 35000, 0]); + assert.ok(street.spawns.some((s) => s[0] === "shutter") && street.spawns.some((s) => s[0] === "villager"), "shutter ghouls and the mob on Main Street"); + assert.ok(inn.spawns.some((s) => s[0] === "moonhound") && inn.spawns.some((s) => s[0] === "villager"), "moonhounds and villagers in the inn"); + assert.ok(square.spawns.filter((s) => s[0] === "hanged").length >= 4, "hanged men in the square"); + for (const kind of Object.keys(vl.MONSTERS)) assert.ok(square.spawns.some((s) => s[0] === kind), `the Square has ${kind}`); + assert.ok(square.shelves.some((s) => s[1] - s[0] >= 20), "the gallows platform"); + assert.equal(green.boss, "beast"); + assert.equal(green.horde.length, 0); + assert.ok(street.spawns.length <= inn.spawns.length && inn.spawns.length <= square.spawns.length); + assert.ok(street.hordeMs > inn.hordeMs && inn.hordeMs > square.hordeMs, "harder in order"); + assert.ok(street.moon > inn.moon && inn.moon > square.moon, "the moon rises sooner in order"); + // The street, the square and the green are out under the sky; the inn is indoors. + assert.ok(LOOKS.street.outdoor && LOOKS.square.outdoor && LOOKS.green.outdoor); + assert.ok(!LOOKS.inn.outdoor && LOOKS.inn.custom && LOOKS.inn.pack === "village", "the inn is indoors, a custom room the village draws whole"); + // A window is a little way up its wall; a hanged man's beam is 13 over what he hangs above. + for (const room of [street, inn, square]) { + for (const [kind, x, y] of room.spawns.filter((s) => s[0] === "shutter" || s[0] === "hanged")) { + const floor = ghoul.groundAt(room, x); + assert.ok(floor > -Infinity, `${room.id}: the ${kind} at ${x} over a floor`); + if (kind === "shutter") assert.ok(y - floor >= 6.5 && y - floor <= 8, `${room.id}: the window at ${x} (${y - floor} up)`); + else { + const top = Math.max(floor, ...room.shelves.filter(([a, b, t]) => x >= a && x <= b && t < y).map((s) => s[2])); + assert.equal(y - top, 13, `${room.id}: the beam at ${x}`); + } + } + } +}); + +/* ---------------------------------------------------------- the moonrise */ + +test("Ghoul Rush's moon climbs over a room in its own time, is full once with a fullMoon, and starts over in the next room and after a life lost", () => { + const round = vilRound("street"); + round.twist = null; + standAt(round, 40); + round.you.safeMs = 1e9; + ghoul.advance(round, 8, steady); + assert.ok(round.twist && round.twist.moon > 0 && round.twist.moon < 0.001 && !round.twist.full); + run(round, 22400); + assert.ok(Math.abs(round.twist.moon - 0.5) < 0.01, `half way (${round.twist.moon})`); + assert.equal(events(round, "fullMoon").length, 0); + const got = log(round, 23000, "fullMoon"); + assert.equal(got.length, 1, "one fullMoon"); + assert.ok(Math.abs(got[0][0] - 45000) < 40, `at 45 s (${got[0][0]})`); + assert.equal(round.twist.moon, 1); + assert.equal(round.twist.full, true); + run(round, 2000); + assert.equal(events(round, "fullMoon").length, 0, "never again"); + // The next room's moon starts at the bottom of the sky. + through(round); + assert.equal(round.spec.id, "inn"); + assert.equal(round.twist, null); + round.phase = "play"; + for (const st of round.spawns) st.over = true; + round.hordeMs = Infinity; + round.timeMs = 1e9; + round.you.safeMs = 1e9; + round.twist = null; + run(round, 8); + assert.ok(round.twist.moon < 0.001 && !round.twist.full); + run(round, 20000); + assert.ok(Math.abs(round.twist.moon - 0.5) < 0.01, "the inn's moon is quicker (40 s)"); + // A life lost puts the moon back where it began. + ghoul.lose(round, "zombie"); + run(round, ghoul.CRASH_MS + 100); + assert.equal(round.twist, null); + assert.equal(round.phase, "ready"); +}); + +test("Ghoul Rush's full moon turns every villager in view for 800 ms into a wolf-man with 2 more hp and no torches, and one that comes into view later turns too", () => { + const round = vilRound("street"); + standAt(round, 40); + round.you.safeMs = 1e9; + const a = put(round, "villager", 70, { group: true }); + const b = put(round, "villager", 300, { group: true }); + assert.equal(a.hp, 3); + round.twist = { moon: 0.9999, full: false, ms: 44999 }; + const turned = log(round, 40, "villagerTurn"); + assert.equal(events(round, "fullMoon").length + turned.length > 0, true); + assert.equal(a.act, "turn", "in view: turning"); + assert.equal(b.act, "walk", "out of view: not yet"); + const started = turned[0][0]; + const wolf = log(round, 1000, "villagerWolf"); + assert.equal(wolf.length, 1, "one wolf-man"); + assert.ok(Math.abs(wolf[0][0] - started - vl.VILLAGER_TURN_MS) < 40, `800 ms to turn (${wolf[0][0] - started})`); + assert.equal(a.turned, true); + assert.equal(a.hp, 5); + assert.equal(a.max, 5); + // No more torches from it, though it is near enough to throw. + a.x = 70; + assert.equal(log(round, 3000, "torchWind").length, 0); + // The other comes into view: it turns then. + b.x = 100; + round.camX = 0; + const later = log(round, 40, "villagerTurn"); + assert.equal(later.length, 1); + assert.equal(later[0][1].x, b.x); +}); + +test("Ghoul Rush's moonhounds grow 1.5 times with 3 more hp at full moon, each told by houndGrow once, and one born later is grown too", () => { + const round = vilRound("inn"); + standAt(round, 20); + round.you.safeMs = 1e9; + const h = put(round, "moonhound", 70, { act: "rest", wait: 1e9 }); + run(round, 400); + assert.equal(h.grown, undefined); + assert.equal(h.w, 3.8); + round.twist = { moon: 1, full: true, ms: 1e9 }; + const grew = log(round, 40, "houndGrow"); + assert.equal(grew.length, 1); + assert.equal(h.grown, true); + assert.ok(Math.abs(h.w - 5.7) < 1e-9 && Math.abs(h.h - 3.9) < 1e-9); + assert.equal(h.hp, 5); + assert.equal(h.max, 5); + assert.equal(log(round, 400, "houndGrow").length, 0, "once"); + const late = put(round, "moonhound", 90, { act: "rest", wait: 1e9 }); + assert.equal(log(round, 40, "houndGrow").length, 1); + assert.equal(late.hp, 5); +}); + +/* ----------------------------------------------------------- the villager */ + +test("Ghoul Rush's villager: a spawn row is a group of three, a horde one comes alone, it walks at you and stops 16 away", () => { + const round = vilRound("street"); + standAt(round, 40); + round.you.safeMs = 1e9; + const v = put(round, "villager", 130); + run(round, 8); + const crowd = round.monsters.filter((m) => m.kind === "villager"); + assert.equal(crowd.length, vl.VILLAGER_GROUP); + const xs = crowd.map((m) => m.x).sort((a, c) => a - c); + assert.ok(Math.abs(xs[1] - xs[0] - vl.VILLAGER_SPREAD) < 0.3 && Math.abs(xs[2] - xs[1] - vl.VILLAGER_SPREAD) < 0.3, `2.6 apart (${xs})`); + assert.ok(crowd.every((m) => m.y === ghoul.groundAt(round.spec, m.x)), "all on the floor"); + const horde = vilRound("street"); + put(horde, "villager", 130, { horde: true }); + run(horde, 8); + assert.equal(horde.monsters.length, 1, "alone"); + // Walks at you, stops 16 away. + const walker = vilRound("street"); + standAt(walker, 40); + walker.you.safeMs = 1e9; + const w = put(walker, "villager", 80, { group: true }); + const x0 = w.x; + run(walker, 400); + assert.ok(w.x < x0 - 2, "it walks at you"); + run(walker, 3000); + const away = w.x - walker.you.x; + assert.ok(away >= vl.VILLAGER_KEEP - 0.1 && away < vl.VILLAGER_KEEP + 2, `about 16 away (${away})`); + assert.equal(v.kind, "villager"); +}); + +test("Ghoul Rush's villager winds up 500 ms, lobs a torch at you that comes down in a patch of fire for 3.2 s, and the torch in the air and the fire both cost a life", () => { + const round = vilRound("street"); + standAt(round, 40); + round.you.safeMs = 1e9; + const v = put(round, "villager", 56, { group: true }); + v.init = true; + v.throwIn = 0; + const wind = log(round, 8, "torchWind"); + assert.equal(wind.length, 1); + const startedAt = wind[0][0]; + const throws = log(round, 700, "throw"); + assert.equal(throws.length, 1); + assert.ok(Math.abs(throws[0][0] - startedAt - vl.TORCH_WIND_MS) < 40, `500 ms of wind-up (${throws[0][0] - startedAt})`); + assert.equal(throws[0][1].kind, "torch"); + assert.equal(throws[0][1].by, "villager"); + const torch = round.bones.find((b) => b.kind === "torch"); + assert.ok(torch && torch.cause === "torch"); + const landed = []; + for (let t = 0; t < 2000 && !landed.length; t += 4) { + ghoul.advance(round, 4, steady); + for (const e of round.events) if (e.type === "torchLand") landed.push([round.clock, e]); + round.events.length = 0; + } + assert.equal(landed.length, 1); + const fire = round.hazards.find((h) => h.kind === "torchfire"); + assert.ok(fire && Math.abs(fire.x - 40) < 6, "the fire where you stood"); + assert.ok(fire.live > vl.TORCHFIRE_MS - 100 && fire.w === vl.TORCHFIRE_W && fire.h === vl.TORCHFIRE_H); + const burnt = landed[0][0]; + run(round, 3000); + assert.ok(round.hazards.some((h) => h.kind === "torchfire"), "still burning"); + run(round, 400); + assert.equal(round.hazards.filter((h) => h.kind === "torchfire").length, 0, "burnt out"); + assert.ok(round.clock - burnt > 3200 - 100); + // A torch shot out of the air is points, not fire. + const shot = vilRound("street"); + standAt(shot, 40); + shot.bones.push({ id: 9e9, kind: "torch", cause: "torch", x: 45, y: 8.4, vx: 0, vy: 0, spin: 0, life: 4000 }); + shot.shots.push({ x: 44.2, y: 8.4, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(shot, 8, steady); + assert.equal(shot.bones.length, 0); + assert.equal(events(shot, "bone")[0]?.kind, "torch"); + // Fire in the air and on the floor costs a life, the cause torch. + const air = vilRound("street"); + standAt(air, 40); + air.bones.push({ id: 9e9, kind: "torch", cause: "torch", x: 40, y: 8, vx: 0, vy: 0, spin: 0, life: 4000 }); + ghoul.advance(air, 8, steady); + assert.equal(events(air, "lose")[0]?.cause, "torch"); + const floor = vilRound("street"); + standAt(floor, 40); + floor.hazards.push({ kind: "torchfire", x: 40, y: 6, w: 4.4, h: 2.4, live: 2000, max: 3200, cause: "torch" }); + ghoul.advance(floor, 8, steady); + assert.equal(events(floor, "lose")[0]?.cause, "torch"); + // Standing beside it is safe; jumping over it, too. + const beside = vilRound("street"); + standAt(beside, 40); + beside.hazards.push({ kind: "torchfire", x: 46, y: 6, w: 4.4, h: 2.4, live: 2000, max: 3200, cause: "torch" }); + ghoul.advance(beside, 8, steady); + assert.equal(events(beside, "lose").length, 0); + const hop = vilRound("street"); + standAt(hop, 40, 1, 9, -1); + Object.assign(hop.you, { state: "air", vy: 0 }); + hop.hazards.push({ kind: "torchfire", x: 40, y: 6, w: 4.4, h: 2.4, live: 2000, max: 3200, cause: "torch" }); + ghoul.advance(hop, 4, steady); + assert.equal(events(hop, "lose").length, 0, "over the fire"); + // At most five patches burn: the oldest goes. + const cap = vilRound("street"); + standAt(cap, 10); + cap.you.safeMs = 1e9; + for (let i = 0; i < 7; i++) { + cap.bones.push({ id: 9e9 + i, kind: "torch", cause: "torch", x: 60 + i * 6, y: 6.2, vx: 0, vy: -5, spin: 0, life: 4000 }); + } + run(cap, 60); + const fires = cap.hazards.filter((h) => h.kind === "torchfire"); + assert.equal(fires.length, vl.TORCHFIRE_CAP); + assert.ok(fires.every((h) => h.x > 60), "the oldest went"); +}); + +/* ---------------------------------------------------------------- hanged */ + +test("Ghoul Rush's hanged man sways under his beam, creaks 220 ms when you pass under, drops to your height, holds 450 ms and is hauled back up", () => { + const round = vilRound("square"); + standAt(round, 60, 1, 6); + round.you.safeMs = 1e9; + const h = put(round, "hanged", 330, { y: 19 }); + assert.equal(h.act, "sway"); + assert.equal(ghoul.MONSTERS.hanged.stomp, false); + standAt(round, 320, 1, 6); + round.you.safeMs = 1e9; + run(round, 600); + assert.equal(h.beam, 19); + assert.equal(h.rest, 11.5); + assert.equal(h.y, 11.5); + assert.equal(events(round, "hangedWarn").length, 0, "10 away: no"); + // Shot any time, even at rest. + bolt(round, h, 13); + ghoul.advance(round, 8, steady); + assert.equal(h.hp, 2, "shot at rest"); + standAt(round, 326, 1, 6); + round.you.safeMs = 1e9; + const seen = []; + for (let t = 0; t < 1400; t += 4) { + ghoul.advance(round, 4, steady); + for (const e of round.events) if (e.type.startsWith("hanged")) seen.push([e.type, round.clock]); + round.events.length = 0; + } + assert.deepEqual(seen.map((s) => s[0]), ["hangedWarn", "hangedDrop", "hangedSnap", "hangedHaul"]); + const at = Object.fromEntries(seen); + assert.ok(Math.abs(at.hangedDrop - at.hangedWarn - vl.HANGED_WARN_MS) < 20, "220 ms of creak"); + assert.ok(at.hangedSnap - at.hangedDrop < 80, "a quick snap"); + assert.ok(Math.abs(at.hangedHaul - at.hangedSnap - vl.HANGED_HOLD_MS) < 20, "450 ms at the bottom"); + assert.ok(Math.abs(h.to - 6.4) < 1e-9, "to just over your feet"); + until(round, () => h.act === "sway", 1000); + assert.equal(h.y, 11.5, "back up"); + // He sways a while before he drops again, and then does. + const again = vilRound("square"); + standAt(again, 326, 1, 6); + again.you.safeMs = 1e9; + const g = put(again, "hanged", 330, { y: 19 }); + until(again, () => g.act === "sway" && g.cool > 0 && g.y === g.rest, 100); + g.act = "haul"; + g.y = g.rest - 0.01; + run(again, 12); + assert.equal(g.act, "sway"); + assert.ok(g.cool > 0 && g.cool <= vl.HANGED_REST_MS); + again.events.length = 0; + run(again, 1000); + assert.equal(events(again, "hangedWarn").length, 0, "not yet"); + run(again, 700); + assert.equal(events(again, "hangedWarn").length, 1, "again"); +}); + +test("Ghoul Rush's hanged man does not drop for you above him or out of his rope's reach, and a drop costs a life only where he lands", () => { + const round = vilRound("square"); + standAt(round, 326, 1, 12, -1); + Object.assign(round.you, { state: "air", vy: 30 }); + const h = put(round, "hanged", 330, { y: 19 }); + round.you.safeMs = 1e9; + run(round, 120); + assert.equal(events(round, "hangedWarn").length, 0, "above him"); + // On the platform, level with his rest, the beam sits higher and he is in reach. + const deck = vilRound("square"); + const d = put(deck, "hanged", 130, { y: 24 }); + standAt(deck, 126, 1, 11, 0); + deck.you.safeMs = 1e9; + run(deck, 300); + assert.equal(d.rest, 16.5); + assert.equal(events(deck, "hangedDrop").length, 1, "dropped on the deck"); + assert.ok(Math.abs(d.to - 11.4) < 1e-9); + // Out of the rope's reach below (the floor under a high platform's man). + const low = vilRound("square"); + const l = put(low, "hanged", 130, { y: 24 }); + standAt(low, 126, 1, 6); + low.you.safeMs = 1e9; + run(low, 300); + assert.equal(l.rest - vl.HANGED_ROPE, 8.5); + assert.equal(events(low, "hangedWarn").length, 0, "too low to reach"); + // Under him as he lands: a life, the cause hanged. Beside him: none. + const hit = vilRound("square"); + standAt(hit, 330, 1, 6); + put(hit, "hanged", 330, { y: 19 }); + until(hit, () => events(hit, "lose").length > 0, 1500); + assert.equal(events(hit, "lose")[0]?.cause, "hanged"); + assert.equal(events(hit, "hangedDrop").length, 1); + const beside = vilRound("square"); + standAt(beside, 322, 1, 6); + put(beside, "hanged", 330, { y: 19 }); + beside.you.safeMs = 0; + run(beside, 300); + Object.assign(beside.you, { x: 322 }); + run(beside, 700); + assert.equal(events(beside, "lose").length, 0, "the rope does not move sideways"); +}); + +/* --------------------------------------------------------------- shutter */ + +test("Ghoul Rush's shutter ghoul hides (bolts go through, touch does nothing), rattles 800 ms when you come near, lunges out at you, and can be hit and can hurt only while out", () => { + const round = vilRound("street"); + standAt(round, 40); + round.you.safeMs = 1e9; + const s = put(round, "shutter", 96, { y: 13 }); + assert.equal(s.act, "hide"); + assert.equal(ghoul.solid(s), false, "hidden: not solid"); + run(round, 200); + assert.equal(events(round, "shutterRattle").length, 0, "far off"); + bolt(round, s, 15); + ghoul.advance(round, 8, steady); + assert.equal(s.hp, 2, "a bolt goes through the window"); + // Hidden, even standing in it is nothing. + const inside = vilRound("street"); + standAt(inside, 96, 1, 13); + Object.assign(inside.you, { state: "air", vy: 0 }); + const t = put(inside, "shutter", 96, { y: 13 }); + inside.you.safeMs = 0; + ghoul.advance(inside, 4, steady); + assert.equal(events(inside, "lose").length, 0, "touch does nothing while it hides or rattles"); + assert.equal(ghoul.solid(t), false); + // Near: it rattles, then lunges, and is out (solid) a while. + standAt(round, 88); + round.you.safeMs = 1e9; + const rattle = log(round, 8, "shutterRattle"); + assert.equal(rattle.length, 1); + assert.equal(s.act, "rattle"); + assert.equal(ghoul.solid(s), false, "rattling is still hiding"); + const lunge = log(round, 1000, "shutterLunge"); + assert.equal(lunge.length, 1); + assert.ok(Math.abs(lunge[0][0] - rattle[0][0] - vl.SHUTTER_RATTLE_MS) < 40, `800 ms of rattle (${lunge[0][0] - rattle[0][0]})`); + until(round, () => s.act === "out", 400); + assert.equal(s.act, "out"); + assert.equal(ghoul.solid(s), true, "out: solid"); + const reach = Math.hypot(s.x - s.hx, s.y - s.hy); + assert.ok(Math.abs(reach - vl.SHUTTER_REACH) < 0.2 || reach < vl.SHUTTER_REACH + 1e-6, `out no further than 9 (${reach.toFixed(2)})`); + assert.ok(s.x < 96 && s.y < 13, "out toward you, down and across"); + // Out, a bolt hits it. + bolt(round, s, s.y + 2); + ghoul.advance(round, 8, steady); + assert.equal(s.hp, 1, "hit while out"); + // It stays out about 800 ms, pulls back and hides, then rests before it rattles again. + const pulled = log(round, 1000, "shutterPull"); + assert.equal(pulled.length, 1); + until(round, () => s.act === "hide", 600); + assert.equal(s.act, "hide"); + assert.equal(s.x, 96); + assert.equal(s.y, 13); + assert.equal(ghoul.solid(s), false); + round.events.length = 0; + run(round, 1500); + assert.equal(events(round, "shutterRattle").length, 0, "resting"); + run(round, 500); + assert.equal(events(round, "shutterRattle").length, 1, "again"); + // Out and touching you, it costs a life, the cause shutter. + const bite = vilRound("street"); + standAt(bite, 90); + put(bite, "shutter", 96, { y: 13 }); + until(bite, () => events(bite, "lose").length > 0, 1500); + assert.equal(events(bite, "lose")[0]?.cause, "shutter"); +}); + +/* ------------------------------------------------------------- moonhound */ + +test("Ghoul Rush's moonhound prowls, crouches 300 ms within 18 growling, leaps, and rests 600 ms where it lands, like the hellhound", () => { + const round = vilRound("inn"); + standAt(round, 20); + round.you.safeMs = 1e9; + const h = put(round, "moonhound", 70); + assert.equal(h.act, "prowl"); + run(round, 400); + assert.ok(h.x < 70 - 4, "it prowls at you"); + Object.assign(h, { x: 34 }); + const growl = log(round, 8, "growl"); + assert.equal(growl.length, 1); + assert.equal(growl[0][1].kind, "moonhound"); + assert.equal(h.act, "crouch"); + const lunge = log(round, 400, "lunge"); + assert.equal(lunge.length, 1); + assert.equal(lunge[0][1].kind, "moonhound"); + assert.ok(Math.abs(lunge[0][0] - growl[0][0] - vl.HOUND_LEAP.crouch) < 20, "300 ms crouch"); + assert.equal(h.act, "leap"); + until(round, () => h.act === "rest", 1200); + assert.equal(h.act, "rest"); + assert.equal(h.y, 6); + assert.ok(h.wait > 500); + const landedAt = round.clock; + until(round, () => h.act !== "rest", 1200); + assert.ok(Math.abs(round.clock - landedAt - vl.HOUND_LEAP.rest) < 40 + 8, `600 ms of rest (${round.clock - landedAt})`); +}); + +test("Ghoul Rush's turned villager leaps like a hound, faster, and growls and lunges as a villager", () => { + const round = vilRound("street", { full: true }); + standAt(round, 20); + round.you.safeMs = 1e9; + const v = put(round, "villager", 70, { group: true, turned: true, act: "prowl", hp: 5, max: 5 }); + v.init = true; + run(round, 400); + assert.ok(70 - v.x >= 22 * 0.4 - 1, `faster than a walk (${70 - v.x} in 400 ms, 22 a second against 8)`); + round.events.length = 0; + Object.assign(v, { x: 32, act: "prowl", wait: 0 }); + const growl = log(round, 8, "growl"); + assert.equal(growl[0]?.[1].kind, "villager"); + const lunge = log(round, 400, "lunge"); + assert.equal(lunge[0]?.[1].kind, "villager"); + assert.ok(Math.abs(lunge[0][0] - growl[0][0] - vl.WOLF_LEAP.crouch) < 20); +}); + +/* ------------------------------------------------------------- wolfsbane */ + +test("Ghoul Rush's Wolfsbane is found only in the Village: never dropped or placed anywhere else, and a placed one elsewhere is swapped", () => { + assert.equal(ghoul.POWERS.bane.stage, "village"); + assert.equal(ghoul.POWERS.bane.ms, 10000); + assert.equal(PILL_WORDS.bane, "BANE"); + assert.ok(ghoul.TIMED.includes("bane")); + assert.equal(ghoul.powerHere({ dark: true, stage: "manor" }, "bane"), false); + assert.equal(ghoul.powerHere({ dark: false, stage: null }, "bane"), false); + assert.equal(ghoul.powerHere({ dark: false, stage: "sanatorium" }, "bane"), false); + assert.equal(ghoul.powerHere({ dark: false, stage: "village" }, "bane"), true); + const rnd = ghoul.seeded(11); + for (const stage of [null, "manor", "wing", "graveyard", "grounds", "chapel", "sanatorium"]) { + for (let i = 0; i < 400; i++) { + assert.notEqual(pickPower(rnd, { dark: i % 2 === 0, stage }, "", i % 3 === 0), "bane", `${stage}: never picked`); + assert.notEqual(pickPower(rnd, { dark: true, stage }, "life", true), "bane"); + } + } + let sawIt = false; + for (let i = 0; i < 400; i++) if (pickPower(rnd, { dark: false, stage: "village" }) === "bane") sawIt = true; + assert.ok(sawIt, "it turns up in the Village"); + // Placed only in the Village's rooms. + for (const room of ghoul.ROOMS) { + const placed = [...room.items, ...room.sky].some((i) => i[0] === "bane"); + assert.equal(placed, ROOM_IDS.includes(room.id), `${room.id}: Wolfsbane ${placed ? "placed" : "absent"}`); + } + // A Wolfsbane placed in a room of another stage is swapped for something else. + const round = ghoul.newRound(3); + round.dice = 0; + assert.equal(round.stage, null); + const swapped = ghoul.powerHere(round, "bane") ? "bane" : "other"; + assert.equal(swapped, "other"); + // In a Village room a placed one stays. + const vr = vilRound("street"); + assert.equal(vr.loot[vr.spec.items.findIndex((i) => i[0] === "bane")], "bane"); + // Picked up it lasts 10 s. + standAt(vr, vr.spec.items.find((i) => i[0] === "bane")[1]); + vr.items.fill(false); + vr.you.safeMs = 1e9; + ghoul.advance(vr, 8, steady); + assert.equal(vr.effects.bane > 9900, true); + run(vr, 10100); + assert.equal(vr.effects.bane, 0); + assert.equal(events(vr, "expire").some((e) => e.kind === "bane"), true); +}); + +test("Ghoul Rush's Wolfsbane doubles your bolts against turned villagers and moonhounds, and nothing else", () => { + const round = vilRound("inn", { full: false }); + standAt(round, 20); + round.you.safeMs = 1e9; + const hound = put(round, "moonhound", 60, { act: "rest", wait: 1e9, hp: 6, max: 6 }); + const wolf = put(round, "villager", 80, { group: true, turned: true, act: "rest", wait: 1e9, hp: 6, max: 6 }); + const mob = put(round, "villager", 92, { group: true, hp: 6, max: 6 }); + const dead = put(round, "zombie", 120, { hp: 6, max: 6 }); + mob.init = wolf.init = true; + const hit = (m) => { + round.events.length = 0; + const before = m.hp; + bolt(round, m, m.y + m.h / 2); + ghoul.advance(round, 8, steady); + return before - m.hp; + }; + for (const m of [hound, wolf, mob, dead]) assert.equal(hit(m), 1, `${m.kind}: one without Wolfsbane`); + round.effects.bane = 5000; + assert.equal(hit(hound), 2, "a moonhound: double"); + assert.equal(hit(wolf), 2, "a turned villager: double"); + assert.equal(hit(mob), 1, "a villager still in his coat: no"); + assert.equal(hit(dead), 1, "a zombie: no"); +}); + +test("Ghoul Rush's Wolfsbane makes moonhounds and wolf-men shy away: they back off within 24, never crouch, and say so once", () => { + const plain = vilRound("inn"); + standAt(plain, 40); + plain.you.safeMs = 1e9; + const a = put(plain, "moonhound", 52); + run(plain, 600); + assert.ok(a.act === "crouch" || a.act === "leap" || a.act === "rest" || a.x < 50, "without it, it comes"); + const round = vilRound("inn"); + standAt(round, 40); + round.you.safeMs = 1e9; + round.effects.bane = 8000; + const h = put(round, "moonhound", 52); + const wolf = put(round, "villager", 56, { group: true, turned: true, act: "prowl", hp: 5, max: 5 }); + wolf.init = true; + const x0 = [h.x, wolf.x]; + const shy = log(round, 600, "baneShy"); + assert.equal(shy.length, 2, "each tells baneShy once"); + assert.deepEqual(shy.map((s) => s[1].kind).sort(), ["moonhound", "villager"]); + assert.ok(h.x > x0[0] + 2 && wolf.x > x0[1] + 2, "backing off"); + assert.equal(events(round, "growl").length, 0); + assert.equal(h.act, "prowl"); + assert.equal(events(round, "lose").length, 0); + // Far enough away, they are free to come again; the effect ending ends the shyness. + round.effects.bane = 0; + Object.assign(h, { x: 50 }); + const growl = log(round, 40, "growl"); + assert.equal(growl.length >= 1, true, "Wolfsbane gone: back to hunting"); +}); + +/* ------------------------------------------------------------- the Beast */ + +function greenFight() { + const round = vilRound("green"); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + ghoul.advance(round, 8, steady); + round.you.safeMs = 1e9; + round.events.length = 0; + return round; +} + +// The Beast about to choose its `n`th move. +function choose(round, n) { + const b = round.boss; + Object.assign(b, { act: "idle", wait: 0, moves: n - 1 }); +} + +test("Ghoul Rush's Beast waits at the end of the green, then in turn bounds to the farther wall, clings 600 ms, pounces where you stand under a shadow and shakes the ground as it lands", () => { + const round = greenFight(); + const b = round.boss; + assert.equal(b.kind, "beast"); + assert.equal(b.max, 110); + assert.equal(ghoul.roomFor("green", 0).bossHp, 110); + assert.deepEqual([b.w, b.h], [9, 10.5]); + assert.equal(round.twist.moon, vl.BEAST_MOON, "the moon hangs high"); + assert.equal(round.twist.full, false); + choose(round, 1); + const t0 = round.clock; + const seen = []; + for (let t = 0; t < 3200; t += 4) { + ghoul.advance(round, 4, steady); + for (const e of round.events) if (/^beast(Leap|Cling|Pounce|Land)$/.test(e.type)) seen.push([e.type, round.clock - t0, e]); + round.events.length = 0; + if (seen.length === 4) break; + } + assert.deepEqual(seen.map((s) => s[0]), ["beastLeap", "beastCling", "beastPounce", "beastLand"]); + const [leap, cling, pounce, land] = seen; + assert.equal(leap[2].side, 1, "the wall farther from you (you stand at the left)"); + assert.ok(Math.abs(cling[1] - leap[1] - vl.BOUND_MS) < 20, `480 ms to the wall (${cling[1] - leap[1]})`); + assert.ok(Math.abs(pounce[1] - cling[1] - vl.BEAST_CLING_MS) < 20, `600 ms clinging (${pounce[1] - cling[1]})`); + assert.ok(Math.abs(land[1] - pounce[1] - vl.POUNCE_MS) < 20, `700 ms in the air (${land[1] - pounce[1]})`); + assert.ok(Math.abs(cling[2].x - (200 - 4.5 + vl.WALL_INSET)) < 0.5, "on the right wall"); + assert.ok(Math.abs(cling[2].y - (6 + vl.BEAST_CLING_UP + 5.25)) < 0.5); + assert.ok(Math.abs(pounce[2].tx - round.you.x) < 1e-6, "where you stand"); + assert.ok(Math.abs(land[2].x - round.you.x) < 1e-6, "and down it comes there"); + assert.equal(land[2].big, true); + assert.equal(b.y, 6); + assert.equal(b.act, "rest"); + // The shadow marks the landing for the whole flight. + const fight = greenFight(); + choose(fight, 1); + until(fight, () => fight.boss.act === "cling", 1000); + until(fight, () => fight.boss.act === "pounce", 1000); + const shadow = fight.hazards.find((h) => h.kind === "shadow"); + assert.ok(shadow && shadow.w === 9 && shadow.live === 0 && Math.abs(shadow.x - fight.you.x) < 1e-6); + assert.ok(shadow.warn > 650 && shadow.total === 700); + run(fight, 300); + assert.ok(fight.hazards.find((h) => h.kind === "shadow").warn < 450); + until(fight, () => fight.boss.act === "rest", 1000); + assert.equal(fight.hazards.filter((h) => h.kind === "shadow").length, 0, "gone once it lands"); +}); + +test("Ghoul Rush's Beast is open to a double shot only while it clings, and Wolfsbane doubles every shot to it", () => { + const round = greenFight(); + const b = round.boss; + const shoot = () => { + const before = b.hp; + round.events.length = 0; + round.shots.push({ x: b.x - b.w / 2 - 0.3, y: b.y + 5, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + return before - b.hp; + }; + Object.assign(b, { act: "rest", wait: 1e9, y: 6 }); + assert.equal(shoot(), 1, "on the ground: one"); + assert.equal(events(round, "bossHit")[0]?.how, "shot"); + assert.equal(events(round, "bossHit")[0]?.kind, "beast"); + Object.assign(b, { act: "cling", wait: 1e9, x: 195.9, y: 9.6, side: 1 }); + assert.equal(shoot(), 2, "clinging: two"); + const hit = events(round, "bossHit")[0]; + assert.equal(hit.how, "weak"); + assert.equal(hit.weak, true); + assert.equal(hit.kind, "beast"); + round.effects.bane = 9000; + assert.equal(shoot(), 4, "clinging and Wolfsbane: four"); + Object.assign(b, { act: "rest", wait: 1e9, x: 150, y: 6 }); + assert.equal(shoot(), 2, "Wolfsbane alone: two"); + // The spot is off the ground: a shot from the floor misses a clinging Beast, one from a board hits. + const w = greenFight(); + Object.assign(w.boss, { act: "cling", wait: 1e9, x: 195.9, y: 9.6, side: 1 }); + standAt(w, 150); + w.shots.push({ x: 160, y: w.you.y + ghoul.SHOT_Y, vx: 130, vy: 0, gone: 0 }); + const hp = w.boss.hp; + run(w, 600); + assert.equal(w.boss.hp, hp, "the chest-high shot passes under it"); + standAt(w, 150, 1, 12.5, 0); + w.shots.push({ x: 160, y: 12.5 + ghoul.SHOT_Y, vx: 130, vy: 0, gone: 0 }); + Object.assign(w.boss, { act: "cling", wait: 1e9 }); + run(w, 600); + assert.equal(w.boss.hp, hp - 2, "a shot from a board hits"); +}); + +test("Ghoul Rush's Beast swipes when you are close: a 400 ms wind-up, then a claw 7.5 long that you jump or step out of", () => { + const round = greenFight(); + const b = round.boss; + standAt(round, b.x - 8); + round.you.safeMs = 1e9; + choose(round, 1); + const wind = log(round, 8, "swipeWind"); + assert.equal(wind.length, 1); + const swipe = log(round, 600, "beastSwipe"); + assert.equal(swipe.length, 1); + assert.ok(Math.abs(swipe[0][0] - wind[0][0] - vl.SWIPE_WIND_MS) < 20, `400 ms (${swipe[0][0] - wind[0][0]})`); + assert.equal(b.swipeCool > 0, true); + // The claw: in front of it, short-lived, a life on the floor, none in a jump. + const c = greenFight(); + const cb = c.boss; + standAt(c, cb.x - 8); + c.you.safeMs = 1e9; + choose(c, 1); + until(c, () => c.hazards.some((h) => h.kind === "claw"), 800); + const h = c.hazards.find((q) => q.kind === "claw"); + assert.ok(h && h.w === vl.SWIPE_REACH && h.h === vl.SWIPE_H && h.cause === "claw"); + assert.ok(h.x < cb.x - cb.w / 2, "on the side it faces"); + assert.ok(Math.abs(h.x - c.you.x) < h.w / 2); + c.you.safeMs = 0; + ghoul.advance(c, 4, steady); + assert.equal(events(c, "lose")[0]?.cause, "claw"); + const jump = greenFight(); + standAt(jump, jump.boss.x - 8, 1, 13.4); + Object.assign(jump.you, { state: "air", vy: 0 }); + Object.assign(jump.boss, { x: 180, act: "rest", wait: 1e9 }); + jump.hazards.push({ kind: "claw", x: jump.you.x, y: 6, w: 7.5, h: 7, dir: -1, live: 100, max: 200, cause: "claw" }); + jump.you.safeMs = 0; + ghoul.advance(jump, 4, steady); + assert.equal(events(jump, "lose").length, 0, "over the claw"); + const gone = greenFight(); + Object.assign(gone.boss, { x: 180, act: "rest", wait: 1e9 }); + gone.hazards.push({ kind: "claw", x: 172, y: 6, w: 7.5, h: 7, dir: 1, live: 200, max: 200, cause: "claw" }); + run(gone, 180); + assert.equal(gone.hazards.filter((q) => q.kind === "claw").length, 1); + run(gone, 40); + assert.equal(gone.hazards.filter((q) => q.kind === "claw").length, 0, "gone after 200 ms"); + // No second swipe at once. + const again = greenFight(); + standAt(again, again.boss.x - 8); + choose(again, 1); + until(again, () => events(again, "beastSwipe").length > 0, 1000); + choose(again, 2); + again.events.length = 0; + run(again, 100); + assert.equal(events(again, "swipeWind").length, 0, "cooling: it does something else"); +}); + +test("Ghoul Rush's Beast howls every third move for 1 s and calls two moonhounds in from the arena's ends, never more than four alive", () => { + const round = greenFight(); + const b = round.boss; + assert.equal(round.monsters.filter((m) => m.kind === "moonhound").length, 0); + choose(round, 3); + const howl = log(round, 8, "beastHowl"); + assert.equal(howl.length, 1); + assert.equal(b.act, "howl"); + const call = log(round, 1100, "houndCall"); + assert.equal(call.length, 1); + assert.ok(Math.abs(call[0][0] - howl[0][0] - vl.HOWL_MS) < 20, "a second"); + assert.equal(call[0][1].n, 2); + const hounds = round.monsters.filter((m) => m.kind === "moonhound"); + assert.equal(hounds.length, 2); + const hx = hounds.map((m) => m.x).sort((x, y) => x - y); + assert.ok(Math.abs(hx[0] - (round.spec.arena + 3)) < 2 && Math.abs(hx[1] - (round.spec.length - 3)) < 4, `from the arena's two ends (${hx})`); + // With three alive, one more; with four, it leaps instead. + const three = greenFight(); + for (let i = 0; i < 3; i++) put(three, "moonhound", 150 + i * 8, { act: "rest", wait: 1e9 }); + choose(three, 3); + until(three, () => events(three, "houndCall").length > 0, 1500); + assert.equal(events(three, "houndCall")[0].n, 1); + assert.equal(three.monsters.filter((m) => m.kind === "moonhound").length, 4); + const four = greenFight(); + for (let i = 0; i < 4; i++) put(four, "moonhound", 150 + i * 8, { act: "rest", wait: 1e9 }); + choose(four, 3); + four.events.length = 0; + run(four, 40); + assert.equal(events(four, "beastHowl").length, 0); + assert.equal(events(four, "beastLeap").length, 1, "a leap instead"); + // The order: two leaps, then a howl, and so on, when you stay far off. + const moves = []; + for (const n of [1, 2, 3, 4, 5, 6]) { + const order = greenFight(); + choose(order, n); + order.events.length = 0; + run(order, 20); + moves.push(events(order, "beastLeap").length ? "leap" : events(order, "beastHowl").length ? "howl" : "?"); + } + assert.deepEqual(moves, ["leap", "leap", "howl", "leap", "leap", "howl"]); +}); + +test("Ghoul Rush's Beast rages at half its hp: beastMoon once, a full moon, shorter waits, two pounces in a row, and the hounds it calls are grown", () => { + const round = greenFight(); + const b = round.boss; + b.hp = Math.floor(b.max / 2); + const moon = log(round, 8, "beastMoon"); + assert.equal(moon.length, 1); + assert.equal(b.raged, true); + ghoul.advance(round, 8, steady); + assert.equal(round.twist.full, true); + assert.equal(round.twist.moon, 1); + assert.equal(log(round, 200, "beastMoon").length, 0, "once"); + choose(round, 1); + const seen = []; + const t0 = round.clock; + for (let t = 0; t < 4200; t += 4) { + ghoul.advance(round, 4, steady); + for (const e of round.events) if (e.type === "beastPounce" || e.type === "beastLand") seen.push([e.type, round.clock - t0, e.second]); + round.events.length = 0; + if (round.boss.act === "rest" && seen.length === 4) break; + } + assert.deepEqual(seen.map((s) => s[0]), ["beastPounce", "beastLand", "beastPounce", "beastLand"]); + assert.deepEqual(seen.map((s) => Boolean(s[2])), [false, false, true, true]); + const gap = seen[2][1] - seen[1][1]; + assert.ok(Math.abs(gap - vl.SECOND_WAIT_MS * vl.BEAST_QUICK) < 24, `a short crouch between (${gap})`); + assert.ok(Math.abs(seen[3][1] - seen[2][1] - vl.SECOND_MS) < 20); + assert.ok(Math.abs(b.wait - vl.LAND_REST_MS * vl.BEAST_QUICK) < 12, `a shorter rest (${b.wait})`); + // Without the rage, one pounce and the rest. + const calm = greenFight(); + choose(calm, 1); + until(calm, () => calm.boss.act === "rest", 4000); + assert.ok(Math.abs(calm.boss.wait - vl.LAND_REST_MS) < 12); + assert.equal(events(calm, "beastPounce").length, 1); + // The hounds it calls now are grown. + round.monsters.length = 0; + b.swipeCool = 1e9; + choose(round, 3); + until(round, () => events(round, "houndCall").length > 0, 2000); + run(round, 20); + const hounds = round.monsters.filter((m) => m.kind === "moonhound"); + assert.equal(hounds.length, 2); + assert.ok(hounds.every((m) => m.grown && m.hp === 5), "grown, with more hp"); +}); + +/* ------------------------------------------------- lives and the dice of luck */ + +test("Ghoul Rush's every new way to lose a life goes through the endless-lives code: the life is spared, the loss still told", () => { + const causes = { + villager: (r) => put(r, "villager", r.you.x, { group: true }), + hanged: (r) => Object.assign(put(r, "hanged", r.you.x, { y: 19 }), { beam: 19, rest: 11.5, low: 3.5, y: r.you.y + 0.4, act: "hold", wait: 1e9, cool: 0 }), + shutter: (r) => Object.assign(put(r, "shutter", r.you.x, { y: r.you.y }), { hx: r.you.x, hy: r.you.y, ext: 1, rx: 0, ry: 0, reach: 1, act: "out", wait: 1e9, cool: 0 }), + moonhound: (r) => put(r, "moonhound", r.you.x, { act: "rest", wait: 1e9 }), + torch: (r) => r.bones.push({ id: 9e9, kind: "torch", cause: "torch", x: r.you.x, y: r.you.y + 2, vx: 0, vy: 0, spin: 0, life: 4000 }), + claw: (r) => r.hazards.push({ kind: "claw", x: r.you.x, y: 6, w: 7.5, h: 7, dir: 1, live: 200, max: 200, cause: "claw" }), + }; + for (const [cause, setup] of Object.entries(causes)) { + for (const infinite of [false, true]) { + const round = vilRound(cause === "hanged" ? "square" : "street"); + standAt(round, cause === "hanged" ? 330 : 50); + round.infinite = infinite; + setup(round); + const lives = round.lives; + run(round, 8); + assert.equal(events(round, "lose")[0]?.cause, cause, `${cause}: lost`); + assert.equal(round.lives, infinite ? lives : lives - 1, `${cause}${infinite ? " (endless)" : ""}`); + } + } + // The fire on the floor: the cause torch again. + for (const infinite of [false, true]) { + const round = vilRound("street"); + standAt(round, 50); + round.infinite = infinite; + round.hazards.push({ kind: "torchfire", x: 50, y: 6, w: 4.4, h: 2.4, live: 2000, max: 3200, cause: "torch" }); + const lives = round.lives; + run(round, 8); + assert.equal(events(round, "lose")[0]?.cause, "torch"); + assert.equal(round.lives, infinite ? lives : lives - 1); + } + // The Beast's body (landing on you, or at the wall), the cause beast. + for (const infinite of [false, true]) { + const round = greenFight(); + round.infinite = infinite; + standAt(round, 150); + round.you.safeMs = 0; + Object.assign(round.boss, { act: "rest", wait: 1e9, x: 150, y: 6 }); + const lives = round.lives; + run(round, 8); + assert.equal(events(round, "lose")[0]?.cause, "beast"); + assert.equal(round.lives, infinite ? lives : lives - 1, "the Beast"); + } + // The Lucky die and Garlic are the game's own; the cause must at least have words. + for (const cause of ["villager", "hanged", "shutter", "moonhound", "beast", "torch", "claw"]) assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], cause); +}); + +test("Ghoul Rush's village draws no random number: villagers, hanged men, shutter ghouls, hounds and the Beast move on a random that throws", () => { + const round = vilRound("street"); + standAt(round, 40); + round.you.safeMs = 1e9; + put(round, "villager", 70); + put(round, "moonhound", 90); + put(round, "shutter", 96, { y: 13 }); + run(round, 3000, {}, never); + const sq = vilRound("square"); + standAt(sq, 326); + sq.you.safeMs = 1e9; + put(sq, "hanged", 330, { y: 19 }); + run(sq, 2500, {}, never); + const fight = greenFight(); + for (let n = 1; n <= 7; n++) { + choose(fight, n); + fight.boss.hp = n > 4 ? Math.floor(fight.boss.max / 2) : fight.boss.hp; + run(fight, 1800, {}, never); + } + assert.ok(["beastLeap", "beastHowl", "beastPounce", "swipeWind"].every((type) => events(fight, type).length > 0), "it moved, drawing nothing"); +}); + +/* ---------------------------------------------------- voices and drawing */ + +test("Ghoul Rush's Village: every new kind has a voice for every act, each a real tone, and every event of the pack plays its own sound exactly once", () => { + // The acts the sound pick page names, and the two the game's own growl and lunge give a turned villager. + const listed = { + villager: ["appear", "wind", "throw", "land", "turn", "wolf", "hurt", "die"], + hanged: ["appear", "warn", "drop", "snap", "haul", "hurt", "die"], + shutter: ["appear", "rattle", "lunge", "pull", "hurt", "die"], + moonhound: ["appear", "growl", "lunge", "grow", "shy", "hurt", "die"], + beast: ["wake", "leap", "cling", "pounce", "land", "swipeWind", "swipe", "howl", "moon", "hurt", "weak", "die"], + moon: ["full"], + bane: ["active"], + }; + const own = { ...listed, villager: [...listed.villager, "growl", "lunge"] }; + for (const [kind, acts] of Object.entries(own)) assert.deepEqual(Object.keys(VOICES[kind]).sort(), [...acts].sort(), `${kind}: every act`); + const merged = ghoulSfx.default.tones; + for (const [kind, acts] of Object.entries(own)) for (const act of acts) assert.ok(merged[VOICES[kind][act]]?.layers?.length, `${kind}.${act}: ${VOICES[kind][act]} is a tone`); + for (const kind of [...Object.keys(vl.MONSTERS), ...Object.keys(vl.BOSSES)]) assert.ok(VOICES[kind] && VOICES[kind].die, `${kind} has a voice and a death`); + // Every event the pack emits is answered by one act, played once and nothing else; the hounds' call is quiet. + for (const type of vl.EVENTS) assert.ok(EVENT_VOICE[type] || type === "houndCall", `${type} is heard or deliberately quiet`); + for (const type of Object.keys(EVENT_VOICE)) assert.ok(vl.EVENTS.includes(type), `${type} is an event of the pack`); + for (const [type, [kind, act]] of Object.entries(EVENT_VOICE)) { + assert.ok(listed[kind].includes(act), `${type}: ${kind} ${act} is a listed act`); + assert.deepEqual(heard({ type, kind }).played, [VOICES[kind][act]], `${type}: ${kind} ${act}, once`); + } + assert.deepEqual(heard({ type: "houndCall", kind: "beast", n: 2 }).played, [], "the hounds' call is quiet"); + // Each listed act is the voice of some event (or the game's own play of it). + const reached = new Set(Object.values(EVENT_VOICE).map(([kind, act]) => `${kind}.${act}`)); + const theGames = ["villager.appear", "villager.throw", "villager.hurt", "villager.die", "hanged.appear", "hanged.hurt", "hanged.die", "shutter.appear", "shutter.hurt", "shutter.die", "moonhound.appear", "moonhound.growl", "moonhound.lunge", "moonhound.hurt", "moonhound.die", "beast.wake", "beast.hurt", "beast.weak", "beast.die", "bane.active"]; + for (const [kind, acts] of Object.entries(listed)) for (const act of acts) assert.ok(reached.has(`${kind}.${act}`) || theGames.includes(`${kind}.${act}`), `${kind}.${act} is played by something`); + // The game's own events carry the kind and find the voice, once. + const once = (e, kind, act, not = []) => { + const played = heard(e).played; + assert.equal(played.filter((n) => n === VOICES[kind][act]).length, 1, `${e.type}: ${kind} ${act} once`); + for (const n of not) assert.ok(!played.includes(n), `${e.type} does not play ${n}`); + }; + once({ type: "spawn", kind: "villager" }, "villager", "appear"); + once({ type: "spawn", kind: "hanged" }, "hanged", "appear"); + once({ type: "spawn", kind: "shutter" }, "shutter", "appear"); + once({ type: "spawn", kind: "moonhound" }, "moonhound", "appear"); + once({ type: "growl", kind: "moonhound" }, "moonhound", "growl"); + once({ type: "lunge", kind: "moonhound" }, "moonhound", "lunge"); + once({ type: "growl", kind: "villager" }, "villager", "growl"); + once({ type: "lunge", kind: "villager" }, "villager", "lunge"); + once({ type: "throw", by: "villager", kind: "torch" }, "villager", "throw", ["swoosh"]); + once({ type: "bossWake", kind: "beast" }, "beast", "wake"); + once({ type: "bossHit", kind: "beast", how: "shot" }, "beast", "hurt"); + once({ type: "bossHit", kind: "beast", how: "weak", weak: true }, "beast", "weak", [VOICES.beast.hurt]); + once({ type: "bossDown", kind: "beast", points: 1 }, "beast", "die"); + once({ type: "hit", kind: "hanged" }, "hanged", "hurt"); + once({ type: "kill", kind: "shutter", mult: 1, how: "shot", points: 1 }, "shutter", "die"); + once({ type: "kill", kind: "villager", mult: 1, how: "shot", points: 1 }, "villager", "die"); + // A weak hit on the Beast says "Double!". + const words = []; + heard({ type: "bossHit", kind: "beast", how: "weak", weak: true }, { float: (x, y, text) => words.push(text) }); + assert.ok(words.includes("Double!"), "a weak hit says Double!"); + // Wolfsbane's pickup plays its own sound, not the shared power-up one. + const bane = heard({ type: "power", kind: "bane", points: 50 }).played; + assert.ok(bane.includes(VOICES.bane.active) && !bane.includes("powerUp"), "the pickup is Wolfsbane's own sound"); +}); + +test("Ghoul Rush's Village: every new way to die has its words and its own sound", () => { + for (const cause of ["villager", "hanged", "shutter", "moonhound", "beast", "torch", "claw"]) { + assert.ok(LOSE_WORDS[cause] && LOSE_SOUNDS[cause], `${cause} has its words and its sound`); + assert.ok(heard({ type: "lose", cause, lives: 2 }).played.includes(LOSE_SOUNDS[cause][0]), `${cause} plays its own sound`); + } +}); + +test("Ghoul Rush's Village draws: every room, every monster in every act, the moon at every height, the Beast in each move with its shadow, claw and fire, the torch, Wolfsbane's badge, and the stage's card, in a lit room and a dark one", () => { + const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) }); + const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + r.offer = ["village"]; + r.phaseMs = 0; + ghoul.pickStage(r, 0); + const acts = { + villager: [{ act: "walk" }, { act: "wind", windup: 200 }, { act: "turn", wait: 400 }, { act: "prowl", turned: true }, { act: "crouch", turned: true, wait: 1e9 }, { act: "leap", turned: true, vx: 0, vy: 10 }], + hanged: [{ act: "sway" }, { act: "warn", wait: 1e9 }, { act: "drop" }, { act: "hold", wait: 1e9 }, { act: "haul" }], + shutter: [{ act: "hide" }, { act: "rattle", wait: 1e9 }, { act: "out", wait: 1e9 }], + moonhound: [{ act: "prowl" }, { act: "crouch", wait: 1e9 }, { act: "rest", wait: 1e9 }, { act: "rest", wait: 1e9, grown: true }], + }; + for (const id of ROOM_IDS) { + while (r.spec.id !== id) through(r); + for (const dark of [true, false]) { + for (const moon of [0, 0.5, 1]) { + r.dark = dark; + r.phase = "play"; + r.lives = 99; + for (const st of r.spawns) st.over = true; + r.hordeMs = Infinity; + r.monsters.length = 0; + standAt(r, id === "green" ? r.spec.arena + ghoul.BOSS_LOCK + 2 : 40); + r.you.safeMs = 1e9; + if (!r.boss) r.twist = { moon, full: moon === 1, ms: -1e12 }; + for (const [kind, list] of Object.entries(acts)) list.forEach((over, i) => put(r, kind, r.you.x + 6 + i * 5, { y: kind === "hanged" ? 19 : kind === "shutter" ? 13 : undefined, wait: 1e9, init: true, ...over })); + r.hazards.push({ kind: "torchfire", x: r.you.x + 8, y: 6, w: 4.4, h: 2.4, live: 2000, max: 3200, cause: "torch" }, { kind: "claw", x: r.you.x + 12, y: 6, w: 7.5, h: 7, dir: 1, live: 100, max: 200, cause: "claw" }, { kind: "shadow", x: r.you.x + 16, y: 6, w: 9, h: 0.6, warn: 300, total: 700, live: 0, cause: "beast" }); + r.bones.push({ id: 9e9, kind: "torch", cause: "torch", x: r.you.x + 12, y: 14, vx: 0, vy: 0, spin: 0, life: 4000 }); + if (r.boss) { + ghoul.advance(r, ghoul.BOSS_INTRO_MS + 16, steady); + for (const act of ["idle", "bound", "cling", "pounce", "crouch", "rest", "swipeWind", "howl"]) { + Object.assign(r.boss, { act, wait: 1e9, dir: -1, side: 1, fly: { x0: 150, y0: 6, x1: 190, y1: 9.6, T: 700, t: 100, arc: 5 } }); + g.tick(16); + } + r.boss.raged = true; + } + for (let k = 0; k < 20; k++) g.tick(16); + r.you.safeMs = 1e9; + } + } + } + assert.ok(r.spec.id === "green", "got to the green and drew it"); + for (const kind of ["bane"]) { + const p = vilRound("street"); + p.drops.push({ id: 1, kind, x: 30, y: 8, vx: 0, vy: 0, life: 9000, rest: true }); + p.sky.fill(false); + g.tick(16); + ghoul.applyPower(p, kind); + } + const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + pick.resize(900, 900); + pick.key("action"); + pick.tick(16); + const p = pick.round; + through(p); + p.offer = ["village", "chapel"]; + p.phase = "pick"; + p.phaseMs = 0; + for (let k = 0; k < 4; k++) pick.tick(16); + assert.equal(p.phase, "pick", "the pick screen draws the Village's card"); +}); diff --git a/scripts/test-web-console-activities-ghoul.mjs b/scripts/test-web-console-activities-ghoul.mjs new file mode 100644 index 0000000..fddd4ee --- /dev/null +++ b/scripts/test-web-console-activities-ghoul.mjs @@ -0,0 +1,3077 @@ +// Web console tests, Ghoul Rush: the game contract, running, jumping and the one-way shelves, the pits, the blaster, each monster, the chain, the power-ups, the key and the door, the bosses, a hit and the moment safe after it, the memo, every room's layout, the pills, the banners, the still layers, and a bot that plays the house, and its sounds. +// Run with: node --test scripts/test-web-console-activities-ghoul.mjs +// +// No browser and no server: the game draws only through the canvas it is +// handed, so stub canvases that count or record calls stand in for the page. +// The rules are plain functions over a round, driven here slice by slice. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import { BANNER_SHADE, CHUNK, GAUGE_COOL, GAUGE_HOT, GAUGE_WARM, LOOKS, SEAM, VOICES, contrast, gaugeColor, hudLayout, labelSpot, limbInk } from "../src/web-console/public/activities/ghoul-draw.js"; +import { ACCENTS } from "../src/web-console/public/palette.js"; +import { humNames, toneNames } from "../src/web-console/public/tones.js"; +import ghoulSfx from "../src/web-console/public/activities/ghoul-sfx.js"; +import { LIVES, LIVES_BACK, LIVES_INK, livesText } from "../src/web-console/public/activities/pills.js"; + +const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); +// The blips this game added to tones.js. +const GHOUL_TONES = Object.freeze(["ghoulBlast", "ghoulStomp", "ghoulBoo", "ghoulRoar", "ghoulCandy", "zombiePop", "zombieGroan", "batSwoop", "doorUnlock", "doorThrough", "creakBoard", "ghoulGrowl", "ghoulShriek", "ghoulSkitter", "ghoulSpit", "ghoulThunder"]); +const steady = () => 0.5; + +/* ------------------------------------------------------------ canvases */ + +// A 2D context whose every method is a no-op that counts itself. +function stubCanvas() { + const calls = { count: 0 }; + const ctx = new Proxy({}, { + get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }), + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls }; +} + +// A 2D context that records where each strip in a banner's shade is filled +// (its top and height), and does nothing else. +function bannerCanvas(shade) { + const shades = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillRect" ? (x, y, w, h) => t.fillStyle === shade && shades.push([y, h]) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, shades }; +} + +// A 2D context that keeps the style each fill used. +function styleCanvas() { + const fills = []; + const ctx = new Proxy({}, { + get: (target, name) => { + if (name === "fill" || name === "fillRect") return () => fills.push(target.fillStyle); + return name in target ? target[name] : () => {}; + }, + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, fills }; +} + +// A 2D context that keeps every method name it was called with, and answers +// the few calls the still layers need. +function recordingCanvas() { + const names = []; + const target = { getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), measureText: () => ({ width: 50 }) }; + const ctx = new Proxy(target, { + get: (t, name) => (name in t ? t[name] : () => { names.push(name); }), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 800, height: 600, getContext: () => ctx }; + ctx.canvas = canvas; + return { canvas, names }; +} + +// A 2D context that keeps every text drawn, with the font it was drawn in. +function textCanvas() { + const texts = []; + let font = ""; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text), font]) : name in target ? target[name] : () => {}), + set: (target, name, value) => { if (name === "font") font = value; target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, texts }; +} + +// The page's tokens in light and dark, for readColors() through a stubbed +// getComputedStyle. +const THEME_TOKENS = Object.freeze({ + light: Object.freeze({ "--panel": "#ffffff", "--panel-2": "#fbf9f6", "--rule": "#e4ddd1", "--accent": "#206cc3", "--ink": "#1d1a17" }), + dark: Object.freeze({ "--panel": "#201d1a", "--panel-2": "#262220", "--rule": "#332e29", "--accent": "#619fe5", "--ink": "#f0ece5" }), +}); + +// "#rrggbb" or "rgb(a)(...)" as [r, g, b, a], and the WCAG contrast of two. +function rgbaOf(color) { + const hex = /^#([0-9a-f]{6})$/i.exec(color); + if (hex) return [0, 2, 4].map((k) => parseInt(hex[1].slice(k, k + 2), 16)).concat(1); + const [r, g, b, a = 1] = /rgba?\(([^)]*)\)/.exec(color)[1].split(",").map(Number); + return [r, g, b, a]; +} +const toHex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`; +const overColor = (top, alpha, base) => top.slice(0, 3).map((v, i) => v * alpha + base[i] * (1 - alpha)); +function wcag(a, b) { + const lum = (c) => { + const [r, g, bl] = rgbaOf(c).slice(0, 3).map((v) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4)); + return 0.2126 * r + 0.7152 * g + 0.0722 * bl; + }; + const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); + return (x + 0.05) / (y + 0.05); +} + +// A 2D context that keeps, for each pill it draws (a rounded fill, perhaps +// a timer's rounded tint, then the text with no dark edge), the text's +// color, the backing composited over `board` and each tint over that. +function pillCanvas(board) { + const drawn = []; + let since = []; + const target = { globalAlpha: 1, getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), measureText: () => ({ width: 50 }) }; + const ctx = new Proxy(target, { + get: (t, name) => { + if (name in t) return t[name]; + if (name === "roundRect") return () => since.push({ k: "round" }); + if (name === "fill") return () => since.push({ k: "fill", style: t.fillStyle, alpha: t.globalAlpha }); + if (name === "fillText") return (text) => { drawn.push({ text: String(text), ink: t.fillStyle, since }); since = []; }; + if (name === "strokeText" || name === "fillRect" || name === "stroke") return () => since.push({ k: name }); + return () => {}; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 900, height: 900, getContext: () => ctx }; + ctx.canvas = canvas; + const pills = () => drawn.flatMap(({ text, ink, since: seq }) => { + if (seq.some((e) => e.k === "strokeText") || seq.at(-1)?.k !== "fill") return []; + const fills = seq.filter((e, i) => e.k === "fill" && seq[i - 1]?.k === "round"); + const back = fills.find((e) => e.alpha === 1); + if (!back) return []; + const b = rgbaOf(back.style); + const backing = toHex(overColor(b, b[3], rgbaOf(board))); + const tints = fills.slice(fills.indexOf(back) + 1).map((e) => { + const c = rgbaOf(e.style); + return toHex(overColor(c, e.alpha * c[3], rgbaOf(backing))); + }); + return [{ text, ink, backing, tints }]; + }); + return { canvas, pills, reset: () => { drawn.length = 0; since = []; } }; +} + +// Runs `fn` with getComputedStyle answering `values`. +function withTokens(values, fn) { + const saved = globalThis.getComputedStyle; + globalThis.getComputedStyle = () => ({ getPropertyValue: (name) => values[name] || "" }); + try { + return fn(); + } finally { + if (saved === undefined) delete globalThis.getComputedStyle; + else globalThis.getComputedStyle = saved; + } +} + +/* ---------------------------------------------------------- round helpers */ + +// Goes through the door of the room the round is in. +function through(round) { + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); +} + +// A round in the room `id`, reached the way play reaches it (out of the +// hall, its stage picked, the stage's rooms before it gone through), +// `depth` stages already cleared, nothing woken unless a test says so: +// every spawner spent, the bonus clock still. +function ghoulRound(id = "foyer", depth = 0) { + const round = ghoul.newRound(5); + round.dice = 0; + for (let i = 0; i < depth; i++) round.cleared.push(`cleared${i}`); + if (id !== "hall") { + const st = ghoul.STAGES.find((s) => s.rooms.includes(id)); + through(round); + assert.equal(round.phase, "pick"); + round.offer = [st.id]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== id) through(round); + } + round.phase = "play"; + quiet(round); + round.events.length = 0; + return round; +} + +// Spends every spawner and holds the horde back, so nothing else wakes. +function quiet(round) { + for (const st of round.spawns) st.over = true; + round.monsters.length = 0; + round.hordeMs = Infinity; + return round; +} + +// Puts you standing on the ground (or shelf `shelf`) at `x`. +function standAt(round, x, shelf = -1) { + const y = shelf >= 0 ? round.spec.shelves[shelf][2] : ghoul.groundAt(round.spec, x); + Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, cuttable: false, out: 0, safeMs: 0 }); + round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 36)); +} + +// A monster of `kind` standing on the ground at `x`, awake and ready. +function put(round, kind, x, over = {}) { + return ghoul.spawnMonster(round, kind, x, over.y ?? ghoul.groundAt(round.spec, x), { rise: 0, awake: true, ...over }); +} + +const events = (round, type) => round.events.filter((e) => e.type === type); + +// Holds `keys` for `ms`, slice by slice. +function hold(round, keys, ms) { + Object.assign(round.input, keys); + ghoul.advance(round, ms, steady); + for (const k of Object.keys(keys)) round.input[k] = typeof keys[k] === "number" ? 0 : false; +} + +// Plays a jump from where you stand until you land: its top and its time. +function jumpOnce(round, up = true) { + const you = round.you; + const y0 = you.y; + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = up; + let top = y0; + let ms = 0; + for (; ms < 3000 && (ms === 0 || you.state === "air"); ms += 4) { + ghoul.advance(round, 4, steady); + top = Math.max(top, you.y); + } + round.input.up = false; + return { rise: top - y0, ms }; +} + +/* ---------------------------------------------------------------- contract */ + +test("Ghoul Rush answers the game contract: ready until started, pause and resume, keys, a tick moves it, a tiny board is refused, and onScore once at the end", () => { + assert.equal(ghoul.default.id, "ghoul"); + assert.equal(ghoul.default.title, "Ghoul Rush"); + assert.ok(Object.isFrozen(ghoul.default)); + assert.equal("lowerIsBetter" in ghoul.default, false); + const { canvas, calls } = stubCanvas(); + const scores = []; + const g = ghoul.default.create({ canvas, tone: () => {}, onScore: (n) => scores.push(n) }); + assert.equal(g.state, "ready"); + assert.equal(typeof g.score, "number"); + g.pause(); + g.resume(); + g.tick(10_000); + assert.equal(g.state, "ready", "nothing before a start"); + assert.equal(g.resize(1, 1), false, "a tiny board is refused"); + assert.equal(g.resize(ghoul.W * ghoul.MIN_CELL - 1, 2000), false, "just too narrow"); + assert.equal(g.resize(ghoul.W * ghoul.MIN_CELL, ghoul.H * ghoul.MIN_CELL), true, "just big enough"); + assert.equal(g.resize(2000, 2000), true); + g.start(); + g.round.dice = 0; + assert.equal(g.state, "running"); + g.pause(); + assert.equal(g.state, "paused"); + const before = { score: g.score, calls: calls.count, x: g.round.you.x }; + g.tick(10_000); + assert.deepEqual({ score: g.score, calls: calls.count, x: g.round.you.x }, before, "ticks while paused change nothing"); + g.resume(); + assert.equal(g.state, "running"); + for (const name of ["up", "down", "left", "right", "action"]) assert.equal(g.key(name), true, `${name} is used`); + assert.equal(g.key("jump"), false, "an unknown key is not"); + const drawn = calls.count; + g.tick(16); + assert.ok(calls.count > drawn, "a tick draws"); + g.round.lives = 1; + ghoul.lose(g.round, "zombie"); + for (let ms = 0; ms < ghoul.CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score], "onScore once, with the score"); + g.tick(1000); + g.key("left"); + assert.equal(scores.length, 1); + g.key("action"); + assert.equal(g.state, "running", "space starts the next round at once"); + assert.equal(g.round.lives, ghoul.START_LIVES); +}); + +/* ---------------------------------------------------------------- moving */ + +test("Ghoul Rush: running holds RUN_SPEED and stops at once, a jump rises 12 units and lands in about 0.61 s, and letting up go early cuts it to a short hop", () => { + const round = ghoulRound(); + const you = round.you; + standAt(round, 20); + hold(round, { right: true }, 500); + assert.ok(Math.abs(you.x - (20 + ghoul.RUN_SPEED / 2)) < 0.1, `ran ${(you.x - 20).toFixed(2)} in half a second`); + const x = you.x; + ghoul.advance(round, 100, steady); + assert.equal(you.x, x, "and stopped the moment it was let go"); + assert.ok(Math.abs(ghoul.JUMP_TOP - 12) < 0.1); + const full = jumpOnce(round, true); + assert.ok(Math.abs(full.rise - ghoul.JUMP_TOP) < 0.2, `up ${full.rise.toFixed(2)}`); + assert.ok(full.ms > 580 && full.ms < 650, `down in ${full.ms} ms`); + const hop = jumpOnce(round, false); + assert.ok(hop.rise < full.rise / 2, `a tap is a short hop (${hop.rise.toFixed(2)})`); + assert.ok(Math.abs(ghoul.jumpHeightAt(0)) < 1e-9 && ghoul.jumpHeightAt(ghoul.RUN_SPEED * (ghoul.JUMP_V / ghoul.GRAVITY)) > 11, "jumpHeightAt follows the arc"); +}); + +test("Ghoul Rush: a jump pressed within COYOTE_MS of running off an edge still leaves it, a later one does not, and one pressed just before landing jumps as you land", () => { + const offEdge = (waitMs) => { + const round = ghoulRound("gallery"); + const you = round.you; + standAt(round, 96); + round.input.right = true; + while (you.state === "run") ghoul.advance(round, 4, steady); + ghoul.advance(round, waitMs, steady); + round.input.jump = 4; + round.input.up = true; + ghoul.advance(round, 4, steady); + return you.vy; + }; + assert.ok(offEdge(ghoul.COYOTE_MS - 30) > 0, "a moment after the edge, it jumps"); + assert.ok(offEdge(ghoul.COYOTE_MS + 30) < 0, "later, it falls"); + const round = ghoulRound(); + const you = round.you; + standAt(round, 40); + Object.assign(you, { state: "air", y: 6.6, vy: -10 }); + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = true; + for (let k = 0; k < 40 && you.vy <= 0; k++) ghoul.advance(round, 4, steady); + assert.ok(you.vy > 0, "the early press jumped on landing"); +}); + +test("Ghoul Rush: shelves are one way (jumped up through from below, landed on from above, dropped through with down), a small step is walked, a tall one is a wall, and no fall goes through a surface", () => { + const round = ghoulRound(); + const you = round.you; + const shelf = round.spec.shelves.findIndex(([x0, x1, y]) => y === 15 && x0 === 60); + const [x0, x1, top] = round.spec.shelves[shelf]; + standAt(round, (x0 + x1) / 2); + jumpOnce(round); + assert.deepEqual([you.state, you.shelf, you.y], ["run", shelf, top], "up through it and onto it"); + hold(round, { down: true }, 40); + assert.equal(you.state, "air", "down drops through"); + ghoul.advance(round, 800, steady); + assert.deepEqual([you.shelf, you.y], [-1, ghoul.groundAt(round.spec, you.x)], "back on the floor"); + // The Foyer's stairs climb in steps of 2.5: walked. + standAt(round, 140); + hold(round, { right: true }, 1200); + assert.equal(you.y, 13.5, "up the stairs to the landing"); + // The Kitchen's counter is 5 up: a wall until jumped. + const kitchen = ghoulRound("kitchen"); + standAt(kitchen, 60); + hold(kitchen, { right: true }, 600); + assert.ok(kitchen.you.x < 70 && kitchen.you.y === 6, `held at the counter (${kitchen.you.x.toFixed(1)})`); + kitchen.input.right = true; + jumpOnce(kitchen); + kitchen.input.right = false; + assert.equal(kitchen.you.y, 11, "and onto it with a jump"); + // A fall at FALL_MAX lands on the highest surface under it, everywhere. + for (const { id } of ghoul.ROOMS) { + const r = ghoulRound(id); + for (let x = 3; x < r.spec.length - 3; x += 3.7) { + const ground = ghoul.groundAt(r.spec, x); + const tops = r.spec.shelves.filter(([a, b]) => x >= a && x <= b).map(([, , y]) => y); + const want = Math.max(ground, ...tops); + if (want === -Infinity) continue; + Object.assign(r.you, { x, y: 40, vy: -ghoul.FALL_MAX, state: "air", shelf: -1, drop: -1, out: 0 }); + for (let k = 0; k < 500 && r.you.state === "air"; k++) ghoul.moveYou(r, 4); + assert.equal(r.you.y, want, `${r.spec.id} at ${x.toFixed(1)}`); + } + } +}); + +test("Ghoul Rush: a fall down a pit costs a life, garlic or not, and puts you back at the room's start safe for SAFE_MS", () => { + const round = ghoulRound("gallery"); + const you = round.you; + you.garlic = true; + standAt(round, 99); + Object.assign(round.you, { garlic: true, x: 104, state: "air", vy: 0 }); + for (let k = 0; k < 500 && round.phase === "play"; k++) ghoul.advance(round, 4, steady); + assert.equal(round.phase, "crash"); + assert.equal(round.lives, ghoul.START_LIVES - 1); + assert.equal(events(round, "lose")[0].cause, "pit"); + ghoul.advance(round, ghoul.CRASH_MS + 10, steady); + assert.equal(round.phase, "ready"); + assert.equal(round.you.x, round.spec.start, "back at the start"); + assert.equal(round.you.safeMs, ghoul.SAFE_MS); + ghoul.advance(round, ghoul.READY_MS + 10, steady); + assert.equal(round.phase, "play"); +}); + +/* ---------------------------------------------------------------- blaster */ + +test("Ghoul Rush: held fire shoots a bolt every FIRE_MS the way you face (RAPID_MS with Rapid fire, three with Spread shot), and a bolt stops at a wall or after SHOT_RANGE", () => { + const count = (setup) => { + const round = ghoulRound(); + standAt(round, 40); + setup(round); + round.input.fire = true; + let shots = 0; + for (let ms = 0; ms < 1020; ms += 4) { + ghoul.advance(round, 4, steady); + shots += events(round, "fire").length; + round.events.length = 0; + } + return { shots, round }; + }; + const plain = count(() => {}); + assert.equal(plain.shots, Math.ceil(1020 / ghoul.FIRE_MS), "a bolt every FIRE_MS"); + assert.ok(plain.round.shots.every((s) => s.vx > 0), "facing right, they fly right"); + const rapid = count((r) => ghoul.applyPower(r, "rapid")); + assert.equal(rapid.shots, Math.ceil(1020 / ghoul.RAPID_MS), "twice as often with Rapid fire"); + const left = count((r) => (r.you.face = -1)); + assert.ok(left.round.shots.every((s) => s.vx < 0), "facing left, they fly left"); + const round = ghoulRound(); + standAt(round, 40); + ghoul.applyPower(round, "spread"); + round.input.fire = true; + ghoul.advance(round, 4, steady); + assert.equal(round.shots.length, 3, "Spread shot: three"); + assert.deepEqual(round.shots.map((s) => Math.sign(s.vy)).sort(), [-1, 0, 1]); + // A bolt flies SHOT_RANGE at most. + round.input.fire = false; + round.shots.length = 0; + round.effects.spread = 0; + round.fireMs = 0; + round.input.fire = true; + ghoul.advance(round, 4, steady); + round.input.fire = false; + const s = round.shots[0]; + ghoul.advance(round, 2000, steady); + assert.ok(!round.shots.includes(s) && s.gone >= ghoul.SHOT_RANGE - 2 && s.gone < ghoul.SHOT_RANGE + 2, `gone after ${s.gone.toFixed(1)}`); + // From the foot of the Kitchen's counter, a bolt hits its side. + const kitchen = ghoulRound("kitchen"); + standAt(kitchen, 60); + kitchen.input.fire = true; + ghoul.advance(kitchen, 4, steady); + kitchen.input.fire = false; + ghoul.advance(kitchen, 300, steady); + assert.ok(events(kitchen, "puff").length >= 1 && kitchen.shots.length === 0, "into the counter's side"); +}); + +test("Ghoul Rush: the blaster heats up, slowing a held or hammered fire to one bolt every SLOW_FIRE_MS, and cools only once let go past COOL_DELAY_MS", () => { + assert.equal(ghoul.fireGap(0), ghoul.FIRE_MS); + assert.equal(ghoul.fireGap(ghoul.HEAT_FREE), ghoul.FIRE_MS, "the first HEAT_FREE bolts go at the full rate"); + assert.ok(ghoul.fireGap(ghoul.HEAT_FREE + 1) > ghoul.FIRE_MS, "then each waits longer"); + assert.equal(ghoul.fireGap(ghoul.HEAT_MAX), ghoul.SLOW_FIRE_MS, "down to the floor"); + const shotsIn = (round, ms) => { + let shots = 0; + for (let t = 0; t < ms; t += 4) { + ghoul.advance(round, 4, steady); + shots += events(round, "fire").length; + round.events.length = 0; + } + return shots; + }; + // Held: the full rate at first, and one a second once the blaster is hot. + const round = ghoulRound(); + standAt(round, 40); + round.input.fire = true; + shotsIn(round, 20000); + assert.equal(round.heat, ghoul.HEAT_MAX, "held long enough, the blaster is at its hottest"); + const hot = shotsIn(round, 3000); + assert.ok(hot >= 2 && hot <= 4, `${hot} bolts in 3 seconds when hot`); + // Hammered: a tap every 150ms never gets past COOL_DELAY_MS, so it heats too. + const tapped = ghoulRound(); + standAt(tapped, 40); + for (let i = 0; i < 160; i++) { + tapped.input.fire = true; + shotsIn(tapped, 40); + tapped.input.fire = false; + shotsIn(tapped, 110); + } + assert.equal(tapped.heat, ghoul.HEAT_MAX, "tapping heats it as much as holding"); + // Let go: no cooling for COOL_DELAY_MS, then COOL_RATE a second, cool again in time. + round.input.fire = false; + shotsIn(round, ghoul.COOL_DELAY_MS - 20); + assert.equal(round.heat, ghoul.HEAT_MAX, "a short let-go does not cool it"); + shotsIn(round, 1020); + assert.ok(Math.abs(round.heat - (ghoul.HEAT_MAX - ghoul.COOL_RATE)) < 0.5, `${round.heat} after a second of cooling`); + shotsIn(round, 3000); + assert.equal(round.heat, 0, "cool again"); + round.input.fire = true; + assert.equal(shotsIn(round, 1020), Math.ceil(1020 / ghoul.FIRE_MS), "and at the full rate again"); + // Rapid fire adds no heat and ignores it. + const rapid = ghoulRound(); + standAt(rapid, 40); + rapid.heat = ghoul.HEAT_MAX; + ghoul.applyPower(rapid, "rapid"); + rapid.input.fire = true; + assert.equal(shotsIn(rapid, 1020), Math.ceil(1020 / ghoul.RAPID_MS), "Rapid fire's full rate even when hot"); + assert.equal(rapid.heat, ghoul.HEAT_MAX, "and no heat added"); +}); + +test("Ghoul Rush: a bolt tilts toward the nearest monster ahead near your chest's height, by no more than AIM_MAX", () => { + const round = ghoulRound(); + standAt(round, 40); + assert.equal(ghoul.aimAt(round), 0, "nothing ahead: level"); + put(round, "skeleton", 60, { y: 11 }); + const a = ghoul.aimAt(round); + assert.ok(a > 0 && a <= ghoul.AIM_MAX, `up toward it (${a.toFixed(3)})`); + round.you.face = -1; + assert.equal(ghoul.aimAt(round), 0, "behind you: level"); + round.you.face = 1; + round.monsters[0].y = 30; + assert.equal(ghoul.aimAt(round), 0, "far above: level"); +}); + +/* ---------------------------------------------------------------- monsters */ + +test("Ghoul Rush: a zombie shambles toward you, sprints within LURCH_RANGE, never walks off an edge or onto a shelf, takes three bolts, and scores its points", () => { + const round = ghoulRound("gallery"); + standAt(round, 30); + const z = put(round, "zombie", 80); + ghoul.advance(round, 1000, steady); + assert.ok(Math.abs(z.x - (80 - ghoul.MONSTERS.zombie.speed)) < 0.1, `shambles (${z.x.toFixed(2)})`); + z.x = 30 + ghoul.LURCH_RANGE - 2; + const x = z.x; + round.you.safeMs = 1e9; + ghoul.advance(round, 100, steady); + assert.ok(Math.abs(x - z.x - ghoul.MONSTERS.zombie.lurch * 0.1) < 0.05, "sprints when close"); + // At the Gallery's first pit (10 across), it stops at the edge, thinks + // about it, then leaps it. + standAt(round, 120); + const e = put(round, "zombie", 96); + round.events.length = 0; + for (let k = 0; k < 300 && !events(round, "ponder").length; k++) ghoul.advance(round, 16, steady); + assert.equal(events(round, "ponder").length, 1, "at the edge, thinking about it"); + ghoul.advance(round, ghoul.PONDER_MS - 50, steady); + assert.ok(e.x < 100 && e.y === 6 && !e.hop, `held at the edge a while (${e.x.toFixed(1)})`); + ghoul.advance(round, 4 * ghoul.PONDER_STEP_MS, steady); + assert.equal(events(round, "leap").length, 1, "then it leaps"); + ghoul.advance(round, 1000, steady); + assert.ok(!e.dead && e.x > 110 && e.y === 6 && !e.hop, `over the pit (${e.x.toFixed(1)}, ${e.y})`); + // The Library's first pit (12 across), its bridge crumbled away, is too + // wide: held there for good. + const lib = ghoulRound("library"); + lib.down[0] = 1e9; + standAt(lib, 110); + const w = put(lib, "zombie", 85); + ghoul.advance(lib, 8000, steady); + assert.ok(w.x < 90 && w.y === 6 && !w.hop, `too wide to leap (${w.x.toFixed(1)})`); + assert.equal(events(lib, "leap").length, 0); + // Down is further: the Kitchen's pit from its counter (11) to the floor + // (6) is 12 across too, but the drop gives the leap the time to clear it. + const down = (n, from, to, at) => { + const r = ghoulRound(n); + standAt(r, at); + r.you.safeMs = 1e9; + const m = put(r, "zombie", from); + ghoul.advance(r, 8000, steady); + return m; + }; + const kit = down("kitchen", 262, 282, 300); + assert.ok(!kit.dead && kit.x > 282 && kit.y === 6, `down across the Kitchen's wide pit (${kit.x.toFixed(1)}, ${kit.y})`); + // And straight down off a ledge to the floor below it. + const ledge = down("kitchen", 100, 110, 130); + assert.ok(!ledge.dead && ledge.x > 110 && ledge.y === 6, `down off the counter (${ledge.x.toFixed(1)}, ${ledge.y})`); + // Three bolts, then gone, for its points. + const r2 = ghoulRound(); + standAt(r2, 30); + const k = put(r2, "zombie", 50); + const before = r2.score; + r2.input.fire = true; + for (let ms = 0; ms < 1000 && r2.monsters.includes(k); ms += 4) ghoul.advance(r2, 4, steady); + r2.input.fire = false; + assert.equal(events(r2, "hit").length, ghoul.MONSTERS.zombie.hp - 1, "the first bolts hurt"); + assert.deepEqual(events(r2, "kill").map((ev) => [ev.kind, ev.points, ev.how]), [["zombie", ghoul.MONSTERS.zombie.points, "shot"]]); + assert.ok(r2.score - before >= ghoul.MONSTERS.zombie.points); +}); + +test("Ghoul Rush: a bolt to the head (the top HEAD_SHARE) or a stomp from above doubles a kill, a stomp bounces you, and a ghost cannot be stomped", () => { + const round = ghoulRound(); + standAt(round, 30); + const z = put(round, "zombie", 34, { hp: 1 }); + round.shots.push({ x: 33, y: z.y + z.h - 0.5, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.deepEqual(events(round, "kill").map((e) => [e.how, e.points]), [["head", ghoul.MONSTERS.zombie.points * 2]]); + const r2 = ghoulRound(); + standAt(r2, 30); + r2.you.safeMs = 0; + const c = put(r2, "crawler", 30); + Object.assign(r2.you, { y: c.y + c.h + 0.2, vy: -20, state: "air" }); + ghoul.advance(r2, 40, steady); + assert.deepEqual(events(r2, "kill").map((e) => [e.kind, e.how, e.points]), [["crawler", "stomp", ghoul.MONSTERS.crawler.points * 2]]); + assert.ok(r2.you.vy > 0 && r2.lives === ghoul.START_LIVES, "bounced up, unhurt"); + const r3 = ghoulRound(); + standAt(r3, 30); + const g = put(r3, "ghost", 30, { y: 6, phase: ghoul.GHOST_APPEAR_MS + 100 }); + Object.assign(r3.you, { y: g.y + g.h + 0.2, vy: -20, state: "air" }); + ghoul.advance(r3, 40, steady); + assert.equal(events(r3, "kill").length, 0, "no stomping a ghost"); +}); + +test("Ghoul Rush: a crawler is harmless and unhittable for RISE_MS as it comes up, a door holds its zombies while you are within DOOR_CLEAR and each steps out harmless", () => { + const round = ghoulRound("gallery"); + standAt(round, 60); + round.spawns = round.spec.spawns.map(() => ({ over: false, on: false, done: 0, t: 0 })); + round.spawns.forEach((st, i) => (st.over = i !== 0)); + ghoul.advance(round, 4, steady); + const c = round.monsters.find((m) => m.kind === "crawler"); + assert.ok(c && c.rise > 0, "woken by you near its board"); + assert.equal(ghoul.solid(c), false); + c.x = round.you.x; + ghoul.advance(round, ghoul.RISE_MS - 50, steady); + assert.equal(round.lives, ghoul.START_LIVES, "no hit while it comes up"); + ghoul.advance(round, 100, steady); + assert.equal(round.phase, "crash", "up, and on you: a hit"); + const foyer = ghoulRound(); + const door = foyer.spec.spawns.findIndex((s) => s[0] === "door"); + const dx = foyer.spec.spawns[door][1]; + foyer.spawns[door].over = false; + standAt(foyer, dx - 5); + foyer.camX = dx - 50; + ghoul.advance(foyer, 3000, steady); + assert.equal(foyer.monsters.length, 0, "held while you are close"); + standAt(foyer, dx - ghoul.DOOR_CLEAR - 6); + foyer.camX = dx - 50; + ghoul.advance(foyer, ghoul.EMERGE_MS / 2, steady); + const z = foyer.monsters[0]; + assert.ok(z && z.rise > 0 && !ghoul.solid(z), "out it steps, harmless at first"); +}); + +test("Ghoul Rush: a bat roosts until you come within BAT_NEAR, then swoops in level passes at your chest and never drops onto your head", () => { + const round = ghoulRound("library"); + standAt(round, 20); + round.you.safeMs = 1e9; + const b = put(round, "bat", 20 + ghoul.BAT_NEAR + 4, { y: 44, awake: false }); + ghoul.advance(round, 500, steady); + assert.equal(b.awake, false, "asleep while you are far"); + standAt(round, 30); + round.you.safeMs = 1e9; + ghoul.advance(round, 16, steady); + assert.equal(b.awake, true); + let passes = 0; + let level = 0; + let side = Math.sign(b.x - round.you.x); + const chest = round.you.y + ghoul.SHOT_Y; + for (let ms = 0; ms < 8000; ms += 16) { + ghoul.advance(round, 16, steady); + if (Math.abs(b.x - round.you.x) < 2) assert.ok(Math.abs(b.y + b.h / 2 - chest) < 3.5 || b.y > round.you.y + ghoul.YOU_H + 3, `over you it is at your chest or well clear of your head (${b.y.toFixed(1)})`); + const s = Math.sign(b.x - round.you.x); + if (s && s !== side) { + passes++; + side = s; + if (Math.abs(b.y + b.h / 2 - chest) < 3.5) level++; + } + } + assert.ok(passes >= 3, `it comes back for more (${passes} passes)`); + assert.ok(level >= 2, `level with your chest, where a bolt finds it (${level} of ${passes})`); +}); + +test("Ghoul Rush: a ghost can be hit and can hurt only while solid, never turns solid on top of you, and takes two bolts", () => { + const round = ghoulRound("conservatory"); + standAt(round, 30); + const g = put(round, "ghost", 30, { y: 6, phase: ghoul.GHOST_SHOW_MS + 100 }); + assert.equal(ghoul.solid(g), false, "faded"); + ghoul.advance(round, 4000, steady); + assert.equal(round.lives, ghoul.START_LIVES, "faded on top of you, it waits"); + assert.equal(ghoul.solid(g), false); + g.x = 50; + round.you.safeMs = 1e9; + for (let ms = 0; ms < 3000 && !ghoul.solid(g); ms += 4) ghoul.advance(round, 4, steady); + assert.ok(ghoul.solid(g), "clear of you, it turns solid"); + const faded = put(round, "ghost", 40, { y: 6, phase: ghoul.GHOST_SHOW_MS + 600 }); + round.shots.push({ x: 39.5, y: 8, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(faded.hp, ghoul.MONSTERS.ghost.hp, "a bolt goes through a faded ghost"); + assert.ok(ghoul.ghostSight(faded) < 0.2); +}); + +test("Ghoul Rush: a skeleton winds up, then throws a bone timed to come down at you; it holds its bone within SKEL_NEAR; a bone shot down scores BONE_POINTS and one that lands on you is a hit", () => { + const round = ghoulRound("kitchen"); + standAt(round, 40); + round.camX = 20; + const s = put(round, "skeleton", 66, { throwIn: 10 }); + ghoul.advance(round, 20, steady); + assert.equal(events(round, "windup").length, 1, "the arm goes up"); + assert.equal(round.bones.length, 0); + ghoul.advance(round, ghoul.SKEL_WINDUP_MS, steady); + assert.equal(round.bones.length, 1, "and the bone flies"); + assert.deepEqual(events(round, "throw").map((e) => e.by), ["skeleton"], "the throw says who threw it, for its sound"); + const b = round.bones[0]; + assert.ok(b.vx < 0, "toward you"); + for (let ms = 0; ms < 3000 && round.phase === "play"; ms += 4) ghoul.advance(round, 4, steady); + assert.deepEqual(events(round, "lose").map((e) => e.cause), ["bone"], "standing still, it lands on you"); + const r2 = ghoulRound("kitchen"); + standAt(r2, 60); + r2.camX = 30; + const near = put(r2, "skeleton", 60 + ghoul.SKEL_NEAR - 1, { throwIn: 10 }); + r2.you.safeMs = 1e9; + ghoul.advance(r2, 1000, steady); + assert.equal(near.windup + r2.bones.length, 0, "too close to throw"); + const r3 = ghoulRound("kitchen"); + standAt(r3, 40); + r3.bones.push({ id: 1, x: 50, y: 8.4, vx: 0, vy: 0, spin: 0, life: 4000 }); + r3.shots.push({ x: 49, y: 8.4, vx: 80, vy: 0, gone: 0 }); + const before = r3.score; + ghoul.advance(r3, 4, steady); + assert.equal(r3.score - before, ghoul.BONE_POINTS); + assert.equal(r3.bones.length, 0); + assert.ok(s); +}); + +test("Ghoul Rush: a hellhound prowls toward you, crouches growling within HOUND_RANGE, then lunges in a low arc a jump clears, rests after it lands, and dies in a pit it lunges into", () => { + const round = ghoulRound("gallery"); + standAt(round, 30); + round.you.safeMs = 1e9; + const h = put(round, "hound", 70); + ghoul.advance(round, 1000, steady); + assert.ok(Math.abs(h.x - (70 - ghoul.MONSTERS.hound.speed)) < 0.2, `prowls (${h.x.toFixed(2)})`); + h.x = 30 + ghoul.HOUND_RANGE - 2; + ghoul.advance(round, 8, steady); + assert.deepEqual([h.act, events(round, "growl").length], ["crouch", 1], "crouches, growling"); + const x = h.x; + ghoul.advance(round, ghoul.HOUND_CROUCH_MS - 20, steady); + assert.equal(h.x, x, "still while it crouches"); + ghoul.advance(round, 40, steady); + assert.deepEqual([h.act, events(round, "lunge").length], ["leap", 1], "then lunges"); + let top = h.y; + for (let ms = 0; ms < 2000 && h.act === "leap"; ms += 4) { + ghoul.advance(round, 4, steady); + top = Math.max(top, h.y); + } + assert.ok(top - 6 < ghoul.JUMP_TOP / 2, `a low arc (${(top - 6).toFixed(2)} up)`); + assert.equal(h.act, "rest"); + // Standing, its lunge lands on you; jumping, it passes under. + const lunge = (jumped) => { + const r = ghoulRound("gallery"); + standAt(r, 30); + put(r, "hound", 30 + ghoul.HOUND_RANGE - 2); + for (let ms = 0; ms < 1500 && r.phase === "play"; ms += 4) { + const m = r.monsters[0]; + if (jumped && m && m.act === "leap" && r.you.state === "run" && !r.input.jump) Object.assign(r.input, { jump: ghoul.JUMP_BUFFER_MS, up: true }); + ghoul.advance(r, 4, steady); + } + return r.phase !== "play"; + }; + assert.equal(lunge(false), true, "standing still, it gets you"); + assert.equal(lunge(true), false, "a jump clears it"); + // At the Gallery's first pit, a lunge over it falls in. + const r2 = ghoulRound("gallery"); + standAt(r2, 108); + r2.you.safeMs = 1e9; + const p = put(r2, "hound", 96, { act: "leap", vx: ghoul.HOUND_LUNGE_VX, vy: 4, dir: 1 }); + p.x = 101; + ghoul.advance(r2, 2000, steady); + assert.ok(!r2.monsters.includes(p) && events(r2, "kill").length === 0, "gone down the pit, no points"); +}); + +test("Ghoul Rush: a widow hangs out of reach and out of the banner's strip till you come within SPIDER_NEAR, drops onto the surface under it, then skitters after you", () => { + const round = ghoulRound("gallery"); + standAt(round, 30); + round.you.safeMs = 1e9; + const s = put(round, "spider", 30 + ghoul.SPIDER_NEAR + 6, { y: ghoul.SPIDER_Y, act: "hang" }); + ghoul.advance(round, 500, steady); + assert.deepEqual([s.act, s.y], ["hang", ghoul.SPIDER_Y], "it waits"); + assert.equal(ghoul.roused(s), false, "and does not count yet"); + assert.equal(ghoul.aimAt(round), 0, "nor draws your aim"); + standAt(round, 40); + round.you.safeMs = 1e9; + ghoul.advance(round, 4, steady); + assert.deepEqual([s.act, events(round, "skitter").length], ["drop", 1]); + for (let ms = 0; ms < 2000 && s.act === "drop"; ms += 4) ghoul.advance(round, 4, steady); + assert.deepEqual([s.act, s.y], ["walk", 6], "down on the floor"); + const x = s.x; + ghoul.advance(round, 200, steady); + assert.ok(s.x < x, "and after you"); + // One right over you drops onto you. + const r2 = ghoulRound("gallery"); + standAt(r2, 30); + put(r2, "spider", 30, { y: ghoul.SPIDER_Y, act: "hang" }); + for (let ms = 0; ms < 1500 && r2.phase === "play"; ms += 4) ghoul.advance(r2, 4, steady); + assert.deepEqual(events(r2, "lose").map((e) => e.cause), ["spider"]); +}); + +test("Ghoul Rush: a wraith is unseen till you come within WRAITH_NEAR, hovers ahead of you within a tilted bolt's reach, shrieks for WRAITH_WIND_MS, then dives at where your chest was, so moving off the spot dodges it and a bolt brings it down", () => { + const round = ghoulRound("conservatory"); + standAt(round, 30); + round.you.safeMs = 1e9; + const w = put(round, "wraith", 30 + ghoul.WRAITH_NEAR + 10, { y: 32, act: "idle", home: 32 }); + ghoul.advance(round, 300, steady); + assert.deepEqual([w.act, ghoul.solid(w)], ["idle", false], "unseen while you are far"); + standAt(round, 30 + 20); + round.you.safeMs = 1e9; + ghoul.advance(round, 4, steady); + assert.deepEqual([w.act, ghoul.solid(w), events(round, "wraith").length], ["hover", true, 1]); + w.wait = 1e9; + ghoul.advance(round, 2000, steady); + assert.ok(Math.abs(w.x - (round.you.x + ghoul.WRAITH_KEEP)) < 3, `hovers ahead (${(w.x - round.you.x).toFixed(1)})`); + assert.ok(w.y <= round.you.y + ghoul.WRAITH_ABOVE + 1.6, "never too high to shoot"); + const a = ghoul.aimAt(round); + assert.ok(a > 0 && a <= ghoul.AIM_MAX, `a bolt tilts up to it (${a.toFixed(2)})`); + // The dive: standing still it gets you; stepping back, it misses. + const dive = (dodge) => { + const r = ghoulRound("conservatory"); + standAt(r, 60); + const m = put(r, "wraith", 60 + ghoul.WRAITH_KEEP, { y: 23, act: "wind", wait: 10, home: 23 }); + let shrieked = false; + for (let ms = 0; ms < 2500 && r.phase === "play" && m.act !== "rise"; ms += 4) { + if (dodge && m.act === "dive") r.input.left = true; + ghoul.advance(r, 4, steady); + shrieked ||= events(r, "dive").length > 0; + } + r.input.left = false; + assert.ok(shrieked, "it dives"); + return r.phase !== "play"; + }; + assert.equal(dive(false), true, "standing still, it gets you"); + assert.equal(dive(true), false, "stepping back, it misses and climbs away"); + const r3 = ghoulRound("conservatory"); + standAt(r3, 30); + r3.you.safeMs = 1e9; + const m = put(r3, "wraith", 50, { y: 20, act: "hover", wait: 1e9, home: 20 }); + r3.input.fire = true; + for (let ms = 0; ms < 1000 && r3.monsters.includes(m); ms += 4) ghoul.advance(r3, 4, steady); + assert.deepEqual(events(r3, "kill").map((e) => e.kind), ["wraith"], "shot down while it hovers"); +}); + +test("Ghoul Rush: a bloater wades in to SPIT_KEEP, swells, and lobs acid that leaves a burning puddle for PUDDLE_MS (jumped, it is harmless); shot down, it bursts in a harmless splash, no acid flung and no puddle", () => { + const round = ghoulRound("kitchen"); + standAt(round, 40); + round.camX = 20; + round.you.safeMs = 1e9; + const b = put(round, "spitter", 90, { throwIn: 1e9 }); + ghoul.advance(round, 3000, steady); + assert.ok(b.x < 90 && b.x - round.you.x >= ghoul.SPIT_KEEP - 0.5, `wades in, then keeps off (${(b.x - round.you.x).toFixed(1)})`); + b.throwIn = 10; + ghoul.advance(round, 20, steady); + assert.equal(events(round, "spit").length, 1, "it swells"); + ghoul.advance(round, ghoul.SPIT_WINDUP_MS, steady); + assert.deepEqual(round.bones.map((g) => g.kind), ["acid"], "and lobs acid"); + assert.deepEqual([events(round, "spit")[0].kind, events(round, "throw")[0].by], ["spitter", "spitter"], "the swell and the throw say who, for their sounds"); + b.throwIn = 1e9; + for (let ms = 0; ms < 3000 && !round.puddles.length; ms += 4) ghoul.advance(round, 4, steady); + assert.equal(round.puddles.length, 1); + assert.equal(events(round, "splash").length, 1); + const p = round.puddles[0]; + // Standing in it burns; over it in the air does not. + const r2 = ghoulRound("kitchen"); + standAt(r2, 40); + r2.puddles.push({ id: 1, x: 40, y: 6, life: ghoul.PUDDLE_MS }); + Object.assign(r2.you, { state: "air", y: 9, vy: 10 }); + ghoul.advance(r2, 40, steady); + assert.equal(r2.phase, "play", "over it, unhurt"); + standAt(r2, 40); + ghoul.advance(r2, 4, steady); + assert.deepEqual(events(r2, "lose").map((e) => e.cause), ["acid"], "in it, burned"); + ghoul.advance(round, ghoul.PUDDLE_MS, steady); + assert.ok(!round.puddles.includes(p), "and the puddle dries up"); + // Five bolts, and it bursts. + const r3 = ghoulRound("kitchen"); + standAt(r3, 40); + r3.camX = 20; + r3.you.safeMs = 1e9; + const k = put(r3, "spitter", 64, { throwIn: 1e9 }); + r3.input.fire = true; + for (let ms = 0; ms < 2000 && r3.monsters.includes(k); ms += 4) ghoul.advance(r3, 4, steady); + r3.input.fire = false; + assert.equal(events(r3, "hit").length + events(r3, "kill").length, ghoul.MONSTERS.spitter.hp); + assert.equal(events(r3, "burst").length, 1); + assert.equal(r3.bones.filter((x) => x.kind === "acid").length, 0, "no acid flung"); + for (let ms = 0; ms < 1500; ms += 4) ghoul.advance(r3, 4, steady); + assert.equal(r3.puddles.length, 0, "no puddle where it fell"); +}); + +test("Ghoul Rush: a monster that reaches the spot under you on a shelf stops there facing the way it went, never turning back and forth, and turns to follow once you move off", () => { + for (const kind of ["zombie", "crawler", "rotter", "legs"]) { + const round = ghoulRound("foyer"); + standAt(round, 68, 0); + round.you.safeMs = 1e9; + const m = put(round, kind, 58); + m.dir = 1; + const turns = []; + let last = m.dir; + for (let ms = 0; ms < 6000; ms += 16) { + round.you.safeMs = 1e9; + round.timeMs = 1e9; + ghoul.advance(round, 16, steady); + if (m.dir !== last) turns.push(ms); + last = m.dir; + } + assert.ok(Math.abs(m.x - 68) < ghoul.UNDER_DX, `${kind} under you (at ${m.x.toFixed(2)})`); + assert.deepEqual(turns, [], `${kind} never turned`); + assert.equal(m.dir, 1, `${kind} still facing the way it came`); + // You walk off to the left along the shelf: it turns once and follows. + round.you.x = 62; + for (let ms = 0; ms < 1500; ms += 16) { + round.you.safeMs = 1e9; + ghoul.advance(round, 16, steady); + if (m.dir !== last) turns.push(ms); + last = m.dir; + } + assert.equal(turns.length, 1, `${kind} turned once`); + assert.equal(m.dir, -1); + assert.ok(Math.abs(m.x - 62) < ghoul.UNDER_DX, `${kind} under you again`); + } +}); + +test("Ghoul Rush: in a dark room half as many come in from the edge behind you, the horde and the stragglers alike, and as many from ahead", () => { + // What comes in from ahead and behind in `ms`, facing `face`. + const count = (dark, face, hurry) => { + const round = ghoulRound(); + round.dark = dark; + standAt(round, 150); + round.camX = 100; + round.you.face = face; + round.hordeMs = hurry ? Infinity : round.spec.hordeMs; + round.hurry = hurry; + const random = ghoul.seeded(11); + let ahead = 0; + let behind = 0; + for (let ms = 0; ms < 240000; ms += 16) { + round.you.safeMs = 1e9; + round.you.face = face; + round.timeMs = 1e9; + if (hurry) round.hordeMs = Infinity; + ghoul.advance(round, 16, random); + for (const e of events(round, "spawn")) { + const right = e.x > round.camX + ghoul.FIELD_W; + if (right ? face > 0 : face < 0) ahead++; + else behind++; + } + round.events.length = 0; + round.monsters.length = 0; + } + return { ahead, behind }; + }; + for (const face of [1, -1]) { + const lit = count(false, face, false); + const dark = count(true, face, false); + const share = dark.behind / lit.behind; + assert.ok(lit.behind > 20 && Math.abs(share - ghoul.DARK_BEHIND) < 0.15, `horde facing ${face}: ${dark.behind} behind in the dark to ${lit.behind} lit`); + assert.ok(Math.abs(dark.ahead / lit.ahead - 1) < 0.15, `horde facing ${face}: ${dark.ahead} ahead in the dark to ${lit.ahead} lit`); + } + // Stragglers come in from ahead when they can, so face left to see them behind. + const lit = count(false, -1, true); + const dark = count(true, -1, true); + assert.ok(lit.behind > 20 && Math.abs(dark.behind / lit.behind - ghoul.DARK_BEHIND) < 0.15, `stragglers: ${dark.behind} in the dark to ${lit.behind} lit`); +}); + +test("Ghoul Rush: every room but a boss's keeps a horde coming in from the edges of the view, mostly ahead, one of its kinds every hordeMs or so, never past MAX_MONSTERS, held back a little less each stage deeper", () => { + for (const base of ghoul.ROOMS) { + if (base.boss) assert.deepEqual([base.horde.length, base.hordeMs], [0, 0], `${base.id}: no horde in a boss's room`); + else if (base.ride && base.ride.gallery) assert.deepEqual([base.horde.length, base.hordeMs], [0, 0], `${base.id}: the dark ride is a gallery, no horde`); + else if (base.ride && base.ride.sled) assert.deepEqual([base.horde.length, base.hordeMs], [0, 0], `${base.id}: the sled's things are the pack's own, no horde`); + else assert.ok(base.horde.length > 0 && base.hordeMs > 0, `${base.id} has a horde`); + for (const kind of base.horde) assert.ok(ghoul.MONSTERS[kind], `${base.id}: ${kind} is a monster`); + } + const round = ghoulRound(); + round.dark = false; + standAt(round, 150); + round.camX = 100; + round.you.safeMs = 1e9; + round.hordeMs = round.spec.hordeMs; + const random = ghoul.seeded(9); + let ahead = 0; + let behind = 0; + for (let ms = 0; ms < 30000; ms += 16) { + round.you.safeMs = 1e9; + round.monsters.forEach((m) => (m.x = Math.max(m.x, round.camX - 6))); + ghoul.advance(round, 16, random); + for (const e of events(round, "spawn")) { + const base = { runner: "zombie", glutton: "zombie" }[e.kind] ?? e.kind; + assert.ok(round.spec.horde.includes(base), `a ${e.kind} from the Foyer's horde`); + if (e.x > round.camX + ghoul.FIELD_W) ahead++; + else if (e.x < round.camX) behind++; + } + round.events.length = 0; + assert.ok(round.monsters.length <= 18); + } + assert.ok(ahead > behind && behind > 0, `mostly ahead (${ahead} ahead, ${behind} behind)`); + assert.ok(ahead + behind >= 30000 / round.spec.hordeMs / 2, `steady (${ahead + behind} in 30 s)`); + assert.ok(ghoul.roomFor("foyer", 2).hordeMs * ghoul.roomFor("foyer", 2).every < ghoul.roomFor("foyer").hordeMs, "quicker two stages deeper"); + const boss = ghoulRound("ballroom"); + boss.hordeMs = 0; + ghoul.advance(boss, 10000, steady); + assert.equal(events(boss, "spawn").length, 0, "none in a boss's room"); +}); + +/* ---------------------------------------------------------------- chain */ + +test("Ghoul Rush: kills each within CHAIN_MS raise the chain, which multiplies their points up to MAX_MULT, runs out after CHAIN_MS, and ends on a hit", () => { + const round = ghoulRound(); + standAt(round, 20); + const killOne = () => ghoul.kill(round, put(round, "bat", 60, { y: 30 }), "shot", () => 0.99); + assert.equal(killOne(), ghoul.MONSTERS.bat.points); + assert.equal(killOne(), ghoul.MONSTERS.bat.points * 2); + assert.equal(killOne(), ghoul.MONSTERS.bat.points * 3); + for (let k = 0; k < 10; k++) killOne(); + assert.equal(killOne(), ghoul.MONSTERS.bat.points * ghoul.MAX_MULT, "capped"); + assert.equal(round.stats.bestChain, 14); + round.monsters.length = 0; + ghoul.advance(round, ghoul.CHAIN_MS + 8, steady); + assert.equal(round.chain, 0, "it runs out"); + assert.equal(killOne(), ghoul.MONSTERS.bat.points); + killOne(); + ghoul.lose(round, "zombie"); + assert.equal(round.chain, 0, "a hit ends it"); + assert.deepEqual([1, 2, 8, 99].map(ghoul.chainMult), [1, 2, 8, ghoul.MAX_MULT]); +}); + +/* ---------------------------------------------------------------- powers */ + +test("Ghoul Rush: a timed power-up taken while the same one runs adds its time to what is left, and the HUD pill stays full till it is back under one pickup", () => { + const round = ghoulRound(); + standAt(round, 30); + const ms = ghoul.POWERS.rapid.ms; + ghoul.applyPower(round, "rapid"); + ghoul.applyPower(round, "rapid"); + assert.equal(round.effects.rapid, ms * 2, "two back to back: twice the time"); + ghoul.advance(round, 1000, steady); + ghoul.applyPower(round, "rapid"); + assert.equal(round.effects.rapid, ms * 3 - 1000, "a third tops up what was left"); + ghoul.applyPower(round, "spread"); + assert.equal(round.effects.spread, ghoul.POWERS.spread.ms, "another kind keeps its own time"); + ghoul.advance(round, ms * 3, steady); + assert.equal(round.effects.rapid, 0); + assert.equal(events(round, "expire").filter((e) => e.kind === "rapid").length, 1, "one run, one expiry"); +}); + +test("Ghoul Rush: Spread shot and Rapid fire run out after their time, the Garlic shield takes one hit and sees off what touched you, a 1UP is a life up to MAX_LIVES, and kills sometimes leave candy or a power-up", () => { + const round = ghoulRound(); + standAt(round, 30); + ghoul.applyPower(round, "spread"); + ghoul.applyPower(round, "rapid"); + ghoul.advance(round, ghoul.POWERS.spread.ms + 8, steady); + assert.deepEqual(round.effects, { spread: 0, rapid: 0, lantern: 0, wings: 0, bell: 0, silver: 0, shears: 0, holy: 0, salts: 0, saw: 0, bane: 0, floss: 0, cocoa: 0 }); + assert.equal(events(round, "expire").length, 2); + ghoul.applyPower(round, "garlic"); + const z = put(round, "zombie", 30); + ghoul.advance(round, 4, steady); + assert.deepEqual([round.lives, round.you.garlic, round.monsters.includes(z)], [ghoul.START_LIVES, false, false], "the garlic took it, and the zombie is gone"); + assert.equal(events(round, "garlic").length, 1); + assert.ok(round.you.safeMs > 0); + ghoul.applyPower(round, "life"); + assert.equal(round.lives, ghoul.START_LIVES + 1); + round.lives = ghoul.MAX_LIVES; + const score = round.score; + ghoul.applyPower(round, "life"); + assert.equal(round.lives, ghoul.MAX_LIVES, "never past MAX_LIVES"); + assert.ok(round.score > score, "points instead"); + // Placed power-ups are taken by touching them, and drops fall to the floor. + const r2 = ghoulRound(); + const [kind, x, y] = r2.spec.items[0]; + standAt(r2, x, r2.spec.shelves.findIndex(([a, b, top]) => x >= a && x <= b && top === y)); + ghoul.advance(r2, 4, steady); + assert.deepEqual(events(r2, "power").map((e) => e.kind), [kind]); + ghoul.kill(r2, put(r2, "zombie", 80), "shot", () => ghoul.DROP_POWER + 0.01); + assert.equal(r2.drops.at(-1).kind, "candy"); + ghoul.kill(r2, put(r2, "zombie", 80), "shot", () => 0); + assert.notEqual(r2.drops.at(-1).kind, "candy"); + ghoul.advance(r2, 1500, steady); + assert.ok(r2.drops.every((d) => d.rest && Math.abs(d.y - 7) < 1e-6), "both on the floor"); + standAt(r2, 80); + ghoul.advance(r2, 4, steady); + assert.equal(r2.drops.length, 0, "and taken"); +}); + +test("Ghoul Rush: a room is dark some of the times it is entered, the same each time for a seed, and a lit one never has a Lantern, placed or dropped", () => { + const rooms = []; + for (let seed = 1; seed <= 400; seed++) { + const round = ghoul.newRound(seed); + round.dice = 0; + through(round); + round.offer = ["manor"]; + round.phaseMs = 0; + ghoul.pickStage(round, 0); + while (round.spec.id !== "library") through(round); + rooms.push(round); + } + // Each run's hall. + const halls = Array.from({ length: 400 }, (_, i) => ghoul.newRound(i + 1).dark); + const share = halls.filter(Boolean).length / halls.length; + assert.ok(Math.abs(share - ghoul.DARK_CHANCE) < 0.08, `dark ${share} of the time`); + assert.deepEqual(Array.from({ length: 50 }, (_, i) => ghoul.newRound(i + 1).dark), halls.slice(0, 50), "a seed plays the same"); + const lit = rooms.filter((r) => !r.dark); + const dark = rooms.filter((r) => r.dark); + assert.ok(lit.length && dark.length, "the Library both ways"); + const at = ghoul.roomFor("library").items.findIndex(([kind]) => kind === "lantern"); + assert.ok(at >= 0, "the Library places a Lantern"); + for (const r of dark) assert.equal(r.loot[at], "lantern", "kept in the dark"); + for (const r of lit) { + assert.ok(!r.loot.includes("lantern"), "swapped in the light"); + assert.notEqual(r.loot[at], "life", "never for a 1UP"); + assert.ok(ghoul.POWERS[r.loot[at]], "for a power-up"); + // No drop is a Lantern, whatever the roll. + for (let k = 0; k < 40; k++) { + r.monsters.length = 0; + ghoul.kill(r, put(r, "zombie", 80, { force: true }), "shot", ((n) => () => (n++ === 0 ? 0 : k / 40))(0)); + assert.notEqual(r.drops.at(-1).kind, "lantern"); + } + } + // Taken, the swapped one is what was shown. + const r = lit[0]; + quiet(r); + r.phase = "play"; + r.events.length = 0; + const [, x, y] = r.spec.items[at]; + standAt(r, x, r.spec.shelves.findIndex(([a, b, top]) => x >= a && x <= b && top === y)); + ghoul.advance(r, 4, steady); + assert.deepEqual(events(r, "power").map((e) => e.kind), [r.loot[at]]); +}); + +test("Ghoul Rush: Bat wings give one flap in the air each time you leave the ground, and a press just before landing is still a jump on landing", () => { + const plain = ghoulRound(); + standAt(plain, 30); + hold(plain, { up: true, jump: ghoul.JUMP_BUFFER_MS }, 120); + hold(plain, { up: true, jump: ghoul.JUMP_BUFFER_MS }, 8); + assert.equal(events(plain, "flap").length, 0, "no wings, no flap"); + const round = ghoulRound(); + standAt(round, 30); + ghoul.applyPower(round, "wings"); + hold(round, { up: true, jump: ghoul.JUMP_BUFFER_MS }, 120); + assert.equal(round.you.state, "air"); + hold(round, { up: true, jump: ghoul.JUMP_BUFFER_MS }, 8); + assert.equal(events(round, "flap").length, 1, "a press in the air flaps"); + assert.ok(round.you.vy > ghoul.JUMP_V * 0.9, "for a full jump's lift"); + hold(round, { up: true, jump: ghoul.JUMP_BUFFER_MS }, 8); + assert.equal(events(round, "flap").length, 1, "once a jump"); + ghoul.advance(round, 2000, steady); + assert.equal(round.you.state, "run", "landed"); + // Coming down just over the floor, a press waits for the landing. + Object.assign(round.you, { y: ghoul.groundAt(round.spec, 30) + 2, vy: -30, state: "air", flapped: false }); + round.events.length = 0; + round.input.jump = ghoul.JUMP_BUFFER_MS; + ghoul.advance(round, 120, steady); + assert.equal(events(round, "flap").length, 0, "no flap so close to the floor"); + assert.equal(events(round, "jump").length, 1, "a jump on landing instead"); +}); + +test("Ghoul Rush: every treasure up high is out of one jump's reach from anywhere, but Bat wings' second jump from the shelf under it takes it, and each such room has wings on the way", () => { + const reach = ghoul.JUMP_TOP + ghoul.HIT_H + 1.2; + let rooms = 0; + for (const base of ghoul.ROOMS) { + if (!base.sky.length) continue; + rooms++; + const firstSky = Math.min(...base.sky.map(([, x]) => x)); + assert.ok(base.items.some(([kind, x]) => kind === "wings" && x < firstSky), `${base.id}: Bat wings before the treasure`); + for (const [y0] of [...base.ground.map((g) => [g[2]]), ...base.shelves.map((sh) => [sh[2]])]) { + for (const [kind, , y] of base.sky) assert.ok(y0 >= y || y0 + reach < y, `${base.id}: ${kind} at ${y} is out of one jump's reach from a floor at ${y0}`); + } + base.sky.forEach(([kind, x, y], k) => { + const shelf = base.shelves.reduce((best, sh, i) => (x >= sh[0] && x <= sh[1] && (best < 0 || sh[2] > base.shelves[best][2]) ? i : best), -1); + assert.ok(shelf >= 0, `${base.id}: a shelf under the ${kind}`); + const leap = (wings) => { + const round = ghoulRound(base.id); + standAt(round, x, shelf); + round.you.safeMs = 1e9; + if (wings) ghoul.applyPower(round, "wings"); + round.input.up = true; + round.input.jump = ghoul.JUMP_BUFFER_MS; + let flapped = false; + for (let ms = 0; ms < 3000 && (ms < 40 || round.you.state === "air"); ms += 4) { + if (wings && !flapped && round.you.state === "air" && round.you.vy <= 0) { + round.input.jump = ghoul.JUMP_BUFFER_MS; + flapped = true; + } + ghoul.advance(round, 4, steady); + } + return round.sky[k]; + }; + assert.equal(leap(false), false, `${base.id}: one jump falls short of the ${kind} at ${x}`); + assert.equal(leap(true), true, `${base.id}: a jump and a flap take the ${kind} at ${x}`); + }); + } + assert.equal(rooms, ghoul.ROOMS.filter((r) => !r.boss && !r.ride).length, "every room but a boss's and a ride's has some"); +}); + +test("Ghoul Rush: a crystal is CRYSTAL_POINTS, and Silver bolts, never dropped, send each bolt on through every monster it hits", () => { + assert.equal(ghoul.POWERS.silver.weight, 0, "never dropped"); + const round = ghoulRound("gallery"); + const k = round.spec.sky.findIndex(([kind]) => kind === "crystal"); + const [, cx, cy] = round.spec.sky[k]; + const score = round.score; + Object.assign(round.you, { x: cx, y: cy - 2, vy: 0, state: "air" }); + ghoul.advance(round, 4, steady); + assert.equal(round.sky[k], true); + assert.equal(events(round, "crystal").length, 1); + assert.equal(round.score - score, ghoul.CRYSTAL_POINTS); + assert.equal(round.stats.crystals, 1); + const shoot = (silver) => { + const r = ghoulRound(); + standAt(r, 30); + r.you.face = 1; + r.you.safeMs = 1e9; + if (silver) ghoul.applyPower(r, "silver"); + const a = put(r, "zombie", 40); + const b = put(r, "zombie", 44); + r.shots.push({ x: 32, y: r.you.y + 2, vx: ghoul.SHOT_SPEED, vy: 0, gone: 0 }); + ghoul.advance(r, 200, steady); + return [a.hp, b.hp]; + }; + const [a0, b0] = shoot(false); + assert.ok(a0 < b0, "a plain bolt stops at the first"); + const [a1, b1] = shoot(true); + assert.equal(a1, a0, "a silver bolt hits the first once"); + assert.equal(b1, a1, "and the one behind it too"); +}); + +test("Ghoul Rush: the Church bell holds every monster still and lets none in until it stops or you go through the door, and the Lantern runs out like the others", () => { + const round = ghoulRound(); + standAt(round, 20); + const z = put(round, "zombie", 60); + ghoul.applyPower(round, "bell"); + ghoul.advance(round, 1000, steady); + assert.equal(z.x, 60, "the zombie stands still"); + ghoul.advance(round, ghoul.POWERS.bell.ms, steady); + assert.ok(z.x < 60, "and walks again once the bell stops"); + ghoul.applyPower(round, "lantern"); + assert.equal(round.effects.lantern, ghoul.POWERS.lantern.ms); + ghoul.applyPower(round, "bell"); + round.phase = "clear"; + round.phaseMs = 1; + ghoul.advance(round, 4, steady); + assert.equal(round.effects.bell, 0, "the bell stops at the door"); +}); + +test("Ghoul Rush: every room but a boss's has a clock of 70 to 80 seconds (a ride's own, up to 120); at none a life goes and the room starts over with a full clock, and the Hourglass adds HOURGLASS_MS", () => { + for (const base of ghoul.ROOMS) { + const spec = ghoul.roomFor(base.id); + const ms = ghoul.timeFor(spec); + if (spec.boss) assert.equal(ms, 0, `${spec.id}: no clock in a boss room`); + // A ride room (the Runaway Cart, a long bonus round) has the clock of its own ride. + else if (spec.ride) assert.ok(ms === spec.ride.time && ms >= 70000 && ms <= 120000, `${spec.id}: ${ms}`); + else assert.ok(ms >= 70000 && ms <= 80000 && ms % 5000 === 0, `${spec.id}: ${ms}`); + } + const round = ghoulRound(); + standAt(round, 30); + assert.equal(round.timeMs, ghoul.timeFor(round.spec)); + ghoul.applyPower(round, "hourglass"); + assert.equal(round.timeMs, ghoul.timeFor(round.spec) + ghoul.HOURGLASS_MS); + round.timeMs = 3500; + ghoul.advance(round, 3000, steady); + assert.deepEqual(events(round, "tick").map((e) => e.left), [3, 2, 1], "the last seconds tick"); + ghoul.advance(round, 600, steady); + assert.equal(events(round, "lose")[0]?.cause, "time", "out of time"); + assert.equal(round.lives, ghoul.START_LIVES - 1); + ghoul.advance(round, ghoul.CRASH_MS + ghoul.READY_MS + 20, steady); + assert.equal(round.phase, "play"); + assert.ok(round.timeMs > ghoul.timeFor(round.spec) - 500, "a full clock again"); + const boss = ghoulRound("ballroom"); + const score = boss.score; + ghoul.applyPower(boss, "hourglass"); + assert.equal(boss.timeMs, 0); + assert.ok(boss.score > score, "points where there is no clock"); +}); + +test("Ghoul Rush: two or more walkers bunched under you on a shelf climb over each other to reach you, one alone does not, and they come back down once you leave", () => { + // Shelf 0 of the Foyer, [60, 76] at 15, over the floor at 6. + const setup = (n) => { + const round = ghoulRound(); + standAt(round, 68, 0); + round.timeMs = 0; + const crowd = []; + for (let k = 0; k < n; k++) crowd.push(put(round, "zombie", 66.5 + k)); + return { round, crowd }; + }; + const one = setup(1); + one.round.you.safeMs = 1e9; + ghoul.advance(one.round, 1500, steady); + assert.ok(one.crowd.every((m) => !m.lift), "one alone stays on the floor"); + const two = setup(2); + two.round.you.safeMs = 1e9; + ghoul.advance(two.round, 600, steady); + assert.ok(two.crowd[1].lift > 0 && !two.crowd[0].lift, "two: the newer climbs the older at once"); + const four = setup(4); + four.round.you.safeMs = 1e9; + const found = ghoul.piles(four.round, 0); + assert.equal(found.length, 1); + assert.deepEqual(found[0], four.crowd, "one pile, the oldest at the bottom"); + ghoul.advance(four.round, 1500, steady); + const lifts = four.crowd.map((m) => m.lift); + assert.equal(lifts[0], 0, "the bottom one stays on the floor"); + assert.ok(lifts[1] > 0 && lifts[2] > lifts[1], `each higher than the one below (${lifts.map((l) => l.toFixed(1))})`); + const top = Math.max(...four.crowd.map((m) => m.y + m.h)); + assert.ok(top > four.round.you.y, "the pile reaches up past your feet"); + assert.equal(events(four.round, "climb").length, 1, "the climb is called once"); + // Off the shelf and away, the pile comes down. + standAt(four.round, 92); + ghoul.advance(four.round, 1000, steady); + assert.ok(four.crowd.every((m) => !m.lift), "back on the floor"); + // Unprotected, the pile gets you. + const hit = setup(4); + ghoul.advance(hit.round, 2500, steady); + assert.equal(events(hit.round, "lose").length, 1, "a pile is not safe to sit over"); +}); + +test("Ghoul Rush: a climbing walker's raised arms hurt you if you land on them, but its head between them still takes a stomp; not climbing, the whole top does", () => { + const drop = (dx, climbing) => { + const round = ghoulRound(); + standAt(round, 30); + const z = put(round, "zombie", 40); + // Up a wall (one that never ends), its arms up the whole time. + if (climbing) z.scale = { top: 1e9, x: 40 }; + Object.assign(round.you, { x: 40 + dx, y: z.y + z.h + ghoul.ARMS_UP + 1, vy: -20, state: "air", shelf: -1, safeMs: 0 }); + for (let ms = 0; ms < 300 && !events(round, "stomp").length && !events(round, "lose").length; ms += 4) ghoul.advance(round, 4, steady); + return events(round, "stomp").length ? "stomp" : events(round, "lose").length ? "hurt" : "none"; + }; + assert.equal(drop(1.6, true), "hurt", "onto a raised arm"); + assert.equal(drop(-1.6, true), "hurt", "onto the other"); + assert.equal(drop(0, true), "stomp", "onto its head between them"); + assert.equal(drop(1.6, false), "stomp", "not climbing, its shoulder is a stomp as before"); +}); + +test("Ghoul Rush: the horde's stragglers are worth less each kill in a room, down to STRAY_MIN, and never leave anything behind, so camping by the door to farm them pays next to nothing", () => { + const round = ghoulRound(); + standAt(round, 30); + const z = ghoul.MONSTERS.zombie.points; + const got = []; + for (let k = 0; k < 14; k++) { + round.chainMs = 0; + const m = put(round, "zombie", 50, { horde: true }); + got.push(ghoul.kill(round, m, "shot", () => 0)); + } + assert.equal(got[0], z, "the first, in full"); + assert.equal(got[1], Math.round(z * ghoul.STRAY_FADE), "then less"); + assert.equal(got.at(-1), Math.round(z * ghoul.STRAY_MIN), "never under STRAY_MIN"); + assert.equal(round.drops.length, 0, "and nothing dropped, even on the luckiest roll"); + round.chainMs = 0; + assert.equal(ghoul.kill(round, put(round, "zombie", 50), "shot", () => 0), z, "one of the room's own: full points"); + assert.equal(round.drops.length, 1, "and its drop"); +}); + +test("Ghoul Rush: anything on four legs leaps a gap twice as far as any other monster", () => { + const lib = ghoulRound("library"); + lib.down[0] = 1e9; + // The Library's first pit runs 90 to 102: 12 across, past a plain leap. + const leaps = (m) => ghoul.farSide(lib, { y: 6, ...m }, 90.1, 1); + for (const m of [{ kind: "hound" }, { kind: "moonhound" }, { kind: "topiary" }, { kind: "villager", turned: true }]) assert.ok(leaps(m), `${m.kind} clears it`); + for (const m of [{ kind: "zombie" }, { kind: "villager" }, { kind: "huntsman" }, { kind: "mulch" }]) assert.equal(leaps(m), null, `${m.kind} does not`); + assert.equal(ghoul.hopReach({ kind: "hound" }), ghoul.hopReach({ kind: "zombie" }) * 2); + // And in play: where the zombie test holds for good, a hellhound goes over. + standAt(lib, 125); + lib.you.safeMs = 1e9; + const h = put(lib, "hound", 85); + lib.events.length = 0; + for (let k = 0; k < 800 && !events(lib, "leap").length; k++) ghoul.advance(lib, 16, steady); + assert.equal(events(lib, "leap").length, 1, "it leaps"); + for (let k = 0; k < 100 && h.hop; k++) ghoul.advance(lib, 16, steady); + assert.ok(!h.dead && h.x > 102 && h.y === 6, `over the pit (${h.x.toFixed(1)}, ${h.y})`); + // Twice as far is still a limit: a pit wider than the bound holds it. + const wide = ghoulRound("library"); + wide.spec = { ...wide.spec, ground: [[0, 90, 6], [112, 300, 6]] }; + assert.equal(ghoul.farSide(wide, { kind: "hound", y: 6 }, 90.1, 1), null, "22 across is too far"); +}); + +test("Ghoul Rush: anything on four legs leaps up to higher floor across a gap; no other monster does, and a wall still stops it", () => { + // Coming back left over a pit to floor above: the Kitchen's counter (6 up to + // 11, a pit 270 to 282) and the Tower's beams (6 up to 13.5, 240 to 252). + const over = (id, kind, from, at) => { + const round = ghoulRound(id); + standAt(round, at); + round.you.safeMs = 1e9; + const m = put(round, kind, from); + round.events.length = 0; + for (let k = 0; k < 600 && !events(round, "leap").length; k++) ghoul.advance(round, 16, steady); + for (let k = 0; k < 100 && m.hop; k++) ghoul.advance(round, 16, steady); + return { m, round }; + }; + const hound = over("kitchen", "hound", 300, 240); + assert.ok(!hound.m.dead && hound.m.y === 11 && hound.m.x < 270, `up on the far side (${hound.m.x.toFixed(1)}, ${hound.m.y})`); + const zombie = over("kitchen", "zombie", 300, 240); + assert.ok(zombie.m.y === 6 && zombie.m.x > 282, "a zombie stays down"); + assert.equal(events(zombie.round, "leap").length, 0); + const tower = ghoulRound("tower"); + assert.ok(ghoul.farSide(tower, { kind: "moonhound", y: 6 }, 251.9, -1), "7.5 up is in reach"); + // Higher than the bound is not. + const high = ghoulRound("kitchen"); + high.spec = { ...high.spec, ground: [[0, 270, 6 + ghoul.BOUND_UP + 1], [282, 400, 6]] }; + assert.equal(ghoul.farSide(high, { kind: "hound", y: 6 }, 281.9, -1), null, "past the bound"); + // The Kitchen's counter face has no gap before it: still a wall. + const wall = ghoulRound("kitchen"); + standAt(wall, 90); + wall.you.safeMs = 1e9; + const h = put(wall, "hound", 60); + ghoul.advance(wall, 6000, steady); + assert.ok(h.y === 6 && h.x < 70, `stopped by the wall (${h.x.toFixed(1)}, ${h.y})`); +}); + +test("Ghoul Rush: down ducks on the ground, on the spot, and drops through a shelf instead; a direction runs and up jumps out of it", () => { + const round = ghoulRound("gallery"); + round.phase = "play"; + standAt(round, 60); + round.you.safeMs = 1e9; + round.input.down = true; + ghoul.moveYou(round, 16); + assert.equal(round.you.ducking, true); + assert.equal(events(round, "duck").length, 1, "a sound as he goes down"); + ghoul.moveYou(round, 16); + assert.equal(events(round, "duck").length, 1, "only the once"); + const x = round.you.x; + round.input.right = true; + ghoul.moveYou(round, 16); + assert.ok(!round.you.ducking && round.you.x > x, "a direction runs"); + round.input.right = false; + ghoul.moveYou(round, 16); + assert.equal(round.you.ducking, true); + ghoul.jump(round); + assert.ok(!round.you.ducking && round.you.state === "air", "up jumps out of it"); + round.input.down = false; + // On a shelf: down still drops. + const shelf = ghoulRound("gallery"); + standAt(shelf, shelf.spec.shelves[0][0] + 2, 0); + shelf.input.down = true; + ghoul.moveYou(shelf, 16); + assert.ok(!shelf.you.ducking && shelf.you.state === "air", "through the shelf"); + // In the air: no duck. + const air = ghoulRound("gallery"); + standAt(air, 60); + ghoul.jump(air); + air.input.down = true; + ghoul.moveYou(air, 16); + assert.equal(air.you.ducking, false); +}); + +test("Ghoul Rush: ducking passes under every swooper, whatever its dive, and the same swoop hits him standing", () => { + // Each comes at him as it does in play, from well off and high up. + const swoopers = { + bat: { y: 14 }, + crow: { y: 16, act: "climb", wait: 1, vx: 0, vy: 0 }, + moth: { y: 14 }, + gargoyle: { y: 18, act: "wake", wait: 1, px: 40, home: 18 }, + bellbat: { y: 14, act: "swoop" }, + wraith: { y: 16, act: "wind", wait: 1, home: 16 }, + icewraith: { y: 16, act: "wind", wait: 1, home: 16 }, + }; + const swoop = (kind, ducked, x) => { + const round = ghoulRound("ballroom"); + round.phase = "play"; + round.spec = { ...round.spec, horde: [], spawns: [] }; + round.monsters.length = 0; + standAt(round, 60); + round.input.down = ducked; + const m = put(round, kind, x, swoopers[kind]); + round.events.length = 0; + for (let t = 0; t < 4000 && !events(round, "lose").length; t += 8) ghoul.advance(round, 8, steady); + return { m, lost: events(round, "lose") }; + }; + for (const kind of Object.keys(swoopers)) { + for (const x of [44, 49, 72, 80]) { + const under = swoop(kind, true, x); + assert.equal(under.lost.length, 0, `${kind} from ${x}: passed overhead (${under.lost[0]?.cause})`); + const up = swoop(kind, false, x); + assert.equal(up.lost[0]?.cause, kind, `${kind} from ${x}: standing, it hits`); + } + } +}); + +test("Ghoul Rush: ducking does not dodge what comes along the floor, and his bolts fly lower", () => { + const round = ghoulRound("ballroom"); + round.phase = "play"; + standAt(round, 60); + round.input.down = true; + ghoul.moveYou(round, 16); + put(round, "zombie", 60.5); + round.events.length = 0; + ghoul.advance(round, 16, steady); + assert.equal(events(round, "lose")[0]?.cause, "zombie"); + const low = ghoulRound("ballroom"); + low.phase = "play"; + low.spec = { ...low.spec, horde: [], spawns: [] }; + standAt(low, 60); + low.you.safeMs = 1e9; + low.input.down = true; + low.input.fire = true; + ghoul.advance(low, 16, steady); + assert.ok(low.shots.length > 0 && Math.abs(low.shots[0].y - (low.you.y + ghoul.DUCK_SHOT_Y)) < 0.5, "from his crouch"); +}); + +test("Ghoul Rush: walkers cross a bridge level with their floor while it is there, and drop into the pit when it crumbles under them", () => { + // The Library's first pit [90, 102] has a crumbling board over it at 6. + const round = ghoulRound("library"); + standAt(round, 120); + round.you.safeMs = 1e9; + const z = put(round, "zombie", 80); + for (let ms = 0; ms < 6000 && z.x < 104; ms += 16) ghoul.advance(round, 16, steady); + assert.ok(z.x > 102 && z.y === 6 && !z.dead, `over the bridge (${z.x.toFixed(1)})`); + assert.equal(events(round, "ponder").length, 0, "with no stop to think"); + const r2 = ghoulRound("library"); + standAt(r2, 120); + const w = put(r2, "zombie", 96); + w.y = 6; + r2.down[0] = 1e9; + ghoul.advance(r2, 1500, steady); + assert.ok(w.dead || w.y < 0, "the board gone, it falls"); +}); + +test("Ghoul Rush: a zombie, a runner or a crawler stopped by a wall thinks about it, then climbs up it; a glutton never does", () => { + // The Kitchen's counter: floor at 6 below x 70... and at 11 from 70 to 110. + const climb = (kind) => { + const round = ghoulRound("kitchen"); + standAt(round, 90); + round.you.safeMs = 1e9; + const m = put(round, kind, 60); + ghoul.advance(round, 6000, steady); + return { m, round }; + }; + for (const kind of ["zombie", "runner", "crawler"]) { + const { m, round } = climb(kind); + assert.equal(events(round, "scale").length, 1, `${kind}: it climbs`); + assert.ok(m.y === 11 && m.x > 70 && !m.scale, `${kind}: up on the counter (${m.x.toFixed(1)}, ${m.y})`); + } + const { m, round } = climb("glutton"); + assert.ok(m.y === 6 && m.x < 70, "a glutton stays down"); + assert.equal(events(round, "scale").length + events(round, "leap").length, 0); +}); + +test("Ghoul Rush: a life lost within QUICK_LOSS_MS of coming in brings Planny back holding the Garlic shield; a later one does not", () => { + const back = (aliveMs) => { + const round = ghoulRound("foyer"); + round.phase = "play"; + standAt(round, 60); + round.you.aliveMs = aliveMs; + assert.ok(ghoul.lose(round, "zombie")); + for (let ms = 0; ms < 3000 && round.phase !== "play"; ms += 16) ghoul.advance(round, 16, steady); + return round; + }; + const quick = back(ghoul.QUICK_LOSS_MS - 100); + assert.equal(quick.phase, "play"); + assert.ok(quick.you.garlic, "a quick fall: back with the shield"); + assert.ok(events(quick, "power").some((e) => e.kind === "garlic" && e.gift), "and told so"); + const slow = back(ghoul.QUICK_LOSS_MS + 100); + assert.ok(!slow.you.garlic, "a later fall: no shield"); + assert.equal(slow.you.aliveMs < ghoul.QUICK_LOSS_MS, true, "the clock starts over on coming back"); +}); + +test("Ghoul Rush: every walker comes down off a ledge after you, a glutton included, instead of walking in place at its edge", () => { + // The Kitchen's counter: floor at 11 from 70 to 110, then at 6 to 150. + for (const kind of ["zombie", "runner", "glutton", "crawler", "hound"]) { + const round = ghoulRound("kitchen"); + standAt(round, 135); + round.you.safeMs = 1e9; + const m = put(round, kind, 100); + assert.equal(m.y, 11, `${kind}: starts up on the counter`); + ghoul.advance(round, 8000, steady); + // Down off the counter (a hound may be caught mid-lunge). + assert.ok(m.dead || (m.y < 11 && m.x > 110), `${kind}: down off the counter (${m.x.toFixed(1)}, ${m.y})`); + } +}); + +test("Ghoul Rush: a Runner is fast and down in one bolt, a Glutton slow and five times a zombie's bolts with a stomp only hurting it, and now and then a zombie, widow or hound comes as one of them or a Huntsman", () => { + const M = ghoul.MONSTERS; + assert.ok(M.runner.speed > M.zombie.speed * 2 && M.runner.hp === 1); + assert.ok(M.glutton.speed < M.zombie.speed && M.glutton.hp === M.zombie.hp * 5); + assert.ok(M.huntsman.hp > M.spider.hp && M.huntsman.w > M.spider.w); + const round = ghoulRound(); + standAt(round, 30); + round.you.safeMs = 1e9; + const g = put(round, "glutton", 40); + Object.assign(round.you, { x: 40, y: g.y + g.h + 0.3, vy: -20, state: "air" }); + ghoul.advance(round, 40, steady); + assert.ok(!g.dead && g.hp === M.glutton.hp - M.glutton.stompDamage, "a stomp only bruises a glutton"); + // The dice: low rolls are the rare ones. + assert.equal(ghoul.variant("zombie", () => 0), "glutton"); + assert.equal(ghoul.variant("zombie", () => ghoul.GLUTTON_CHANCE + 0.01), "runner"); + assert.equal(ghoul.variant("zombie", () => 0.9), "zombie"); + assert.equal(ghoul.variant("spider", () => 0), "huntsman"); + assert.equal(ghoul.variant("hound", () => 0.9), "hound"); + assert.equal(ghoul.variant("bat", () => 0), "bat"); +}); + +test("Ghoul Rush: a Runner shrieks once as it nears the view, marked on the screen's edge nearest it, even coming up from behind", () => { + const round = ghoulRound(); + standAt(round, 200); + round.you.safeMs = 1e9; + const r = put(round, "runner", round.camX - ghoul.RUNNER_WARN - 2); + for (let ms = 0; ms < 3000 && !events(round, "runner").length; ms += 16) ghoul.advance(round, 16, steady); + const [e] = events(round, "runner"); + assert.ok(e, "it shrieks"); + assert.ok(r.x < round.camX, `before it is on screen (${r.x.toFixed(1)} against ${round.camX.toFixed(1)})`); + assert.ok(e.x >= round.camX && e.side === -1, "marked on the left edge, behind you"); + ghoul.advance(round, 1500, steady); + assert.equal(events(round, "runner").length, 1, "once"); +}); + +test("Ghoul Rush: a Huntsman runs at you, crouches, and springs as high as you are, up onto a shelf", () => { + const round = ghoulRound(); + standAt(round, 68, 0); + round.you.safeMs = 1e9; + const h = put(round, "huntsman", 50); + let top = h.y; + for (let ms = 0; ms < 4000 && !events(round, "lunge").length; ms += 16) ghoul.advance(round, 16, steady); + assert.equal(events(round, "growl").length, 1, "it crouches first"); + assert.equal(events(round, "lunge").length, 1, "then springs"); + for (let ms = 0; ms < 1500 && h.act === "leap"; ms += 4) { + ghoul.advance(round, 4, steady); + top = Math.max(top, h.y); + } + assert.ok(top >= round.you.y, `as high as you on the shelf (${top.toFixed(1)} against ${round.you.y})`); +}); + +test("Ghoul Rush: the Gourd picks hop, spit or quake at random, never one three times running; a spit lobs acid at you and a quake sends a shockwave both ways", () => { + const b = { act: "", run: 0 }; + const seen = []; + for (let k = 0; k < 12; k++) seen.push((b.act = ghoul.gourdAct(b, () => 0))); + for (let k = 2; k < seen.length; k++) assert.ok(!(seen[k] === seen[k - 1] && seen[k] === seen[k - 2]), `no three in a row (${seen})`); + assert.deepEqual(new Set(seen.concat(ghoul.GOURD_ACTS)).size, 3); + const spit = bossFight("ballroom"); + spit.you.safeMs = 1e9; + ghoul.advance(spit, ghoul.GOURD_WAIT_MS + 20, () => 0.5); + assert.equal(spit.boss.act, "spit"); + ghoul.advance(spit, ghoul.GOURD_SPIT_MS + 20, () => 0.5); + assert.equal(spit.bones.filter((x) => x.kind === "acid").length, ghoul.GOURD_SPIT.length, "a glob for each scale"); + const quake = bossFight("ballroom"); + quake.you.safeMs = 1e9; + ghoul.advance(quake, ghoul.GOURD_WAIT_MS + 20, () => 0.9); + assert.equal(quake.boss.act, "quake"); + const x = quake.boss.x; + for (let ms = 0; ms < 2000 && !quake.waves.length; ms += 4) ghoul.advance(quake, 4, () => 0.9); + assert.equal(quake.boss.x, x, "straight up and down"); + assert.deepEqual(quake.waves.map((w) => w.dir).sort(), [-1, 1], "a shockwave each way"); +}); + +/* ---------------------------------------------------------------- key, door, rooms */ + +test("Ghoul Rush: the door stays shut until you hold the key, then through it scores ROOM_POINTS times the room, the time bonus left and FLAWLESS_POINTS with no life lost, and the next room comes after CLEAR_MS and READY_MS", () => { + const round = ghoulRound(); + standAt(round, round.spec.door); + ghoul.advance(round, 40, steady); + assert.equal(round.phase, "play", "shut without the key"); + const [kx, ky] = round.spec.key; + standAt(round, kx, round.spec.shelves.findIndex(([a, b, top]) => kx >= a && kx <= b && top === ky)); + ghoul.advance(round, 4, steady); + assert.equal(round.hasKey, true); + assert.equal(events(round, "key").length, 1); + ghoul.advance(round, 2000, steady); + assert.equal(round.bonus, ghoul.BONUS_START - 2 * ghoul.BONUS_STEP); + standAt(round, round.spec.door); + const before = round.score; + ghoul.advance(round, 4, steady); + assert.equal(round.phase, "clear"); + assert.equal(round.score - before, ghoul.ROOM_POINTS * 2 + round.bonus + ghoul.FLAWLESS_POINTS, "the Foyer is the run's second room, after the hall"); + ghoul.advance(round, ghoul.CLEAR_MS + ghoul.READY_MS + 20, steady); + assert.deepEqual([round.room, round.spec.id, round.phase, round.hasKey], [3, "gallery", "play", false]); + assert.equal(round.you.x, round.spec.start); + quiet(round); + round.roomLost = true; + round.hasKey = true; + standAt(round, round.spec.door); + const b2 = round.score; + ghoul.advance(round, 4, steady); + assert.equal(round.score - b2, ghoul.ROOM_POINTS * 3 + round.bonus, "no flawless bonus after a life lost"); +}); + +test("Ghoul Rush: with the time bonus run out, a zombie shambles in from the edge every HURRY_MS", () => { + const round = ghoulRound(); + standAt(round, 60); + round.you.safeMs = 1e9; + Object.assign(round, { bonus: ghoul.BONUS_STEP, bonusMs: 990 }); + ghoul.advance(round, 20, steady); + assert.deepEqual([round.bonus, round.hurry], [0, true]); + assert.equal(events(round, "hurry").length, 1); + ghoul.advance(round, ghoul.HURRY_MS + 20, steady); + assert.equal(round.monsters.filter((m) => m.kind === "zombie").length, 1); +}); + +test("Ghoul Rush: each stage is three rooms and a boss's, every room in one stage but the hall, and roomFor builds a room deeper into a run quicker and tougher, its boss with more hp and points, each capped", () => { + assert.equal(ghoul.ROOMS[0].id, "hall", "every run starts in the hall"); + assert.equal(ghoul.ROOMS[0].boss, null); + const placed = ghoul.STAGES.flatMap((st) => st.rooms); + assert.equal(new Set(placed).size, placed.length, "no room in two stages"); + assert.deepEqual([...placed].sort(), ghoul.ROOMS.slice(1).map((r) => r.id).sort(), "every room but the hall in a stage"); + for (const st of ghoul.STAGES) { + // Four rooms; the Mine's Runaway Cart makes it five. + assert.ok(st.rooms.length >= 4 && st.rooms.length <= 5, `${st.id}: four rooms (five with a ride)`); + assert.deepEqual(st.rooms.map((id) => Boolean(ghoul.roomById(id).boss)), [...st.rooms.slice(1).map(() => false), true], `${st.id}: the boss's room last`); + assert.equal(st.boss, ghoul.roomById(st.rooms.at(-1)).boss); + assert.ok(ghoul.BOSSES[st.boss], `${st.id}: ${st.boss} is a boss`); + assert.ok(st.title && st.sub, `${st.id}: named`); + } + assert.equal(new Set(ghoul.STAGES.map((st) => st.id)).size, ghoul.STAGES.length, "stage ids are unique"); + assert.equal(ghoul.roomFor("library").name, "Library"); + assert.equal(ghoul.roomFor("library", 2), ghoul.roomFor("library", 2), "built once"); + assert.equal(ghoul.roomName(ghoul.roomFor("library"), 4), "Library (room 4)"); + const deep = ghoul.roomFor("foyer", 6); + const top = ghoul.roomFor("foyer"); + assert.ok(deep.pace > top.pace && deep.every < top.every && deep.tough > 0 && deep.extra > 0); + assert.ok(ghoul.roomFor("ballroom", 3).bossHp > ghoul.roomFor("ballroom").bossHp); + assert.ok(ghoul.roomFor("ballroom", 3).bossPoints > ghoul.roomFor("ballroom").bossPoints); + assert.equal(ghoul.roomFor("ballroom").bossPoints, ghoul.BOSSES.gourd.points); + const far = ghoul.roomFor("ballroom", 400); + assert.ok(far.pace <= 1.4 && far.every >= 0.55 && far.tough <= 2 && far.extra <= 2); + assert.equal(far.bossHp, ghoul.roomFor("ballroom", ghoul.BOSS_DEPTH_MAX).bossHp, "boss hp stops growing"); + const r = ghoulRound("foyer", 3); + const z = put(r, "zombie", 80); + assert.equal(z.hp, ghoul.MONSTERS.zombie.hp + 1, "three stages in, zombies take a bolt more"); +}); + +test("Ghoul Rush: out of the hall, and out of each boss's room, you pick the next stage from two not yet played; left and right move the pick, a press only takes one once the offer settles, and a stage never comes again", () => { + const round = ghoul.newRound(5); + round.dice = 0; + quiet(round); + assert.deepEqual([round.spec.id, round.stage, round.room], ["hall", null, 1]); + through(round); + assert.equal(round.phase, "pick"); + assert.equal(round.offer.length, Math.min(ghoul.OFFER_N, ghoul.STAGES.length)); + assert.equal(new Set(round.offer).size, round.offer.length, "two different stages"); + assert.deepEqual(events(round, "offer").map((e) => e.offer), [round.offer]); + ghoul.advance(round, 5000, steady); + assert.equal(round.phase, "pick", "it waits on you"); + const r2 = ghoul.newRound(5); + r2.dice = 0; + through(r2); + assert.equal(ghoul.pickStage(r2), false, "not while the offer settles"); + ghoul.advance(r2, ghoul.PICK_HOLD_MS, steady); + assert.equal(ghoul.steerPick(r2, -1), false, "already at the left"); + assert.equal(ghoul.steerPick(r2, 1), r2.offer.length > 1); + const want = r2.offer[r2.pick]; + assert.equal(ghoul.pickStage(r2), true); + assert.deepEqual([r2.stage, r2.stageAt, r2.offer, r2.room, r2.phase], [want, 0, null, 2, "ready"]); + assert.equal(r2.spec.id, ghoul.stageById(want).rooms[0]); + assert.deepEqual(events(r2, "stage").map((e) => [e.stage, e.n]), [[want, 1]]); + // Through the stage's rooms in order, then the boss's door: cleared, and + // the next offer leaves it out. + for (const id of ghoul.stageById(want).rooms.slice(1)) { + through(r2); + assert.equal(r2.spec.id, id); + } + through(r2); + assert.deepEqual(r2.cleared, [want]); + assert.equal(r2.stats.stages, 1); + assert.deepEqual(events(r2, "stageClear").map((e) => [e.stage, e.n, e.of]), [[want, 1, ghoul.STAGES.length]]); + assert.equal(r2.phase, "pick"); + assert.ok(!r2.offer.includes(want), "a stage cleared is never offered again"); + assert.deepEqual(ghoul.stagesLeft(r2).map((st) => st.id), ghoul.STAGES.filter((st) => st.id !== want).map((st) => st.id)); + // A seeded run offers its own pair, and both stages come up across seeds. + const seen = new Set(); + for (let seed = 1; seed < 40; seed++) { + const r = ghoul.newRound(seed); + r.dice = 0; + r.phase = "clear"; + r.phaseMs = 1; + ghoul.advance(r, 4, ghoul.seeded(seed)); + seen.add(r.offer[0]); + } + assert.equal(seen.size, ghoul.STAGES.length, "the offer is shuffled: any stage can come first"); +}); + +test("Ghoul Rush: clearing every stage wins the run, and its end says so", () => { + const round = ghoul.newRound(5); + round.dice = 0; + through(round); + while (!round.over) { + assert.equal(round.phase, "pick"); + round.phaseMs = 0; + ghoul.pickStage(round); + for (let k = 0, n = ghoul.stageById(round.stage).rooms.length; k < n; k++) through(round); + } + assert.equal(round.won, true); + assert.equal(round.cleared.length, ghoul.STAGES.length); + assert.deepEqual(new Set(round.cleared), new Set(ghoul.STAGES.map((st) => st.id)), "each stage once"); + assert.equal(events(round, "won").length, 1); + assert.equal(ghoul.advance(round, 16, steady), "over"); +}); + +test("Ghoul Rush: a boss always gives a life (up to MAX_LIVES, 9), and the 1UP turns up a little more often than before", () => { + assert.equal(ghoul.MAX_LIVES, 9); + assert.equal(ghoul.POWERS.life.weight, 1.5); + const round = bossFight("ballroom"); + const b = round.boss; + round.lives = ghoul.MAX_LIVES - 1; + b.hp = 1; + round.shots.push({ x: b.x - b.w / 2 - 0.2, y: b.y + 2, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(round.lives, ghoul.MAX_LIVES); + assert.equal(events(round, "bossDown")[0].life, true); +}); + +/* ---------------------------------------------------------------- bosses */ + +// A boss room with you in the arena and the boss awake. +function bossFight(n) { + const round = ghoulRound(n); + standAt(round, round.spec.arena + ghoul.BOSS_LOCK + 2); + ghoul.advance(round, 4, steady); + assert.equal(round.lockX, round.spec.arena, "the arena locks"); + assert.equal(round.boss.state, "intro"); + ghoul.advance(round, ghoul.BOSS_INTRO_MS + 8, steady); + assert.equal(round.boss.state, "fight"); + round.events.length = 0; + return round; +} + +test("Ghoul Rush: the Great Gourd hops to where you stood and lands with a slam that lets gourdlings loose, harmless till they find their feet; bolts and stomps hurt it, and its fall opens the door and gives a life back", () => { + const round = bossFight("ballroom"); + const b = round.boss; + round.you.safeMs = 1e9; + ghoul.advance(round, ghoul.GOURD_WAIT_MS + 20, () => 0.1); + assert.equal(events(round, "hop").length, 1, "it hops"); + const landX = b.landX; + assert.ok(Math.abs(landX - Math.max(round.you.x, round.spec.arena + ghoul.ARENA_POCKET + b.w / 2)) < 1e-6, "aimed where you stood, short of the corner"); + for (let ms = 0; ms < 2000 && !events(round, "slam").length; ms += 4) ghoul.advance(round, 4, steady); + assert.ok(Math.abs(b.x - landX) < 0.5, `down where it aimed (${b.x.toFixed(1)})`); + const seeds = round.monsters.filter((m) => m.kind === "seed"); + assert.ok(seeds.length >= 1 && seeds.length <= ghoul.MAX_SEEDS); + assert.ok(seeds.every((m) => !ghoul.solid(m)), "harmless in the air"); + for (let ms = 0; ms < 2000 && seeds.some((m) => m.vy !== 0); ms += 4) ghoul.advance(round, 4, steady); + assert.ok(seeds.every((m) => m.dead || !ghoul.solid(m)), "and as they land"); + // Bolts and a stomp. + const r2 = bossFight("ballroom"); + const g = r2.boss; + r2.you.safeMs = 1e9; + r2.shots.push({ x: g.x - g.w / 2 - 0.2, y: g.y + 2, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(r2, 4, steady); + assert.equal(g.hp, g.max - 1); + Object.assign(r2.you, { x: g.x, y: g.y + g.h + 0.3, vy: -20, state: "air" }); + ghoul.advance(r2, 40, steady); + assert.equal(g.hp, g.max - 1 - ghoul.STOMP_DAMAGE, "a stomp"); + assert.ok(r2.you.vy > 0); + r2.lives = 2; + g.hp = 1; + r2.shots.push({ x: g.x - g.w / 2 - 0.2, y: g.y + 2, vx: 80, vy: 0, gone: 0 }); + const before = r2.score; + ghoul.advance(r2, 4, steady); + assert.equal(g.state, "down"); + assert.equal(r2.score - before, ghoul.BOSSES.gourd.points); + assert.deepEqual([r2.hasKey, r2.lives, r2.monsters.length], [true, 3, 0], "the door opens, a life back, the gourdlings gone"); + standAt(r2, r2.spec.door); + ghoul.advance(r2, 4, steady); + assert.equal(r2.phase, "clear"); +}); + +test("Ghoul Rush: the Ballroom's arena is stacked with balconies; the Gourd never lands in a corner's pocket, only spits at you up over its head, and its gourdlings jump up after you and run off the ends after you", () => { + const spec = ghoul.roomFor("ballroom"); + assert.ok(spec.shelves.filter(([x0]) => x0 >= spec.arena).length >= 8, "balconies across the arena"); + assert.ok(!spec.shelves.some(([x0, x1]) => spec.door >= x0 - 2 && spec.door <= x1 + 2), "none over the door"); + // In a corner, the hop lands short of you. + for (const end of ["left", "right"]) { + const round = bossFight("ballroom"); + const b = round.boss; + round.you.safeMs = 0; + standAt(round, end === "left" ? round.lockX + 1.5 : round.spec.length - 1.5); + ghoul.advance(round, ghoul.GOURD_WAIT_MS + 20, () => 0.1); + assert.equal(b.act, "hop"); + const gap = Math.abs(b.landX - round.you.x) - (b.w + ghoul.HIT_W) / 2; + assert.ok(gap > 1, `${end} corner: ${gap.toFixed(1)} clear of you`); + } + // Up on a balcony over its head, a spit, never a hop. + const up = bossFight("ballroom"); + const shelf = up.spec.shelves.findIndex(([x0, , top]) => x0 >= up.spec.arena && top === 24); + standAt(up, up.spec.shelves[shelf][0] + 4, shelf); + up.you.safeMs = 1e9; + ghoul.advance(up, ghoul.GOURD_WAIT_MS + 20, () => 0.1); + assert.equal(up.boss.act, "spit"); + // A gourdling jumps up onto the balcony you are on, then off its end after you. + const r = bossFight("ballroom"); + r.boss.state = "down"; + const low = r.spec.shelves.findIndex(([x0, , top]) => x0 >= r.spec.arena && top === 15); + const [x0, x1] = r.spec.shelves[low]; + standAt(r, (x0 + x1) / 2, low); + r.you.safeMs = 1e9; + const seed = put(r, "seed", x0 - 4); + for (let ms = 0; ms < 4000 && seed.y !== 15; ms += 16) ghoul.advance(r, 16, steady); + assert.equal(seed.y, 15, "up on the balcony"); + assert.ok(events(r, "leap").length >= 1); + standAt(r, x1 + 10); + for (let ms = 0; ms < 4000 && seed.y !== 6; ms += 16) ghoul.advance(r, 16, steady); + assert.equal(seed.y, 6, "and back down after you"); +}); + +test("Ghoul Rush: losing a life in a boss fight puts you back in the arena with the boss's hp kept", () => { + const round = bossFight("ballroom"); + round.boss.hp = 20; + ghoul.lose(round, "gourd"); + ghoul.advance(round, ghoul.CRASH_MS + 10, steady); + assert.equal(round.lockX, round.spec.arena); + assert.ok(round.you.x > round.spec.arena); + assert.deepEqual([round.boss.hp, round.boss.state], [20, "intro"]); +}); + +/* ---------------------------------------------------------------- the house */ + +test("Ghoul Rush: a chandelier shakes as you run under it, then drops and crushes the monsters under it (double points) and you if you stay", () => { + const round = ghoulRound(); + const c = round.falls[0]; + standAt(round, c.x - 4); + const z = put(round, "zombie", c.x + 1, { speed: 0 }); + z.x = c.x + 1; + ghoul.advance(round, 4, steady); + assert.equal(c.state, "shake"); + assert.equal(events(round, "creak").length, 1); + round.monsters.length = 0; + const z2 = put(round, "zombie", c.x + 2); + round.you.safeMs = 0; + for (let ms = 0; ms < 2000 && c.state !== "down"; ms += 4) { + z2.x = c.x + 2; + ghoul.advance(round, 4, steady); + } + assert.deepEqual(events(round, "kill").map((e) => [e.how, e.points]), [["crush", ghoul.MONSTERS.zombie.points * 2]]); + assert.deepEqual(events(round, "lose").map((e) => e.cause), ["chandelier"], "you stayed under it"); +}); + +test("Ghoul Rush: a crumbling board shakes CRUMBLE_MS once stood on, falls away, and comes back after CRUMBLE_BACK_MS", () => { + const round = ghoulRound("library"); + const i = round.spec.shelves.findIndex((s) => s[3] === "crumble" && s[2] > 6); + const [x0, x1] = round.spec.shelves[i]; + standAt(round, (x0 + x1) / 2, i); + ghoul.advance(round, 4, steady); + assert.equal(round.shake[i], ghoul.CRUMBLE_MS); + ghoul.advance(round, ghoul.CRUMBLE_MS + 8, steady); + assert.equal(ghoul.shelfThere(round, i), false); + assert.equal(round.you.state, "air", "and you fall with it"); + ghoul.advance(round, ghoul.CRUMBLE_BACK_MS + 8, steady); + assert.equal(ghoul.shelfThere(round, i), true); +}); + +test("Ghoul Rush: a hit costs a life, holds CRASH_MS, puts you back at the start safe for SAFE_MS (nothing hurts you then), and the last life ends the round", () => { + const round = ghoulRound(); + standAt(round, 60); + // Long enough in the room that the fall brings no Garlic shield back. + round.you.aliveMs = ghoul.QUICK_LOSS_MS; + const z = put(round, "zombie", 60); + ghoul.advance(round, 4, steady); + assert.deepEqual([round.phase, round.lives], ["crash", ghoul.START_LIVES - 1]); + ghoul.advance(round, ghoul.CRASH_MS + ghoul.READY_MS + 20, steady); + assert.equal(round.phase, "play"); + assert.ok(!round.monsters.includes(z) && round.spawns.every((st) => !st.done), "the room's monsters back where they began"); + quiet(round); + put(round, "skeleton", round.you.x, { throwIn: 1e9 }); + ghoul.advance(round, ghoul.SAFE_MS - 100, steady); + assert.equal(round.lives, ghoul.START_LIVES - 1, "safe for a moment"); + ghoul.advance(round, 300, steady); + assert.equal(round.lives, ghoul.START_LIVES - 2, "then not"); + ghoul.advance(round, ghoul.CRASH_MS + 10, steady); + round.lives = 1; + round.phase = "play"; + ghoul.lose(round, "bat"); + ghoul.advance(round, ghoul.CRASH_MS + 10, steady); + assert.equal(round.over, true); +}); + +test("Ghoul Rush: the banner's strip ignores a roosting bat, a faded ghost and a crawler still coming up", () => { + const round = ghoulRound("library"); + standAt(round, 30); + const high = ghoul.FIELD_H * 0.3; + const y = ghoul.FIELD_H - high - 1; + const bat = put(round, "bat", 50, { y, awake: false }); + assert.equal(ghoul.underBanner(round, high), false, "asleep: it does not count"); + bat.awake = true; + assert.equal(ghoul.underBanner(round, high), true, "awake, it does"); + round.monsters.length = 0; + put(round, "ghost", 50, { y, phase: ghoul.GHOST_SHOW_MS + 600 }); + assert.equal(ghoul.underBanner(round, high), false, "a faded ghost does not"); + round.monsters.length = 0; + put(round, "crawler", 50, { y, rise: 300 }); + assert.equal(ghoul.underBanner(round, high), false, "nor a crawler still coming up"); +}); + +test("Ghoul Rush: a level bolt from the Crypt's shelf finds Old Rattlebones' skull for double", () => { + const round = bossFight("crypt"); + const b = round.boss; + const shelf = round.spec.shelves.findIndex(([x0, x1, y]) => y === 17); + const [x0, x1] = round.spec.shelves[shelf]; + standAt(round, (x0 + x1) / 2, shelf); + round.you.safeMs = 1e9; + b.t = -1e9; + b.x = round.you.x + 14; + const hp = b.hp; + round.shots.push({ x: b.x - b.w / 2 - 0.3, y: round.you.y + ghoul.SHOT_Y, vx: 80, vy: 0, gone: 0 }); + ghoul.advance(round, 4, steady); + assert.equal(b.hp, hp - 2, "the skull"); + assert.ok(b.y + b.h * ghoul.SKULL_FROM < round.you.y + ghoul.SHOT_Y); +}); + +test("Ghoul Rush: a jump saved for a landing and let go before it still rises CUT_AFTER_MS before the cut, never a twitch", () => { + const round = ghoulRound(); + const you = round.you; + standAt(round, 40); + Object.assign(you, { state: "air", y: 6.6, vy: -10 }); + round.input.jump = ghoul.JUMP_BUFFER_MS; + round.input.up = false; + let top = 0; + for (let k = 0; k < 400 && (k < 30 || you.state === "air"); k++) { + ghoul.advance(round, 4, steady); + top = Math.max(top, you.y - 6); + } + assert.ok(top > 3.5, `a real hop (${top.toFixed(2)} up)`); + assert.ok(top < ghoul.JUMP_TOP / 2, "but still a short one"); +}); + +test("Ghoul Rush: a life lost in a boss's arena after it fell puts you back in the arena, never across the room", () => { + const round = bossFight("ballroom"); + round.boss.state = "down"; + round.hasKey = true; + ghoul.lose(round, "bat"); + ghoul.advance(round, ghoul.CRASH_MS + 10, steady); + assert.equal(round.you.x, round.spec.arena + ghoul.BOSS_LOCK + 2); + assert.equal(round.lockX, round.spec.arena); +}); + +/* ---------------------------------------------------------------- layouts */ + +const MARGIN = 0.6; + +// The surfaces of a room a route may use: its ground pieces and its shelves +// that never crumble. +function surfaces(base) { + // A thin tile (the Frozen Lake's) may break: the route must work with it cut out, a pit to jump. + const pieces = []; + for (const [x0, x1, y] of base.ground) { + let a = x0; + for (const [t0, t1] of (base.thin || []).filter(([t0, t1]) => t0 >= x0 && t1 <= x1).sort((p, q) => p[0] - q[0])) { + pieces.push({ x0: a, x1: t0, y, ground: true }); + a = t1; + } + pieces.push({ x0: a, x1, y, ground: true }); + } + return [...pieces, ...base.shelves.filter((s) => s[3] !== "crumble").map(([x0, x1, y]) => ({ x0, x1, y, ground: false }))]; +} + +// Whether a run and jump from surface A reaches surface B. +function reaches(A, B) { + const dy = B.y - A.y; + const touching = A.ground && B.ground && (A.x1 === B.x0 || B.x1 === A.x0); + if (touching && Math.abs(dy) <= ghoul.STEP_UP) return true; + const gap = Math.max(B.x0 - A.x1, A.x0 - B.x1); + if (gap <= 0) return dy < 0 || dy <= ghoul.JUMP_TOP - MARGIN; + return ghoul.jumpHeightAt(gap + MARGIN) >= dy + MARGIN; +} + +// The surfaces reachable from `from`. +function reachable(list, from) { + const seen = new Set([from]); + const queue = [from]; + while (queue.length) { + const a = queue.shift(); + for (const b of list) if (!seen.has(b) && reaches(a, b)) (seen.add(b), queue.push(b)); + } + return seen; +} + +const surfaceAt = (list, x, y) => list.find((s) => x >= s.x0 && x <= s.x1 && s.y === y); + +test("Ghoul Rush: every room can be finished: a route from the start to the key and on to the door, every pit narrower than a jump clears, every rise lower than a jump, and everything placed on a surface", () => { + for (const base of ghoul.ROOMS) { + // A ride room is not walked: its own suite (ghoul-cart) proves the ride can be finished. + if (base.ride) continue; + const list = surfaces(base); + const g = base.ground; + for (let i = 0; i + 1 < g.length; i++) { + assert.ok(g[i][1] <= g[i + 1][0], `${base.id}: ground in order`); + const gap = g[i + 1][0] - g[i][1]; + const dy = g[i + 1][2] - g[i][2]; + if (gap > 0) assert.ok(ghoul.jumpHeightAt(gap + MARGIN) >= dy + MARGIN, `${base.id}: the pit at ${g[i][1]} (${gap} wide, ${dy} up) clears`); + else assert.ok(dy <= ghoul.JUMP_TOP - MARGIN, `${base.id}: the rise at ${g[i][1]} (${dy}) clears`); + } + assert.equal(g[0][0], 0); + assert.equal(g.at(-1)[1], base.length); + for (const [a, b] of base.thin || []) assert.ok(ghoul.jumpHeightAt(b - a + MARGIN) >= MARGIN, `${base.id}: the thin tile at ${a} (${b - a} wide) can be jumped`); + const start = surfaceAt(list, base.start, ghoul.groundAt(base, base.start)); + const door = surfaceAt(list, base.door, ghoul.groundAt(base, base.door)); + assert.ok(start && door, `${base.id}: start and door on the ground`); + assert.ok(base.door > base.length - 14, `${base.id}: the door at the room's end`); + let from = start; + if (base.key) { + const key = surfaceAt(list, base.key[0], base.key[1]); + assert.ok(key, `${base.id}: the key on a surface that stays`); + assert.ok(reachable(list, start).has(key), `${base.id}: a route to the key`); + from = key; + } + assert.ok(reachable(list, from).has(door), `${base.id}: a route on to the door`); + for (const [kind, x, y] of base.items) assert.ok(base.shelves.some(([a, b, top]) => x >= a && x <= b && top === y) || ghoul.groundAt(base, x) === y, `${base.id}: the ${kind} on a surface`); + for (const s of base.spawns) { + assert.ok(s[1] > 0 && s[1] < base.length, `${base.id}: ${s[0]} in the room`); + if (s[0] === "door" || s[0] === "crawl" || s[0] === "zombie" || s[0] === "hound" || s[0] === "spitter") assert.ok(ghoul.groundAt(base, s[1]) > -Infinity, `${base.id}: the ${s[0]} at ${s[1]} on the ground`); + if (s[0] === "spider") assert.ok(ghoul.groundAt(base, s[1]) > -Infinity, `${base.id}: the widow at ${s[1]} over a floor`); + if (s[0] === "skel") assert.ok(base.shelves.some(([a, b, top]) => s[1] >= a && s[1] <= b && top === s[2]) || ghoul.groundAt(base, s[1]) === s[2], `${base.id}: the skeleton at ${s[1]} on a surface`); + } + for (const x of base.chandeliers) assert.ok(ghoul.groundAt(base, x) > -Infinity, `${base.id}: the chandelier at ${x} over the floor`); + if (base.boss) assert.ok(base.length - ghoul.FIELD_W > 30, `${base.id}: room to walk into the arena`); + } +}); + +/* ---------------------------------------------------------------- the bot */ + +// A bot for Planny that runs for the key then the door, holds fire and turns +// to shoot what comes close, jumps pits, walls, the key's shelves and low +// monsters, jump-shoots monsters up a step, steers onto heads, drops through +// shelves it is done with, dodges bones, chandeliers and gourdlings, keeps +// clear of the Gourd as it hops and jumps Rattlebones' shockwaves. `skill` +// 1 is sharp, and holds fire but lets the blaster cool once it starts to +// slow (to half its free heat), unless a monster is close; lower skill stops +// now and then, misses some jumps, and lets go of fire, as a casual player +// does. +const go0 = (tx, you) => (tx > you.x ? 1 : tx < you.x ? -1 : you.face); +function makeBot(G, skill, random) { + let idle = 0; + let last = -1; + let late = 0; + let venting = false; + const missed = new Set(); + return (round) => { + const { you, input: inp, spec } = round; + const dt = last < 0 ? 16 : Math.max(0, round.clock - last); + last = round.clock; + inp.left = inp.right = inp.down = false; + if (round.phase !== "play") { + inp.up = false; + inp.fire = false; + return; + } + if (skill < 1 && idle <= 0 && random() < (1 - skill) * dt * 0.0004) idle = 200 + random() * 900; + idle = Math.max(0, idle - dt); + let tx = !round.hasKey && spec.key ? spec.key[0] : spec.door; + const boss = round.boss && round.boss.state !== "down" && round.boss.state !== "sleep" ? round.boss : null; + const fire = skill >= 1 || random() < 0.5 + skill * 0.5; + let face = 0; + let near = null; + for (const m of round.monsters) { + if (!G.solid(m)) continue; + if (m.x < round.camX - 2 || m.x > round.camX + G.FIELD_W + 2) continue; + if (Math.abs(m.y + m.h / 2 - (you.y + G.SHOT_Y)) > (m.kind === "wraith" ? 16 : 7)) continue; + if (!near || Math.abs(m.x - you.x) < Math.abs(near.x - you.x)) near = m; + } + let jumpNow = false; + if (boss) { + const side = you.x < boss.x ? -1 : 1; + tx = boss.x + side * (boss.kind === "gourd" ? 22 : 26); + face = Math.sign(boss.x - you.x); + if (boss.kind === "gourd" && boss.y > G.groundAt(spec, boss.x) + 0.1) { + if (Math.abs(you.x - boss.landX) < boss.w / 2 + 6) tx = boss.landX + (you.x < boss.landX ? -1 : 1) * (boss.w / 2 + 8); + if (tx < spec.arena + 3 || tx > spec.length - 3) tx = boss.landX + (you.x < boss.landX ? 1 : -1) * (boss.w / 2 + 8); + // Pinned against the arena's end: run under it while it is up, to + // the side with room. + if (boss.act === "hop" && boss.y > G.groundAt(spec, boss.x) + 4 && (side > 0 ? spec.length - 3 - boss.landX : boss.landX - spec.arena - 3) < 24) tx = boss.landX - side * (boss.w / 2 + 12); + } + if (near && Math.abs(near.x - you.x) < 14) face = Math.sign(near.x - you.x) || face; + for (const w of round.waves) if (Math.sign(you.x - w.x) === w.dir && Math.abs(w.x - you.x) < 4.5) jumpNow = true; + } else if (near && Math.abs(near.x - you.x) < 26) face = Math.sign(near.x - you.x); + // A glutton in the way soaks up bolts for too long: jump over it. + for (const m of round.monsters) { + const ahead = (m.x - you.x) * (go0(tx, you) || you.face); + if (m.kind === "glutton" && !m.dead && you.state === "run" && Math.abs(m.y - you.y) < 2 && ahead > 0 && ahead < 7) jumpNow = true; + } + // Where every bone and glob in the air comes down at your chest's height, + // and the way to run (or not) that stays furthest from all of them. + let dodge = false; + const threats = []; + for (const b of round.bones) { + const dy = b.y - (you.y + 2.4); + const disc = b.vy * b.vy + 2 * G.BONE_G * dy; + if (disc < 0) continue; + const t = (b.vy + Math.sqrt(disc)) / G.BONE_G; + if (t >= 0.05 && t <= 1.4) threats.push({ t, px: b.x + b.vx * t }); + } + if (boss && boss.kind === "gourd" && round.bones.length) { + // The Gourd's spit: run on past where the furthest glob comes down. + const lands = round.bones.map((b) => { + const disc = b.vy * b.vy + 2 * G.BONE_G * (b.y - you.y); + return b.x + b.vx * ((b.vy + Math.sqrt(Math.max(0, disc))) / G.BONE_G); + }); + const side = you.x < boss.x ? -1 : 1; + tx = side < 0 ? Math.min(...lands) - 5 : Math.max(...lands) + 5; + if (tx < spec.arena + 3 || tx > spec.length - 3) tx = side < 0 ? Math.max(...lands) + 4 : Math.min(...lands) - 4; + dodge = true; + } else if (threats.length) { + const room = (d) => { + const x = you.x + d * 8; + return x > (boss ? spec.arena + 3 : 3) && x < spec.length - 3; + }; + const miss = (d) => Math.min(...threats.map(({ t, px }) => Math.abs(px - (you.x + d * G.RUN_SPEED * Math.min(t, 0.5))))); + const way = go0(tx, you); + if (miss(way) <= 3.5) { + const pick = [way, -way, 0, 1, -1].filter(room).sort((a, c) => miss(c) - miss(a))[0] ?? 0; + tx = you.x + pick * 8; + dodge = true; + } + } + for (const m of round.monsters) { + const dx = m.x - you.x; + const dirTo = Math.sign(tx - you.x); + if (!boss && m.rise > 0 && Math.sign(dx) === dirTo && Math.abs(dx) < 9) tx = you.x - dirTo * 2; + } + if (boss && boss.kind === "gourd" && boss.vy === 0 && boss.wait < 600 && Math.abs(you.x - boss.x) < 15) { + const side = you.x < boss.x ? -1 : 1; + tx = boss.x + side * 22; + if (tx < spec.arena + 3 || tx > spec.length - 3) tx = boss.x - side * 22; + dodge = true; + } + if (boss) { + for (const m of round.monsters) { + if (m.kind !== "seed" || m.vy !== 0 || Math.abs(m.x - you.x) >= 4) continue; + tx = m.x + (you.x >= m.x ? 7 : -7); + if (tx < spec.arena + 3 || tx > spec.length - 3) tx = m.x + (you.x >= m.x ? -7 : 7); + dodge = true; + } + } + // Never stand in a burning puddle (nor run through one): head for the + // nearest spot clear of them all. + const clear = G.PUDDLE_W / 2 + 1.5; + const wet = (x) => round.puddles.some((p) => p.y <= you.y + 1 && Math.abs(p.x - x) < clear); + if (wet(tx) || wet(you.x)) { + const lo = boss ? spec.arena + 3 : 3; + for (let d = 0; d <= 30; d += 0.5) { + const pick = [tx + d, tx - d].find((x) => x > lo && x < spec.length - 3 && !wet(x)); + if (pick !== undefined) { + tx = pick; + break; + } + } + dodge = true; + } + for (const c of round.falls) { + if ((c.state === "shake" || c.state === "fall") && Math.abs(c.x - you.x) < 6) { + tx = c.x + (go0(tx, you) >= 0 ? 9 : -9); + dodge = true; + } + } + if (idle > 0) tx = you.x; + const slack = boss && !dodge ? 2 : 0.6; + let go = tx > you.x + slack ? 1 : tx < you.x - slack ? -1 : 0; + const airBoss = boss && boss.kind === "gourd" && boss.y > G.groundAt(spec, boss.x) + 0.1 && Math.abs(you.x - boss.landX) < boss.w / 2 + 6; + if (!dodge && !airBoss && face && face !== go && (!go || (near && Math.abs(near.x - you.x) < 14) || boss)) { + if (!near || Math.abs(near.x - you.x) > 1.5) go = you.face === face ? 0 : face; + } + // A ghost ahead and not yet level with your blaster: hold, face it and + // shoot as it comes. A wraith about to dive or diving: keep moving, so it + // dives at where you were. + if (!dodge && !boss) { + for (const m of round.monsters) { + if (m.kind === "wraith" && (m.act === "wind" || m.act === "dive") && Math.abs(m.x - you.x) < 34) { + go = go || you.face; + break; + } + if (m.kind !== "ghost" || !G.roused(m)) continue; + const dx = m.x - you.x; + if (Math.abs(dx) < 16 && Math.abs(m.y + m.h / 2 - (you.y + G.SHOT_Y)) > 2) { + go = you.face === Math.sign(dx) ? 0 : Math.sign(dx); + break; + } + } + } + if (you.state === "air" && you.vy < 0 && !boss) { + for (const m of round.monsters) { + if (!G.solid(m) || !G.MONSTERS[m.kind].stomp) continue; + const top = m.y + m.h; + if (you.y > top && you.y - top < 10 && Math.abs(m.x - you.x) < 7) go = Math.abs(m.x - you.x) < 0.5 ? 0 : Math.sign(m.x - you.x); + } + } + if (you.state === "air") { + const lands = (d) => { + let x = you.x; + let y = you.y; + let vy = you.vy; + for (let k = 0; k < 120; k++) { + vy -= G.GRAVITY * 0.016; + x += d * G.RUN_SPEED * 0.016; + y += vy * 0.016; + const gy = G.groundAt(spec, x); + if (vy < 0 && y <= gy) return true; + if (gy > y + 0.1 && gy > -Infinity) return true; + if (y < -2) return false; + } + return true; + }; + if (!lands(go)) go = [0, -go || -you.face, go || you.face].find((d) => lands(d)) ?? go; + } + const below = G.groundAt(spec, you.x); + if (you.state === "run" && you.shelf >= 0 && !boss && Math.abs(tx - you.x) > 6 && below > -Infinity && below < you.y - 3 && !(!round.hasKey && spec.key && spec.key[1] >= you.y - 1)) { + inp.down = true; + go = 0; + } + if (go) inp[go > 0 ? "right" : "left"] = true; + if (you.state === "run") { + const dir = go || you.face; + const ahead = you.x + dir * 2.4; + const g1 = G.groundAt(spec, ahead); + const f = G.footing(round, ahead, you.y); + if (go && you.shelf < 0 && (!f || g1 === -Infinity || g1 > you.y + G.STEP_UP)) jumpNow = true; + if (go && you.shelf >= 0 && !f && G.groundAt(spec, ahead + dir * 2) === -Infinity) jumpNow = true; + for (const m of round.monsters) { + const dx = (m.x - you.x) * you.face; + if (!boss && G.solid(m) && m.kind !== "bat" && dx > 0 && dx < 12 && m.y > you.y + 1.5 && m.y < you.y + 9) jumpNow = true; + } + if (!round.hasKey && spec.key && Math.abs(spec.key[0] - you.x) < 1.5 && spec.key[1] > you.y + 1) jumpNow = true; + // A puddle of acid just ahead on this level: over it. + for (const p of round.puddles) { + const dx = (p.x - you.x) * (go || you.face); + if (p.y === you.y && dx > -1 && dx < 5.5) jumpNow = true; + } + for (const m of round.monsters) { + if (boss || !G.solid(m) || m.kind === "ghost" || m.kind === "bat") continue; + if (Math.abs(m.y - you.y) < 2 && Math.abs(m.x - you.x) < 3.4 && m.h < 3) jumpNow = true; + } + } + if (jumpNow && skill < 1 && !missed.has(round.clock >> 9) && random() < (1 - skill) * 0.25) { + missed.add(round.clock >> 9); + late = 250; + } + if (late > 0) { + late -= dt; + jumpNow = false; + } + if (jumpNow && you.state === "run") { + inp.jump = G.JUMP_BUFFER_MS; + inp.up = true; + } else if (you.state === "run") inp.up = false; + if (skill >= 1) { + if (round.heat >= G.HEAT_FREE) venting = true; + else if (round.heat <= G.HEAT_FREE / 2) venting = false; + const gap = near ? Math.abs(near.x - you.x) : Infinity; + inp.fire = !venting || gap < 20 || round.effects.rapid > 0; + return; + } + inp.fire = fire && !(idle > 0 && skill < 1); + }; +} + +// Plays a round with a bot until it gets through `rooms` rooms or runs out +// of lives (or time): each room's seconds and lives lost, and the tones. +function botPlay(seed, skill, rooms, limitMs = 15 * 60000) { + const random = ghoul.seeded(seed * 977 + 13); + const round = ghoul.newRound(seed); + round.lives = 3; + round.dice = 0; + const bot = makeBot(ghoul, skill, ghoul.seeded(seed * 31 + 7)); + const per = []; + let ms = 0; + let at = 0; + let lost = 0; + while (!round.over && round.room <= rooms && ms < limitMs) { + // Out of the hall it takes the Manor (the house in its old order), then + // whatever is left. + if (round.phase === "pick" && round.phaseMs <= 0) { + if (!round.cleared.includes("manor") && !round.offer.includes("manor")) round.offer[0] = "manor"; + ghoul.pickStage(round, Math.max(0, round.offer.indexOf("manor"))); + } + bot(round); + ghoul.advance(round, 16, random); + ms += 16; + for (const e of round.events) { + if (e.type === "lose") lost++; + if (e.type === "clear") { + per.push({ secs: (ms - at) / 1000, lost }); + at = ms; + lost = 0; + } + } + round.events.length = 0; + } + return { round, per, ms }; +} + +test("Ghoul Rush: of ten runs a sharp bot gets nearly all through the hall and the Foyer, most past the Rotting Gourd and some on into the next stage, in 10 to 40 seconds a room (60 for the Gourd's), a sloppy one that dawdles and misses jumps is dead inside two minutes, and holding right and fire never gets past the Gallery", () => { + // The house is a real fight now (runners, gluttons, huntsmen, piles that + // climb, a Gourd with three moves), and the bot plays it simply, so this + // checks the share of ten runs rather than every one. + let outOfFoyer = 0; + let pastGourd = 0; + let through = 0; + for (const seed of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { + const { round, per } = botPlay(seed, 1, 6); + if (round.room >= 3) outOfFoyer++; + if (round.room >= 6) pastGourd++; + if (round.room < 7) continue; + through++; + // The Rotting Gourd's room (the fifth, after the hall) runs longer: the + // blaster has to cool between bursts at a boss. So does the sixth, the + // first of whichever stage the pick deals (it changes with every stage + // added: Hollow End's Main Street takes the bot up to a minute). + per.forEach((p, i) => assert.ok(p.secs >= 10 && p.secs <= (i === 4 ? 60 : i === 5 ? 70 : 40), `seed ${seed}: room ${i + 1} took ${p.secs.toFixed(1)} s`)); + } + assert.ok(outOfFoyer >= 9, `${outOfFoyer} of 10 through the hall and out of the Foyer`); + assert.ok(pastGourd >= 5, `${pastGourd} of 10 past the Gourd`); + assert.ok(through >= 3, `${through} of 10 through five rooms`); + for (const seed of [1, 2, 3, 4, 5]) { + const { round, ms } = botPlay(seed, 0.3, 99, 6 * 60000); + assert.equal(round.over, true, `sloppy seed ${seed} loses (room ${round.room})`); + assert.ok(ms > 20000 && ms < 2 * 60000, `in ${(ms / 1000).toFixed(0)} s`); + } + for (const seed of [1, 2, 3]) { + const random = ghoul.seeded(seed); + const round = ghoul.newRound(seed); + round.dice = 0; + round.lives = 3; + for (let ms = 0; ms < 3 * 60000 && !round.over; ms += 16) { + Object.assign(round.input, { right: true, fire: true, up: false }); + if (round.you.state === "run" && Math.floor(ms / 700) % 2 === 0) Object.assign(round.input, { jump: ghoul.JUMP_BUFFER_MS, up: true }); + ghoul.advance(round, 16, random); + round.events.length = 0; + } + // The Garlic gift for a quick loss can carry a masher out of the hall; it + // then waits on the stage pick, since it never picks, and goes no further. + assert.ok((round.over || round.phase === "pick") && round.room <= 2, `a masher (seed ${seed}) is dead, or stuck on the pick, by the Gallery (room ${round.room}, ${round.phase})`); + } +}); + +/* ---------------------------------------------------------------- game */ + +// On the pick screen, takes the Manor (put on offer if it is not, and not +// yet cleared) once the offer settles, so a run goes through the house in +// its old order. +function takeManor(g) { + const r = g.round; + if (r.phase !== "pick") return; + r.phaseMs = 0; + if (!r.cleared.includes("manor") && !r.offer.includes("manor")) r.offer[0] = "manor"; + r.pick = Math.max(0, r.offer.indexOf("manor")); + g.key("action"); +} + +// Starts a game with nothing waking. +function ghoulGame(opts = {}) { + const { canvas, calls } = stubCanvas(); + const g = ghoul.default.create({ canvas, ...opts }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + quiet(g.round); + return { g, calls }; +} + +test("Ghoul Rush game: held arrows run until let go; up jumps once a press, never on its key repeat, never again until let go, never with the press that plays on; space held fires and let go stops; a pause lets go of everything", () => { + const { g } = ghoulGame(); + const you = g.round.you; + const x0 = you.x; + g.key("right", true); + for (let i = 0; i < 20; i++) g.tick(16); + assert.ok(you.x > x0 + 4, "right held through the countdown (its repeats) runs"); + g.release("right"); + assert.equal(g.round.input.right, false); + g.key("up", true); + g.tick(16); + assert.equal(you.state, "run", "a repeat of up never jumps"); + g.release("up"); + g.key("up"); + g.tick(16); + assert.equal(you.state, "air", "a press jumps"); + for (let i = 0; i < 80; i++) { + g.key("up", true); + g.tick(16); + } + assert.equal(you.state, "run", "held, it jumped only once"); + g.key("up"); + g.tick(16); + assert.equal(you.state, "run", "a second press with up still held does nothing"); + g.release("up"); + g.key("action"); + g.tick(16); + assert.ok(g.round.shots.length >= 1, "space fires"); + for (let i = 0; i < 30; i++) g.tick(16); + assert.ok(g.round.stats.shots >= 3, "and keeps firing while held"); + g.release("action"); + const shots = g.round.stats.shots; + for (let i = 0; i < 30; i++) g.tick(16); + assert.equal(g.round.stats.shots, shots, "let go, it stops"); + g.key("left"); + g.key("action"); + g.pause(); + assert.deepEqual(g.round.input, { up: false, down: false, left: false, right: false, fire: false, jump: 0 }, "a pause holds nothing"); + g.resume(); + g.key("up"); + g.tick(16); + assert.equal(you.state, "run", "the press that plays on never jumps"); + g.release("up"); + g.key("up"); + g.tick(16); + assert.equal(you.state, "air"); + const y = you.y; + g.pause(); + g.tick(500); + assert.equal(you.y, y, "a pause holds a jump mid-air"); +}); + +test("Ghoul Rush game: space while paused does nothing (only the window plays on, through resume()), and a start from ready or over by space or Enter leaves fire off", () => { + const { canvas } = stubCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.round.dice = 0; + assert.equal(g.state, "running"); + assert.equal(g.round.input.fire, false, "the press that starts never fires"); + g.pause(); + assert.equal(g.key("action"), true); + assert.equal(g.state, "paused", "still paused"); + g.resume(); + assert.equal(g.state, "running"); + assert.equal(g.round.input.fire, false); + g.round.lives = 1; + ghoul.lose(g.round, "zombie"); + for (let ms = 0; ms < ghoul.CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + g.key("action"); + assert.equal(g.state, "running"); + assert.equal(g.round.input.fire, false, "nor the press that starts again"); + g.tick(16); + assert.equal(g.round.shots.length, 0); +}); + +test("Ghoul Rush game: the start screen names the record, the pick screen shows each stage offered and takes left, right and space, the memo keeps the most stages cleared and only grows, and the round's end shows its score big with onScore called once", (t) => { + t.mock.method(Math, "random", ghoul.seeded(4)); + const { canvas, texts } = textCanvas(); + let saved = 0; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = ghoul.default.create({ canvas, memo, onScore: (n) => scores.push(n) }); + g.resize(900, 900); + assert.ok(texts.some(([t]) => t.includes(`Best: 0 of ${ghoul.STAGES.length} stages`)), "the start screen names the record"); + g.key("action"); + g.round.dice = 0; + g.tick(16); + const through = () => { + const r = g.round; + quiet(r); + r.hasKey = true; + if (r.boss) r.boss.state = "down"; + standAt(r, r.spec.door); + for (let ms = 0; ms < ghoul.CLEAR_MS + ghoul.READY_MS + ghoul.CARD_MS + 200 && g.round.phase !== "pick"; ms += 16) g.tick(16); + }; + through(); + assert.equal(g.round.phase, "pick"); + texts.length = 0; + g.tick(16); + assert.ok(texts.some(([t]) => t === "Choose your way in"), "the pick screen"); + for (const id of g.round.offer) assert.ok(texts.some(([t]) => t === ghoul.stageById(id).title), `${id} on a card`); + assert.ok(texts.some(([t]) => t.startsWith("Boss: ")), "each card names its boss"); + g.key("right"); + g.key("action"); + assert.equal(g.round.phase, "pick", "a press before the offer settles does nothing"); + for (let ms = 0; ms < ghoul.PICK_HOLD_MS + 50; ms += 16) g.tick(16); + assert.equal(g.round.pick, 1, "right picked out the second"); + g.key("left"); + assert.equal(g.round.pick, 0); + g.key("action", true); + assert.equal(g.round.phase, "pick", "never on a key repeat"); + const want = g.round.offer[0]; + g.key("action"); + assert.deepEqual([g.round.stage, g.round.input.fire], [want, false], "space takes the stage, and fires nothing"); + for (let k = 0; k < ghoul.stageById(want).rooms.length - 1; k++) { + through(); + assert.equal(saved, 0, "no stage cleared yet"); + } + through(); + assert.equal(saved, 1, "a stage cleared is saved"); + assert.equal(g.round.phase, "pick"); + texts.length = 0; + g.tick(16); + assert.ok(texts.some(([t]) => t === `STAGE 1 OF ${ghoul.STAGES.length} CLEARED`)); + for (let ms = 0; ms < ghoul.PICK_HOLD_MS + 50; ms += 16) g.tick(16); + g.key("up"); + assert.ok(g.round.stage && g.round.stage !== want, "up takes one too, never the stage just cleared"); + for (let ms = 0; ms < ghoul.READY_MS + 50; ms += 16) g.tick(16); + g.round.dice = 0; + g.round.lives = 1; + ghoul.lose(g.round, "zombie"); + for (let ms = 0; ms < ghoul.CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + texts.length = 0; + g.resize(900, 900); + assert.ok(texts.some(([t, font]) => t === String(g.score) && /\b7px/.test(font)), "the score, big"); + assert.ok(texts.some(([t]) => t.startsWith(`Cleared 1 of ${ghoul.STAGES.length} stages, out in `) && t.includes("A new record!")), "how far, and the record"); + const again = ghoul.default.create({ canvas, memo: { get: () => 9, set: () => assert.fail("never lowered") } }); + again.resize(900, 900); + again.key("action"); + again.tick(16); +}); + +test("Ghoul Rush game: stageSelect() (the window's stage code) opens a practice round on every stage, nothing moving; up and down pick a stage, left and right a room, each clamped; space goes straight into that room with endless lives carried over; and the run keeps no record or score", () => { + const { canvas, texts } = textCanvas(); + let saved = 0; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = ghoul.default.create({ canvas, memo, onScore: (n) => scores.push(n) }); + g.resize(900, 900); + g.cheat(true); + texts.length = 0; + g.stageSelect(); + const r = g.round; + assert.equal(g.state, "running"); + assert.equal(r.phase, "select"); + assert.equal(r.practice, true); + assert.equal(r.infinite, true, "endless lives already on carry over"); + assert.ok(texts.some(([t]) => t === "Stage select"), "the select screen is drawn"); + for (let i = 0; i < 30; i++) g.tick(16); + assert.equal(r.phase, "select", "it waits on a choice"); + assert.equal(r.clock, 0, "nothing moves"); + const last = ghoul.STAGES.length - 1; + for (let i = 0; i < last + 3; i++) g.key("down"); + assert.equal(r.select.at, last, "down stops at the last stage"); + // Two up: the Mine, whose second to last room is a walked one (the Carnival's is the dark ride). + g.key("up"); + g.key("up"); + assert.equal(r.select.at, last - 2); + const st = ghoul.STAGES[last - 2]; + for (let i = 0; i < st.rooms.length + 3; i++) g.key("right"); + assert.equal(r.select.room, st.rooms.length - 1, "right stops at the boss room"); + g.key("left"); + assert.equal(r.select.room, st.rooms.length - 2); + g.key("action"); + assert.equal(r.phase, "ready"); + assert.equal(r.stage, st.id); + assert.equal(r.stageAt, st.rooms.length - 2); + assert.equal(r.spec.id, st.rooms[st.rooms.length - 2], "straight into the room picked"); + r.events.push({ type: "stageClear", stage: st.id, n: 3, of: ghoul.STAGES.length }); + g.tick(16); + assert.equal(saved, 0, "a practice run never sets the record"); + r.score = 5000; + r.over = true; + texts.length = 0; + g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [], "a practice run never posts a score"); + assert.ok(texts.some(([t]) => t.includes("A practice run: nothing kept.")), "the end screen says so"); + g.key("action"); + assert.equal(g.round.practice, undefined, "a new round from the end screen is a normal one"); +}); + +test("Ghoul Rush game: a run that clears every stage ends in a win, with a fanfare and the word on the end screen", () => { + const { canvas, texts } = textCanvas(); + const played = []; + const scores = []; + const g = ghoul.default.create({ canvas, tone: (name) => played.push(name), onScore: (n) => scores.push(n) }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const r = g.round; + through(r); + while (!r.over) { + r.phaseMs = 0; + ghoul.pickStage(r); + for (let k = 0; k < 4; k++) through(r); + } + g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + assert.ok(played.includes("victory") && !played.includes("gameOver"), "a win, not a loss"); + assert.ok(texts.some(([t]) => t.startsWith("You escaped!"))); +}); + +test("Ghoul Rush: every monster and boss has its own voice, each a tone tones.js has under this game's prefix, and every kind a death", () => { + const known = new Set(toneNames()); + for (const kind of [...Object.keys(ghoul.MONSTERS), ...Object.keys(ghoul.BOSSES)]) { + assert.ok(VOICES[kind], `${kind} has a voice`); + assert.ok(VOICES[kind].die, `${kind} has a death`); + for (const [act, name] of Object.entries(VOICES[kind])) { + assert.ok(known.has(name), `${kind}.${act}: ${name} is in tones.js`); + assert.match(name, /^ghoul[A-Z]/, `${name} keeps to this game's prefix`); + } + } +}); + +test("Ghoul Rush game: every tone it plays is one tones.js has, its own blips among them under this game's prefixes, and a run plays the blaster, kills, candy, the key and the door", () => { + const known = new Set(toneNames()); + assert.ok(known.has("hop") && known.has("power"), "read the table"); + for (const name of GHOUL_TONES) { + assert.ok(known.has(name), `${name} is in tones.js`); + assert.match(name, /^(ghoul|zombie|bat|door|creak)/, `${name} keeps to this game's prefixes`); + } + const heard = new Set(); + const g = ghoul.default.create({ canvas: stubCanvas().canvas, tone: (name) => heard.add(name) }); + g.resize(900, 900); + g.key("action"); + const bot = makeBot(ghoul, 1, ghoul.seeded(3)); + for (let ms = 0; ms < 90000 && g.round.room < 3 && g.state === "running"; ms += 16) { + takeManor(g); + bot(g.round); + g.tick(16); + } + for (const name of heard) assert.ok(known.has(name), `${name} is a known tone`); + for (const name of ["ghoulBlast", "zombiePop", "ghoulCandy", "doorUnlock", "doorThrough", "hop"]) assert.ok(heard.has(name), `${name} played`); +}); + +test("Ghoul Rush game: its own sounds keep its prefix, and a run holds a monster's hum (and no drone under the music), steps on the boards, and tolls at the end", () => { + for (const name of [...Object.keys(ghoulSfx.tones), ...Object.keys(ghoulSfx.hums)]) assert.match(name, /^ghoul/, `${name} keeps to this game's prefix`); + const known = new Set(toneNames()); + const hums = new Set(humNames()); + const heard = new Set(); + const held = new Map(); + const songs = new Map(); + const g = ghoul.default.create({ + canvas: stubCanvas().canvas, + tone: (name) => heard.add(name), + hum: (id, name, level, pitch) => held.set(id, { name, level, pitch }), + music: (name, dread) => songs.set(name, Math.max(songs.get(name) ?? 0, dread)), + }); + g.resize(900, 900); + g.key("action"); + g.round.dice = 0; + const bot = makeBot(ghoul, 1, ghoul.seeded(3)); + for (let ms = 0; ms < 180000 && g.round.room < 4 && g.state === "running"; ms += 16) { + takeManor(g); + bot(g.round); + g.tick(16); + } + for (const name of heard) assert.ok(known.has(name), `${name} is a known tone`); + for (const [id, h] of held) { + assert.ok(id.startsWith("ghoul:"), `${id} is this game's hum`); + assert.ok(hums.has(h.name), `${h.name} is a known hum`); + assert.ok(h.level >= 0 && h.level <= 1.0001 && h.pitch > 0, `${id}: a level and a pitch`); + } + assert.ok(!held.has("ghoul:house"), "no drone under the music"); + assert.ok(held.has("ghoul:near"), "a monster close by is heard"); + const tracks = [...new Set(["hall", "foyer", "gallery"].map((id) => ghoul.ROOM_MUSIC[id]))]; + assert.deepEqual([...songs.keys()].slice(0, tracks.length), tracks, `each room plays its own track (${[...songs.keys()]})`); + for (const [name, dread] of songs) assert.ok(Object.hasOwn(ghoulSfx.music, name) && dread > 0 && dread <= 1, `${name}: a known track, played with some dread`); + for (const name of ["ghoulStep", "jump", "land", "ghoulKey", "ghoulRoomIn"]) assert.ok(heard.has(name), `${name} played`); + // The last life: the heart pounds; then out of lives, the toll. + const sounds = []; + const h = ghoul.default.create({ canvas: stubCanvas().canvas, tone: (name) => sounds.push(name) }); + h.resize(900, 900); + h.key("action"); + h.round.dice = 0; + h.round.lives = 1; + for (let k = 0; k < 60; k++) h.tick(16); + assert.equal(h.round.phase, "play"); + assert.ok(sounds.includes("heartbeat"), "a heartbeat on the last life"); + ghoul.lose(h.round, "zombie"); + for (let k = 0; k < 200 && h.state === "running"; k++) h.tick(16); + assert.equal(h.state, "over"); + assert.ok(sounds.includes("gameOver") && sounds.includes("ghoulToll"), "the run ends on a toll"); +}); + +test("Ghoul Rush: every room has a track, played at one steady level whatever the monsters do (fuller in the clock's last seconds), and near full in a boss fight", () => { + for (const spec of ghoul.ROOMS) assert.ok(Object.hasOwn(ghoulSfx.music, ghoul.ROOM_MUSIC[spec.id]), `${spec.id} has a track`); + const round = ghoulRound("foyer"); + standAt(round, 60); + round.timeMs = 60000; + const steady = ghoul.dread(round); + assert.equal(steady, 0.7, "an empty stretch: the room's level"); + for (let k = 0; k < 8; k++) put(round, "zombie", 62); + assert.equal(ghoul.dread(round), steady, "a crowd right on you changes nothing"); + // The level brings in each track's melody and drums, never only its drone. + for (const name of Object.values(ghoul.ROOM_MUSIC)) { + const playing = Object.entries(ghoulSfx.music[name].voices).filter(([, v]) => (v.from ?? 0) <= steady); + assert.ok(playing.length >= 4, `${name}: ${playing.map(([k]) => k).join(", ")} at the room's level`); + } + round.timeMs = 5000; + assert.ok(Math.abs(ghoul.dread(round) - 0.9) < 1e-9, "the clock running out adds a little"); + const fight = ghoulRound("ballroom"); + fight.lockX = 10; + fight.boss.state = "fight"; + assert.equal(ghoul.dread(fight), 0.9, "a boss at full health: near full"); + fight.boss.hp = 0; + assert.equal(ghoul.dread(fight), 1, "and full as it nears its end"); +}); + +/* ---------------------------------------------------------------- drawing */ + +// A 2D context that records each banner shade fill's alpha, and every text. +function seeCanvas() { + const alphas = []; + const texts = []; + const ctx = new Proxy({ globalAlpha: 1 }, { + get: (t, name) => { + if (name === "fillRect") return () => t.fillStyle === BANNER_SHADE && alphas.push(t.globalAlpha); + if (name === "fillText") return (text) => texts.push(String(text)); + return name in t ? t[name] : () => {}; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, alphas, texts }; +} + +test("Ghoul Rush game: a banner fades to see-through while something that can hurt you crosses its strip, and comes back once it has gone", () => { + const { canvas, alphas } = seeCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + quiet(g.round); + for (let k = 0; k < 10; k++) g.tick(16); + assert.ok(alphas.at(-1) > 0.9, `clear strip: solid (${alphas.at(-1)})`); + const r = g.round; + const y = ghoul.FIELD_H - ghoul.bannerY(r) - 1; + const bat = put(r, "bat", r.camX + 70, { y, vx: 0 }); + for (let k = 0; k < 30; k++) { + Object.assign(bat, { x: r.camX + 70, y, vx: 0, vy: 0 }); + g.tick(16); + } + assert.ok(alphas.at(-1) < 0.2, `a bat in the strip: see-through (${alphas.at(-1).toFixed(2)})`); + r.monsters.length = 0; + for (let k = 0; k < 30; k++) g.tick(16); + assert.ok(alphas.at(-1) > 0.85, `gone: solid again (${alphas.at(-1).toFixed(2)})`); +}); + +test("Ghoul Rush game: a \"Ready?\" banner still waiting when play begins is dropped, and \"New best!\" makes room for itself in a full queue", () => { + const { canvas, texts } = seeCanvas(); + const g = ghoul.default.create({ canvas, best: () => 1 }); + g.resize(900, 900); + g.key("action"); + g.round.dice = 0; + quiet(g.round); + g.tick(16); + ghoul.lose(g.round, "zombie"); + for (let ms = 0; ms < ghoul.CRASH_MS + ghoul.READY_MS + 100; ms += 16) g.tick(16); + assert.equal(g.round.phase, "play"); + texts.length = 0; + for (let ms = 0; ms < 3000; ms += 16) g.tick(16); + assert.ok(!texts.includes("Ready?"), "not shown late, once play is on"); + const r = g.round; + for (const kind of ["spread", "rapid", "garlic"]) r.events.push({ type: "power", kind, x: r.you.x, y: r.you.y }); + g.tick(16); + r.score = 50; + g.tick(16); + texts.length = 0; + for (let ms = 0; ms < 8000; ms += 16) { + quiet(r); + r.you.safeMs = 1e9; + g.tick(16); + } + assert.ok(texts.includes("New best!"), "the record is never dropped"); +}); + +test("Ghoul Rush: every pill's text reads at 4.5:1 on its backing and its timer's tint, in light and dark under every highlight, the chain, a spent bonus, the key and every power-up included", () => { + for (const [theme, tokens] of Object.entries(THEME_TOKENS)) { + for (const [id, accent] of Object.entries(ACCENTS)) { + const values = { ...tokens, "--accent": accent[theme][0] }; + withTokens(values, () => { + const { canvas, pills, reset } = pillCanvas(values["--panel"]); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + const r = g.round; + quiet(r); + Object.assign(r, { bonus: 0, chain: 4, chainMs: ghoul.CHAIN_MS / 2, hasKey: true }); + r.effects.spread = 5000; + r.effects.rapid = 5000; + r.you.garlic = true; + reset(); + g.tick(1); + const seen = pills(); + for (const p of seen) { + for (const under of [p.backing, ...p.tints]) { + const k = wcag(p.ink, under); + assert.ok(k >= 4.5, `${theme}/${id}: "${p.text}" in ${p.ink} on ${under} reads ${k.toFixed(2)}:1`); + } + } + for (const want of ["THE LONG HALL", `STAGE 0 OF ${ghoul.STAGES.length}`, "♥", "BONUS 0", "~CHAIN x4", "KEY", "~SPREAD", "~RAPID", "GARLIC"]) { + const tinted = want.startsWith("~"); + const text = tinted ? want.slice(1) : want; + assert.ok(seen.some((p) => p.text.includes(text) && (!tinted || p.tints.length)), `${theme}/${id}: "${text}" drawn (${seen.map((p) => p.text)})`); + } + }); + } + } +}); + +test("Ghoul Rush: the top bar names the stage (or the hall) and counts the stages cleared of all there are, lives sit in the solid lives pill right after them, white with a heart per life, and the pills keep to one row in the slim strip with everything showing, spilling a row onto the field only on the smallest board", () => { + const { canvas, pills, reset } = pillCanvas("#ffffff"); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + reset(); + g.tick(16); + const seen = pills(); + const at = seen.findIndex((p) => p.text.startsWith("♥")); + assert.deepEqual(seen.slice(0, 2).map((p) => p.text), ["THE LONG HALL", `STAGE 0 OF ${ghoul.STAGES.length}`], "the hall, nothing cleared yet"); + assert.equal(at, 2, `right after the stage pills (${seen.map((p) => p.text)})`); + assert.equal(seen[at].text, livesText(g.round.lives)); + assert.equal(seen[at].backing, LIVES_BACK); + assert.equal(seen[at].ink, LIVES_INK); + assert.equal(LIVES, ghoul.POWERS.life.color, "the 1UP keeps the lives pink"); + const box = (p, h) => [p.x, p.y, p.x + p.w, p.y + h]; + for (const h of [Math.max(12 / ghoul.MIN_CELL, 2.4), 2.4]) { + const hud = { room: "THE GRAND OPERA HOUSE", stage: "STAGE 20 OF 21", time: 80, timeLow: false, bonus: ghoul.BONUS_START, chain: ghoul.MAX_MULT, chainFill: 0.5, key: true, effects: ["SPREAD", "RAPID", "GARLIC"].map((text) => ({ text, color: "#ffffff", fill: 0.5 })), gauge: { fill: 0.5, free: 0.6, rapid: null } }; + const laid = hudLayout(h, ghoul.W, ghoul.MAX_LIVES, hud, ghoul.HUD_H); + assert.ok(laid.every((p) => p.h >= h * 0.6), "shrunk no more than it must"); + const placed = laid.map((p) => box(p, p.h)); + // A pill 2.4 units tall is every board but the smallest: one row, in the strip. + const roomy = h === 2.4; + if (roomy) assert.equal(new Set(laid.map((p) => p.y)).size, 1, "one row"); + for (const [x0, y0, x1, y1] of placed) { + assert.ok(x0 >= 0 && x1 <= ghoul.W, `on the board (h ${h})`); + assert.ok(y0 >= 0 && y1 <= (roomy ? ghoul.HUD_H : ghoul.HUD_H + 3), `in the strip, or just below it on the smallest board (h ${h}, ${y0.toFixed(2)}..${y1.toFixed(2)})`); + } + for (let i = 0; i < placed.length; i++) { + for (let j = i + 1; j < placed.length; j++) { + const [p, q] = [placed[i], placed[j]]; + assert.ok(p[2] <= q[0] || q[2] <= p[0] || p[3] <= q[1] || q[3] <= p[1], `pills ${i} and ${j} apart (h ${h})`); + } + } + } + for (const text of ["Headshot! +1600", "Down the hole!", "A line much too long to fit across the field at all, however small it is drawn"]) { + for (let x = -10; x <= ghoul.FIELD_W + 10; x += 13) { + for (let y = -10; y <= ghoul.FIELD_H + 10; y += 11) { + const spot = labelSpot(text, x, y, 2.6, ghoul.FIELD_W, ghoul.FIELD_H); + assert.ok(spot.x - spot.max / 2 >= 0 && spot.x + spot.max / 2 <= ghoul.FIELD_W); + assert.ok(spot.y - 1.3 >= 0 && spot.y + 1.3 <= ghoul.FIELD_H); + } + } + } +}); + +test("Ghoul Rush: the blaster's gauge fills with its heat, notched where the bolts slow, and empties as it cools", () => { + const g = ghoul.default.create({ canvas: stubCanvas().canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + const gauge = () => g.hud.gauge; + assert.equal(gauge().free, ghoul.HEAT_FREE / ghoul.HEAT_MAX, "the notch sits where fireGap() starts to slow"); + assert.equal(gauge().fill, 0, "cool at the start"); + g.round.heat = ghoul.HEAT_FREE + 5; + g.tick(16); + const hot = gauge().fill; + assert.ok(hot > gauge().free, "past the notch once the bolts slow"); + g.round.input.fire = false; + for (let k = 0; k < 40; k++) g.tick(16); + assert.ok(gauge().fill < hot, "and down again as it cools"); + assert.equal(gaugeColor(0.1, 0.6), GAUGE_COOL); + assert.equal(gaugeColor(0.5, 0.6), GAUGE_WARM); + assert.equal(gaugeColor(0.7, 0.6), GAUGE_HOT); + assert.equal(gaugeColor(0.7, 0.6, ghoul.POWERS.rapid.color), ghoul.POWERS.rapid.color, "Rapid fire's bolts ignore the heat"); +}); + +test("Ghoul Rush: Planny's arms and feet read on every room's walls, and every room has a look", () => { + for (const base of ghoul.ROOMS) assert.ok(LOOKS[base.id], `${base.id} has a look`); + for (const [look, t] of Object.entries(LOOKS)) { + const ink = limbInk(look); + for (const tone of [t.wallTop, t.wallLow, t.paper]) assert.ok(contrast(ink, tone) >= 3, `${look}: ${ink} on ${tone} (${contrast(ink, tone).toFixed(2)})`); + } +}); + +test("Ghoul Rush: the banner's strip counts you, a monster or a boss on screen, a bone or a shockwave, and nothing off screen or elsewhere", () => { + const round = ghoulRound(); + standAt(round, 30); + const high = ghoul.FIELD_H * 0.3; + assert.equal(ghoul.bannerY(round), high, "high on the field while you are low"); + assert.equal(ghoul.underBanner(round, high), false, "nothing in the strip"); + assert.equal(ghoul.underBanner(round, ghoul.FIELD_H - 8), true, "you, low down"); + const bat = put(round, "bat", 40, { y: ghoul.FIELD_H - high - 1 }); + assert.equal(ghoul.underBanner(round, high), true, "a bat in the strip"); + bat.x = round.camX + ghoul.FIELD_W + 20; + assert.equal(ghoul.underBanner(round, high), false, "off screen, it does not count"); + round.monsters.length = 0; + round.bones.push({ x: 50, y: ghoul.FIELD_H - high, vx: 0, vy: 0 }); + assert.equal(ghoul.underBanner(round, high), true, "a bone"); + round.bones.length = 0; + round.you.y = ghoul.FIELD_H * 0.6; + assert.equal(ghoul.bannerY(round), ghoul.FIELD_H * 0.72, "low while you are high"); +}); + +test("Ghoul Rush game: the opening banner sits in the field from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas(BANNER_SHADE); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + shades.length = 0; + g.key("action"); + assert.equal(shades.length, 1, "the start paints its banner"); + const [[top, h]] = shades; + assert.ok(top >= 0 && top + h <= ghoul.FIELD_H, `inside the field (${top})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [[top, h]], "in the same place once play begins"); +}); + +test("Ghoul Rush game: Planny keeps his star eye in your highlight running, firing, in the air, hit, with garlic, cheering at the door and at the end", () => { + const frame = (setup) => { + const { canvas, fills } = styleCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.round.dice = 0; + g.tick(16); + quiet(g.round); + setup(g, g.round.you); + fills.length = 0; + g.resize(900, 900); + return fills.filter((f) => f === "#206cc3").length; + }; + assert.equal(frame((g) => { g.key("right"); g.tick(100); }), 1, "running"); + assert.equal(frame((g) => { g.key("action"); g.tick(20); }), 1, "firing"); + assert.equal(frame((g, you) => Object.assign(you, { state: "air", vy: 10, y: you.y + 3 })), 1, "in the air"); + assert.equal(frame((g) => ghoul.lose(g.round, "zombie")), 1, "hit"); + assert.equal(frame((g, you) => (you.garlic = true)), 1, "with garlic"); + assert.equal(frame((g) => { + g.round.hasKey = true; + standAt(g.round, g.round.spec.door); + g.tick(16); + assert.equal(g.round.phase, "clear"); + }), 1, "cheering at the door"); + assert.equal(frame((g) => { + g.round.lives = 1; + ghoul.lose(g.round, "bat"); + for (let ms = 0; ms < ghoul.CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + }), 1, "at the end"); +}); + +test("Ghoul Rush game: what never moves in a room is drawn off screen once, CHUNK units at a time, and copied every frame; a new stretch or room draws only its own", () => { + const saved = globalThis.OffscreenCanvas; + const layers = []; + globalThis.OffscreenCanvas = class { + constructor(w, h) { + this.width = w; + this.height = h; + this.names = []; + layers.push(this); + const names = this.names; + this.ctx = new Proxy({}, { + get: (t, name) => (name in t ? t[name] : () => { names.push(name); }), + set: (t, n, v) => { t[n] = v; return true; }, + }); + } + getContext() { return this.ctx; } + }; + try { + const { canvas, names } = recordingCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + quiet(g.round); + g.tick(16); + // The dark layer is one canvas the field's size, kept and redrawn each + // frame; the still layers are the CHUNK-wide ones. + const still = () => layers.filter((l) => l.width === Math.ceil((CHUNK + SEAM) * 2)); + const first = still().length; + assert.equal(first, Math.floor(ghoul.FIELD_W / CHUNK) + 1, "the chunks on screen drawn once"); + assert.ok(still().every((l) => l.names.length > 100), "the room drawn on them"); + assert.equal(layers.length - first, 1, "and one dark layer"); + layers.length = 0; + names.length = 0; + for (let k = 0; k < 10; k++) g.tick(16); + assert.equal(layers.length, 0, "kept from frame to frame"); + assert.ok(names.filter((n) => n === "drawImage").length >= 10 * first, "copied every frame"); + assert.equal(names.filter((n) => n === "createLinearGradient").length, 0, "no wall gradient made per frame"); + g.key("right"); + for (let k = 0; k < 220; k++) g.tick(16); + g.release("right"); + assert.ok(layers.length >= 1 && layers.length <= 3, `running on draws the next stretch (${layers.length})`); + layers.length = 0; + const r = g.round; + quiet(r); + r.hasKey = true; + standAt(r, r.spec.door); + r.camX = r.spec.length - ghoul.FIELD_W; + g.tick(16); + layers.length = 0; + for (let ms = 0; ms < ghoul.CLEAR_MS + 100; ms += 16) g.tick(16); + takeManor(g); + for (let ms = 0; ms < ghoul.READY_MS + 100; ms += 16) g.tick(16); + assert.equal(g.round.room, 2); + assert.ok(layers.length >= 1 && layers.length <= 3, `the next room draws its own (${layers.length})`); + } finally { + if (saved === undefined) delete globalThis.OffscreenCanvas; + else globalThis.OffscreenCanvas = saved; + } +}); + +test("Ghoul Rush game: every room and boss draws, and each pick of stage, through a short bot run of each, on to the win", () => { + const { canvas, calls } = stubCanvas(); + const g = ghoul.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let n = 1; n <= ghoul.ROOMS.length; n++) { + const r = g.round; + r.lives = 99; + const bot = makeBot(ghoul, 1, ghoul.seeded(n)); + const drawn = calls.count; + // The dark ride holds on its title for a press. + if (r.gallery) g.key("action"); + for (let ms = 0; ms < 4000; ms += 16) { + bot(r); + g.tick(16); + } + assert.ok(calls.count > drawn, `room ${n} draws`); + if (r.boss) r.boss.state = "down"; + r.hasKey = true; + // Through the door, once any life lost in the run is over with. + for (let ms = 0; ms < 8000 && g.round.room === n && g.state === "running"; ms += 16) { + if (r.phase === "play" && r.you.out <= 0) { + r.monsters.length = 0; + standAt(r, r.spec.door); + } + if (r.phase === "pick") { + const before = calls.count; + g.tick(16); + assert.ok(calls.count > before, `the pick after room ${n} draws`); + r.phaseMs = 0; + g.key("action"); + } + g.tick(16); + } + if (n === ghoul.ROOMS.length) break; + for (let ms = 0; ms < ghoul.READY_MS + 100; ms += 16) g.tick(16); + assert.equal(g.round.room, n + 1); + } + assert.deepEqual([g.state, g.round.won], ["over", true], "every stage cleared, a win"); +}); diff --git a/scripts/test-web-console-activities-rapids.mjs b/scripts/test-web-console-activities-rapids.mjs new file mode 100644 index 0000000..481a9db --- /dev/null +++ b/scripts/test-web-console-activities-rapids.mjs @@ -0,0 +1,1422 @@ +// Web console tests, Rapids Run: the game contract, the river's shape, steering, speed, the guns, the battery and its buoys, crashes and the restart at the last dam, dams, combos, skims, power-ups, the river's foes and mini-bosses, the memo, the pills, the banners, and bots that show the river is always passable and that a careless run ends quickly. +// Run with: node --test scripts/test-web-console-activities-rapids.mjs +// +// No browser and no server: the game draws only through the canvas it is +// handed, so a stub canvas stands in for the page, as in +// scripts/test-web-console-activities.mjs, whose helpers this file copies. + +import test from "node:test"; +import assert from "node:assert/strict"; +import * as rapids from "../src/web-console/public/activities/rapids.js"; +import { hudLayout, labelSpot, LOOKS, inkOn, contrast } from "../src/web-console/public/activities/rapids-draw.js"; +import { ACCENTS } from "../src/web-console/public/palette.js"; +import { LIVES_BACK, LIVES_INK, livesText } from "../src/web-console/public/activities/pills.js"; + +const { + advance, applyPower, channelAt, channelsAt, ensureRiver, hurtBoss, isWater, lose, newRiver, newRound, onLand, placeAt, riverAt, screenY, stretchFor, stretchName, underBanner, + AHEAD, BATTERY, BOSS_EVERY, BOSS_POINTS, BUOY_CHARGE, BUOY_POINTS, COMBO_MS, CRASH_MS, CRUISE, DAM_POINTS, DAM_W, DIST_STEP, DRAIN, EDGE, FAST, FIELD_H, FIELD_W, FIRE_MS, FLAWLESS_POINTS, FOES, + GRACE_MS, H, LOW_BATTERY, MAX_COMBO, MAX_LIVES, MAX_SHIELDS, MIN_CELL, MIN_CHANNEL, POWERS, READY_MS, RESPAWN_AT, ROW, SHIP_L, SHIP_W, SKIM_MS, SKIM_POINTS, SLOPE, SLOW, START_LIVES, STRETCHES, W, BANNER_Y, +} = rapids; +const game = rapids.default; + +/* ------------------------------------------------------------- helpers */ + +// A 2D context whose every method is a no-op that counts itself. +function stubCanvas() { + const calls = { count: 0 }; + const ctx = new Proxy({}, { + get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }), + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls }; +} + +// A 2D context that records where each strip in a banner's shade is filled +// (its top and height), and does nothing else. +function bannerCanvas(shade) { + const shades = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillRect" ? (x, y, w, h) => t.fillStyle === shade && shades.push([y, h]) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, shades }; +} + +// The page's tokens in light and dark, for readColors() through a stubbed +// getComputedStyle. +const THEME_TOKENS = Object.freeze({ + light: Object.freeze({ "--panel": "#ffffff", "--panel-2": "#fbf9f6", "--rule": "#e4ddd1", "--accent": "#206cc3", "--ink": "#1d1a17" }), + dark: Object.freeze({ "--panel": "#201d1a", "--panel-2": "#262220", "--rule": "#332e29", "--accent": "#619fe5", "--ink": "#f0ece5" }), +}); + +// "#rrggbb" or "rgb(a)(...)" as [r, g, b, a], and the WCAG contrast of two. +function rgbaOf(color) { + const hex = /^#([0-9a-f]{6})$/i.exec(color); + if (hex) return [0, 2, 4].map((k) => parseInt(hex[1].slice(k, k + 2), 16)).concat(1); + const [r, g, b, a = 1] = /rgba?\(([^)]*)\)/.exec(color)[1].split(",").map(Number); + return [r, g, b, a]; +} +const toHex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`; +const overColor = (top, alpha, base) => top.slice(0, 3).map((v, i) => v * alpha + base[i] * (1 - alpha)); +function wcag(a, b) { + const lum = (c) => { + const [r, g, bl] = rgbaOf(c).slice(0, 3).map((v) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4)); + return 0.2126 * r + 0.7152 * g + 0.0722 * bl; + }; + const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); + return (x + 0.05) / (y + 0.05); +} + +// A 2D context that keeps, for each pill it draws (a rounded fill, perhaps +// a timer's rounded tint, then the text with no dark edge), the text's +// color, the backing composited over `board` and each tint over that. +function pillCanvas(board) { + const drawn = []; + let since = []; + const target = { globalAlpha: 1, getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), measureText: () => ({ width: 50 }) }; + const ctx = new Proxy(target, { + get: (t, name) => { + if (name in t) return t[name]; + if (name === "roundRect") return () => since.push({ k: "round" }); + if (name === "fill") return () => since.push({ k: "fill", style: t.fillStyle, alpha: t.globalAlpha }); + if (name === "fillText") return (text) => { drawn.push({ text: String(text), ink: t.fillStyle, since }); since = []; }; + if (name === "strokeText" || name === "fillRect" || name === "stroke") return () => since.push({ k: name }); + return () => {}; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 900, height: 900, getContext: () => ctx }; + ctx.canvas = canvas; + const pills = () => drawn.flatMap(({ text, ink, since: seq }) => { + if (seq.some((e) => e.k === "strokeText") || seq.at(-1)?.k !== "fill") return []; + const fills = seq.filter((e, i) => e.k === "fill" && seq[i - 1]?.k === "round"); + const back = fills.find((e) => e.alpha === 1); + if (!back) return []; + const b = rgbaOf(back.style); + const backing = toHex(overColor(b, b[3], rgbaOf(board))); + const tints = fills.slice(fills.indexOf(back) + 1).map((e) => { + const c = rgbaOf(e.style); + return toHex(overColor(c, e.alpha * c[3], rgbaOf(backing))); + }); + return [{ text, ink, backing, tints }]; + }); + return { canvas, pills, reset: () => { drawn.length = 0; since = []; } }; +} + +// Plays the game a few frames in light and dark under every highlight, runs +// `setup(round)`, draws one more frame and checks every pill's text reads +// at 4.5:1 on its backing and each tint, and that each of `expect` showed +// (a "~" before one: drawn with a timer's tint). +function checkPills({ setup = () => {}, expect = [] } = {}) { + const saved = globalThis.getComputedStyle; + try { + for (const [theme, tokens] of Object.entries(THEME_TOKENS)) { + for (const [id, accent] of Object.entries(ACCENTS)) { + const values = { ...tokens, "--accent": accent[theme][0] }; + globalThis.getComputedStyle = () => ({ getPropertyValue: (name) => values[name] || "" }); + const { canvas, pills, reset } = pillCanvas(values["--panel"]); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + setup(g.round); + reset(); + g.tick(16); + const seen = pills(); + assert.ok(seen.length > 0, `${theme}/${id}: pills drawn`); + for (const p of seen) { + for (const under of [p.backing, ...p.tints]) { + const k = wcag(p.ink, under); + assert.ok(k >= 4.5, `${theme}/${id}: "${p.text}" in ${p.ink} on ${under} reads ${k.toFixed(2)}:1`); + } + } + for (const want of expect) { + const tinted = want.startsWith("~"); + const text = tinted ? want.slice(1) : want; + assert.ok(seen.some((p) => p.text.includes(text) && (!tinted || p.tints.length)), `${theme}/${id}: "${text}" drawn${tinted ? " with its tint" : ""} (${seen.map((p) => p.text)})`); + } + } + } + } finally { + if (saved === undefined) delete globalThis.getComputedStyle; + else globalThis.getComputedStyle = saved; + } +} + +// A round with nothing on the river but the river: no foes, buoys, crates +// or bolts, so a test sets out only what it means to. +function quiet(seed = 7) { + const round = newRound(seed); + clear(round); + return round; +} +function clear(round) { + round.foes.length = 0; + round.buoys.length = 0; + round.crates.length = 0; + round.bolts.length = 0; + round.loaded = round.stretch + 1; + return round; +} + +// A foe set out by hand, shaped as the round's loader makes them. +function foe(round, kind, x, d, extra = {}) { + const f = { kind, n: round.stretch, x, d, vx: 0, hp: FOES[kind].hp, r: FOES[kind].r, t: 0, flash: 0, on: false, fireMs: 600, ...extra }; + round.foes.push(f); + return f; +} + +const eventsOf = (round, type) => round.events.filter((e) => e.type === type); +const center = (round, d = round.ship.d) => riverAt(round.river, d).c; + +// Runs `ms` in frames of 16, clearing the river ahead first if asked. +function run(round, ms, each = () => {}) { + for (let t = 0; t < ms && !round.over; t += 16) { + each(round); + advance(round, 16); + } +} + +// Starts a game the way the window's key does and checks its opening banner: +// painted on the start's own frame, inside the field (0 to `field`), and in +// the same place on the first tick. +function openingBanner(g, shades, field) { + shades.length = 0; + g.key("action"); + assert.equal(shades.length, 1, "the start paints its banner"); + const [[top, h]] = shades; + assert.ok(top >= 0 && top + h <= field, `inside the field, not at its top edge (${top})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [[top, h]], "in the same place once play begins"); +} + +/* ---------------------------------------------------------------- bots */ + +// A careful bot: it keeps to the channel it is in over the next stretch of +// river (its whole hull, the stern too), heads for the middle of the water +// ahead, chases a buoy it can reach when the battery is under 90 and holds +// its fire off it, dodges what it can, slows for a dam still standing and +// fires the rest of the time. +function carefulBot(round) { + const { ship, river } = round; + const inp = round.input; + const look = 6 + ship.v * 0.45; + let lo = -Infinity; + let hi = Infinity; + let cx = ship.x; + for (let a = -3; a <= look; a += 1.5) { + const ch = channelAt(river, cx, ship.d + a); + lo = Math.max(lo, ch.lo); + hi = Math.min(hi, ch.hi); + if (hi - lo < 6) { + lo = ch.lo; + hi = ch.hi; + cx = (lo + hi) / 2; + } + } + const far = channelAt(river, cx, ship.d + look); + let tx = (far.lo + far.hi) / 2; + const want = round.battery < 90; + if (want) { + const reach = (b) => { + const ch = channelAt(river, ship.x, b.d); + return b.x > ch.lo + 1 && b.x < ch.hi - 1; + }; + const b = round.buoys.filter((o) => o.d > ship.d + 1 && o.d < ship.d + 60 && reach(o)).sort((a, c) => a.d - c.d)[0]; + if (b) tx = b.x; + } + for (const f of round.foes) { + const ahead = f.d - ship.d; + if (f.kind === "whirl" || f.kind === "sentry") continue; + if (ahead > -2 && ahead < 16 && Math.abs(f.x - ship.x) < f.r + 2.4) tx = f.x > (lo + hi) / 2 ? lo + 2.6 : hi - 2.6; + } + inp.fire = !(want && round.buoys.some((b) => b.d > ship.d && b.d < ship.d + 75 && Math.abs(b.x - ship.x) < 3.5)); + if (hi - lo > 5.4) tx = Math.min(hi - 2.7, Math.max(lo + 2.7, tx)); + inp.left = tx < ship.x - 0.3; + inp.right = tx > ship.x + 0.3; + inp.down = round.dam.hp > 0 && round.dam.d - ship.d < 75; + inp.up = false; +} + +/* ------------------------------------------------------------ contract */ + +test("Rapids Run answers the game contract: start, pause, resume, keys, releases, ticks, a too small board refused, a number score and a state", () => { + assert.equal(game.id, "rapids"); + assert.equal(game.title, "Rapids Run"); + assert.equal(typeof game.create, "function"); + assert.ok(Object.isFrozen(game)); + assert.ok(!("lowerIsBetter" in game), "the highest score is the best"); + const { canvas, calls } = stubCanvas(); + const g = game.create({ canvas, tone: () => {}, onScore: () => {} }); + assert.equal(g.state, "ready"); + assert.equal(g.score, 0); + g.pause(); + assert.equal(g.state, "ready", "pause before start does nothing"); + g.resume(); + assert.equal(g.state, "ready", "resume before start does nothing"); + g.tick(10_000); + assert.equal(g.state, "ready", "a tick before start does nothing"); + assert.equal(g.resize(1, 1), false, "a tiny board is refused"); + assert.equal(g.resize(W * MIN_CELL - 1, 4000), false, "too narrow to play"); + assert.equal(g.resize(4000, H * MIN_CELL - 1), false, "too short to play"); + assert.equal(g.resize(W * MIN_CELL, H * MIN_CELL), true, "just big enough"); + assert.equal(g.resize(2000, 2000), true); + g.start(); + assert.equal(g.state, "running"); + g.key("left"); + g.key("action"); + g.pause(); + assert.equal(g.state, "paused"); + assert.deepEqual(Object.values(g.round.input), [false, false, false, false, false], "a pause lets go of every held key"); + const before = { score: g.score, calls: calls.count, clock: g.round.clock }; + g.tick(10_000); + assert.deepEqual({ score: g.score, calls: calls.count, clock: g.round.clock }, before, "ticks while paused change nothing"); + g.resume(); + assert.equal(g.state, "running"); + for (const name of ["up", "down", "left", "right"]) assert.equal(g.key(name), true, `${name} is used`); + assert.equal(g.key("action"), true); + assert.equal(g.key("jump"), false, "an unknown key is not used"); + assert.equal(g.round.input.fire, true, "space held fires"); + g.release("action"); + g.release("left"); + assert.equal(g.round.input.fire, false, "let go, it stops firing"); + assert.equal(g.round.input.left, false); + const drawn = calls.count; + g.tick(200); + assert.ok(calls.count > drawn, "a tick while running draws"); + assert.equal(typeof g.score, "number"); +}); + +test("Rapids Run: space or Enter starts a round from the start or end screen without firing (Enter has no release), a press while running fires, and a press while paused leaves resuming to the window", () => { + const { canvas } = stubCanvas(); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + assert.equal(g.state, "running"); + assert.equal(g.round.input.fire, false, "the start does not fire"); + g.round.battery = 50; + g.round.buoys.push({ x: g.round.ship.x, d: g.round.ship.d + 40, n: 1, t: 0 }); + for (let k = 0; k < 30; k++) g.tick(16); + assert.equal(g.round.stats.popped, 0, "so no buoy ahead is shot"); + g.key("action"); + assert.equal(g.round.input.fire, true, "a press while running fires"); + g.release("action"); + g.pause(); + g.key("action"); + assert.equal(g.state, "paused", "only the window plays on"); + g.resume(); + g.round.lives = 1; + lose(g.round, "flat"); + for (let k = 0; k < 100 && g.state === "running"; k++) g.tick(16); + assert.equal(g.state, "over"); + g.key("action"); + assert.equal(g.state, "running", "a fresh round"); + assert.equal(g.round.input.fire, false, "again without firing"); +}); + +test("Rapids Run: the round's end calls onScore once with its score, shows it big, and space starts a fresh round", () => { + const texts = []; + let font = ""; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text), font]) : name in target ? target[name] : () => {}), + set: (target, name, value) => { if (name === "font") font = value; target[name] = value; return true; }, + }); + const scores = []; + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, onScore: (n) => scores.push(n) }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + clear(g.round); + g.round.lives = 1; + g.round.score = 1234; + g.round.ship.x = riverAt(g.round.river, g.round.ship.d).L + 0.2; + for (let ms = 0; ms < CRASH_MS + 200 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score], "onScore once, with the score"); + assert.ok(g.score >= 1234); + texts.length = 0; + g.resize(900, 900); + assert.ok(texts.some(([t, f]) => t === String(g.score) && /\b7px/.test(f)), "the score, big"); + assert.ok(texts.some(([t]) => t.startsWith("Reached Willow Run (dam 1)"))); + g.tick(1000); + assert.equal(scores.length, 1, "once"); + g.key("action"); + assert.equal(g.state, "running", "space starts again at once"); + assert.equal(g.score, 0); + assert.equal(g.round.lives, START_LIVES); +}); + +/* -------------------------------------------------------------- river */ + +test("Rapids Run: the same seed builds the same river and plan, a different seed another", () => { + const a = newRiver(42); + const b = newRiver(42); + const c = newRiver(43); + for (const r of [a, b, c]) ensureRiver(r, 3000); + assert.deepEqual(a.C.slice(0, 1200), b.C.slice(0, 1200)); + assert.deepEqual(a.plans[2], b.plans[2]); + assert.notDeepEqual(a.C.slice(0, 1200), c.C.slice(0, 1200)); +}); + +test("Rapids Run: over the first ten stretches on many rivers, every row keeps a channel at least MIN_CHANNEL wide, the banks on the field, no bank slanting past SLOPE, and a dam DAM_W wide at each stretch's end", () => { + for (let seed = 1; seed <= 25; seed++) { + const river = newRiver(seed * 977); + ensureRiver(river, 0); + while (river.built < 10) rapids.buildStretch(river, river.built + 1); + let prev = null; + for (let i = 0; i < river.rows; i++) { + const d = i * ROW; + const r = riverAt(river, d); + assert.ok(r.L >= EDGE - 1e-9 && r.R <= FIELD_W - EDGE + 1e-9, `seed ${seed} row ${i}: banks on the field (${r.L}, ${r.R})`); + for (const ch of channelsAt(river, d)) assert.ok(ch.hi - ch.lo >= MIN_CHANNEL - 1e-9, `seed ${seed} row ${i}: a channel ${ch.hi - ch.lo} wide`); + if (prev) { + for (const k of ["L", "R"]) assert.ok(Math.abs(r[k] - prev[k]) <= SLOPE * ROW + 1e-9, `seed ${seed} row ${i}: ${k} slants ${Math.abs(r[k] - prev[k])}`); + if (r.island && prev.island) for (const k of ["IL", "IR"]) assert.ok(Math.abs(r[k] - prev[k]) <= SLOPE * ROW + 1e-9, `seed ${seed} row ${i}: the island's ${k}`); + } + prev = r; + } + for (let n = 1; n <= 10; n++) { + const dam = riverAt(river, river.damAt[n]); + assert.ok(Math.abs(dam.w - DAM_W) < 1e-6 && !dam.island, `seed ${seed}: dam ${n} spans the river, ${DAM_W} wide`); + assert.ok(river.damAt[n] > river.startAt[n] + 400, `seed ${seed}: stretch ${n} has room`); + if (n > 1) assert.ok(river.startAt[n] > river.damAt[n - 1], "a stretch starts past the last dam"); + assert.equal(river.bossAt[n] > 0, n % BOSS_EVERY === 0, "a basin before every BOSS_EVERYth dam"); + } + } +}); + +test("Rapids Run: a stretch's plan puts foes, buoys and crates on open water (sentries on the bank), none where you start again and none just before the dam", () => { + for (let seed = 1; seed <= 15; seed++) { + const river = newRiver(seed * 31); + ensureRiver(river, 0); + while (river.built < 8) rapids.buildStretch(river, river.built + 1); + for (let n = 1; n <= 8; n++) { + const plan = river.plans[n]; + assert.ok(plan.some((p) => p.kind === "buoy"), "buoys"); + assert.ok(plan.some((p) => p.kind === "crate"), "a crate"); + for (const p of plan) { + assert.ok(p.d >= river.startAt[n] + 30, `seed ${seed} stretch ${n}: ${p.kind} clear of the restart`); + assert.ok(p.d <= river.damAt[n] - 20, `seed ${seed} stretch ${n}: ${p.kind} clear of the dam`); + if (p.kind === "gull") continue; + if (p.kind === "sentry") assert.ok(!isWater(river, p.x, p.d) && p.x > 0 && p.x < FIELD_W, `${p.kind} on the bank`); + else assert.ok(isWater(river, p.x, p.d), `seed ${seed} stretch ${n}: ${p.kind} at ${p.x} on the water`); + if (p.kind !== "buoy" && p.kind !== "crate") assert.ok(FOES[p.kind].from <= n, `${p.kind} not before stretch ${FOES[p.kind].from}`); + } + } + } +}); + +test("Rapids Run: stretches are named, the eight then Night Water again and again, quicker each time, a boss every BOSS_EVERY", () => { + assert.equal(STRETCHES.length, 8); + assert.equal(stretchFor(1).name, "Willow Run"); + assert.equal(stretchName(3), "Stone Gate (dam 3)"); + assert.equal(stretchFor(9).name, "Night Water"); + assert.equal(stretchFor(10).name, "Night Water 2"); + assert.ok(stretchFor(4).boss && stretchFor(8).boss && !stretchFor(5).boss); + for (let n = 1; n < 14; n++) assert.ok(stretchFor(n + 1).pace >= stretchFor(n).pace); + for (let n = 1; n <= 14; n++) assert.ok(LOOKS[stretchFor(n).look], `stretch ${n} has a look`); +}); + +/* -------------------------------------------------------------- moving */ + +test("Rapids Run: held arrows steer until let go, the skimmer stays on the field, and up, down or neither sets the speed", () => { + const round = quiet(); + const ship = round.ship; + const x = ship.x; + round.input.right = true; + run(round, 300); + assert.ok(ship.x > x + 4, "right steers right"); + round.input.right = false; + run(round, 400); + assert.ok(Math.abs(ship.vx) < 0.5, "let go, it stops sliding"); + const pace = stretchFor(1).pace; + round.input.up = true; + run(round, 1000); + assert.ok(Math.abs(ship.v - FAST * pace) < 1e-6, "up held: full speed"); + round.input.up = false; + round.input.down = true; + run(round, 1000); + assert.ok(Math.abs(ship.v - SLOW * pace) < 1e-6, "down held: slow"); + round.input.down = false; + run(round, 1000); + assert.ok(Math.abs(ship.v - CRUISE * pace) < 1e-6, "neither: cruising"); + assert.ok(Math.abs(round.cam - (ship.d - rapids.BEHIND)) < 1e-9, "the view follows"); +}); + +test("Rapids Run: the river runs DIST_POINTS a DIST_STEP, twice that at full speed", () => { + const slow = quiet(); + const fast = quiet(); + fast.input.up = true; + run(fast, 600); + const d0 = { slow: slow.ship.d, fast: fast.ship.d }; + const s0 = { slow: slow.score, fast: fast.score }; + run(slow, 1000); + run(fast, 1000); + const rate = (r, k) => (r.score - s0[k]) / ((r.ship.d - d0[k]) / DIST_STEP); + assert.ok(Math.abs(rate(slow, "slow") - 1) < 0.2, `cruising: about 1 a step (${rate(slow, "slow")})`); + assert.ok(Math.abs(rate(fast, "fast") - 2) < 0.3, `full speed: about 2 a step (${rate(fast, "fast")})`); +}); + +test("Rapids Run: held fire shoots every FIRE_MS, spread shot fans three, and a shot sinks a skiff", () => { + const round = quiet(); + round.input.fire = true; + advance(round, 1000); + const shots = eventsOf(round, "shoot").length; + assert.ok(Math.abs(shots - 1000 / FIRE_MS) <= 1, `${shots} shots a second`); + round.events.length = 0; + round.shots.length = 0; + applyPower(round, "spread"); + advance(round, FIRE_MS); + assert.equal(round.shots.length % 3, 0, "three at a time"); + assert.ok(round.shots.some((s) => s.vx < 0) && round.shots.some((s) => s.vx > 0), "fanned out"); + round.input.fire = false; + round.shots.length = 0; + const f = foe(round, "skiff", round.ship.x, round.ship.d + 20); + round.input.fire = true; + advance(round, 400); + assert.ok(!round.foes.includes(f), "sunk"); + assert.equal(eventsOf(round, "kill")[0].points, FOES.skiff.points); + assert.equal(round.stats.kills, 1); +}); + +/* ------------------------------------------------------------ battery */ + +test("Rapids Run: the battery drains DRAIN a second cruising, more at speed and less slowed; a buoy run over charges BUOY_CHARGE, never past full; a shot one is gone for BUOY_POINTS", () => { + const cruise = quiet(); + run(cruise, 1000); + assert.ok(Math.abs(BATTERY - cruise.battery - DRAIN) < 0.1, `cruising drains ${BATTERY - cruise.battery}`); + const fast = quiet(); + fast.input.up = true; + const slow = quiet(); + slow.input.down = true; + run(fast, 2000); + run(slow, 2000); + assert.ok(fast.battery < cruise.battery - DRAIN, "faster drains more"); + assert.ok(slow.battery > BATTERY - 2 * DRAIN, "slowed drains less"); + const round = quiet(); + round.battery = 30; + round.buoys.push({ x: round.ship.x, d: round.ship.d + 6, n: 1, t: 0 }); + run(round, 400); + assert.equal(round.buoys.length, 0); + assert.ok(round.battery > 30 + BUOY_CHARGE - 2, `charged to ${round.battery}`); + assert.equal(eventsOf(round, "charge").length, 1); + round.battery = BATTERY - 5; + round.buoys.push({ x: round.ship.x, d: round.ship.d + 6, n: 1, t: 0 }); + run(round, 400); + assert.ok(round.battery <= BATTERY, "never past full"); + const shoot = quiet(); + shoot.battery = 50; + shoot.buoys.push({ x: shoot.ship.x, d: shoot.ship.d + 40, n: 1, t: 0 }); + shoot.input.fire = true; + const score = shoot.score; + run(shoot, 500); + assert.equal(shoot.buoys.length, 0, "shot to pieces"); + assert.equal(eventsOf(shoot, "popbuoy")[0].points, BUOY_POINTS); + assert.equal(eventsOf(shoot, "charge").length, 0, "and no charge from it"); + assert.ok(shoot.score >= score + BUOY_POINTS); + assert.ok(shoot.battery < 50); +}); + +test("Rapids Run: a flat battery costs a life even with a shield, and the stretch starts again with a full one", () => { + const round = quiet(); + round.shield = 1; + round.battery = 0.5; + run(round, 400); + const lost = eventsOf(round, "lose"); + assert.equal(lost.length, 1); + assert.equal(lost[0].cause, "flat"); + assert.equal(round.lives, START_LIVES - 1); + assert.equal(round.shield, 1, "the shield cannot help"); + run(round, CRASH_MS + 50); + assert.equal(round.phase, "ready"); + assert.equal(round.battery, BATTERY); +}); + +/* ------------------------------------------------------------ crashes */ + +test("Rapids Run: a bank or an island under the hull costs a life, the wreck shows CRASH_MS, then the skimmer waits READY_MS at the stretch's start, blinking for GRACE_MS", () => { + const round = quiet(); + const ship = round.ship; + ship.x = riverAt(round.river, ship.d).R - 0.4; + advance(round, 16); + assert.equal(eventsOf(round, "lose")[0].cause, "bank"); + assert.equal(round.phase, "crash"); + assert.equal(ship.alive, false); + const d = ship.d; + advance(round, CRASH_MS - 100); + assert.equal(ship.d, d, "the wreck holds still"); + advance(round, 150); + assert.equal(round.phase, "ready"); + assert.equal(eventsOf(round, "respawn").length, 1); + assert.equal(ship.d, round.river.startAt[1] + RESPAWN_AT); + assert.ok(ship.invuln > GRACE_MS - 200); + const at = ship.d; + advance(round, READY_MS - 200); + assert.equal(ship.d, at, "waiting still"); + advance(round, 200); + assert.equal(round.phase, "run"); + assert.equal(eventsOf(round, "go").length, 1); + // An island. + const r2 = quiet(3); + let isle = -1; + for (let i = 0; i < r2.river.rows; i++) if (r2.river.IW[i] > 8) { isle = i; break; } + if (isle < 0) { + ensureRiver(r2.river, 4000); + for (let i = 0; i < r2.river.rows; i++) if (r2.river.IW[i] > 8) { isle = i; break; } + } + assert.ok(isle > 0, "an island somewhere"); + r2.ship.d = isle * ROW; + r2.ship.x = r2.river.C[isle]; + advance(r2, 16); + assert.equal(eventsOf(r2, "lose")[0]?.cause, "bank", "an island is land too"); +}); + +test("Rapids Run: running into a foe or a bolt costs a life; a shield takes one crash of any kind but a flat battery, and slides you off a bank", () => { + const round = quiet(); + foe(round, "mine", round.ship.x, round.ship.d + 3); + advance(round, 100); + assert.equal(eventsOf(round, "lose")[0].cause, "foe"); + const r2 = quiet(); + r2.bolts.push({ x: r2.ship.x, d: r2.ship.d + 3, vx: 0, vd: -20 }); + advance(r2, 200); + assert.equal(eventsOf(r2, "lose")[0].cause, "bolt"); + const r3 = quiet(); + applyPower(r3, "shield"); + applyPower(r3, "shield"); + applyPower(r3, "shield"); + assert.equal(r3.shield, MAX_SHIELDS); + const m = foe(r3, "skiff", r3.ship.x, r3.ship.d + 3); + advance(r3, 100); + assert.equal(eventsOf(r3, "lose").length, 0); + assert.equal(eventsOf(r3, "shield").length, 1); + assert.ok(!r3.foes.includes(m), "the skiff is rammed and sunk"); + assert.equal(r3.shield, MAX_SHIELDS - 1); + r3.ship.invuln = 0; + r3.ship.x = riverAt(r3.river, r3.ship.d).L + 0.3; + advance(r3, 16); + assert.equal(eventsOf(r3, "lose").length, 0, "the last shield takes the bank"); + assert.equal(r3.shield, 0); + assert.ok(!onLand(r3.river, r3.ship.x, r3.ship.d), "and slides you off it"); + assert.equal(r3.lives, START_LIVES); +}); + +test("Rapids Run: while blinking after a crash nothing hits you, and lose() never takes two lives at once", () => { + const round = quiet(); + round.ship.invuln = 500; + foe(round, "mine", round.ship.x, round.ship.d + 2); + advance(round, 100); + assert.equal(eventsOf(round, "lose").length, 0); + round.ship.invuln = 0; + assert.equal(lose(round, "foe"), true); + assert.equal(lose(round, "foe"), false); + assert.equal(round.lives, START_LIVES - 1); +}); + +test("Rapids Run: losing the last life ends the round once the wreck has shown", () => { + const round = quiet(); + round.lives = 1; + lose(round, "bank"); + assert.equal(round.over, false); + assert.equal(advance(round, CRASH_MS + 20), "over"); + assert.equal(eventsOf(round, "over").length, 1); +}); + +/* --------------------------------------------------------------- dams */ + +// Puts a quiet round just short of its dam, slowed and firing. +function atDam(round, gap = 60) { + const dam = round.dam; + round.ship.d = dam.d - gap; + round.ship.x = center(round); + round.cam = round.ship.d - rapids.BEHIND; + round.input.down = true; + round.input.fire = true; +} + +test("Rapids Run: a dam takes its stretch's damHp shots, scores DAM_POINTS times the stretch, and once past it the next stretch begins, with a bonus for no life lost", () => { + const round = quiet(); + atDam(round); + const hp = stretchFor(1).damHp; + assert.equal(round.dam.hp, hp); + run(round, 4000, () => clear(round)); + const hits = eventsOf(round, "damhit"); + assert.equal(hits.length, hp - 1); + const broke = eventsOf(round, "dambreak"); + assert.equal(broke.length, 1); + assert.equal(broke[0].points, DAM_POINTS * 1); + assert.equal(round.stats.dams, 1); + round.input.down = false; + run(round, 3000, () => clear(round)); + const next = eventsOf(round, "stretch"); + assert.equal(next.length, 1); + assert.equal(next[0].n, 2); + assert.equal(next[0].bonus, FLAWLESS_POINTS); + assert.equal(round.stretch, 2); + assert.equal(round.dam.hp, stretchFor(2).damHp); + assert.equal(round.dam.d, round.river.damAt[2]); +}); + +test("Rapids Run: a dam still standing is a crash, and after one in stretch 2 you start again just past dam 1 with dam 2 whole", () => { + const round = quiet(); + placeAt(round, 2); + clear(round); + round.ship.d = round.dam.d - SHIP_L; + round.ship.x = center(round, round.dam.d); + round.dam.hp = 3; + advance(round, 200); + assert.equal(eventsOf(round, "lose")[0].cause, "dam"); + advance(round, CRASH_MS + 50); + assert.equal(round.stretch, 2); + assert.equal(round.ship.d, round.river.startAt[2] + RESPAWN_AT); + assert.ok(round.ship.d > round.river.damAt[1]); + assert.equal(round.dam.hp, stretchFor(2).damHp, "the dam is whole again"); + assert.equal(round.stretchHit, true, "and the life stays lost until the next dam"); +}); + +test("Rapids Run: a stretch with a life lost earns no flawless bonus, even after the restart; a dam blasted then a crash before it stays open and is paid once", () => { + const round = quiet(); + round.ship.x = riverAt(round.river, round.ship.d).L + 0.2; + advance(round, 16); + assert.equal(eventsOf(round, "lose").length, 1); + advance(round, CRASH_MS + READY_MS + 100); + assert.equal(round.phase, "run"); + clear(round); + atDam(round); + run(round, 6000, () => clear(round)); + const next = eventsOf(round, "stretch"); + assert.equal(next.length, 1); + assert.equal(next[0].bonus, 0, "no flawless bonus"); + assert.equal(round.stretchHit, false, "the next stretch starts clean"); + const r2 = quiet(); + atDam(r2); + run(r2, 6000, (r) => { + clear(r); + if (r.dam.hp <= 0 && !eventsOf(r, "lose").length) lose(r, "foe"); + }); + assert.equal(eventsOf(r2, "dambreak").length, 1); + assert.equal(eventsOf(r2, "lose").length, 1); + const score = r2.score; + advance(r2, CRASH_MS + READY_MS + 100); + assert.equal(r2.dam.hp, 0, "the dam stays open after the restart"); + run(r2, 40_000, (r) => { + clear(r); + r.battery = BATTERY; + carefulBot(r); + if (eventsOf(r, "stretch").length) r.over = true; + }); + assert.equal(eventsOf(r2, "dambreak").length, 1, "and is paid for once"); + const passed = eventsOf(r2, "stretch"); + assert.equal(passed.length, 1); + assert.equal(passed[0].bonus, 0); + assert.ok(r2.score >= score, "nothing taken back"); +}); + +/* ------------------------------------------------------- combos, skims */ + +test("Rapids Run: kills within COMBO_MS step the combo up to MAX_COMBO, multiplying the points, and it lapses after", () => { + const round = quiet(); + const points = []; + for (let k = 0; k < MAX_COMBO + 2; k++) { + const f = foe(round, "skiff", 10, round.ship.d + 30); + rapids.hurtFoe(round, f); + points.push(round.events.at(-1).points); + advance(round, 100); + } + assert.deepEqual(points, [1, 2, 3, 4, 5, 5, 5].map((m) => m * FOES.skiff.points)); + assert.equal(round.bestCombo, MAX_COMBO); + advance(round, COMBO_MS + 50); + assert.equal(round.combo, 1); + const f = foe(round, "mine", 10, round.ship.d + 30); + assert.equal(rapids.hurtFoe(round, f), false, "a mine takes two"); + assert.equal(rapids.hurtFoe(round, f), true); + assert.equal(round.events.at(-1).points, FOES.mine.points); +}); + +test("Rapids Run: skimming a bank closer than SKIM_GAP at cruising speed scores SKIM_POINTS each SKIM_MS; slowed down it scores nothing", () => { + const skimming = quiet(); + const hug = (r) => { + const ch = channelAt(r.river, r.ship.x, r.ship.d); + const ch2 = channelAt(r.river, r.ship.x, r.ship.d + SHIP_L / 2); + r.ship.x = Math.max(ch.lo, ch2.lo) + SHIP_W / 2 + 0.5; + r.ship.vx = 0; + }; + run(skimming, 1000, hug); + const skims = eventsOf(skimming, "skim"); + assert.ok(Math.abs(skims.length - 1000 / SKIM_MS) <= 1, `${skims.length} skims a second`); + assert.equal(skims[0].points, SKIM_POINTS); + const slow = quiet(); + slow.input.down = true; + run(slow, 600); + slow.events.length = 0; + run(slow, 1000, hug); + assert.equal(eventsOf(slow, "skim").length, 0); +}); + +/* ------------------------------------------------------------ powers */ + +test("Rapids Run: power-ups: a crate run over is taken; spread and magnet run out; the magnet pulls buoys in; surge fills the battery", () => { + const round = quiet(); + round.crates.push({ x: round.ship.x, d: round.ship.d + 6, n: 1, kind: "magnet" }); + run(round, 400); + assert.equal(round.crates.length, 0); + assert.ok(rapids.active(round, "magnet")); + round.battery = 40; + const b = { x: round.ship.x + 12, d: round.ship.d + 14, n: 1, t: 0 }; + round.buoys.push(b); + run(round, 900); + assert.equal(round.buoys.length, 0, "pulled in and taken"); + assert.ok(round.battery > 60); + run(round, POWERS.magnet.ms); + assert.ok(!rapids.active(round, "magnet"), "it runs out"); + round.battery = 10; + applyPower(round, "surge"); + assert.equal(round.battery, BATTERY); + applyPower(round, "spread"); + assert.equal(round.effects.spread, POWERS.spread.ms); + assert.deepEqual(Object.keys(POWERS).sort(), ["magnet", "shield", "spread", "surge"]); +}); + +/* -------------------------------------------------------------- foes */ + +test("Rapids Run: a skiff drifts and turns at the banks, a darter swerves into your lane, a mine sits still, and a whirlpool tugs you toward its eye and lets shots through", () => { + const round = quiet(); + const ch = channelAt(round.river, round.ship.x, round.ship.d + 30); + const skiff = foe(round, "skiff", ch.hi - 2.5, round.ship.d + 40, { vx: 8 }); + round.ship.d += 0; + for (let k = 0; k < 40; k++) { + advance(round, 16); + round.ship.d = skiff.d - 40; + } + assert.ok(skiff.vx < 0, "turned at the bank"); + const r2 = quiet(); + r2.ship.x = center(r2) - 4; + const dart = foe(r2, "darter", r2.ship.x + 6, r2.ship.d + 30, { vx: 2 }); + advance(r2, 300); + assert.ok(Math.abs(dart.x - r2.ship.x) < 6 - 1, "swerved toward you"); + const r3 = quiet(); + const mine = foe(r3, "mine", 10, r3.ship.d + 40); + advance(r3, 300); + assert.equal(mine.x, 10); + const r4 = quiet(); + r4.ship.x = center(r4) - 3; + foe(r4, "whirl", center(r4), r4.ship.d + 1); + const x0 = r4.ship.x; + advance(r4, 100); + assert.ok(r4.ship.x > x0 + 0.3, "tugged toward the eye"); + r4.foes[0].d = r4.ship.d + 25; + r4.foes[0].x = r4.ship.x; + r4.input.fire = true; + advance(r4, 300); + assert.equal(r4.foes.length, 1, "a whirlpool cannot be shot"); + assert.equal(eventsOf(r4, "kill").length, 0); +}); + +test("Rapids Run: a gull drone takes off as you near and swoops across over land and all; a bank sentry fires at you while you are in its range", () => { + const round = quiet(); + const gull = foe(round, "gull", -3, round.ship.d + 80, { vx: 18 }); + advance(round, 16); + assert.equal(gull.on, false, "still waiting"); + round.ship.d = gull.d - 50; + advance(round, 16); + assert.equal(gull.on, true); + assert.equal(eventsOf(round, "gull").length, 1); + const x = gull.x; + const d = gull.d; + advance(round, 500); + assert.ok(gull.x > x + 8 && gull.d < d, "across and down at you"); + const r2 = quiet(); + const r = riverAt(r2.river, r2.ship.d + 40); + foe(r2, "sentry", r.L - 3, r2.ship.d + 40); + r2.input.down = true; + advance(r2, 1000); + assert.ok(eventsOf(r2, "bolt").length >= 1, "it fires"); + assert.ok(r2.bolts.length >= 1); +}); + +test("Rapids Run: foes turn up from their own stretch, and each stretch has more of them", () => { + for (const [kind, from] of [["skiff", 1], ["mine", 1], ["gull", 2], ["sentry", 3], ["whirl", 5], ["darter", 6]]) assert.equal(FOES[kind].from, from); + for (let n = 1; n < 10; n++) { + if (stretchFor(n).boss || stretchFor(n + 1).boss) continue; + assert.ok(stretchFor(n + 1).foes >= stretchFor(n).foes); + } + const river = newRiver(5); + ensureRiver(river, 0); + while (river.built < 7) rapids.buildStretch(river, river.built + 1); + const kinds = new Set(river.plans.slice(1, 8).flatMap((p) => p.map((e) => e.kind))); + for (const k of Object.keys(FOES)) assert.ok(kinds.has(k), `${k} turns up by stretch 7`); +}); + +/* -------------------------------------------------------------- boss */ + +test("Rapids Run: at every BOSS_EVERYth dam a mini-boss holds the basin: the river stops, the battery holds, it fires, and sinking it scores, gives a life and opens the way", () => { + const round = quiet(); + placeAt(round, BOSS_EVERY); + clear(round); + round.ship.d = round.river.bossAt[BOSS_EVERY] - 2; + round.ship.x = center(round); + advance(round, 200); + assert.equal(round.phase, "boss"); + assert.equal(eventsOf(round, "bossin").length, 1); + const boss = round.boss; + assert.equal(boss.kind, "dredger"); + const d = round.ship.d; + const battery = round.battery; + run(round, 3000, (r) => (r.ship.invuln = 1e9)); + assert.equal(round.ship.d, d, "the river holds still"); + assert.equal(round.battery, battery, "and the battery holds"); + assert.ok(eventsOf(round, "bolt").some((e) => e.boss), "it fires"); + round.lives = 2; + assert.equal(hurtBoss(round, boss.hp), true); + assert.equal(round.boss, null); + assert.equal(round.phase, "run"); + const down = eventsOf(round, "bossdown")[0]; + assert.equal(down.points, BOSS_POINTS); + assert.equal(round.lives, 3, "a life back"); + assert.equal(round.crates.length, 1, "and a crate"); + run(round, 2000); + assert.ok(round.ship.d > d + 20, "the river runs again"); + assert.equal(eventsOf(round, "bossin").length, 1, "and the boss never comes back"); + const r2 = quiet(); + placeAt(r2, BOSS_EVERY * 2); + clear(r2); + r2.ship.d = r2.river.bossAt[BOSS_EVERY * 2] - 1; + r2.ship.x = center(r2); + advance(r2, 100); + assert.equal(r2.boss.kind, "ironclad", "the next boss is another"); + r2.lives = MAX_LIVES; + run(r2, 1500, (r) => (r.ship.invuln = 1e9)); + hurtBoss(r2, r2.boss.hp); + assert.equal(r2.lives, MAX_LIVES, "never past MAX_LIVES"); + assert.equal(eventsOf(r2, "bossdown")[0].life, false); +}); + +test("Rapids Run: a life lost once the boss's basin is reached starts again at the basin's mouth, not the whole stretch, and the boss comes back", () => { + const round = quiet(); + placeAt(round, BOSS_EVERY); + clear(round); + const bossAt = round.river.bossAt[BOSS_EVERY]; + round.ship.d = bossAt - 1; + round.ship.x = center(round); + advance(round, 100); + assert.equal(round.phase, "boss"); + round.ship.invuln = 0; + lose(round, "bolt"); + advance(round, CRASH_MS + 50); + assert.equal(round.phase, "ready"); + assert.ok(round.ship.d < bossAt && round.ship.d > bossAt - 30, `at the basin's mouth (${round.ship.d}, the boss at ${bossAt})`); + assert.ok(!onLand(round.river, round.ship.x, round.ship.d)); + run(round, 3000, (r) => (r.ship.invuln = 1e9)); + assert.equal(round.phase, "boss", "the boss again"); + assert.ok(round.boss); +}); + +/* ------------------------------------------------------------- banners */ + +test("Rapids Run: the banner's strip counts a foe, a bolt, the boss or a standing dam under it, and not a gull still waiting or a dam already open", () => { + const round = quiet(); + const dAt = (y) => round.cam + FIELD_H - y; + assert.equal(underBanner(round), false, "nothing there"); + const f = foe(round, "skiff", 20, dAt(BANNER_Y)); + assert.equal(underBanner(round), true, "a skiff in the strip"); + f.d = dAt(BANNER_Y + 20); + assert.equal(underBanner(round), false, "well below it"); + const g = foe(round, "gull", -3, dAt(BANNER_Y)); + assert.equal(underBanner(round), false, "a gull not yet flying"); + g.on = true; + assert.equal(underBanner(round), true, "a gull swooping"); + round.foes.length = 0; + round.bolts.push({ x: 10, d: dAt(BANNER_Y + 2), vx: 0, vd: -10 }); + assert.equal(underBanner(round), true, "a bolt"); + round.bolts.length = 0; + round.dam.d = dAt(BANNER_Y); + assert.equal(underBanner(round), true, "a dam to shoot"); + round.dam.hp = 0; + assert.equal(underBanner(round), false, "an open dam"); + assert.ok(BANNER_Y < FIELD_H - rapids.BEHIND - 15, "the strip sits well above the skimmer"); + assert.equal(screenY(round, round.ship.d), FIELD_H - rapids.BEHIND); +}); + +test("Rapids Run game: the opening banner sits in the field from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.32)"); + const g = game.create({ canvas }); + g.resize(900, 900); + openingBanner(g, shades, FIELD_H); +}); + +test("Rapids Run game: a banner fades to see-through while something you must react to is in its strip, and back once it is gone", () => { + const alphas = []; + const ctx = new Proxy({ globalAlpha: 1 }, { + get: (t, name) => (name === "fillRect" ? () => t.fillStyle === "rgba(0, 0, 0, 0.32)" && alphas.push(t.globalAlpha) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + clear(g.round); + const mine = foe(g.round, "mine", 6, 0); + for (let k = 0; k < 40; k++) { + mine.d = g.round.cam + FIELD_H - BANNER_Y; + g.tick(16); + } + assert.ok(alphas.at(-1) <= 0.15, `see-through over the mine (${alphas.at(-1)})`); + clear(g.round); + for (let k = 0; k < 40; k++) g.tick(16); + assert.ok(alphas.at(-1) > 0.9, `back once it is gone (${alphas.at(-1)})`); +}); + +test("Rapids Run game: a banner that first shows during a boss fight sits lower, clear of the boss and still above the skimmer, and keeps the see-through rule", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.32)"); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + const round = g.round; + placeAt(round, BOSS_EVERY); + clear(round); + round.ship.d = round.river.bossAt[BOSS_EVERY] - 1; + round.ship.x = center(round); + // Past the opening banner, into the fight; the boss's own banner comes next. + for (let k = 0; k < 150; k++) { + round.ship.invuln = 1e9; + shades.length = 0; + g.tick(16); + } + assert.equal(round.phase, "boss"); + assert.equal(shades.length, 1, "a banner showing"); + const [[top, h]] = shades; + const mid = top + h / 2; + assert.ok(Math.abs(mid - rapids.BOSS_BANNER_Y) < 0.01, `placed low (${mid})`); + assert.ok(Math.abs(screenY(round, round.boss.d) - mid) > rapids.BANNER_HALF + 2, "clear of the boss"); + assert.ok(top + h < screenY(round, round.ship.d) - SHIP_L, "and above the skimmer"); + round.bolts.length = 0; + assert.equal(underBanner(round, mid), false, "nothing in its strip"); + round.bolts.push({ x: 20, d: round.cam + FIELD_H - mid, vx: 0, vd: -10 }); + assert.equal(underBanner(round, mid), true, "a bolt crossing it still counts"); +}); + +test("Rapids Run game: the start and end screens' lines all fit the field at full size, and the start screen's strip is clear of the skimmer", () => { + const lines = []; + const shades = []; + let font = ""; + const ctx = new Proxy({}, { + get: (t, name) => { + if (name === "fillText") return (text, x, y, max) => lines.push({ text: String(text), size: Number(/([\d.]+)px/.exec(font)?.[1]), max, y }); + if (name === "fillRect") return (x, y, w, h) => t.fillStyle === "rgba(0, 0, 0, 0.55)" && shades.push([y, h]); + return name in t ? t[name] : () => {}; + }, + set: (t, name, value) => { if (name === "font") font = value; t[name] = value; return true; }, + }); + const memo = { get: () => 19, set() {} }; + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo, best: () => 1 }); + g.resize(900, 900); + const fits = (what) => { + const tally = lines.filter((l) => l.max === FIELD_W - 4); + assert.ok(tally.length >= 3, `${what}: several lines (${tally.map((l) => l.text)})`); + for (const l of tally) assert.ok(l.text.length * l.size * 0.62 <= l.max, `${what}: "${l.text}" fits without a squeeze`); + }; + fits("start"); + const skimmer = FIELD_H - rapids.BEHIND - SHIP_L; + assert.ok(shades.length && shades.every(([y, h]) => y + h < skimmer), `the start strip is clear of the skimmer (${shades})`); + g.key("action"); + g.tick(16); + placeAt(g.round, 20); + g.round.score = 99999; + g.round.lives = 1; + lose(g.round, "flat"); + for (let k = 0; k < 100 && g.state === "running"; k++) g.tick(16); + assert.equal(g.state, "over"); + lines.length = 0; + g.resize(900, 900); + fits("end"); + assert.ok(lines.some((l) => l.text === "Reached Night Water 12 (dam 20)")); + assert.ok(lines.some((l) => l.text === "A new best!"), "the news on its own line"); +}); + +test("Rapids Run: the end screen's boss hint names the next boss's dam from the one still standing", () => { + const round = quiet(); + placeAt(round, 7); + assert.equal(rapids.teaser(round, 3), "A boss guards dam 8. One more go?"); + placeAt(round, 8); + assert.equal(rapids.teaser(round, 3), "A boss guards dam 8. One more go?", "dam 8 still standing"); + round.dam.hp = 0; + assert.equal(rapids.teaser(round, 3), "A boss guards dam 12. One more go?", "dam 8 open"); + assert.equal(rapids.teaser(round, 14), "Can you beat dam 15?"); + placeAt(round, 2); + assert.equal(rapids.teaser(round, 0), "A new foe waits at stretch 3..."); +}); + +/* --------------------------------------------------------------- pills */ + +test("Rapids Run: lives are drawn in the lives pill, solid, white, a heart per life, right after the stretch pill", () => { + for (const lives of [3, 1, 5]) { + const { canvas, pills, reset } = pillCanvas("#ffffff"); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + g.round.lives = lives; + reset(); + g.tick(16); + const all = pills(); + const at = all.findIndex((p) => p.text.startsWith("♥")); + assert.ok(at >= 0, `a lives pill (${all.map((p) => p.text)})`); + const p = all[at]; + assert.equal(p.text, livesText(lives)); + assert.equal(p.backing, LIVES_BACK); + assert.equal(p.ink, LIVES_INK); + assert.ok(all[at - 1].text.startsWith("STRETCH"), "after the stretch pill"); + } +}); + +test("Rapids Run: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives, a shield, spread, magnet and the combo included, in light and dark under every highlight", () => { + checkPills({ + setup: (r) => { + r.shield = 1; + r.effects.spread = POWERS.spread.ms / 2; + r.effects.magnet = POWERS.magnet.ms / 2; + r.combo = 3; + r.comboMs = COMBO_MS / 2; + }, + expect: ["STRETCH 1", "♥", "SHIELD", "~SPREAD", "~MAGNET", "~x3 COMBO"], + }); +}); + +test("Rapids Run: the pills never overlap, leave the board or spill out of their strip, even on the smallest board with every pill wanted; every word stays on the field; Planny's arms stand out on the skimmer in every highlight", () => { + const hud = { stretch: "STRETCH 12", color: "#57b54a", effects: [{ text: "SHIELD x2", color: "#1fb6d9", fill: 1 }, { text: "SPREAD", color: "#ff8a1f", fill: 0.5 }, { text: "MAGNET", color: "#a466ff", fill: 0.5 }], combo: 5, comboFill: 0.5 }; + for (const u of [MIN_CELL, 4, 6, 10]) { + const h = Math.max(12 / u, 2.4); + const placed = hudLayout(h, W, MAX_LIVES, hud, rapids.HUD_H); + assert.equal(placed.length, 6); + for (const p of placed) { + assert.ok(p.x >= 0 && p.x + p.w <= W, `u ${u}: ${p.text} on the board`); + assert.ok(p.y >= 0 && p.y + p.h <= rapids.HUD_H, `u ${u}: ${p.text} in the strip (${p.y})`); + } + for (let i = 0; i < placed.length; i++) { + for (let j = i + 1; j < placed.length; j++) { + const a = placed[i]; + const b = placed[j]; + const apart = a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y; + assert.ok(apart, `u ${u}: ${a.text} and ${b.text} apart`); + } + } + } + for (const [x, y] of [[0, 0], [FIELD_W, FIELD_H], [FIELD_W / 2, -5]]) { + const at = labelSpot("Into the dam!", x, y, 2.8, FIELD_W, FIELD_H); + assert.ok(at.x - at.max / 2 >= 0 && at.x + at.max / 2 <= FIELD_W && at.y > 0 && at.y < FIELD_H); + } + for (const theme of ["light", "dark"]) { + for (const [id, accent] of Object.entries(ACCENTS)) { + const fill = accent[theme][0]; + assert.ok(contrast(inkOn(fill), fill) >= 3, `${theme}/${id}: arms on ${fill}`); + } + } +}); + +/* ---------------------------------------------------- memo and tones */ + +test("Rapids Run game: the start screen names the furthest dam, and the memo only grows", () => { + const texts = []; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push(String(text)) : name in target ? target[name] : () => {}), + set: (target, name, value) => { target[name] = value; return true; }, + }); + let saved = 3; + const sets = []; + const memo = { get: () => saved, set: (n) => { sets.push(n); saved = n; } }; + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo }); + g.resize(900, 900); + assert.ok(texts.some((t) => t.includes("Furthest: Stone Gate (dam 3)")), "the start screen names it"); + assert.deepEqual(sets, [], "drawing writes nothing"); + g.key("action"); + g.tick(16); + const breakDam = () => { + clear(g.round); + const dam = g.round.dam; + dam.hp = 1; + g.round.ship.d = dam.d - 30; + g.round.ship.x = center(g.round); + g.round.shots.push({ x: center(g.round, dam.d), d: dam.d - 2, vx: 0, vd: 60 }); + g.tick(100); + }; + breakDam(); + assert.equal(g.round.stats.dams, 1); + assert.deepEqual(sets, [], "dam 1 is not further than dam 3"); + placeAt(g.round, 5); + breakDam(); + assert.deepEqual(sets, [5], "dam 5 is"); + placeAt(g.round, 2); + breakDam(); + assert.deepEqual(sets, [5], "and it never shrinks"); + const fresh = game.create({ canvas: stubCanvas().canvas }); + assert.equal(fresh.state, "ready", "no memo is fine"); +}); + +test("Rapids Run game: every event has its sound: a soft pew, a charge, a kill, the dam's thunk and its break, the low battery's beep and the skim's whoosh, and passing the best plays the fanfare once", () => { + const tones = []; + const { canvas } = stubCanvas(); + const g = game.create({ canvas, tone: (name, level = 1, pitch = 1) => tones.push({ name, level, pitch }), best: () => 50 }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + clear(g.round); + g.key("action"); + g.tick(200); + const pew = tones.find((t) => t.name === "pew"); + assert.ok(pew && pew.level <= 0.25, "a quiet pew for every shot"); + g.release("action"); + g.round.battery = 30; + g.round.buoys.push({ x: g.round.ship.x, d: g.round.ship.d + 4, n: 1, t: 0 }); + g.tick(300); + assert.ok(tones.some((t) => t.name === "charge")); + rapids.hurtFoe(g.round, foe(g.round, "skiff", 10, g.round.ship.d + 30)); + g.tick(16); + assert.ok(tones.some((t) => t.name === "eat")); + g.round.score = 60; + g.tick(16); + g.tick(16); + assert.equal(tones.filter((t) => t.name === "best").length, 1, "the fanfare, once"); + g.round.battery = LOW_BATTERY - 5; + for (let k = 0; k < 30; k++) g.tick(16); + assert.ok(tones.filter((t) => t.name === "lowcell").length >= 1, "the low battery beeps"); + tones.length = 0; + const dam = g.round.dam; + g.round.ship.d = dam.d - 40; + g.round.ship.x = center(g.round); + g.round.battery = BATTERY; + for (let k = 0; k < dam.max; k++) g.round.shots.push({ x: center(g.round, dam.d), d: dam.d - 2 - k * 0.01, vx: 0, vd: 60 }); + g.tick(50); + assert.ok(tones.some((t) => t.name === "thunk"), "each hit thunks"); + assert.ok(tones.some((t) => t.name === "dambreak"), "and it breaks"); + tones.length = 0; + const skim = g.round; + for (let k = 0; k < 40; k++) { + clear(skim); + const ch = channelAt(skim.river, skim.ship.x, skim.ship.d); + const ch2 = channelAt(skim.river, skim.ship.x, skim.ship.d + SHIP_L / 2); + skim.ship.x = Math.max(ch.lo, ch2.lo) + SHIP_W / 2 + 0.5; + g.tick(16); + } + assert.ok(tones.some((t) => t.name === "skim"), "a skim whooshes"); + for (const t of tones) assert.ok(t.level > 0 && t.level <= 1); +}); + +test("Rapids Run game: a crash plays the crash, shakes and floats its cause, and the respawn's banner says the lives left", () => { + const tones = []; + const texts = []; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push(String(text)) : name in target ? target[name] : () => {}), + set: (target, name, value) => { target[name] = value; return true; }, + }); + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, tone: (n) => tones.push(n) }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + clear(g.round); + g.round.ship.x = riverAt(g.round.river, g.round.ship.d).L + 0.2; + texts.length = 0; + g.tick(16); + assert.ok(tones.includes("crash")); + assert.ok(texts.includes("Ran aground!")); + for (let ms = 0; ms < CRASH_MS + 50; ms += 16) g.tick(16); + assert.ok(texts.includes("Ready?")); + assert.ok(texts.includes("2 lives left")); +}); + +test("Rapids Run game: the hums follow the action (the outboard pitched with the throttle, the river, a whirlpool, a boss's engines) and the big moments sound big", () => { + const tones = []; + const hums = []; + const g = game.create({ canvas: stubCanvas().canvas, tone: (name, level = 1, pitch = 1) => tones.push({ name, level, pitch }), hum: (id, name, level = 1, pitch = 1) => hums.push({ id, name, level, pitch }) }); + g.resize(900, 900); + g.key("action"); + assert.ok(tones.some((t) => t.name === "rapidsPullStart"), "the motor is pulled into life"); + const motor = () => hums.filter((h) => h.id === "rapids:motor").at(-1); + for (let k = 0; k < 10; k++) { + clear(g.round); + g.round.ship.x = center(g.round); + g.tick(16); + } + assert.equal(motor().name, "outboard"); + assert.ok(hums.some((h) => h.id === "rapids:river" && h.name === "river"), "the river runs under it"); + const cruising = motor().pitch; + g.key("up"); + assert.ok(tones.some((t) => t.name === "rapidsRevUp"), "the throttle revs"); + for (let k = 0; k < 60; k++) { + clear(g.round); + g.round.ship.x = center(g.round); + g.tick(16); + } + assert.ok(motor().pitch > cruising, `faster is higher (${motor().pitch} > ${cruising})`); + g.release("up"); + clear(g.round); + foe(g.round, "whirl", g.round.ship.x, g.round.ship.d + 12); + g.round.ship.invuln = 1e6; + g.tick(16); + assert.ok(hums.some((h) => h.name === "rapidsWhirl" && h.level > 0), "a whirlpool swirls nearby"); + clear(g.round); + g.round.effects.spread = 600; + for (let k = 0; k < 50; k++) g.tick(16); + assert.ok(tones.some((t) => t.name === "powerDown"), "a timed power-up winds down when it runs out"); + tones.length = 0; + placeAt(g.round, BOSS_EVERY); + clear(g.round); + g.round.ship.d = g.round.river.bossAt[BOSS_EVERY]; + g.round.ship.x = center(g.round); + g.tick(16); + assert.ok(tones.some((t) => t.name === "bossIntro"), "a boss steams in"); + for (let k = 0; k < 80; k++) { + g.round.ship.invuln = 1e6; + g.tick(16); + } + assert.ok(hums.some((h) => h.id === "rapids:boss" && h.name === "rapidsBossEngine"), "its engines churn"); + hurtBoss(g.round, Math.ceil(g.round.boss.max / 2)); + g.tick(16); + assert.ok(tones.some((t) => t.name === "rapidsBossRoar"), "it roars at its half"); + hurtBoss(g.round, g.round.boss.hp); + for (let k = 0; k < 40; k++) g.tick(16); + assert.ok(tones.some((t) => t.name === "explode"), "it goes up"); + assert.ok(tones.some((t) => t.name === "victory"), "and a victory plays after"); + tones.length = 0; + g.round.lives = 1; + g.round.battery = 0.001; + g.tick(16); + assert.ok(tones.some((t) => t.name === "rapidsSputter"), "a flat battery sputters out"); + for (let ms = 0; ms < CRASH_MS + 50 && g.state === "running"; ms += 16) g.tick(16); + assert.equal(g.state, "over"); + assert.ok(tones.some((t) => t.name === "gameOver"), "and the last life plays the game over"); + for (const t of tones) assert.ok(t.level > 0 && t.level <= 1); + for (const h of hums) assert.ok(h.level >= 0 && h.level <= 1 && h.pitch >= 0.25 && h.pitch <= 4, `${h.id} in range`); +}); + +test("Rapids Run game: plays without a hum (or a tone) handed in", () => { + const g = game.create({ canvas: stubCanvas().canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 20; k++) g.tick(16); + assert.equal(g.state, "running"); +}); + +/* ------------------------------------------------------------ drawing */ + +test("Rapids Run game: every stretch, the boss, a crash and the end draw with finite numbers only, and Planny's hull and star are in your highlight", () => { + const bad = []; + const fills = []; + const target = { globalAlpha: 1, fillStyle: "", getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }) }; + const ctx = new Proxy(target, { + get: (t, name) => { + if (name in t) return t[name]; + if (name === "fill") return () => fills.push(t.fillStyle); + return (...args) => { + for (const a of args) if (typeof a === "number" && !Number.isFinite(a)) bad.push(`${String(name)}(${args.join(", ")})`); + }; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + const saved = globalThis.getComputedStyle; + const values = { ...THEME_TOKENS.dark, "--accent": "#e75874" }; + globalThis.getComputedStyle = () => ({ getPropertyValue: (name) => values[name] || "" }); + try { + const g = game.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(16); + assert.ok(fills.filter((f) => f === "#e75874").length >= 2, "the hull and the star"); + for (let n = 1; n <= 10; n++) { + placeAt(g.round, n); + for (let k = 0; k < 20; k++) g.tick(50); + if (stretchFor(n).boss) { + g.round.ship.d = g.round.river.bossAt[n] - 1; + for (let k = 0; k < 40; k++) { + g.round.ship.invuln = 1e9; + g.tick(50); + } + assert.ok(g.round.boss, `stretch ${n}: a boss`); + hurtBoss(g.round, g.round.boss.hp); + g.tick(50); + } + } + g.round.lives = 1; + g.round.ship.invuln = 0; + g.round.shield = 0; + lose(g.round, "foe"); + for (let k = 0; k < 40 && g.state === "running"; k++) g.tick(50); + assert.equal(g.state, "over"); + g.resize(900, 900); + assert.deepEqual(bad, [], "no NaN or Infinity reaches the canvas"); + } finally { + if (saved === undefined) delete globalThis.getComputedStyle; + else globalThis.getComputedStyle = saved; + } +}); + +/* --------------------------------------------------------------- bots */ + +test("Rapids Run: a careful bot plays the first seven stretches of many rivers, with the foes cleared away, and never runs aground, never meets a dam standing and is never trapped, each stretch taking 15 to 60 seconds", () => { + for (let seed = 1; seed <= 6; seed++) { + const round = newRound(seed); + let t = 0; + let since = 0; + const lost = []; + while (!round.over && round.stretch <= 7 && t < 600_000) { + round.foes.length = 0; + round.bolts.length = 0; + if (round.boss) round.boss.hp = Math.min(round.boss.hp, 1); + // Never trapped: the water the hull sits in is always wide enough. + if (round.phase === "run") { + const ch = channelAt(round.river, round.ship.x, round.ship.d); + assert.ok(ch.hi - ch.lo >= MIN_CHANNEL - 1e-9, `seed ${seed}: room at ${round.ship.d}`); + } + carefulBot(round); + advance(round, 16); + t += 16; + since += 16; + for (const e of round.events.splice(0)) { + if (e.type === "lose") lost.push(`${e.cause}@${round.stretch}`); + if (e.type === "stretch") { + assert.ok(since >= 15_000 && since <= 60_000, `seed ${seed}: stretch ${e.n - 1} took ${since} ms`); + since = 0; + } + } + } + assert.ok(round.stretch > 7, `seed ${seed}: past dam 7 (at ${round.stretch}, lost ${lost})`); + assert.ok(!lost.some((l) => l.startsWith("bank") || l.startsWith("dam")), `seed ${seed}: never aground or into a dam (${lost})`); + } +}); + +test("Rapids Run: the careful bot, with the foes left in, still blasts its first dam on most rivers", () => { + let first = 0; + for (let seed = 1; seed <= 6; seed++) { + const round = newRound(seed); + for (let t = 0; t < 600_000 && !round.over; t += 16) { + carefulBot(round); + advance(round, 16); + } + if (round.stats.dams >= 1) first += 1; + } + assert.ok(first >= 4, `${first} of 6 past the first dam`); +}); + +test("Rapids Run: a sloppy bot (full speed, firing, steering at random) loses all three lives within 30 seconds, and one that never steers (so never grabs a buoy) within 100", () => { + for (let seed = 1; seed <= 8; seed++) { + const round = newRound(seed); + const random = rapids.seeded(seed); + let t = 0; + for (; t < 30_000 && !round.over; t += 16) { + round.input.up = true; + round.input.fire = true; + if (random() < 0.03) { + const k = random(); + round.input.left = k < 0.4; + round.input.right = k > 0.6; + } + advance(round, 16); + } + assert.ok(round.over, `seed ${seed}: over within 30 s`); + const still = newRound(seed); + still.input.fire = true; + let s = 0; + for (; s < 100_000 && !still.over; s += 16) advance(still, 16); + assert.ok(still.over, `seed ${seed}: never steering ends within 100 s`); + } +}); diff --git a/scripts/test-web-console-activities.mjs b/scripts/test-web-console-activities.mjs index 1261a91..b14a554 100644 --- a/scripts/test-web-console-activities.mjs +++ b/scripts/test-web-console-activities.mjs @@ -1,4 +1,4 @@ -// Web console tests, the activities: the shared game contract every listed game answers, Snake's rules, and mini golf's rules, course and controls. +// Web console tests, the activities: the shared game contract every listed game answers, Snake's rules, mini golf's rules, course and controls, Light Trails' rules and rivals, Bug Hunt's waves, bugs and bosses, Sunset Drive's road, traffic and forks, Stack Deploy's drops, perfects and twists, Bumper Ring's physics, rivals and arenas, the lives pill and tones of Rapids Run, Ghoul Rush and Bounce Road (their rules live in their own suites), Hot Potato's bomb, fuse, rivals and venues, and Crossing Rush's lanes, hops, shoves, planner and zones. // Run with: node --test scripts/test-web-console-activities.mjs // // No browser and no server: a game draws only through the canvas it is handed, @@ -10,12 +10,27 @@ import test from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { ACTIVITIES, bestKey, memoKey } from "../src/web-console/public/activities.js"; -import { BOSS_BITES, COMBO_MS, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js"; +import { ACTIVITIES, bestKey, bestKeys, memoKey, musicKey, musicLevel } from "../src/web-console/public/activities.js"; +import { BOSS_BITES, COMBO_MS, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, tallyBit, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js"; import golf, * as golfRules from "../src/web-console/public/activities/golf.js"; -import { COURSE_W, COURSE_H, HOLES } from "../src/web-console/public/activities/golf-holes.js"; -import { holeQuip, holeWord } from "../src/web-console/public/activities/golf-draw.js"; -import { DECOR_KINDS } from "../src/web-console/public/activities/golf-decor.js"; +import { COURSE_W, COURSE_H, COURSES, FRONT_NINE, HOLE_COUNT, courseById } from "../src/web-console/public/activities/golf-holes.js"; +import { holeQuip, holeWord, knownGround, knownLiquid } from "../src/web-console/public/activities/golf-draw.js"; +import { decorKinds } from "../src/web-console/public/activities/golf-decor.js"; +import * as trails from "../src/web-console/public/activities/trails.js"; +import * as bugs from "../src/web-console/public/activities/bugs.js"; +import * as drive from "../src/web-console/public/activities/drive.js"; +import * as stack from "../src/web-console/public/activities/stack.js"; +import * as bumper from "../src/web-console/public/activities/bumper.js"; +import { hudLayout } from "../src/web-console/public/activities/bumper-draw.js"; +import * as fuse from "../src/web-console/public/activities/fuse.js"; +import { hudLayout as fuseHudLayout, themeFor as fuseTheme, limbInk as fuseLimbInk, contrast as fuseContrast, countY as fuseCountY, CHAR as FUSE_CHAR, SAFE_RING as FUSE_SAFE_RING, SAFE_EDGE as FUSE_SAFE_EDGE } from "../src/web-console/public/activities/fuse-draw.js"; +import * as hop from "../src/web-console/public/activities/hop.js"; +import { hudLayout as hopHudLayout, labelSpot as hopLabelSpot, LANES as HOP_LANES, limbInk as hopLimbInk, contrast as hopContrast } from "../src/web-console/public/activities/hop-draw.js"; +import * as bounce from "../src/web-console/public/activities/bounce.js"; +import * as rapids from "../src/web-console/public/activities/rapids.js"; +import * as ghoul from "../src/web-console/public/activities/ghoul.js"; +import { ACCENTS } from "../src/web-console/public/palette.js"; +import { LIVES, LIVES_BACK, LIVES_INK, livesText, pillContrast } from "../src/web-console/public/activities/pills.js"; const PUBLIC_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "web-console", "public"); @@ -29,6 +44,134 @@ function stubCanvas() { return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls }; } +// A 2D context that records where each strip in a banner's shade is filled +// (its top and height), and does nothing else. +function bannerCanvas(shade) { + const shades = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillRect" ? (x, y, w, h) => t.fillStyle === shade && shades.push([y, h]) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, shades }; +} + +// The page's tokens in light and dark, for a game's readColors() through a +// stubbed getComputedStyle. +const THEME_TOKENS = Object.freeze({ + light: Object.freeze({ "--panel": "#ffffff", "--panel-2": "#fbf9f6", "--rule": "#e4ddd1", "--accent": "#206cc3", "--ink": "#1d1a17" }), + dark: Object.freeze({ "--panel": "#201d1a", "--panel-2": "#262220", "--rule": "#332e29", "--accent": "#619fe5", "--ink": "#f0ece5" }), +}); + +// "#rrggbb" or "rgb(a)(...)" as [r, g, b, a], and the WCAG contrast of two. +function rgbaOf(color) { + const hex = /^#([0-9a-f]{6})$/i.exec(color); + if (hex) return [0, 2, 4].map((k) => parseInt(hex[1].slice(k, k + 2), 16)).concat(1); + const [r, g, b, a = 1] = /rgba?\(([^)]*)\)/.exec(color)[1].split(",").map(Number); + return [r, g, b, a]; +} +const toHex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`; +const overColor = (top, alpha, base) => top.slice(0, 3).map((v, i) => v * alpha + base[i] * (1 - alpha)); +function wcag(a, b) { + const lum = (c) => { + const [r, g, bl] = rgbaOf(c).slice(0, 3).map((v) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4)); + return 0.2126 * r + 0.7152 * g + 0.0722 * bl; + }; + const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); + return (x + 0.05) / (y + 0.05); +} + +// A 2D context that keeps, for each pill it draws (a rounded fill, perhaps +// a timer's rounded tint, then the text with no dark edge), the text's +// color, the backing composited over `board` (a see-through backing shows +// the board through it) and each tint composited over that backing. +function pillCanvas(board) { + const drawn = []; + let since = []; + const target = { globalAlpha: 1, getTransform: () => ({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }), measureText: () => ({ width: 50 }) }; + const ctx = new Proxy(target, { + get: (t, name) => { + if (name in t) return t[name]; + if (name === "roundRect") return () => since.push({ k: "round" }); + if (name === "fill") return () => since.push({ k: "fill", style: t.fillStyle, alpha: t.globalAlpha }); + if (name === "fillText") return (text) => { drawn.push({ text: String(text), ink: t.fillStyle, since }); since = []; }; + if (name === "strokeText" || name === "fillRect" || name === "stroke") return () => since.push({ k: name }); + return () => {}; + }, + set: (t, name, value) => { t[name] = value; return true; }, + }); + const canvas = { width: 900, height: 900, getContext: () => ctx }; + ctx.canvas = canvas; + const pills = () => drawn.flatMap(({ text, ink, since: seq }) => { + if (seq.some((e) => e.k === "strokeText") || seq.at(-1)?.k !== "fill") return []; + const fills = seq.filter((e, i) => e.k === "fill" && seq[i - 1]?.k === "round"); + const back = fills.find((e) => e.alpha === 1); + if (!back) return []; + const b = rgbaOf(back.style); + const backing = toHex(overColor(b, b[3], rgbaOf(board))); + const tints = fills.slice(fills.indexOf(back) + 1).map((e) => { + const c = rgbaOf(e.style); + return toHex(overColor(c, e.alpha * c[3], rgbaOf(backing))); + }); + return [{ text, ink, backing, tints }]; + }); + return { canvas, pills, reset: () => { drawn.length = 0; since = []; } }; +} + +// Plays a game a few frames in light and dark under every highlight, runs +// `setup(round)` (when the game shows its round) to bring up its warnings +// and timers, draws one more frame and checks every pill's text reads at +// 4.5:1 on its backing and on each tint, and that each of `expect` showed +// (a "~" before one: drawn with a timer's tint). +function checkPills(game, { setup = () => {}, expect = [], board = "--panel" } = {}) { + const saved = globalThis.getComputedStyle; + try { + for (const [theme, tokens] of Object.entries(THEME_TOKENS)) { + for (const [id, accent] of Object.entries(ACCENTS)) { + const values = { ...tokens, "--accent": accent[theme][0] }; + globalThis.getComputedStyle = () => ({ getPropertyValue: (name) => values[name] || "" }); + const { canvas, pills, reset } = pillCanvas(values[board]); + const g = game.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + if (g.round) setup(g.round); + reset(); + g.tick(16); + const seen = pills(); + assert.ok(seen.length > 0, `${theme}/${id}: pills drawn`); + for (const p of seen) { + for (const under of [p.backing, ...p.tints]) { + const k = wcag(p.ink, under); + assert.ok(k >= 4.5, `${theme}/${id}: "${p.text}" in ${p.ink} on ${under} reads ${k.toFixed(2)}:1`); + } + } + for (const want of expect) { + const tinted = want.startsWith("~"); + const text = tinted ? want.slice(1) : want; + assert.ok(seen.some((p) => p.text.includes(text) && (!tinted || p.tints.length)), `${theme}/${id}: "${text}" drawn${tinted ? " with its tint" : ""} (${seen.map((p) => p.text)})`); + } + } + } + } finally { + if (saved === undefined) delete globalThis.getComputedStyle; + else globalThis.getComputedStyle = saved; + } +} + +// Starts a game the way the window's key does and checks its opening banner: +// painted on the start's own frame, inside the field (0 to `field`), and in +// the same place on the first tick. +function openingBanner(g, shades, field) { + shades.length = 0; + g.key("action"); + assert.equal(shades.length, 1, "the start paints its banner"); + const [[top, h]] = shades; + assert.ok(top >= 0 && top + h <= field, `inside the field, not at its top edge (${top})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [[top, h]], "in the same place once play begins"); +} + // The smallest game that answers the contract: a counter that moves every // 100 ms. If it passes, the contract test is about the contract, not Snake. const STUB_GAME = Object.freeze({ @@ -119,13 +262,24 @@ const listedGames = async () => { /* --------------------------------------------------------------- list */ -test("the list names Snake and Mini golf, and each entry's module is a file under public/activities/", () => { - assert.deepEqual(ACTIVITIES.map((a) => a.id), ["snake", "golf"]); +test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, and each entry's module is a file under public/activities/", () => { + assert.deepEqual(ACTIVITIES.map((a) => a.id), ["snake", "golf", "trails", "bugs", "drive", "stack", "bumper", "rapids", "fuse", "hop", "bounce", "ghoul"]); assert.equal(ACTIVITIES[1].title, "Mini golf"); + assert.equal(ACTIVITIES[2].title, "Light Trails"); + assert.equal(ACTIVITIES[3].title, "Bug Hunt"); + assert.equal(ACTIVITIES[4].title, "Sunset Drive"); + assert.equal(ACTIVITIES[5].title, "Stack Deploy"); + assert.equal(ACTIVITIES[6].title, "Bumper Ring"); + assert.equal(ACTIVITIES[7].title, "Rapids Run"); + assert.equal(ACTIVITIES[8].title, "Hot Potato"); + assert.equal(ACTIVITIES[9].title, "Crossing Rush"); + assert.equal(ACTIVITIES[10].title, "Bounce Road"); + assert.equal(ACTIVITIES[11].title, "Ghoul Rush"); for (const a of ACTIVITIES) { assert.ok(Object.isFrozen(a), `${a.id} is frozen`); assert.equal(a.module, `/activities/${a.id}.js`); assert.equal(typeof a.title, "string"); + assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`); } assert.equal(new Set(ACTIVITIES.map((a) => a.id)).size, ACTIVITIES.length, "ids are unique"); }); @@ -135,6 +289,14 @@ test("bestKey builds a flat looks.json key from a list id", () => { assert.equal(bestKey("golf"), "activityBestGolf"); assert.equal(bestKey("stub"), "activityBestStub"); assert.equal(bestKey("stubpointer"), "activityBestStubpointer"); + // A game with courses keeps a best per course. + assert.equal(bestKey("golf", "pirate"), "activityBestGolfPirate"); + const golfEntry = ACTIVITIES.find((a) => a.id === "golf"); + assert.deepEqual(golfEntry.courses, ["pirate", "cave", "dino", "candy", "space", "frost"]); + assert.deepEqual(bestKeys(golfEntry), ["activityBestGolfPirate", "activityBestGolfCave", "activityBestGolfDino", "activityBestGolfCandy", "activityBestGolfSpace", "activityBestGolfFrost"]); + assert.deepEqual(bestKeys(ACTIVITIES[0]), ["activityBestSnake"]); + // The course list here and the game's own list agree. + assert.deepEqual(golfEntry.courses, COURSES.map((c) => c.id)); }); test("memoKey builds a flat looks.json key from a list id", () => { @@ -144,6 +306,17 @@ test("memoKey builds a flat looks.json key from a list id", () => { /* ----------------------------------------------------------- contract */ +test("musicKey builds a flat looks.json key, and a game with music has a default volume a saved one replaces", () => { + assert.equal(musicKey("ghoul"), "activityMusicGhoul"); + assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["drive", 70], ["ghoul", 65]], "the games with music, at about the level they were picked at on the prototype pages"); + const ghoulEntry = ACTIVITIES.find((a) => a.id === "ghoul"); + assert.equal(musicLevel(ghoulEntry, undefined), 0.65, "nothing saved: the default"); + assert.equal(musicLevel(ghoulEntry, "loud"), 0.65, "not a number: the default"); + assert.equal(musicLevel(ghoulEntry, 0), 0, "turned all the way down"); + assert.equal(musicLevel(ghoulEntry, 140), 1, "never past full"); + assert.equal(musicLevel(ACTIVITIES[0], 80), 0, "a game with no music has none"); +}); + test("every listed game, and a stub second game, answers the game contract", async () => { const games = [ ...(await listedGames()), @@ -210,6 +383,38 @@ test("every listed game, and a stub second game, answers the game contract", asy } }); +test("every listed game with lives answers the endless-lives code: cheat(true) keeps every life through two minutes of play left alone, its lives pill shows them as endless, and a new round starts without it", async () => { + let withLives = 0; + for (const { entry, game } of await listedGames()) { + const label = entry.id; + const { canvas } = stubCanvas(); + const g = game.create({ canvas, tone: () => {}, onScore: () => {} }); + g.resize(2000, 2000); + g.start(); + if (!g.round || typeof g.round.lives !== "number") { + assert.equal(g.cheat, undefined, `${label}: no lives, no cheat`); + continue; + } + withLives++; + assert.equal(typeof g.cheat, "function", `${label}: a game with lives answers cheat(on)`); + const lives = g.round.lives; + g.cheat(true); + assert.equal(g.round.infinite, true, `${label}: cheat(true) marks the round`); + for (let ms = 0; ms < 120_000; ms += 100) { + g.tick(100); + if (g.state !== "running") g.key("action"); + assert.ok(g.round.lives >= lives, `${label}: no life lost (${g.round.lives} of ${lives} at ${ms} ms)`); + } + g.cheat(false); + assert.equal(g.round.infinite, false, `${label}: cheat(false) lets go`); + g.cheat(true); + g.start(); + assert.ok(!g.round.infinite, `${label}: a new round starts without it`); + } + assert.ok(withLives >= 8, `${withLives} games with lives`); + assert.equal(livesText(Infinity), "♥ x∞", "the pill reads endless"); +}); + /* ---------------------------------------------------------- Snake rules */ test("Snake: the step is 120 ms at three cells, 4 ms quicker per cell beyond, never under 60", () => { @@ -380,6 +585,31 @@ test("Snake game: after eating, the snake moves on the shorter step", async () = } }); +test("Snake game: a banner queued by a step sits in the board on the frame that step paints, and does not jump on the next tick", async () => { + // Food at (11,10) right ahead; eating it passes a best of 0.5, so the step + // queues the New best! banner and the same tick paints it. + const game = (await import("../src/web-console/public/activities/snake.js")).default; + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.3)"); + const g = game.create({ canvas, best: () => 0.5 }); + g.resize(GRID * MIN_CELL, GRID * MIN_CELL); + const real = Math.random; + Math.random = () => 208.5 / (GRID * GRID - 3); + try { + g.start(); + } finally { + Math.random = real; + } + shades.length = 0; + g.tick(stepMs(3)); + assert.equal(g.score, 1, "the food was eaten"); + assert.equal(shades.length, 1, "the tick that eats paints the banner"); + const [[top, h]] = shades; + assert.ok(top >= 0 && top + h <= GRID * MIN_CELL, `inside the board, not at its top edge (${top})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [[top, h]], "in the same place on the next tick"); +}); + /* --------------------------------------------- Snake's power-ups and more */ // A round with the snake at (5,5) heading right, food far off at (0,19). @@ -420,7 +650,7 @@ test("Snake: each level serves its own fruit, the last one staying past the list assert.equal(eats[FOOD_PER_LEVEL], fruitFor(2)); }); -test("Snake: every FOOD_PER_LEVEL foods is a level, and level 2 drops warned rocks clear of the head", () => { +test("Snake: every FOOD_PER_LEVEL foods is a level, opening in Slow-mo, and level 2 drops warned rocks clear of the head", () => { const round = plainRound(); for (let i = 0; i < FOOD_PER_LEVEL; i++) { round.food = { x: round.snake[0].x + 1, y: 5 }; @@ -435,6 +665,8 @@ test("Snake: every FOOD_PER_LEVEL foods is a level, and level 2 drops warned roc assert.ok(Math.abs(r.x - head.x) + Math.abs(r.y - head.y) >= 3, "never next to the head"); assert.ok(!(r.y === head.y && r.x > head.x && r.x <= head.x + 5), "never right ahead"); } + assert.equal(round.effects.slow, POWERS.slow.ms, "a new level opens in Slow-mo"); + delete round.effects.slow; assert.ok(pace(round) < stepMs(round.snake.length), "a higher level steps quicker"); }); @@ -476,19 +708,32 @@ test("Snake: Ghost and a shield wrap the snake through a wall; without either th assert.equal(step(shield), "crash"); }); -test("Snake: Turbo doubles points and quickens the step, Slow-mo slows it, and each cancels the other", () => { +test("Snake: Slow-mo slows the step, then eases back to the usual pace as it runs out", () => { const round = plainRound(); const base = pace(round); - applyPower(round, "turbo"); - assert.ok(pace(round) < base); - round.food = { x: 6, y: 5 }; - step(round, () => 0.99); - assert.equal(round.score, 2, "turbo doubles a food's point"); applyPower(round, "slow"); - assert.equal(round.effects.turbo, undefined, "slow-mo ends turbo"); - assert.ok(pace(round) > stepMs(round.snake.length)); - age(round, POWERS.slow.ms, () => 0.99); + const slowest = pace(round); + assert.ok(slowest > base); + const paces = []; + for (let left = POWERS.slow.ms; left > 0; left -= 250) { + round.effects.slow = left; + paces.push(pace(round)); + } + assert.ok(paces.every((p, i) => i === 0 || p <= paces[i - 1]), "the step never slows again on the way out"); + round.effects.slow = 100; + assert.ok(pace(round) < slowest && pace(round) - base <= 4, "near its end Slow-mo is all but gone"); + age(round, 100, () => 0.99); assert.equal(round.effects.slow, undefined, "a timed power-up runs out"); + assert.equal(pace(round), base); +}); + +test("Snake: Turbo and Mirror world are gone, and the keys always mean what they say", () => { + assert.equal(POWERS.turbo, undefined); + assert.equal(SURPRISES.mirror, undefined); + const round = plainRound(); + assert.equal(turn(round, "down"), true); + step(round); + assert.deepEqual(round.snake[0], { x: 5, y: 6 }); }); test("Snake: Scissors halve the snake and pay a point per cell cut", () => { @@ -507,14 +752,6 @@ test("Snake: a portal sends the head out of its pair, keeping the direction", () assert.ok(round.events.some((e) => e.type === "portal")); }); -test("Snake: Mirror world flips the keys", () => { - const round = plainRound(); - applySurprise(round, "mirror"); - assert.equal(turn(round, "down"), true); - step(round); - assert.deepEqual(round.snake[0], { x: 5, y: 4 }, "down went up"); -}); - test("Snake: a comet through the body cuts the tail there; into the head it is a crash", () => { const round = plainRound(); round.snake = Array.from({ length: 8 }, (_, i) => ({ x: 10 - i, y: 5 })); @@ -561,10 +798,13 @@ test("Snake: DISCOVERIES lists every power-up, surprise, new level and special o for (const k of Object.keys(SPECIALS)) assert.ok(DISCOVERIES.includes(`special:${k}`), `${k} is listed`); assert.equal(new Set(DISCOVERIES).size, DISCOVERIES.length); assert.ok(DISCOVERIES.length <= 30); - // A saved tally's bits never move: the first 21 are where they always were. - assert.equal(DISCOVERIES[0], "power:shield"); - assert.equal(DISCOVERIES[16], "level:2"); - assert.equal(DISCOVERIES[20], "level:6"); + // A saved tally's bits never move, even past a find taken out of the game. + assert.equal(tallyBit("power:shield"), 1 << 0); + assert.equal(tallyBit("power:slow"), 1 << 2); + assert.equal(tallyBit("surprise:lightsOut"), 1 << 11); + assert.equal(tallyBit("level:2"), 1 << 16); + assert.equal(tallyBit("level:6"), 1 << 20); + assert.equal(tallyBit("special:boss"), 1 << 23); }); test("Snake: on the ice level a turn slides on for ICE_STEPS steps before it takes, and takes at once elsewhere", () => { @@ -649,6 +889,11 @@ test("Snake: a runaway fruit hops away from a close head, is caught by running i assert.ok(left.events.some((e) => e.type === "escape")); }); +test("Snake: the level pill's text reads at 4.5:1 on its backing in light and dark under every highlight", async () => { + const { default: snakeActivity } = await import(pathToFileURL(path.join(PUBLIC_DIR, "activities", "snake.js")).href); + checkPills(snakeActivity, { expect: ["LV 1"] }); +}); + test("Snake game: a power-up grabbed is saved in the memo, food is not, and passing a saved best plays the fanfare once", async () => { const game = (await import("../src/web-console/public/activities/snake.js")).default; const { canvas } = stubCanvas(); @@ -685,7 +930,17 @@ test("Snake game: a power-up grabbed is saved in the memo, food is not, and pass /* ------------------------------------------------------ Mini golf rules */ -const { advance, strike, nextHole, SUB_STEP_MS, BALL_R, CUP_R, MAX_STROKES, MAX_SPEED, CANNON_MAX, CARD_MS, POWERUPS, FRONT_NINE } = golfRules; +const { advance, strike, nextHole, SUB_STEP_MS, BALL_R, CUP_R, MAX_STROKES, MAX_SPEED, CANNON_MAX, CARD_MS, POWERUPS } = golfRules; + +// The rules tests below were written against the first mini golf round: +// Pirate Cove's first eight holes and its finale, then the Caves of Doom's +// first eight and their finale. HOLES is that round, and `golfAt(n)` puts a +// round of the right course on its hole n (1 to 18), so the tests keep +// meaning the same holes as the courses grow around them. +const PIRATE = courseById("pirate").holes; +const CAVE = courseById("cave").holes; +const OLD = [...PIRATE.slice(0, 8).map((_, i) => ["pirate", i]), ["pirate", PIRATE.length - 1], ...CAVE.slice(0, 8).map((_, i) => ["cave", i]), ["cave", CAVE.length - 1]]; +const HOLES = OLD.map(([id, i]) => courseById(id).holes[i]); // Plays physics steps until the ball rests (or the hole ends), collecting // every event. Capped, so a ball that never stops fails rather than hangs. @@ -696,11 +951,14 @@ function roll(round, maxMs = 30_000) { return events; } -// A new round moved on to hole `n` (1 to 18) with the ball on its tee. -function golfAt(n) { - const round = golfRules.newRound(); - while (round.hole < n - 1) { - round.card.push(HOLES[round.hole].par); +// A new round moved on to HOLES[n - 1] (n is 1 to 18) with the ball on its +// tee; or, given a course id, that course's own hole n. +function golfAt(n, courseId) { + const [id, index] = courseId ? [courseId, n - 1] : OLD[n - 1]; + const round = golfRules.newRound(id); + const holes = courseById(id).holes; + while (round.hole < index) { + round.card.push(holes[round.hole].par); round.phase = "card"; nextHole(round); } @@ -898,16 +1156,22 @@ test("Mini golf words: a hole's strokes against its par", () => { assert.equal(holeWord(5, 3, false), "Double bogey"); assert.equal(holeWord(8, 3, false), "5 over par"); assert.equal(holeWord(8, 3, true), "Picked up"); - for (const theme of ["pirate", "cave"]) { - const lines = [[1, 3, false], [2, 5, false], [2, 3, false], [3, 3, false], [4, 3, false], [8, 3, false], [8, 3, true]].map(([n, par, up]) => holeQuip(n, par, up, theme)); - assert.ok(lines.every((l) => typeof l === "string" && l.length > 0), `${theme}: a quip for every result`); + for (const c of COURSES) { + const lines = [[1, 3, false], [2, 5, false], [2, 3, false], [3, 3, false], [4, 3, false], [8, 3, false], [8, 3, true]].map(([n, par, up]) => holeQuip(n, par, up, c.voice)); + assert.ok(lines.every((l) => typeof l === "string" && l.length > 0), `${c.id}: a quip for every result`); + assert.equal(new Set(lines.slice(1)).size, 6, `${c.id}: a different quip for each result`); + const v = c.voice; + for (const key of ["label", "ace", "turn", "done"]) assert.ok(typeof v[key] === "string" && v[key].length > 0, `${c.id}: its voice has a ${key}`); + assert.ok(Array.isArray(v.bump) && v.bump.length >= 3, `${c.id}: bump words`); + for (const h of c.holes) if (h.water.length) assert.ok(Array.isArray(v.splash[h.liquid]) && v.splash[h.liquid].length, `${c.id}: splash words for ${h.liquid}`); } - assert.notEqual(holeQuip(3, 3, false, "pirate"), holeQuip(3, 3, false, "cave"), "the caves have their own voice"); + const pars = COURSES.map((c) => holeQuip(3, 3, false, c.voice)); + assert.equal(new Set(pars).size, COURSES.length, "every course has its own voice"); }); // Drops the ball just short of the cup, aimed at it, so a soft putt sinks it. function lineUp(g) { - const cup = HOLES[g.round.hole].cup; + const cup = golfRules.holesOf(g.round)[g.round.hole].cup; Object.assign(g.round.ball, { x: cup.x - 10, y: cup.y }); g.round.aimAngle = 0; } @@ -943,20 +1207,65 @@ test("Mini golf: a full round of eighteen calls onScore once with the total; a h assert.equal(g.score, 0); tones.length = 0; - for (let h = 0; h < HOLES.length; h++) { - lineUp(g); - assert.equal(softPutt(g), true); - assert.equal(g.score, h + 1, "a stroke counts as it is taken"); - g.tick(3000); - if (h < HOLES.length - 1) assert.equal(g.key("action"), true, "space skips the scorecard"); + // Every course, the same way: an ace on each of its eighteen holes. + for (const c of COURSES) { + assert.equal(g.setCourse(c.id), true); + assert.equal(g.course, c.id); + if (g.state === "ready") g.key("action"); + assert.equal(g.state, "running", `${c.id}: the round is under way`); + scores.length = 0; + tones.length = 0; + for (let h = 0; h < HOLE_COUNT; h++) { + lineUp(g); + assert.equal(softPutt(g), true); + assert.equal(g.score, h + 1, `${c.id} hole ${h + 1}: a stroke counts as it is taken`); + g.tick(3000); + if (h < HOLE_COUNT - 1) assert.equal(g.key("action"), true, `${c.id} hole ${h + 1}: sunk, and space skips the scorecard`); + } + assert.equal(g.state, "over", `${c.id}: the round is over`); + assert.deepEqual(scores, [HOLE_COUNT], `${c.id}: one score, the round's total`); + assert.equal(tones.filter((n) => n === "ace").length, HOLE_COUNT); + assert.ok(tones.includes("putt")); + g.tick(10_000); + assert.deepEqual(scores, [HOLE_COUNT], "nothing more once the round is over"); + assert.equal(golfRules.toPar(g.round), HOLE_COUNT - golfRules.coursePar(c)); + } +}); + +test("Mini golf: switching course drops the round, the same course keeps it, and the course list matches the courses", () => { + const { canvas } = stubCanvas(); + const g = golf.create({ canvas, course: "candy" }); + assert.equal(g.course, "candy", "create() takes the course to start on"); + g.resize(800, 600); + g.key("action"); + lineUp(g); + softPutt(g); + g.tick(3000); + g.key("action"); + g.pause(); + assert.equal(g.round.hole, 1); + g.setCourse("candy"); + assert.equal(g.state, "paused", "the same course keeps its paused round"); + assert.equal(g.round.hole, 1); + g.setCourse("space"); + assert.equal(g.state, "ready", "another course starts fresh"); + assert.equal(g.round.hole, 0); + assert.equal(g.course, "space"); + g.setCourse("nowhere"); + assert.equal(g.course, COURSES[0].id, "an unknown course is the first"); + assert.deepEqual(golf.courses.map((c) => c.id), ["pirate", "cave", "dino", "candy", "space", "frost"]); + for (const c of golf.courses) { + assert.ok(Object.isFrozen(c)); + assert.equal(c.holes, HOLE_COUNT, `${c.id}: eighteen holes`); + assert.equal(c.par, golfRules.coursePar(courseById(c.id))); + assert.ok(typeof c.name === "string" && c.name.length > 3 && typeof c.blurb === "string" && c.blurb.length > 10, `${c.id}: a name and a card line`); + } + // The dashboard's art draws without a page. + for (const c of golf.courses) { + const art = stubCanvas(); + golf.preview(art.canvas, c.id, 160, 120); + assert.ok(art.calls.count > 0, `${c.id}: its card art draws`); } - assert.equal(g.state, "over"); - assert.deepEqual(scores, [HOLES.length], "one score, the round's total"); - assert.equal(tones.filter((n) => n === "ace").length, HOLES.length); - assert.ok(tones.includes("putt")); - g.tick(10_000); - assert.deepEqual(scores, [HOLES.length], "nothing more once the round is over"); - assert.equal(golfRules.toPar(g.round), HOLES.length - HOLES.reduce((n, h) => n + h.par, 0)); }); test("Mini golf: a huge tick never moves the ball through a wall", () => { @@ -1009,42 +1318,102 @@ function reachable(hole, from, to) { return false; } -test("Mini golf course: eighteen holes, each finishable, with every element used somewhere", () => { - assert.equal(HOLES.length, 18); - assert.ok(Object.isFrozen(HOLES) && Object.isFrozen(HOLES[0]) && Object.isFrozen(HOLES[0].walls[0]), "the course is frozen"); - assert.ok(HOLES.slice(0, FRONT_NINE).every((h) => h.theme === "pirate"), "the front nine is the pirate cove"); - assert.ok(HOLES.slice(FRONT_NINE).every((h) => h.theme === "cave"), "the back nine is the caves"); - for (const [i, hole] of HOLES.entries()) { - const label = `hole ${i + 1} (${hole.name})`; - assert.ok(typeof hole.name === "string" && hole.name.length > 0, `${label}: named`); - assert.ok(typeof hole.quip === "string" && hole.quip.length > 0, `${label}: has a quip`); - assert.ok(["grass", "deck", "moss", "stone"].includes(hole.ground), `${label}: a known ground`); - assert.ok(["sea", "pool", "lava", "chasm"].includes(hole.liquid), `${label}: a known liquid`); - assert.ok(Number.isInteger(hole.par) && hole.par >= 2 && hole.par <= 5, `${label}: par 2 to 5`); - for (const [what, p] of [["tee", hole.tee], ["cup", hole.cup]]) { - assert.ok(p.x > 0 && p.x < COURSE_W && p.y > 0 && p.y < COURSE_H, `${label}: ${what} on the course`); - assert.ok(golfRules.inPolygon(hole.outline, p.x, p.y), `${label}: ${what} inside its walls`); - assert.ok(!golfRules.inWater(hole, p.x, p.y), `${label}: ${what} not in water`); - assert.ok(!golfRules.onSlope(hole, p.x, p.y), `${label}: ${what} not on a slope`); - } - for (const pad of hole.powerups) { - assert.ok(Object.hasOwn(POWERUPS, pad.kind), `${label}: a known power-up, ${pad.kind}`); - assert.ok(golfRules.inPolygon(hole.outline, pad.x, pad.y) && !golfRules.inWater(hole, pad.x, pad.y), `${label}: its ${pad.kind} pad on dry ground`); - assert.ok(Math.hypot(pad.x - hole.tee.x, pad.y - hole.tee.y) > golfRules.POWERUP_R + BALL_R, `${label}: no pad under the tee`); - } - for (const d of hole.decor) assert.ok(DECOR_KINDS.includes(d.kind), `${label}: known scenery, ${d.kind}`); - assert.ok(reachable(hole, hole.tee, hole.cup), `${label}: the cup can be reached from the tee`); - if (hole.bridges.length) { - const bridgeless = { ...hole, bridges: [] }; - assert.equal(reachable(bridgeless, hole.tee, hole.cup), false, `${label}: only its bridge gets the ball over the water`); +// The elements a hole can hold, every one used on some course. +const ELEMENTS = ["bumpers", "sand", "ice", "water", "slopes", "wells", "bridges", "spinners", "tunnels", "movers", "gates", "powerups", "decor"]; + +test("Mini golf courses: six courses of eighteen holes, each hole finishable, with every element used somewhere", () => { + assert.deepEqual(COURSES.map((c) => c.id), ["pirate", "cave", "dino", "candy", "space", "frost"]); + assert.equal(HOLE_COUNT, 18); + assert.equal(FRONT_NINE, 9); + assert.equal(new Set(COURSES.map((c) => c.name)).size, COURSES.length, "every course has its own name"); + const all = COURSES.flatMap((c) => c.holes); + for (const c of COURSES) { + assert.ok(Object.isFrozen(c) && Object.isFrozen(c.holes) && Object.isFrozen(c.holes[0]) && Object.isFrozen(c.holes[0].walls[0]), `${c.id}: the course is frozen`); + assert.equal(c.holes.length, HOLE_COUNT, `${c.id}: eighteen holes`); + assert.ok(Number.isInteger(c.cover) && c.cover >= 0 && c.cover < HOLE_COUNT, `${c.id}: its card art is one of its holes`); + assert.equal(new Set(c.holes.map((h) => h.name)).size, HOLE_COUNT, `${c.id}: every hole has its own name`); + const par = golfRules.coursePar(c); + assert.ok(par >= 48 && par <= 66, `${c.id}: par ${par} for the eighteen, between 48 and 66`); + // Each course is varied: most kinds of element show up somewhere on it. + const used = ELEMENTS.filter((k) => c.holes.some((h) => h[k].length)); + assert.ok(used.length >= 9, `${c.id}: uses ${used.join(", ")}`); + for (const [i, hole] of c.holes.entries()) { + const label = `${c.id} hole ${i + 1} (${hole.name})`; + assert.equal(hole.theme, c.id, `${label}: the course's theme`); + assert.ok(typeof hole.name === "string" && hole.name.length > 0, `${label}: named`); + assert.ok(typeof hole.quip === "string" && hole.quip.length > 0 && hole.quip.length <= 72, `${label}: a quip that fits its banner`); + assert.ok(knownGround(hole.theme, hole.ground), `${label}: a ground its look draws, ${hole.ground}`); + assert.ok(knownLiquid(hole.theme, hole.liquid), `${label}: a liquid its look draws, ${hole.liquid}`); + assert.ok(Number.isInteger(hole.par) && hole.par >= 2 && hole.par <= 5, `${label}: par 2 to 5`); + for (const [what, p] of [["tee", hole.tee], ["cup", hole.cup]]) { + assert.ok(p.x > 0 && p.x < COURSE_W && p.y > 0 && p.y < COURSE_H, `${label}: ${what} on the course`); + assert.ok(golfRules.inPolygon(hole.outline, p.x, p.y), `${label}: ${what} inside its walls`); + assert.ok(!golfRules.inWater(hole, p.x, p.y), `${label}: ${what} not in water`); + assert.ok(!golfRules.onSlope(hole, p.x, p.y), `${label}: ${what} not on a slope`); + } + assert.ok(!golfRules.inWell(hole, hole.tee.x, hole.tee.y), `${label}: the tee is out of every well's reach`); + // The unit suite lines a putt up from just left of the cup. + const near = { x: hole.cup.x - 10, y: hole.cup.y }; + assert.ok(golfRules.inPolygon(hole.outline, near.x, near.y) && !golfRules.inWater(hole, near.x, near.y), `${label}: open ground just left of the cup`); + assert.ok(hole.walls.every((w) => distToSeg(w, near) >= BALL_R + 1) && hole.bumpers.every((b) => Math.hypot(near.x - b.x, near.y - b.y) >= b.r + BALL_R + 1), `${label}: nothing in the way just left of the cup`); + for (const pad of hole.powerups) { + assert.ok(Object.hasOwn(POWERUPS, pad.kind), `${label}: a known power-up, ${pad.kind}`); + assert.ok(golfRules.inPolygon(hole.outline, pad.x, pad.y) && !golfRules.inWater(hole, pad.x, pad.y), `${label}: its ${pad.kind} pad on dry ground`); + assert.ok(Math.hypot(pad.x - hole.tee.x, pad.y - hole.tee.y) > golfRules.POWERUP_R + BALL_R, `${label}: no pad under the tee`); + } + for (const w of hole.wells) { + assert.ok(w.r > 10 && Number.isFinite(w.pull) && w.pull !== 0, `${label}: a well with a reach and a pull`); + // A well that pulls in drains into water or the cup, so no ball rests in it. + if (w.pull > 0) assert.ok(golfRules.inWater(hole, w.x, w.y) || Math.hypot(w.x - hole.cup.x, w.y - hole.cup.y) < CUP_R, `${label}: a well pulling in has water or the cup at its center`); + } + const kinds = decorKinds(hole.theme); + for (const d of hole.decor) assert.ok(kinds.includes(d.kind), `${label}: known scenery, ${d.kind}`); + assert.ok(reachable(hole, hole.tee, hole.cup), `${label}: the cup can be reached from the tee`); + if (hole.bridges.length) { + const bridgeless = { ...hole, bridges: [] }; + assert.equal(reachable(bridgeless, hole.tee, hole.cup), false, `${label}: only its bridge gets the ball over the water`); + } } } - for (const kind of ["bumpers", "sand", "water", "slopes", "bridges", "spinners", "tunnels", "movers", "gates", "powerups", "decor"]) { - assert.ok(HOLES.some((h) => h[kind].length), `some hole has ${kind}`); + for (const kind of ELEMENTS) assert.ok(all.some((h) => h[kind].length), `some hole has ${kind}`); + for (const liquid of ["sea", "pool", "lava", "chasm"]) assert.ok(all.some((h) => h.liquid === liquid && h.water.length), `some hole has ${liquid}`); + for (const kind of Object.keys(POWERUPS)) assert.ok(all.some((h) => h.powerups.some((p) => p.kind === kind)), `some hole has a ${kind} pad`); + assert.ok(all.some((h) => h.walls.length > h.outline.length), "some hole has walls inside its edge"); +}); + +// How far point p is from wall w. +function distToSeg(w, p) { + const dx = w.x2 - w.x1; + const dy = w.y2 - w.y1; + const k = Math.max(0, Math.min(1, ((p.x - w.x1) * dx + (p.y - w.y1) * dy) / (dx * dx + dy * dy || 1))); + return Math.hypot(p.x - (w.x1 + k * dx), p.y - (w.y1 + k * dy)); +} + +test("Mini golf courses: a ball left anywhere on a slope or in a well rolls off and comes to rest, sinks or splashes", () => { + for (const c of COURSES) { + for (const [i, hole] of c.holes.entries()) { + const spots = []; + for (const s of hole.slopes) { + const xs = s.points.map((q) => q.x); + const ys = s.points.map((q) => q.y); + for (let k = 1; k <= 3; k++) for (let j = 1; j <= 3; j++) spots.push({ x: Math.min(...xs) + ((Math.max(...xs) - Math.min(...xs)) * k) / 4, y: Math.min(...ys) + ((Math.max(...ys) - Math.min(...ys)) * j) / 4 }); + } + // Rings across each well, out to its faint rim, where its pull is weakest. + for (const w of hole.wells) for (const f of [0.3, 0.6, 0.85, 0.97]) for (let k = 0; k < 8; k++) spots.push({ x: w.x + Math.cos(k) * w.r * f, y: w.y + Math.sin(k) * w.r * f }); + for (const spot of spots) { + if (!golfRules.inPolygon(hole.outline, spot.x, spot.y) || golfRules.inWater(hole, spot.x, spot.y)) continue; + if (hole.walls.some((w) => distToSeg(w, spot) < BALL_R + 1) || hole.bumpers.some((b) => Math.hypot(spot.x - b.x, spot.y - b.y) < b.r + BALL_R)) continue; + const round = golfAt(i + 1, c.id); + Object.assign(round.ball, { x: spot.x, y: spot.y, vx: 0, vy: 0, moving: false }); + round.from = { x: hole.tee.x, y: hole.tee.y }; + let t = 0; + // Settling may take a few rolls: a ball can bounce back onto a slope. + const settled = () => (round.phase === "aim" && !golfRules.onPush(hole, round.ball.x, round.ball.y)) || round.phase === "card" || round.phase === "done"; + for (; t < 60_000 && !settled(); t += SUB_STEP_MS) advance(round, SUB_STEP_MS); + assert.ok(t < 60_000, `${c.id} hole ${i + 1}: a ball left at ${Math.round(spot.x)},${Math.round(spot.y)} never settles`); + } + } } - for (const liquid of ["sea", "pool", "lava", "chasm"]) assert.ok(HOLES.some((h) => h.liquid === liquid && h.water.length), `some hole has ${liquid}`); - for (const kind of Object.keys(POWERUPS)) assert.ok(HOLES.some((h) => h.powerups.some((p) => p.kind === kind)), `some hole has a ${kind} pad`); - assert.ok(HOLES.some((h) => h.walls.length > h.outline.length), "some hole has walls inside its edge"); }); /* ------------------------------------------------ Mini golf power-ups */ @@ -1313,6 +1682,31 @@ test("Mini golf pointer: the aim follows the pointer, a press starts the meter, assert.ok(Math.abs(g.round.clock - after - 100) <= SUB_STEP_MS, "letting go plays it at its own speed"); }); +test("Mini golf pointer: the aim stays on the cup until the pointer really moves, and a press without a move putts along it", () => { + const { canvas } = stubCanvas(); + const g = golf.create({ canvas }); + // A course unit is two CSS pixels. + g.resize(800, 600); + const px = HOLES[0].tee.x * 2; + const py = HOLES[0].tee.y * 2; + g.pointer("move", px + 100, py - 100); + g.pointer("down", px + 100, py - 100); + assert.equal(g.state, "running"); + const cup = g.round.aimAngle; + assert.equal(g.pointer("move", px + 103, py - 98), false, "a shake does not move the aim"); + assert.equal(g.round.aimAngle, cup); + assert.equal(g.pointer("down", px + 103, py - 98), true); + assert.equal(g.round.phase, "swing"); + assert.equal(g.round.swingAngle, cup, "a press where the pointer sat putts toward the cup"); + + const h = golf.create({ canvas }); + h.resize(800, 600); + h.pointer("down", px + 100, py - 100); + assert.equal(h.pointer("move", px + 100, py - 120), true, "a real move aims again"); + assert.ok(Math.abs(h.round.aimAngle - Math.atan2(-120, 100)) < 1e-9, "at the pointer"); + assert.equal(h.pointer("move", px + 102, py - 120), true, "and then it follows every move"); +}); + test("Mini golf pointer: a cancel or a pause ends a fast-forward", () => { const { canvas } = stubCanvas(); const g = golf.create({ canvas }); @@ -1377,28 +1771,30 @@ test("Mini golf keys: a press nudges the aim, a held arrow turns it faster the l assert.equal(g.release("action"), true); }); -test("Mini golf draws every hole with a context that only records calls", () => { - const { canvas, calls } = stubCanvas(); - const g = golf.create({ canvas }); - g.resize(800, 600); - g.start(); - for (let h = 0; h < HOLES.length; h++) { - const drawn = calls.count; - g.tick(16); - assert.ok(calls.count > drawn, `hole ${h + 1} draws`); - lineUp(g); - g.key("right"); - g.release("right"); - g.key("action"); - // A frame with the meter up. - g.tick(16); - g.round.swingMs = SOFT_MS; - g.key("action"); - g.tick(200); - g.tick(3000); - if (h < HOLES.length - 1) g.key("action"); +test("Mini golf draws every hole of every course with a context that only records calls", () => { + for (const c of COURSES) { + const { canvas, calls } = stubCanvas(); + const g = golf.create({ canvas, course: c.id }); + g.resize(800, 600); + g.start(); + for (let h = 0; h < HOLE_COUNT; h++) { + const drawn = calls.count; + g.tick(16); + assert.ok(calls.count > drawn, `${c.id} hole ${h + 1} draws`); + lineUp(g); + g.key("right"); + g.release("right"); + g.key("action"); + // A frame with the meter up. + g.tick(16); + g.round.swingMs = SOFT_MS; + g.key("action"); + g.tick(200); + g.tick(3000); + if (h < HOLE_COUNT - 1) g.key("action"); + } + assert.equal(g.state, "over", `${c.id}: every hole sunk`); } - assert.equal(g.state, "over"); }); // A 2D context that keeps every method name it was called with, and answers @@ -1494,13 +1890,21 @@ test("tone() plays only while Play sounds is on, and never throws", async () => const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; let oscillators = 0; const gains = []; - const param = { setValueAtTime() {}, exponentialRampToValueAtTime() {} }; + const freqs = []; + // Every oscillator made, so a test can read its wave. + const oscs = []; + const param = { setValueAtTime(v) { freqs.push(v); }, exponentialRampToValueAtTime() {} }; globalThis.AudioContext = class { state = "running"; currentTime = 0; destination = {}; resume() { return Promise.resolve(); } - createOscillator() { oscillators += 1; return { type: "", frequency: param, connect() {}, start() {}, stop() {} }; } + createOscillator() { + oscillators += 1; + const osc = { type: "", frequency: param, connect() {}, start() {}, stop() {} }; + oscs.push(osc); + return osc; + } // Each gain keeps the values its envelope ramps to, so a test can read a blip's peak. createGain() { const ramps = []; @@ -1526,12 +1930,4008 @@ test("tone() plays only while Play sounds is on, and never throws", async () => tone("putt", 0.2); assert.equal(oscillators, 18, "a quieter level still plays"); assert.ok(lastPeak() < loud, "and peaks lower than a full one"); + freqs.length = 0; + tone("thunk"); + tone("thunk", 1, 1.5); + assert.deepEqual(freqs, [240, 360], "a pitch scales the blip"); + tone("slice", 1, 1.5); + freqs.length = 0; + tone("perfect", 1, 99); + assert.deepEqual(freqs, [660 * 4, 990 * 4], "kept to two octaves up"); + freqs.length = 0; + tone("thunk", 1, 0.01); + tone("thunk", 1, "high"); + assert.deepEqual(freqs, [240 * 0.25, 240], "two octaves down at most, and a wild one plays at its own pitch"); + assert.equal(oscillators, 25, "Stack Deploy's tones play at any pitch, a wild one kept in range"); + freqs.length = 0; + tone("ram", 0.5, 2); + tone("rev"); + assert.deepEqual(freqs, [380, 90], "Bumper Ring's thud, pitched up for a hard hit, and a rival's rev"); + assert.equal(oscillators, 27); + freqs.length = 0; + tone("beat"); + assert.deepEqual(freqs, [95], "Bounce Road's heartbeat"); + assert.equal(oscillators, 28); + freqs.length = 0; + tone("tick", 0.9, 1.5); + tone("pop"); + assert.deepEqual(freqs, [2250, 480], "Hot Potato's fuse tick, pitched up as it burns down, and the pop of a pass"); + assert.equal(oscillators, 30); + freqs.length = 0; + tone("hop", 0.6, 1.5); + tone("boing"); + tone("bell"); + tone("horn"); + assert.deepEqual(freqs, [780, 260, 1320, 990, 370, 466], "Crossing Rush's hop, pitched up for a run of quick hops, the boing of a send-back, the crossing bell and the Horn"); + assert.equal(oscillators, 36); + freqs.length = 0; + tone("engine", 0.3, 1.5); + assert.deepEqual(freqs, [123], "Bounce Road's engine, pitched up with your speed"); + assert.equal(oscs.at(-1).type, "triangle", "the engine's hum is a soft triangle, never a sawtooth's buzz"); + assert.equal(oscillators, 37); + freqs.length = 0; + tone("pew", 0.16); + assert.equal(oscs.at(-1).type, "triangle", "Rapids Run's shot is a soft triangle, never a buzz"); + tone("charge"); + tone("lowcell"); + tone("dambreak"); + tone("skim", 0.2, 1.2); + assert.deepEqual(freqs, [1320, 440, 660, 440, 300, 1800], "Rapids Run's shot, a charge buoy, the low battery's beep, a dam bursting and a skim, pitched up the longer you skim"); + assert.equal(oscillators, 43); + freqs.length = 0; + tone("ghoulBlast"); + tone("zombiePop", 0.5, 1.5); + tone("ghoulStomp"); + tone("ghoulBoo"); + tone("ghoulRoar"); + assert.deepEqual(freqs, [980, 390, 220, 330, 120], "Ghoul Rush's bolt, a ghoul torn apart (pitched up for the chain), a stomp, a ghost's moan and a boss's roar"); + assert.equal(oscs.at(-5).type, "triangle", "the bolt is a soft triangle, never a buzz, since it repeats while fire is held"); + freqs.length = 0; + tone("ghoulCandy", 0.35, 2); + tone("zombieGroan"); + tone("batSwoop"); + tone("creakBoard"); + assert.deepEqual(freqs, [2960, 110, 2200, 180], "a soul (pitched up for a run), a zombie's groan, a bat's screech and a creaking board"); + freqs.length = 0; + tone("doorUnlock"); + tone("doorThrough"); + assert.deepEqual(freqs, [494, 587, 740, 659, 587, 494, 440], "the key turning and the door through, both in a minor key"); + freqs.length = 0; + tone("ghoulGrowl"); + tone("ghoulShriek"); + tone("ghoulSpit"); + tone("ghoulThunder"); + assert.deepEqual(freqs, [95, 1900, 340, 70], "a hellhound's growl, a wraith's shriek, a bloater's spit and thunder"); + tone("ghoulSkitter"); + assert.equal(oscillators, 67); + freqs.length = 0; looks.sound = false; - for (const name of ["crash", "putt", "wall", "bump", "cup", "ace", "splash", "power", "boom"]) tone(name); - assert.equal(oscillators, 18, "Play sounds off: silent"); + for (const name of ["crash", "putt", "wall", "bump", "cup", "ace", "splash", "power", "boom", "ram", "rev", "beat", "tick", "pop", "hop", "boing", "bell", "horn", "engine", "pew", "charge", "lowcell", "dambreak", "skim", "ghoulBlast", "zombiePop", "ghoulStomp", "ghoulBoo", "ghoulRoar", "ghoulCandy", "zombieGroan", "batSwoop", "doorUnlock", "doorThrough", "creakBoard", "ghoulGrowl", "ghoulShriek", "ghoulSkitter", "ghoulSpit", "ghoulThunder"]) tone(name); + assert.equal(oscillators, 67, "Play sounds off: silent"); } finally { looks.sound = saved.sound; if (saved.ctor === undefined) delete globalThis.AudioContext; else globalThis.AudioContext = saved.ctor; } }); + +/* -------------------------------------------------- Light Trails rules */ + +// A fixed random source: every call returns the same value, so a rival never +// guesses and nothing lands anywhere by chance. +const still = () => 0.5; + +// Moves a rider to x, y facing `dir`, as if it had just started there. +function park(round, r, x, y, dir) { + if (round.grid[r.y * trails.COLS + r.x] === r.id + 1) round.grid[r.y * trails.COLS + r.x] = 0; + Object.assign(r, { x, y, dir, prev: { x, y }, path: [{ x, y }], queue: [], acc: 0 }); + round.grid[y * trails.COLS + x] = r.id + 1; +} + +// Straight into the race, past the hold before a heat. +function racing(round) { + trails.advance(round, round.phaseMs, still); + assert.equal(round.phase, "race"); + round.events.length = 0; + return round; +} + +const trailsEvents = (round, type) => round.events.filter((e) => e.type === type); + +test("Light Trails: a round starts at level 1 with three lives, two boosts and one rival, everyone on the grid", () => { + const round = trails.newRound(still); + assert.equal(round.level, 1); + assert.equal(round.lives, trails.START_LIVES); + assert.equal(round.charges, trails.START_CHARGES); + assert.equal(round.riders.length, 2, "you and one rival"); + assert.equal(round.phase, "ready"); + for (const r of round.riders) assert.equal(round.grid[r.y * trails.COLS + r.x], r.id + 1, `rider ${r.id} sits on its own cell`); + assert.equal(round.blocks.length, 0, "no crystals before level 3"); + assert.equal(round.portals.length, 0, "no portals before level 4"); +}); + +test("Light Trails: a turn back the way you came or the way you go is ignored, and only two queue", () => { + const round = racing(trails.newRound(still)); + assert.equal(round.riders[0].dir, "right"); + assert.equal(trails.turn(round, "left"), false, "no turning back"); + assert.equal(trails.turn(round, "right"), false, "already going that way"); + assert.equal(trails.turn(round, "up"), true); + assert.equal(trails.turn(round, "down"), false, "the reverse of the queued turn"); + assert.equal(trails.turn(round, "left"), true); + assert.equal(trails.turn(round, "down"), false, "a third queued turn is mashing"); +}); + +test("Light Trails: the step quickens each level, a boost speeds you up and Slow-mo slows only the rivals", () => { + const round = racing(trails.newRound(still)); + const [you, rival] = round.riders; + assert.equal(trails.pace(round, you), trails.STEP_MS); + round.level = 3; + assert.ok(trails.pace(round, you) < trails.STEP_MS, "level 3 is quicker"); + round.level = 1; + assert.equal(trails.boost(round), true); + assert.equal(round.charges, trails.START_CHARGES - 1); + assert.equal(trails.pace(round, you), trails.STEP_MS * trails.BOOST_PACE); + assert.equal(trails.pace(round, rival), trails.STEP_MS, "a boost is yours alone"); + assert.equal(trails.boost(round), false, "one boost at a time"); + delete round.effects.boost; + round.effects.slow = 1000; + assert.ok(trails.pace(round, rival) > trails.STEP_MS, "Slow-mo slows the rivals"); + assert.equal(trails.pace(round, you), trails.STEP_MS, "and not you"); + round.charges = 0; + assert.equal(trails.boost(round), false, "no charge, no boost"); +}); + +test("Light Trails: riding into the wall costs a life and runs the heat again, and the last life ends the round", () => { + const round = racing(trails.newRound(still)); + for (let life = trails.START_LIVES; life > 0; life--) { + park(round, round.riders[0], 0, 15, "left"); + trails.advance(round, trails.STEP_MS + trails.GRACE_MS, still); + assert.equal(round.riders[0].alive, false, "the wall is out"); + assert.equal(round.result, "lose"); + assert.equal(round.lives, life - 1); + assert.equal(trailsEvents(round, "crash").length, 1); + round.events.length = 0; + trails.advance(round, trails.DONE_MS, still); + if (life > 1) { + assert.equal(round.level, 1, "the same arena again"); + assert.equal(round.phase, "ready"); + assert.equal(trailsEvents(round, "retry").length, 1); + racing(round); + } + } + assert.equal(round.over, true, "no lives left: the round is over"); + assert.equal(trailsEvents(round, "over").length, 1); +}); + +test("Light Trails: a rival that hits your trail scores the out and the cut, the heat is won, and the next arena adds a rival", () => { + const round = racing(trails.newRound(still)); + const [you, rival] = round.riders; + // The rival in a corner with your trail on every side it could turn to. + park(round, rival, 0, 1, "up"); + round.grid[0] = you.id + 1; + round.grid[1 * trails.COLS + 1] = you.id + 1; + trails.advance(round, trails.STEP_MS, still); + assert.equal(rival.alive, false); + assert.equal(rival.by, 0, "it hit your trail"); + const [out] = trailsEvents(round, "out"); + assert.equal(out.points, trails.OUT_POINTS + trails.CUT_POINTS); + assert.equal(round.result, "win", "the last rival out wins the heat"); + assert.equal(round.score, trails.OUT_POINTS + trails.CUT_POINTS + trails.WIN_POINTS); + assert.equal(round.outs, 1); + round.events.length = 0; + trails.advance(round, trails.DONE_MS, still); + assert.equal(round.level, 2); + assert.equal(round.riders.length, 3, "two rivals at level 2"); + assert.equal(round.lives, trails.START_LIVES, "a win costs no life"); + assert.deepEqual(trailsEvents(round, "level").map((e) => e.level), [2]); +}); + +test("Light Trails: a crash is held for GRACE_MS, a turn in that time rides out, and only you get the grace", () => { + const round = racing(trails.newRound(still)); + const [you, rival] = round.riders; + park(round, you, 0, 15, "left"); + park(round, rival, 30, 5, "right"); + trails.advance(round, trails.STEP_MS, still); + assert.equal(you.alive, true, "held up, not out yet"); + assert.deepEqual({ x: you.x, y: you.y }, { x: 0, y: 15 }, "and holding still"); + assert.equal(trails.turn(round, "left"), false, "the way you are held up on is no turn"); + assert.equal(trails.turn(round, "right"), false, "nor is back the way you came"); + assert.equal(trails.turn(round, "up"), true); + trails.advance(round, 8, still); + assert.equal(you.alive, true); + assert.deepEqual({ x: you.x, y: you.y, dir: you.dir }, { x: 0, y: 14, dir: "up" }, "rode out upward"); + assert.equal(you.stall, null); + + // No turn: still riding just before the grace runs out, out just after. + park(round, you, 0, 15, "left"); + trails.advance(round, trails.STEP_MS + trails.GRACE_MS - 16, still); + assert.equal(you.alive, true); + trails.advance(round, 16, still); + assert.equal(you.alive, false, "the grace ran out"); + assert.equal(you.by, "wall"); + + // A rival gets none: it is out on the step itself. + const two = racing(trails.newRound(still)); + const foe = two.riders[1]; + park(two, two.riders[0], 10, 15, "right"); + park(two, foe, trails.COLS - 1, 1, "up"); + two.grid[trails.COLS - 1] = trails.WALL; + two.grid[trails.COLS + trails.COLS - 2] = trails.WALL; + two.grid[trails.COLS + trails.COLS] = trails.WALL; + trails.advance(two, trails.STEP_MS, still); + assert.equal(foe.alive, false); +}); + +test("Light Trails: you and the last rival out together is a draw, and nobody loses a life", () => { + const round = racing(trails.newRound(still)); + const [you, rival] = round.riders; + park(round, you, 0, 15, "left"); + // The rival in the top right corner, walled in on both sides it could turn to. + park(round, rival, trails.COLS - 1, 1, "up"); + round.grid[trails.COLS - 1] = trails.WALL; + round.grid[trails.COLS + trails.COLS - 2] = trails.WALL; + trails.advance(round, trails.STEP_MS + trails.GRACE_MS, still); + assert.equal(you.alive, false); + assert.equal(rival.alive, false); + assert.equal(round.result, "draw"); + assert.equal(round.lives, trails.START_LIVES); +}); + +test("Light Trails: rivals turn away from a wall and toward the room", () => { + const round = racing(trails.newRound(still)); + round.level = 9; + const rival = round.riders[1]; + park(round, rival, trails.COLS - 1, 10, "right"); + assert.ok(["up", "down"].includes(trails.choose(round, rival, still)), "never into the wall"); + // Everything above row 10 walled off: only down has room. + for (let y = 0; y < 10; y++) for (let x = 0; x < trails.COLS; x++) round.grid[y * trails.COLS + x] = trails.WALL; + assert.equal(trails.choose(round, rival, still), "down"); + assert.ok(trails.room(round, 11 * trails.COLS + 5) > 100, "the open half has room"); +}); + +test("Light Trails: crystals from level 3 come in mirrored pairs and never sit in a starting lane", () => { + const round = trails.newRound(still); + let seed = 3; + const random = () => ((seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) / 4294967296); + const STEPS = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] }; + for (const level of [3, 6, 9]) { + round.level = level; + trails.newHeat(round, random); + assert.ok(round.blocks.length > 0, `crystals at level ${level}`); + const has = new Set(round.blocks.map((b) => `${b.x},${b.y}`)); + for (const b of round.blocks) assert.ok(has.has(`${trails.COLS - 1 - b.x},${trails.ROWS - 1 - b.y}`), "each has its mirror"); + for (const r of round.riders) { + const [dx, dy] = STEPS[r.dir]; + for (let k = 1; k <= 10; k++) assert.equal(round.grid[(r.y + dy * k) * trails.COLS + r.x + dx * k], 0, `the lane of rider ${r.id} is open`); + } + } +}); + +test("Light Trails: from level 4 a portal carries a rider out of its partner, going the same way", () => { + const round = trails.newRound(still); + round.level = 4; + racing(trails.newHeat(round, still)); + assert.equal(round.portals.length, 2, "one pair at level 4"); + const [a] = round.portals; + const you = round.riders[0]; + park(round, you, a.x - 1, a.y, "right"); + trails.advance(round, trails.pace(round, you), still); + assert.equal(you.alive, true); + assert.deepEqual({ x: you.x, y: you.y }, { x: a.to.x, y: a.to.y }); + assert.equal(you.dir, "right"); + assert.equal(trailsEvents(round, "portal").filter((e) => e.id === 0).length, 1); + round.level = 6; + trails.newHeat(round, still); + assert.equal(round.portals.length, 4, "two pairs from level 6"); +}); + +test("Light Trails: Phase rides through trails, the Eraser wipes those around you, and a rival only snatches a pad", () => { + const round = racing(trails.newRound(still)); + const you = round.riders[0]; + park(round, you, 10, 15, "right"); + round.grid[15 * trails.COLS + 11] = 2; + trails.applyPower(round, "phase"); + trails.advance(round, trails.STEP_MS, still); + assert.equal(you.alive, true, "phased through the rival's trail"); + assert.equal(you.x, 11); + assert.equal(round.grid[15 * trails.COLS + 11], 2, "and left it as it was"); + + delete round.effects.phase; + const close = 15 * trails.COLS + 14; + const far = 2 * trails.COLS + 30; + round.grid[close] = 2; + round.grid[far] = 2; + trails.applyPower(round, "eraser"); + assert.equal(round.grid[close], 0, "a trail within reach is wiped"); + assert.equal(round.grid[far], 2, "one out of reach stays"); + + const rival = round.riders[1]; + park(round, rival, 30, 25, "up"); + round.items.push({ x: 30, y: 24, kind: "coin", ttl: 5000 }); + const score = round.score; + // Only the rival moves: you are parked well clear and never reach a pace. + you.acc = -1e9; + for (let i = 0; i < 30 && round.items.length; i++) trails.advance(round, 10, still); + assert.equal(round.items.length, 0, "the rival took the pad"); + assert.equal(round.score, score, "and you got nothing for it"); + assert.equal(trailsEvents(round, "snatch").length, 1); +}); + +test("Light Trails: pads turn up from level 2, never at level 1", () => { + const one = racing(trails.newRound(still)); + one.nextItem = 1; + trails.advance(one, 8, still); + assert.equal(one.items.length, 0); + const two = trails.newRound(still); + two.level = 2; + racing(trails.newHeat(two, still)); + two.nextItem = 1; + trails.advance(two, 8, still); + assert.equal(two.items.length, 1); + assert.ok(Object.hasOwn(trails.POWERS, two.items[0].kind)); +}); + +test("Light Trails: from level 5 the walls close in a ring at a time, warning first, and catch anyone on the ring", () => { + const round = trails.newRound(still); + round.level = 5; + racing(trails.newHeat(round, still)); + assert.equal(round.nextRing, trails.SHRINK_FIRST_MS); + round.nextRing = trails.SHRINK_WARN_MS + 4; + trails.advance(round, 8, still); + assert.equal(trailsEvents(round, "warn").length, 1, "the ring warns before it closes"); + const rival = round.riders[1]; + park(round, rival, 0, 20, "up"); + trails.closeRing(round); + assert.equal(round.ring, 1); + assert.equal(round.grid[0], trails.WALL); + assert.equal(round.grid[(trails.ROWS - 1) * trails.COLS + 5], trails.WALL); + assert.equal(round.grid[1 * trails.COLS + 1], 0, "the next ring in is still open"); + assert.equal(rival.alive, false, "a rival on the ring is out"); +}); + +test("Light Trails: the start screen reads the furthest arena from the memo and writes nothing just by drawing", () => { + const { canvas, calls } = stubCanvas(); + let saved = 5; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const g = trails.default.create({ canvas, memo }); + assert.equal(g.resize(800, 600), true); + assert.ok(calls.count > 0, "the start screen draws"); + assert.equal(g.resize(trails.COLS * trails.MIN_CELL - 1, 600), false, "too narrow to play"); + assert.equal(saved, 5, "nothing is written by just opening it"); +}); + +test("Light Trails: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives and running effects included, in light and dark under every highlight", () => { + checkPills(trails.default, { + setup: (r) => Object.assign(r.effects, { boost: trails.BOOST_MS / 2, phase: 1500, slow: 2000 }), + expect: ["LV 1", "♥", "~BOOST", "~PHASE", "~SLOW-MO", "1 RIVAL"], + }); +}); + +test("Light Trails game: the opening banner sits in the board from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.3)"); + const g = trails.default.create({ canvas }); + g.resize(800, 600); + openingBanner(g, shades, 600); +}); + +/* ------------------------------------------------------ Bug Hunt rules */ + +// Each bug settled into its slot, as if the wave had finished flying in. +function settled(round) { + for (const b of round.bugs) { + Object.assign(b, bugs.slotPos(round, b.slot), { state: "form", t: 0 }); + } + round.nextDive = 1e9; + round.events.length = 0; + return round; +} + +// A shot fired straight up from just under `at`. +const shootAt = (round, at) => round.shots.push({ x: at.x, y: at.y + 0.5, vx: 0, vy: -46 }); + +const huntEvents = (round, type) => round.events.filter((e) => e.type === type); + +test("Bug Hunt: a round opens on wave 1, two rows of six everyday bugs flying in, and three lives", () => { + const round = bugs.newRound(still); + assert.equal(round.wave, 1); + assert.equal(round.lives, bugs.START_LIVES); + assert.equal(round.bugs.length, 12); + assert.ok(round.bugs.every((b) => b.kind === "ant" && b.state === "wait"), "every bug waits its turn to fly in"); + assert.equal(huntEvents(round, "wave").length, 1); + bugs.advance(round, 4000, still); + assert.ok(round.bugs.every((b) => b.state === "form" || b.state === "dive"), "after the swoop, all are in place or diving"); +}); + +test("Bug Hunt: each new kind of bug arrives on its own wave, and every fifth wave is a boss", () => { + const round = bugs.newRound(still); + const fresh = {}; + for (let n = 2; n <= 15; n++) { + round.events.length = 0; + round.boss = null; + bugs.spawnWave(round, still); + const [e] = huntEvents(round, "wave"); + if (e.fresh) fresh[e.fresh] = n; + if (n % bugs.BOSS_EVERY === 0) { + assert.ok(round.boss, `wave ${n} is a boss`); + assert.equal(round.bugs.length, 0, "a boss comes alone"); + } else assert.equal(round.boss, null); + } + assert.deepEqual(fresh, { beetle: 2, zigzag: 3, spitter: 4, blinker: 6, firewall: 7 }); + round.boss = null; + round.wave = 4; + bugs.spawnWave(round, still); + assert.equal(round.boss.kind, "leak"); + round.wave = 9; + bugs.spawnWave(round, still); + assert.equal(round.boss.kind, "spaghetti"); + round.wave = 14; + bugs.spawnWave(round, still); + assert.equal(round.boss.kind, "heisen"); + round.wave = 19; + bugs.spawnWave(round, still); + assert.equal(round.boss.kind, "leak", "the bosses come round again"); + assert.ok(round.boss.max > bugs.BOSSES.leak.hp, "and take more the second time"); +}); + +test("Bug Hunt: fire held shoots every FIRE_MS, the ship slides while an arrow is held, and nothing moves it once let go", () => { + const round = settled(bugs.newRound(still)); + round.input.fire = true; + bugs.advance(round, bugs.FIRE_MS * 3 - 8, still); + assert.equal(huntEvents(round, "shoot").length, 3); + round.input.fire = false; + round.events.length = 0; + bugs.advance(round, 1000, still); + assert.equal(huntEvents(round, "shoot").length, 0, "let go, no more shots"); + const x = round.ship.x; + round.input.left = true; + bugs.advance(round, 200, still); + assert.ok(round.ship.x < x, "left slides left"); + round.input.left = false; + const stop = round.ship.x; + bugs.advance(round, 200, still); + assert.equal(round.ship.x, stop); +}); + +test("Bug Hunt: a shot squashes a bug for its points, and quick kills build a combo", () => { + const round = settled(bugs.newRound(still)); + const [a, b] = round.bugs; + shootAt(round, a); + bugs.advance(round, 16, still); + assert.equal(round.bugs.includes(a), false); + assert.equal(round.score, bugs.BUGS.ant.points); + shootAt(round, b); + bugs.advance(round, 16, still); + assert.equal(round.combo, 2); + assert.equal(round.score, bugs.BUGS.ant.points * 3, "the second kill counts twice"); + bugs.advance(round, bugs.COMBO_MS + 50, still); + assert.equal(round.combo, 1, "the combo runs out"); +}); + +test("Bug Hunt: a beetle takes two shots and splits into two bugs that dive on their own", () => { + const round = bugs.newRound(still); + round.wave = 1; + bugs.spawnWave(round, still); + settled(round); + const beetle = round.bugs.find((b) => b.kind === "beetle"); + assert.ok(beetle, "wave 2 has beetles"); + const count = round.bugs.length; + shootAt(round, beetle); + bugs.advance(round, 16, still); + assert.ok(round.bugs.includes(beetle), "one shot only dents it"); + assert.equal(huntEvents(round, "hurt").length, 1); + shootAt(round, beetle); + bugs.advance(round, 16, still); + assert.equal(round.bugs.includes(beetle), false); + assert.equal(round.bugs.length, count + 1, "one beetle out, two bugs in"); + assert.equal(round.bugs.filter((b) => !b.slot && b.state === "dive").length, 2); +}); + +test("Bug Hunt: a hit costs a life, the ship comes back unhittable for a while, a shield takes a hit, and the last life ends the round", () => { + const round = settled(bugs.newRound(still)); + const ship = round.ship; + assert.equal(bugs.hitShip(round), true); + assert.equal(round.lives, bugs.START_LIVES - 1); + assert.equal(ship.alive, false); + bugs.advance(round, bugs.RESPAWN_MS + 16, still); + assert.equal(ship.alive, true, "back after the respawn"); + assert.equal(bugs.hitShip(round), false, "and safe for a moment"); + bugs.advance(round, bugs.INVULN_MS, still); + bugs.applyPower(round, "shield"); + assert.equal(bugs.hitShip(round), true); + assert.equal(round.lives, bugs.START_LIVES - 1, "the shield took it"); + assert.equal(round.shield, 0); + ship.invuln = 0; + round.lives = 1; + bugs.hitShip(round); + assert.equal(round.over, true); + assert.equal(huntEvents(round, "over").length, 1); +}); + +test("Bug Hunt: a bomb that reaches the ship is a hit", () => { + const round = settled(bugs.newRound(still)); + round.bombs.push({ x: round.ship.x, y: round.ship.y - 3, vx: 0, vy: 15 }); + bugs.advance(round, 400, still); + assert.equal(round.lives, bugs.START_LIVES - 1); + assert.equal(round.bombs.length, 0, "a hit clears the bombs"); +}); + +test("Bug Hunt: shots pass through a null pointer while it fades", () => { + const round = bugs.newRound(still); + round.wave = 5; + bugs.spawnWave(round, still); + settled(round); + const blinker = round.bugs.find((b) => b.kind === "blinker"); + blinker.phase = 2000 - round.clock; + assert.equal(bugs.ghostly(round, blinker), true); + shootAt(round, blinker); + bugs.advance(round, 16, still); + assert.ok(round.bugs.includes(blinker), "faded: the shot went through"); + blinker.phase = -round.clock; + assert.equal(bugs.ghostly(round, blinker), false); + shootAt(round, blinker); + bugs.advance(round, 16, still); + assert.equal(round.bugs.includes(blinker), false); +}); + +test("Bug Hunt: a wave cleared scores its bonus, more without a hit, and the next wave follows the rest", () => { + const round = settled(bugs.newRound(still)); + for (const b of [...round.bugs]) bugs.hurtBug(round, b, still); + const before = round.score; + bugs.advance(round, 16, still); + const [clear] = huntEvents(round, "clear"); + assert.ok(clear.perfect); + assert.equal(round.score - before, bugs.CLEAR_POINTS + bugs.PERFECT_POINTS); + assert.equal(round.wave, 1); + bugs.advance(round, bugs.CLEAR_MS, still); + assert.equal(round.wave, 2); +}); + +test("Bug Hunt: the Spaghetti Monster shrugs off shots until its tentacles are cut, and the Heisenbug while it blurs", () => { + const round = bugs.newRound(still); + round.wave = 9; + round.bugs = []; + bugs.spawnWave(round, still); + const boss = round.boss; + bugs.advance(round, 4000, still); + assert.equal(boss.state, "fight"); + round.events.length = 0; + shootAt(round, { x: boss.x, y: boss.y + 2 }); + bugs.advance(round, 16, still); + assert.equal(boss.hp, boss.max, "tentacles up: the body is untouched"); + assert.equal(huntEvents(round, "clink").length, 1); + for (const t of boss.tentacles) t.hp = 0; + shootAt(round, { x: boss.x, y: boss.y + 2 }); + bugs.advance(round, 16, still); + assert.equal(boss.hp, boss.max - 1, "cut: the body takes the shot"); + bugs.hurtBoss(round, boss.hp, still); + assert.equal(round.boss, null); + assert.equal(huntEvents(round, "bossdown")[0].points, bugs.BOSS_POINTS); + + round.wave = 14; + bugs.spawnWave(round, still); + const heisen = round.boss; + bugs.advance(round, 4000, still); + heisen.blur = 400; + heisen.teleMs = 1e9; + shootAt(round, { x: heisen.x, y: heisen.y + 2 }); + bugs.advance(round, 16, still); + assert.equal(heisen.hp, heisen.max, "blurred: untouchable"); +}); + +test("Bug Hunt: Refactor clears the bombs and cleans up the bugs on screen", () => { + const round = settled(bugs.newRound(still)); + round.bombs.push({ x: 5, y: 5, vx: 0, vy: 1 }); + bugs.applyPower(round, "refactor"); + assert.equal(round.bombs.length, 0); + assert.equal(round.bugs.length, 0, "two points of damage squash every everyday bug"); +}); + +test("Bug Hunt: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives, the combo, a shield and every power included, in light and dark under every highlight", () => { + checkPills(bugs.default, { + setup: (r) => { + r.combo = 3; + r.comboMs = bugs.COMBO_MS / 2; + r.shield = 1; + Object.assign(r.effects, { spread: 4000, rapid: 4000, slow: 3000, magnet: 5000 }); + }, + expect: ["WAVE 1", "♥", "~x3 COMBO", "SHIELD", "~SPREAD", "~RAPID", "~SLOW-MO", "~MAGNET"], + }); +}); + +test("Bug Hunt: starting a round meets the first bug, and the tally keeps it in the memo", () => { + const { canvas } = stubCanvas(); + let saved = 0; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const g = bugs.default.create({ canvas, memo }); + assert.equal(g.resize(800, 600), true); + assert.equal(saved, 0, "nothing before a round"); + g.key("action"); + assert.equal(g.state, "running"); + assert.equal(saved & (1 << bugs.DISCOVERIES.indexOf("bug:ant")), 1 << bugs.DISCOVERIES.indexOf("bug:ant")); + assert.equal(g.round.input.fire, true, "space held fires"); + g.release("action"); + assert.equal(g.round.input.fire, false, "and let go stops"); + g.key("left"); + g.pause(); + assert.equal(g.round.input.left, false, "a pause lets go of every key"); + assert.equal(g.resize(bugs.W * bugs.MIN_CELL - 1, 600), false, "too narrow to play"); +}); + +/* ------------------------------------------------------ Sunset Drive rules */ + +// The index of the segment under the car, and a round with nothing on the +// road but what a test puts there. +const driveIndex = (round) => Math.floor((round.pos + drive.PLAYER_Z) / drive.SEG); +const clearRoad = (round) => { + for (const seg of round.segs) { + seg.props = []; + seg.items = []; + } + round.events = []; + return round; +}; +const driveEvents = (round, type) => round.events.filter((e) => e.type === type); +// Traffic out of every test's way: the count stays full, so no new car is +// placed near the car, and each parked one is moved far ahead. +const farCars = (round) => { + round.cars = Array.from({ length: 40 }, () => ({ z: 1e12, x: 0, speed: 0, kind: "car", color: "#fff", ahead: true })); + return round; +}; +const quiet = (round) => farCars(clearRoad(round)); +// No bends either, so a car nobody steers stays on the road, and in the +// right lane, clear of the middle one where the test random puts new cars. +const straight = (round) => { + for (const seg of round.segs) seg.curve = 0; + round.x = 2 / 3; + return quiet(round); +}; + +test("Sunset Drive: a round opens on Sunset Coast at stage 1, with the clock, two nitro cans, traffic ahead and a fork to come", () => { + const round = drive.newRound(still); + assert.equal(round.stage, 1); + assert.equal(round.region, "coast"); + assert.equal(round.time, drive.START_TIME_MS); + assert.equal(round.nitro, drive.START_NITRO); + assert.ok(round.cars.length > 0 && round.cars.every((c) => c.z > round.pos + drive.PLAYER_Z), "every car starts ahead"); + assert.ok(round.forkAt >= drive.STAGE_LEN, "the fork comes after a full stage"); + assert.equal(round.gateAt - round.forkAt, drive.FORK_LEN, "and the split runs to the checkpoint"); + assert.ok(round.gateAt + 1 - driveIndex(round) > drive.DRAW, "the road is built past what is drawn"); + assert.notEqual(round.fork.left, round.fork.right); + assert.ok(drive.REGIONS[round.fork.left].bonus <= drive.REGIONS[round.fork.right].bonus, "the gentler road is on the left"); + assert.deepEqual(driveEvents(round, "stage").map((e) => e.region), ["coast"]); +}); + +test("Sunset Drive: held up speeds the car to top speed and scores the road driven; off the road it slows to a quarter", () => { + const round = straight(drive.newRound(still)); + round.input.up = true; + drive.advance(round, 6000, still); + assert.equal(round.speed, drive.MAX_SPEED, "five seconds to top speed"); + assert.ok(round.score > 0, "the road driven scores"); + round.x = 2; + drive.advance(round, 3000, still); + assert.ok(round.speed <= drive.OFFROAD_LIMIT + 1, "off the road, a quarter of top speed"); + round.input.up = false; + round.input.down = true; + round.x = 2 / 3; + drive.advance(round, 1000, still); + assert.equal(round.speed, 0, "the brakes stop it"); +}); + +test("Sunset Drive: space burns one nitro can for a higher top speed, one at a time, and none with the cans gone", () => { + const round = straight(drive.newRound(still)); + round.speed = drive.MAX_SPEED; + round.input.up = true; + assert.equal(drive.boost(round), true); + assert.equal(round.nitro, drive.START_NITRO - 1); + assert.equal(drive.boost(round), false, "one can at a time"); + drive.advance(round, 1500, still); + assert.ok(round.speed > drive.MAX_SPEED * 1.2, "past top speed while it burns"); + drive.advance(round, drive.NITRO_MS + 2000, still); + assert.equal(round.speed, drive.MAX_SPEED, "and back to top speed after"); + round.nitro = 0; + assert.equal(drive.boost(round), false, "no cans, no nitro"); +}); + +test("Sunset Drive: a car caught up with is a crash, and a car passed close at speed is a close call", () => { + const round = quiet(drive.newRound(still)); + const slow = drive.MAX_SPEED * 0.3; + round.cars[0] = { z: round.pos + drive.PLAYER_Z + 60, x: 0, speed: slow, kind: "car", color: "#fff", ahead: true }; + round.speed = drive.MAX_SPEED; + drive.advance(round, 16, still); + assert.equal(driveEvents(round, "crash").length, 1); + assert.ok(round.speed < slow, "you drop below its speed"); + assert.ok(round.cars[0].z > round.pos + drive.PLAYER_Z, "just behind it"); + + round.events = []; + round.cars[0] = { z: round.pos + drive.PLAYER_Z + 40, x: 0.5, speed: slow, kind: "car", color: "#fff", ahead: true }; + round.speed = drive.MAX_SPEED; + round.input.up = true; + drive.advance(round, 100, still); + assert.equal(driveEvents(round, "crash").length, 0, "half a lane over is clear"); + const [close] = driveEvents(round, "close"); + assert.equal(close.points, drive.CLOSE_POINTS); + assert.equal(round.closeCalls, 1); +}); + +test("Sunset Drive: coins, clocks and nitro cans are picked up from the lane you drive in", () => { + const round = quiet(drive.newRound(still)); + const at = driveIndex(round) - round.first; + round.segs[at + 1].items.push({ kind: "coin", offset: 0 }); + round.segs[at + 2].items.push({ kind: "clock", offset: 0 }); + round.segs[at + 3].items.push({ kind: "nitro", offset: 0 }); + round.segs[at + 4].items.push({ kind: "coin", offset: 2 / 3 }); + round.speed = drive.MAX_SPEED / 2; + round.input.up = true; + const time = round.time; + drive.advance(round, 400, still); + assert.equal(round.coins, 1, "the coin in the next lane stays"); + assert.equal(driveEvents(round, "coin")[0].points, drive.COIN_POINTS); + assert.ok(round.time > time + drive.CLOCK_MS - 500, "a clock adds five seconds"); + assert.equal(round.nitro, drive.START_NITRO + 1); + assert.equal(round.segs[at + 4].items.length, 1); +}); + +test("Sunset Drive: the side you keep to as the road splits picks the next road, the median holds you to it, and the checkpoint adds time and points", () => { + const round = quiet(drive.newRound(still)); + const { left, right } = round.fork; + round.pos = (round.forkAt - 2) * drive.SEG - drive.PLAYER_Z; + round.x = -0.8; + round.speed = drive.MAX_SPEED / 2; + round.input.up = true; + drive.advance(round, 200, still); + assert.deepEqual(driveEvents(round, "choose").map((e) => e.region), [left], "keeping left takes the left road"); + assert.equal(round.side, -1); + assert.ok(round.pending.forkAt > round.gateAt, "the next stage is built on behind the checkpoint"); + assert.equal(round.segs.at(-1).region, left, "in its own scenery"); + + round.pos = (round.forkAt + drive.FORK_LEN / 2) * drive.SEG - drive.PLAYER_Z; + round.x = 0.2; + drive.advance(round, 8, still); + const seg = drive.segAt(round, round.pos + drive.PLAYER_Z); + assert.ok(round.x < -seg.median, "the median pushes you back to your side"); + assert.equal(driveEvents(round, "scrape").length, 1); + + const time = round.time; + const points = round.points; + round.pos = (round.gateAt - 1) * drive.SEG - drive.PLAYER_Z; + round.x = -0.6; + drive.advance(round, 400, still); + assert.equal(round.stage, 2); + assert.equal(round.region, left); + assert.notEqual(round.region, right); + const [check] = driveEvents(round, "checkpoint"); + assert.equal(check.ms, drive.checkTime(2)); + assert.equal(check.points, drive.CHECK_POINTS); + assert.ok(round.time > time + drive.checkTime(2) - 1000, "the clock gains the checkpoint's time"); + assert.ok(round.points >= points + drive.CHECK_POINTS); + assert.equal(round.pending, null); + assert.ok(round.forkAt > driveIndex(round), "and a new fork waits ahead"); +}); + +test("Sunset Drive: every stage puts power-up boxes on the road; a box queues its power-up, up to three, and one past that pays points", () => { + const round = drive.newRound(still); + const boxes = round.segs.flatMap((seg) => seg.items.filter((it) => it.kind === "power")); + assert.ok(boxes.length >= 2, `boxes on the first stage (${boxes.length})`); + assert.ok(boxes.every((b) => drive.POWER_ORDER.includes(b.power)), "each holds a known power-up"); + quiet(round); + const at = driveIndex(round) - round.first; + const ids = ["ghost", "hop", "magnet", "storm"]; + ids.forEach((id, k) => round.segs[at + 1 + k].items.push({ kind: "power", power: id, offset: round.x })); + round.speed = drive.MAX_SPEED / 2; + drive.advance(round, 400, still); + assert.deepEqual(round.powers, ["ghost", "hop", "magnet"], "queued in the order picked up, three at most"); + assert.equal(driveEvents(round, "box").length, drive.MAX_POWERS); + assert.equal(driveEvents(round, "spare")[0].points, drive.POWER_SPARE, "the fourth pays points"); +}); + +test("Sunset Drive: a power-up fires the oldest held first, ahead of nitro, a timed one runs out, and one fired again while it runs adds its time", () => { + const round = straight(drive.newRound(still)); + round.powers = ["ghost", "magnet", "ghost"]; + assert.equal(drive.usePower(round), true); + assert.deepEqual(round.powers, ["magnet", "ghost"], "first in, first out"); + assert.equal(round.active.ghost, drive.POWERS.ghost.ms); + assert.equal(round.nitro, drive.START_NITRO, "no nitro burned"); + drive.usePower(round); + drive.advance(round, 1000, still); + drive.usePower(round); + assert.equal(round.active.ghost, drive.POWERS.ghost.ms * 2 - 1000, "a second ghost adds to the first"); + assert.equal(round.activeMax.ghost, drive.POWERS.ghost.ms * 2); + assert.equal(drive.usePower(round), false, "none left"); + drive.advance(round, drive.POWERS.magnet.ms, still); + assert.equal(round.active.magnet, undefined, "the magnet ran out"); + assert.ok(driveEvents(round, "powerend").some((e) => e.id === "magnet")); + round.powers = ["hop"]; + round.time = 0; + drive.advance(round, 8, still); + assert.equal(drive.usePower(round), false, "none once the time is up"); +}); + +test("Sunset Drive: a Rocket Hop and a Ghost Car pass cars and props untouched, a Monster Truck flings cars for points and flattens props, and a Coin Magnet reaches across the road", () => { + for (const id of ["hop", "ghost", "monster"]) { + const round = quiet(drive.newRound(still)); + round.powers = [id]; + drive.usePower(round); + round.cars[0] = { z: round.pos + drive.PLAYER_Z + 60, x: round.x, speed: drive.MAX_SPEED * 0.3, kind: "car", color: "#fff", ahead: true }; + round.speed = drive.MAX_SPEED; + drive.advance(round, 100, still); + assert.equal(driveEvents(round, "crash").length, 0, `${id}: no crash`); + assert.ok(round.speed > drive.MAX_SPEED * 0.9, `${id}: no slowing`); + if (id === "monster") assert.equal(driveEvents(round, "fling")[0].points, drive.FLING_POINTS, "the car is flung for points"); + const at = driveIndex(round) - round.first; + round.segs[at + 1].props.push({ kind: "rock", offset: round.x, text: null, seed: 0 }); + drive.advance(round, 100, still); + assert.equal(driveEvents(round, "smash").length, 0, `${id}: no smash on a rock`); + if (id === "monster") assert.equal(driveEvents(round, "flatten").length, 1, "the rock is flattened"); + } + const round = quiet(drive.newRound(still)); + round.x = -2 / 3; + round.powers = ["magnet"]; + drive.usePower(round); + const at = driveIndex(round) - round.first; + round.segs[at + 1].items.push({ kind: "coin", offset: 2 / 3 }); + round.speed = drive.MAX_SPEED / 2; + drive.advance(round, 200, still); + assert.equal(round.coins, 1, "a coin two lanes over comes to the magnet"); +}); + +test("Sunset Drive: a Coin Storm turns the cars ahead into coins and sends them far down the road", () => { + const round = quiet(drive.newRound(still)); + const pz = round.pos + drive.PLAYER_Z; + round.cars[0] = { z: pz + drive.SEG * 20, x: 0, speed: 0, kind: "car", color: "#fff", ahead: true }; + round.cars[1] = { z: pz + drive.SEG * 40, x: 2 / 3, speed: 0, kind: "truck", color: "#fff", ahead: true }; + round.powers = ["storm"]; + drive.usePower(round, still); + assert.equal(driveEvents(round, "storm")[0].cars, 2); + assert.ok(round.cars[0].z > pz + drive.SEG * drive.DRAW * 0.8 && round.cars[1].z > pz + drive.SEG * drive.DRAW * 0.8, "both cars sent far ahead"); + const coins = round.segs.flatMap((seg) => seg.items.filter((it) => it.kind === "coin")); + assert.equal(coins.length, 6, "three coins where each car was"); + assert.equal(round.active.storm, undefined, "a storm is over at once"); +}); + +test("Sunset Drive: a checkpoint adds a little less time each stage, never under 18 seconds", () => { + assert.ok(drive.checkTime(3) < drive.checkTime(2)); + assert.equal(drive.checkTime(50), 18000); +}); + +test("Sunset Drive: out of time the car coasts to a stop and the round is over", () => { + const round = quiet(drive.newRound(still)); + round.time = 1500; + round.lastSecond = 2; + round.speed = drive.MAX_SPEED; + round.input.up = true; + drive.advance(round, 1000, still); + assert.deepEqual(driveEvents(round, "hurry").map((e) => e.sec), [1], "the last second is called"); + drive.advance(round, 600, still); + assert.equal(driveEvents(round, "timeup").length, 1); + assert.equal(round.over, false, "it coasts first"); + assert.equal(drive.boost(round), false, "no nitro once the time is up"); + assert.equal(drive.advance(round, drive.COAST_MS, still), "over"); + assert.equal(driveEvents(round, "over").length, 1); +}); + +test("Sunset Drive: every pill's text reads at 4.5:1 on its backing and its timer's tint, the low clock and a burning nitro included, in light and dark under every highlight", () => { + checkPills(drive.default, { + setup: (r) => { + r.time = 5000; + r.nitroMs = drive.NITRO_MS / 2; + r.powers = ["magnet", "hop"]; + for (const id of drive.POWER_ORDER.filter((p) => drive.POWERS[p].ms)) { + r.active[id] = drive.POWERS[id].ms / 2; + r.activeMax[id] = drive.POWERS[id].ms; + } + }, + expect: ["TIME 5", "STAGE 1", "~NITRO!", "SPACE: MAGNET +1", "~HOP!", "~GHOST!", "~MAGNET!", "~MONSTER!"], + }); +}); + +test("Sunset Drive: starting a round finds Sunset Coast for the tally, held keys drive until let go, and a pause lets go of them all", () => { + const { canvas } = stubCanvas(); + let saved = 0; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const g = drive.default.create({ canvas, memo }); + assert.equal(g.resize(1024, 576), true); + assert.equal(saved, 0, "nothing before a round"); + g.key("action"); + assert.equal(g.state, "running"); + assert.equal(saved, 1 << drive.REGION_ORDER.indexOf("coast")); + g.key("up"); + assert.equal(g.round.input.up, true, "up held drives"); + g.release("up"); + assert.equal(g.round.input.up, false, "and let go stops"); + g.key("action"); + assert.equal(g.round.nitro, drive.START_NITRO - 1, "space in a round is nitro"); + g.round.powers = ["ghost"]; + g.round.nitroMs = 0; + g.key("action"); + assert.equal(g.round.nitro, drive.START_NITRO - 1, "with a power-up held, space fires it instead"); + assert.ok(g.round.active.ghost > 0); + // The fork's postcards, and the car in the air, draw without a hitch. + g.round.warned = true; + g.round.powers = ["hop", "monster"]; + g.key("action"); + g.key("action"); + g.tick(400); + assert.ok(drive.hopHeight(g.round) > 0, "the hop has the car in the air"); + g.key("left"); + g.pause(); + assert.equal(g.round.input.left, false, "a pause lets go of every key"); + assert.equal(g.resize(drive.W * drive.MIN_CELL - 1, 600), false, "too narrow to play"); +}); + +/* ------------------------------------------------------ Stack Deploy rules */ + +// The top of the tower, and a slider put exactly `offset` units from it (a +// plus is to the right). +const stackTop = (round) => round.blocks[round.blocks.length - 1]; +const aim = (round, offset) => { + round.slider.x = stackTop(round).x + offset; + return round; +}; +const stackEvents = (round, type) => round.events.filter((e) => e.type === type); + +test("Stack Deploy: a round opens on the base, with a block as wide sliding in from the left wall", () => { + const round = stack.newRound(still); + assert.equal(round.blocks.length, 1); + assert.equal(round.blocks[0].w, stack.BASE_W); + assert.equal(round.blocks[0].x, (stack.W - stack.BASE_W) / 2, "the base sits in the middle"); + assert.equal(round.floor, 0); + assert.equal(round.score, 0); + assert.equal(round.slider.floor, 1); + assert.equal(round.slider.w, stack.BASE_W); + assert.equal(round.slider.x, 0); + assert.equal(round.slider.dir, 1); + stack.advance(round, 100); + assert.ok(Math.abs(round.slider.x - stack.speedAt(1) * 0.1) < 1e-9, "it slides at the floor's speed"); +}); + +test("Stack Deploy: a drop at exact center is perfect, slices nothing and scores the perfect bonus", () => { + const round = aim(stack.newRound(still), 0); + const r = stack.drop(round, still); + assert.deepEqual(r, { kept: stack.BASE_W, sliced: 0, perfect: true, miss: false }); + assert.equal(round.floor, 1); + assert.equal(stackTop(round).w, stack.BASE_W); + assert.equal(round.score, stack.FLOOR_POINTS + stack.PERFECT_POINTS); + assert.equal(round.streak, 1); + assert.equal(stackEvents(round, "perfect").length, 1); + // Just inside the zone snaps on too, exactly over the block below. + const zone = stack.zoneOf(round); + aim(round, zone * 0.9); + assert.equal(stack.drop(round, still).perfect, true); + assert.equal(stackTop(round).x, round.blocks[1].x, "a perfect snaps on"); + assert.equal(round.score, 2 * stack.FLOOR_POINTS + stack.PERFECT_POINTS * 3, "the second in a row is worth twice the bonus"); +}); + +test("Stack Deploy: a drop half off keeps half, slices the overhang off the side it hung over, and breaks the run", () => { + const round = aim(stack.newRound(still), 0); + stack.drop(round, still); + const half = stack.BASE_W / 2; + const left = stackTop(round).x; + aim(round, half); + const r = stack.drop(round, still); + assert.equal(r.perfect, false); + assert.equal(r.miss, false); + assert.ok(Math.abs(r.kept - half) < 1e-9 && Math.abs(r.sliced - half) < 1e-9, "half kept, half sliced"); + assert.ok(Math.abs(stackTop(round).x - (left + half)) < 1e-9, "the kept part is the part over the block below"); + assert.equal(round.slider.w, stackTop(round).w, "the next block is as narrow"); + assert.equal(round.streak, 0); + const [drop] = stackEvents(round, "drop"); + assert.equal(drop.piece.dir, 1, "the overhang falls off the right"); + assert.ok(Math.abs(drop.piece.x - (left + stack.BASE_W)) < 1e-9); + // The other way: the overhang is on the left. + aim(round, -1); + stack.drop(round, still); + assert.equal(stackEvents(round, "drop")[1].piece.dir, -1); +}); + +test("Stack Deploy: a drop with no overlap misses, holds for the outro, then ends the round", () => { + const round = aim(stack.newRound(still), stack.BASE_W + 1); + const r = stack.drop(round, still); + assert.deepEqual(r, { kept: 0, sliced: stack.BASE_W, perfect: false, miss: true }); + assert.equal(round.lost, true); + assert.equal(round.slider, null); + assert.equal(round.floor, 0, "a miss is no floor"); + assert.equal(stack.drop(round, still), null, "nothing left to drop"); + assert.equal(stack.advance(round, stack.OUTRO_MS - 10), "running", "the tower is shown first"); + assert.equal(stack.advance(round, 20), "over"); + // A sliver thinner than MIN_W is a miss too. + const thin = aim(stack.newRound(still), stack.BASE_W - stack.MIN_W / 2); + assert.equal(stack.drop(thin, still).miss, true); +}); + +test("Stack Deploy: three perfects in a row grow the block back, never past the base, and a gold perfect grows it twice as much", () => { + const round = aim(stack.newRound(still), 0); + stack.drop(round, still); + aim(round, 10); + stack.drop(round, still); + const narrow = stackTop(round).w; + assert.ok(Math.abs(narrow - (stack.BASE_W - 10)) < 1e-9); + for (let i = 0; i < 2; i++) { + aim(round, 0); + stack.drop(round, still); + assert.equal(stackTop(round).w, narrow, "no growth before the third"); + } + aim(round, 0); + stack.drop(round, still); + assert.ok(Math.abs(stackTop(round).w - (narrow + stack.GROW)) < 1e-9, "the third grows it"); + assert.equal(round.slider.w, stackTop(round).w, "and the next block is as wide"); + assert.ok(stackEvents(round, "perfect").at(-1).grew > 0); + // Gold: twice the growth and the gold bonus. + round.slider.gold = true; + aim(round, 0); + const before = { w: stackTop(round).w, score: round.score }; + stack.drop(round, still); + assert.ok(Math.abs(stackTop(round).w - (before.w + stack.GROW * 2)) < 1e-9); + assert.equal(round.score - before.score, stack.FLOOR_POINTS + stack.PERFECT_POINTS * 4 + stack.GOLD_POINTS); + // At the base's width, growing does nothing, and the block stays on the board. + for (let i = 0; i < 12; i++) stack.drop(aim(round, 0), still); + assert.equal(stackTop(round).w, stack.BASE_W, "never past the base"); + assert.equal(stack.grow(round), 0); + const edge = stackTop(round); + edge.x = 0; + edge.w = 10; + stack.grow(round, 6); + assert.ok(edge.x >= 0 && edge.x + edge.w <= stack.W, "a grow by the wall stays on the board"); +}); + +test("Stack Deploy: the run multiplies the perfect bonus up to x5, and the drop's pitch climbs with it", () => { + const round = stack.newRound(still); + const gains = []; + for (let i = 0; i < 7; i++) { + const before = round.score; + stack.drop(aim(round, 0), still); + gains.push(round.score - before); + } + assert.deepEqual(gains, [1, 2, 3, 4, 5, 5, 5].map((k) => stack.FLOOR_POINTS + stack.PERFECT_POINTS * k)); + assert.equal(round.bestStreak, 7); + assert.equal(stack.comboPitch(0), 1); + assert.ok(stack.comboPitch(1) > stack.comboPitch(0) && stack.comboPitch(7) === 2, "a step a perfect, an octave at seven"); + assert.equal(stack.comboPitch(99), stack.comboPitch(14), "and it tops out"); +}); + +test("Stack Deploy: the slide is steady to floor 9, 2% quicker a floor from 10, stops at the cap, and faster again from 90", () => { + assert.equal(stack.speedAt(1), stack.speedAt(9)); + assert.ok(stack.speedAt(10) > stack.speedAt(9)); + for (let f = 10; f < 55; f++) assert.ok(stack.speedAt(f + 1) > stack.speedAt(f), `floor ${f + 1} is quicker`); + assert.ok(Math.abs(stack.speedAt(11) / stack.speedAt(10) - 1.02) < 1e-9); + assert.equal(stack.speedAt(70), stack.speedAt(89), "capped"); + assert.ok(stack.speedAt(90) > stack.speedAt(89)); + assert.equal(stack.speedAt(90), stack.speedAt(200)); +}); + +test("Stack Deploy: twists and styles arrive by floor and are announced once, and sides take turns until the mix-up", () => { + assert.deepEqual(stack.twistsAt(1), ["plain"]); + assert.deepEqual(stack.twistsAt(30), ["plain", "ramp", "turn", "lag"]); + assert.ok(stack.twistsAt(40).includes("wind")); + assert.deepEqual([1, 24, 25, 50, 75].map((f) => stack.styleAt(f).id), ["racks", "racks", "offices", "glass", "rockets"]); + assert.equal(stack.styleAt(0).id, "racks", "the base is a rack"); + const round = stack.newRound(still); + const sides = []; + for (let i = 0; i < 6; i++) { + const s = round.slider; + sides.push(s.dir); + assert.equal(s.x, s.dir > 0 ? 0 : stack.W - s.w, "each starts at its own wall"); + stack.drop(aim(round, 0), still); + } + assert.deepEqual(sides, [1, -1, 1, -1, 1, -1], "left, right, left..."); + // Straight to floor 9, then floor 10 announces its twist and floor 25 its style. + round.floor = 9; + round.events.length = 0; + stack.spawnBlock(round, still); + assert.deepEqual(stackEvents(round, "twist").map((e) => e.id), ["ramp"]); + round.floor = 10; + stack.spawnBlock(round, still); + assert.equal(stackEvents(round, "twist").length, 1, "only on the floor it starts"); + round.floor = 24; + stack.spawnBlock(round, still); + assert.deepEqual(stackEvents(round, "style").map((e) => e.id), ["offices"]); + // From 20 the side is a toss: with a random under a half, it comes from the left twice running. + round.floor = 30; + const low = () => 0.1; + stack.spawnBlock(round, low); + stack.spawnBlock(round, low); + assert.equal(round.slider.dir, 1); + assert.equal(round.slider.x, 0); +}); + +test("Stack Deploy: from floor 20 a block may turn back partway, and from 30 a lag spike holds it for LAG_MS, then it jumps", () => { + const round = stack.newRound(still); + round.floor = 29; + const low = () => 0.1; + const s = stack.spawnBlock(round, low); + assert.ok(s.turnAt !== null && s.lagAt !== null, "a low random turns it back and spikes it"); + // Narrow and from the left wall, so no wall is met before the jump. + Object.assign(s, { turnAt: null, w: 8, x: 0, dir: 1 }); + stack.advance(round, s.lagAt - 1); + const at = s.x; + stack.advance(round, stack.LAG_MS - 10); + assert.ok(stack.frozen(s), "frozen"); + assert.ok(Math.abs(s.x - at) < s.speed * 0.01, "and still"); + stack.advance(round, 20); + assert.equal(stack.frozen(s), false); + assert.ok(s.x - at > s.speed * ((stack.LAG_MS - 20) / 1000), "it jumped to where it would have been"); + assert.equal(stackEvents(round, "lag").length, 1); + // A turn back: it reverses before it reaches the far wall. + const turner = stack.newRound(still); + turner.floor = 25; + const t = stack.spawnBlock(turner, low); + t.lagAt = null; + const from = t.dir; + stack.advance(turner, (t.turnAt * (stack.W - t.w) * 1000) / t.speed + 30); + assert.equal(t.dir, -from, "it turned back"); + assert.ok(t.x > 0 && t.x < stack.W - t.w, "partway across"); +}); + +test("Stack Deploy: the perfect zone is 3% of the block, at least the slide in PERFECT_MS, never under the screen's floor and never over half the block", () => { + const round = stack.newRound(still); + const s = round.slider; + assert.equal(stack.zoneOf(round), Math.max(s.w * stack.PERFECT, (s.speed * stack.PERFECT_MS) / 1000)); + s.w = 2; + assert.equal(stack.zoneOf(round), (s.speed * stack.PERFECT_MS) / 1000, "a narrow block keeps a zone it can be timed into"); + s.w = 10; + round.minZone = 3; + assert.equal(stack.zoneOf(round), 3); + assert.equal(stack.isPerfect(round, 2.9), true); + assert.equal(stack.isPerfect(round, -3.1), false); + s.w = 2; + assert.equal(stack.zoneOf(round), 1, "half the block at most"); +}); + +test("Stack Deploy: a narrow, fast block dropped clear of the tower misses, however wide its zone would be", () => { + const round = stack.newRound(still); + round.floor = 59; + stackTop(round).w = 0.5; + const s = stack.spawnBlock(round, still); + assert.ok((s.speed * stack.PERFECT_MS) / 1000 > s.w, "the slide in PERFECT_MS is wider than the block"); + round.minZone = 1; + aim(round, 0.6); + const r = stack.drop(round, still); + assert.equal(r.miss, true, "no overlap ends the round"); + assert.equal(r.perfect, false); + assert.equal(round.streak, 0); + // Just inside half the block still snaps on. + const near = stack.newRound(still); + near.floor = 59; + stackTop(near).w = 0.5; + stack.spawnBlock(near, still); + aim(near, 0.24); + assert.equal(stack.drop(near, still).perfect, true); +}); + +test("Stack Deploy: gold blocks turn up only from GOLD_FROM", () => { + const round = stack.newRound(still); + const low = () => 0.01; + round.floor = stack.GOLD_FROM - 2; + assert.equal(stack.spawnBlock(round, low).gold, false, "never before"); + round.floor = stack.GOLD_FROM - 1; + assert.equal(stack.spawnBlock(round, low).gold, true, "a low random from there on"); + assert.equal(stack.spawnBlock(round, still).gold, false, "and only now and then"); +}); + +test("Stack Deploy: every pill's text reads at 4.5:1 on its backing and its tint, the run of perfects included, in light and dark under every highlight", () => { + checkPills(stack.default, { + setup: (r) => { + r.streak = 2; + }, + expect: ["FLOOR", "~x2 PERFECT"], + }); +}); + +test("Stack Deploy game: a press drops the block where it is drawn, waits for a first tick after a start or a play-on, and a pause holds the block still", () => { + const { canvas, calls } = stubCanvas(); + const g = stack.default.create({ canvas }); + assert.equal(g.resize(stack.W * 10, stack.H * 10), true); + g.key("action"); + assert.equal(g.state, "running"); + g.key("action"); + assert.equal(g.round.floor, 0, "the key that starts a round never also drops"); + g.tick(16); + const x = g.round.slider.x; + assert.ok(x > 0); + g.key("up"); + assert.equal(g.round.floor, 1, "up drops"); + const kept = g.round.blocks[1]; + assert.ok(Math.abs(kept.x + kept.w - Math.min(x + stack.BASE_W, g.round.blocks[0].x + stack.BASE_W)) < 1e-9, "at the place it was drawn"); + g.tick(16); + aim(g.round, 0); + assert.equal(g.pointer("down", 10, 10), true, "a press on the board drops too"); + assert.equal(g.round.floor, 2); + assert.equal(g.pointer("move", 10, 10), false); + g.tick(40); + g.pause(); + const held = { x: g.round.slider.x, calls: calls.count }; + g.tick(5000); + assert.deepEqual({ x: g.round.slider.x, calls: calls.count }, held, "paused, nothing moves"); + g.resume(); + g.key("up"); + assert.equal(g.round.floor, 2, "an arrow that plays on does not drop"); + g.tick(16); + assert.ok(Math.abs(g.round.slider.x - held.x) <= g.round.slider.speed * 0.017, "it picks up where it was"); + assert.equal(g.key("left"), false, "no use for steering"); + assert.equal(g.resize(stack.W * stack.MIN_CELL - 1, 600), false, "too narrow to play"); +}); + +test("Stack Deploy game: a held up drops once until it is let go, and a resize sets the on-screen floor of the perfect zone", () => { + const { canvas } = stubCanvas(); + const g = stack.default.create({ canvas }); + assert.equal(g.resize(stack.W * 10, stack.H * 10), true); + assert.equal(g.round.minZone, stack.MIN_ZONE_PX / 10, "MIN_ZONE_PX in units at 10 px a unit"); + g.key("action"); + g.tick(16); + aim(g.round, 0); + g.key("up"); + assert.equal(g.round.floor, 1); + g.tick(16); + aim(g.round, 0); + assert.equal(g.key("up"), true, "a key repeat is taken"); + assert.equal(g.round.floor, 1, "but drops nothing"); + g.release("up"); + g.tick(16); + aim(g.round, 0); + assert.equal(g.key("up", true), true, "a repeat the window marks is taken"); + assert.equal(g.round.floor, 1, "but drops nothing, even with up let go (held through the countdown)"); + g.key("up"); + assert.equal(g.round.floor, 2, "a fresh press drops"); + assert.equal(g.resize(stack.W * 20, stack.H * 20), true); + assert.equal(g.round.minZone, stack.MIN_ZONE_PX / 20); +}); + +test("Stack Deploy game: the start screen names the style reached once, past the rockets too, and squeezes its lines to the board", () => { + const texts = []; + const ctx = new Proxy({}, { + get: (target, name) => (name in target ? target[name] : name === "fillText" ? (text, x, y, max) => texts.push({ text, max }) : () => {}), + set: (target, name, value) => { target[name] = value; return true; }, + }); + const g = stack.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo: { get: () => 80, set() {} } }); + assert.equal(g.resize(stack.W * 10, stack.H * 10), true); + const line = texts.find((t) => t.text.startsWith("Highest floor 80")); + assert.ok(line, "the start screen names the highest floor"); + assert.equal(line.text, "Highest floor 80: you have reached the rockets. Now beat your best!"); + assert.ok(line.max > 0 && line.max <= stack.W * 10, "kept within the board"); +}); + +test("Stack Deploy game: passing the highest floor ever reached sounds the fanfare once", () => { + const { canvas } = stubCanvas(); + const tones = []; + const memo = { get: () => 2, set() {} }; + const g = stack.default.create({ canvas, memo, tone: (name) => tones.push(name) }); + g.resize(800, 600); + g.key("action"); + g.tick(16); + for (let i = 0; i < 5; i++) { + aim(g.round, 0); + g.key("action"); + g.tick(16); + assert.equal(tones.filter((n) => n === "ace").length, g.round.floor > 2 ? 1 : 0, `at floor ${g.round.floor}`); + } +}); + +test("Stack Deploy game: a miss ends the round after the outro with onScore once, and the memo keeps the highest floor, only ever growing", () => { + const { canvas, calls } = stubCanvas(); + let saved = 3; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = stack.default.create({ canvas, memo, onScore: (n) => scores.push(n) }); + assert.equal(g.resize(800, 600), true); + assert.ok(calls.count > 0, "the start screen draws"); + assert.equal(saved, 3, "nothing is written by just opening it"); + const climb = (floors) => { + g.key("action"); + g.tick(16); + for (let i = 0; i < floors; i++) { + aim(g.round, 0); + g.key("action"); + g.tick(16); + } + aim(g.round, stack.BASE_W + 2); + g.key("action"); + assert.equal(g.round.lost, true); + g.tick(stack.OUTRO_MS / 2); + assert.equal(g.state, "running", "the outro plays first"); + g.tick(stack.OUTRO_MS); + assert.equal(g.state, "over"); + }; + climb(5); + assert.equal(scores.length, 1); + assert.equal(scores[0], g.score); + assert.equal(saved, 5, "the highest floor"); + g.tick(1000); + assert.equal(scores.length, 1, "once"); + climb(2); + assert.equal(saved, 5, "a lower round leaves it"); + assert.equal(scores.length, 2); + // A pause mid-round keeps a new height too. + g.key("action"); + g.tick(16); + for (let i = 0; i < 7; i++) { + aim(g.round, 0); + g.key("action"); + g.tick(16); + } + g.pause(); + assert.equal(saved, 7); +}); + +/* ------------------------------------------------------ Bumper Ring rules */ + +// A fixed random source: no rival ever misjudges by chance (one at +// sharpness 0.3 needs a roll under 0.084) and every spread lands mid-way. +const calm = () => 0.5; + +// A heat at `arena`, past its hold, with only the cars asked for kept (by +// their spot in the arena's lineup, you first), each rival left thinking on +// its own unless `still` says otherwise. +function ring(arena = 1, keep = null, { still = true } = {}) { + const round = bumper.newRound(calm); + round.level = arena; + bumper.newHeat(round, calm, 0); + bumper.advance(round, 4, calm); + assert.equal(round.phase, "fight"); + if (keep) round.cars = keep.map((i) => round.cars[i]); + if (still) for (const c of round.cars) if (c.id !== 0) Object.assign(c, { think: 1e9, push: { x: 0, y: 0 } }); + round.events.length = 0; + return round; +} + +const put = (car, x, y, vx = 0, vy = 0) => Object.assign(car, { x, y, vx, vy }); + +// A heat with you and one rival parked in the dead middle as a ghost, where +// no floor moves it and nothing hits it, so the heat stays on. +function alone(arena) { + const round = ring(arena, [0, 1]); + put(round.cars[1], bumper.CX, bumper.CY); + round.cars[1].fx.ghost = 1e9; + return round; +} +const bumpEvents = (round, type) => round.events.filter((e) => e.type === type); +const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps; + +test("Bumper Ring: a round opens on the Training Mat with three lives, two dashes and the Bully across the ring", () => { + const round = bumper.newRound(calm); + assert.equal(round.level, 1); + assert.equal(round.lives, bumper.START_LIVES); + assert.equal(round.phase, "ready"); + assert.equal(round.R, bumper.RING_R); + assert.deepEqual(round.cars.map((c) => c.kind), ["planny", "bully"]); + const [you, bully] = round.cars; + assert.equal(you.charges, bumper.START_CHARGES); + assert.ok(you.y > bumper.CY && bully.y < bumper.CY, "you at the bottom, the Bully at the top"); + for (const c of round.cars) assert.ok(bumper.edgeGap(round, c.x, c.y) > 20, "everyone starts well clear of the edge"); + assert.equal(bumper.ARENAS[1].title, "Training Mat"); +}); + +test("Bumper Ring: two equal cars meeting head-on bounce back evenly, and nobody is the rammer", () => { + const round = ring(1); + const [a, b] = round.cars; + put(a, 60, 50, 40, 0); + put(b, 60 + bumper.CAR_R * 2 - 0.5, 50, -40, 0); + const hit = bumper.collide(a, b); + assert.equal(hit.rammer, null); + assert.ok(near(hit.speed, 80)); + assert.ok(near(a.vx, -b.vx), "the same speed back each way"); + assert.ok(near(b.vx, 40 * bumper.BOUNCE), "restitution BOUNCE"); + assert.ok(near(a.x + b.x, 120 + bumper.CAR_R * 2 - 0.5), "pushed apart evenly"); + assert.ok(near(b.x - a.x, bumper.CAR_R * 2), "until they just touch"); +}); + +test("Bumper Ring: the faster car rams, giving SHOVE_BONUS more and taking that much less back, and a slow lean is no hit at all", () => { + const round = ring(1); + const [a, b] = round.cars; + put(a, 60, 50, 50, 0); + put(b, 67.9, 50, -20, 0); + const hit = bumper.collide(a, b); + assert.equal(hit.rammer, a); + const j = ((1 + bumper.BOUNCE) * 70) / 2; + assert.ok(near(b.vx, -20 + j * (1 + bumper.SHOVE_BONUS))); + assert.ok(near(a.vx, 50 - j * (1 - bumper.SHOVE_BONUS))); + assert.ok(a.vx > 0, "the rammer follows through"); + assert.ok(b.vx > 50, "the one rammed flies off faster than the rammer came in"); + // Leaning in under IMPACT_SPEED: no bounce and no shove, they just move as one. + put(a, 60, 50, 6, 0); + put(b, 67.9, 50, 0, 0); + const lean = bumper.collide(a, b); + assert.equal(lean.rammer, null); + assert.ok(near(a.vx, 3) && near(b.vx, 3)); + // Apart, nothing happens. + put(b, 80, 50, 0, 0); + assert.equal(bumper.collide(a, b), null); +}); + +test("Bumper Ring: a dash beats a Turtle holding its ground only with Heavy or Spring", () => { + const run = (power) => { + const round = ring(2, [0, 2]); + const [you, turtle] = round.cars; + assert.equal(turtle.kind, "turtle"); + const x = bumper.CX + bumper.RING_R - 9; + put(turtle, x, bumper.CY); + turtle.push = { x: -1, y: 0 }; + put(you, x - you.r - turtle.r - 0.01, bumper.CY); + if (power) bumper.applyPower(round, you, power); + assert.equal(bumper.dash(round, you, { x: 1, y: 0 }), true); + bumper.advance(round, 2000, calm); + return turtle.alive; + }; + assert.equal(run(null), true, "a plain dash leaves it on the ring"); + assert.equal(run("heavy"), false, "Heavy shoves it off"); + assert.equal(run("spring"), false, "so does Spring"); + assert.ok(bumper.massOf({ mass: 1.6, fx: {}, dashMs: 0 }) < bumper.massOf({ mass: 1, fx: { heavy: 1 }, dashMs: 1 }), "a dashing Heavy car outweighs a Turtle"); +}); + +test("Bumper Ring: a car at the edge heading out falls, one teetering can still be pushed back in, and a Shield bounces it back once", () => { + const round = ring(1); + const [you, bully] = round.cars; + put(bully, bumper.CX - bumper.RING_R + 1, bumper.CY, -30, 0); + put(you, bumper.CX, bumper.CY + 20); + bumper.advance(round, 200, calm); + assert.equal(bully.alive, false); + assert.equal(bumpEvents(round, "fall").length, 1); + assert.equal(bumper.outOfRing(round, bully), true); + + // Crawling out in the teeter band with the arrows pushing back in: saved. + const r2 = alone(1); + const [me] = r2.cars; + put(me, bumper.CX + bumper.RING_R - 2, bumper.CY, 12, 0); + r2.input.left = true; + bumper.advance(r2, 600, calm); + assert.equal(me.alive, true); + assert.ok(me.x < bumper.CX + bumper.RING_R - 2, "back in"); + assert.equal(bumpEvents(r2, "teeter").length, 1, "the teeter is noted once"); + assert.equal(r2.close, true, "and the heat is no longer flawless"); + + const r3 = ring(1); + const [, b3] = r3.cars; + bumper.applyPower(r3, b3, "shield"); + put(b3, bumper.CX - bumper.RING_R + 0.5, bumper.CY, -40, 0); + bumper.advance(r3, 40, calm); + assert.equal(b3.alive, true); + assert.equal(b3.shield, false, "used up"); + assert.ok(b3.vx > 0, "bounced back in"); + assert.equal(bumpEvents(r3, "saved").length, 1); +}); + +test("Bumper Ring: a knockout is the last toucher's within CREDIT_MS, and nobody's after it", () => { + const round = ring(3); + const fallen = round.cars[2]; + round.clock = 10000; + fallen.touch = { by: 0, via: null, at: round.clock - bumper.CREDIT_MS + 1 }; + let ko = bumper.creditKo(round, fallen); + assert.equal(ko.by, 0); + assert.equal(ko.points, bumper.KO_POINTS * 3, "times the arena"); + assert.equal(round.score, bumper.KO_POINTS * 3); + fallen.touch = { by: 1, via: null, at: round.clock - 100 }; + ko = bumper.creditKo(round, fallen); + assert.equal(ko.by, 1, "a rival's knockout"); + assert.equal(ko.points, 0, "scores you nothing"); + fallen.touch = { by: 1, via: 0, at: round.clock - 100 }; + assert.equal(bumper.creditKo(round, fallen).by, 0, "your hit carried through a rival: yours"); + fallen.touch = { by: 0, via: null, at: round.clock - bumper.CREDIT_MS - 1 }; + fallen.target = null; + ko = bumper.creditKo(round, fallen); + assert.equal(ko.by, null, "too long ago: nobody's"); + assert.equal(ko.points, 0); + // A touch is noted on both cars by a collision. + const r2 = ring(1); + const [you, bully] = r2.cars; + put(you, 60, 50, 40, 0); + put(bully, 67.5, 50); + bumper.advance(r2, 4, calm); + assert.equal(bully.touch.by, 0); + assert.equal(you.touch.by, bully.id); +}); + +test("Bumper Ring: knockouts within COMBO_MS step a combo up to x5, two within DOUBLE_MS both count twice, and a rival that falls chasing you untouched is bait", () => { + const round = ring(1); + const fallen = round.cars[1]; + const ko = (at) => { + round.clock = at; + fallen.touch = { by: 0, via: null, at }; + return bumper.creditKo(round, fallen); + }; + let k = ko(5000); + assert.deepEqual([k.combo, k.points, k.double], [1, 10, false]); + k = ko(5500); + assert.deepEqual([k.combo, k.points, k.double], [2, 40, true], "x2 combo, x2 double"); + assert.equal(round.score, 10 + 10 + 40, "the first KO counted again"); + k = ko(6000); + assert.deepEqual([k.combo, k.points, k.double], [3, 60, true], "a third within DOUBLE_MS doubles too"); + assert.equal(round.score, 10 + 10 + 40 + 60, "but the second, already doubled, is not paid again"); + k = ko(8500); + assert.deepEqual([k.combo, k.points, k.double], [4, 40, false]); + for (let i = 1; i <= 3; i++) k = ko(8500 + i * 3000); + assert.equal(k.combo, bumper.MAX_COMBO, "capped"); + k = ko(8500 + 4 * 3000 + bumper.COMBO_MS + 1); + assert.equal(k.combo, 1, "a slow one starts again"); + assert.equal(round.kos, 8); + assert.equal(round.bestCombo, bumper.MAX_COMBO); + // Bait: nobody touched it, and it was after you. + const before = round.score; + fallen.touch = null; + fallen.target = 0; + k = bumper.creditKo(round, fallen); + assert.equal(k.bait, true); + assert.equal(round.score - before, bumper.BAIT_POINTS); + fallen.target = null; + assert.equal(bumper.creditKo(round, fallen).bait, false, "one that was after nobody is not"); +}); + +test("Bumper Ring: a heat is won when one car is left, the next arena follows, and a fall costs a life and reruns the same arena", () => { + const round = ring(1); + const [you, bully] = round.cars; + put(bully, bumper.CX + bumper.RING_R + 2, bumper.CY); + bumper.advance(round, 8, calm); + assert.equal(round.phase, "done"); + assert.equal(round.result, "win"); + const win = bumpEvents(round, "win")[0]; + assert.equal(win.flawless, true); + assert.equal(win.points, bumper.WIN_POINTS + bumper.FLAWLESS_POINTS); + assert.equal(round.heatsWon, 1); + bumper.advance(round, bumper.DONE_MS, calm); + assert.equal(round.level, 2); + assert.equal(bumpEvents(round, "level")[0].level, 2); + assert.equal(round.cars.length, 3, "a Turtle joins"); + + bumper.advance(round, bumper.READY_MS, calm); + round.events.length = 0; + put(round.cars[0], bumper.CX, bumper.CY + bumper.RING_R + 2); + bumper.advance(round, 8, calm); + assert.equal(round.result, "lose"); + assert.equal(round.lives, bumper.START_LIVES - 1); + bumper.advance(round, bumper.DONE_MS, calm); + assert.equal(round.level, 2, "the same arena again"); + assert.equal(bumpEvents(round, "retry").length, 1); + assert.equal(round.cars.every((c) => c.alive), true, "everyone back on"); + for (let life = round.lives; life > 0; life--) { + bumper.advance(round, bumper.READY_MS, calm); + put(round.cars[0], bumper.CX, bumper.CY + bumper.RING_R + 2); + bumper.advance(round, 8 + bumper.DONE_MS, calm); + } + assert.equal(round.over, true, "the last life ends the round"); + assert.equal(you.alive, true, "the first heat's car was left behind"); +}); + +test("Bumper Ring: you and the last rival off together is a draw, and nobody loses a life", () => { + const round = ring(1); + const [you, bully] = round.cars; + put(you, bumper.CX, bumper.CY + bumper.RING_R + 1); + put(bully, bumper.CX, bumper.CY - bumper.RING_R - 1); + bumper.advance(round, 4, calm); + assert.equal(round.result, "draw"); + assert.equal(round.lives, bumper.START_LIVES); + bumper.advance(round, bumper.DONE_MS, calm); + assert.equal(round.level, 1); +}); + +test("Bumper Ring: the ring holds for SHRINK_START_MS, shrinks SHRINK_STEP a step after a warning, holds at MIN_RING, then sudden death takes it to LAST_RING", () => { + const round = ring(2); + const every = bumper.ARENAS[2].shrinkMs; + assert.equal(bumper.shrinkAt(round, 0), bumper.RING_R); + assert.equal(bumper.shrinkAt(round, bumper.SHRINK_START_MS - 1), bumper.RING_R); + assert.equal(bumper.shrinkAt(round, bumper.SHRINK_START_MS), bumper.RING_R - bumper.SHRINK_STEP); + assert.equal(bumper.shrinkAt(round, bumper.SHRINK_START_MS + every), bumper.RING_R - 2 * bumper.SHRINK_STEP); + assert.equal(bumper.nextShrinkIn(round, 1000), bumper.SHRINK_START_MS - 1000); + let t = bumper.SHRINK_START_MS; + while (bumper.shrinkAt(round, t) > bumper.MIN_RING) t += every; + assert.equal(bumper.shrinkAt(round, t), bumper.MIN_RING); + assert.equal(bumper.suddenDeath(round, t), false); + assert.equal(bumper.shrinkAt(round, t + bumper.SUDDEN_MS - 1), bumper.MIN_RING, "the floor holds a while"); + assert.equal(bumper.shrinkAt(round, t + bumper.SUDDEN_MS), bumper.MIN_RING - 1); + assert.equal(bumper.suddenDeath(round, t + bumper.SUDDEN_MS), true); + assert.equal(bumper.shrinkAt(round, t + 600000), bumper.LAST_RING); + assert.equal(bumper.nextShrinkIn(round, t + 600000), Infinity); + assert.ok(bumper.LAST_RING < bumper.CAR_R, "two touching cars can no longer both be on"); + assert.ok(bumper.arenaFor(1).shrinkMs > bumper.arenaFor(5).shrinkMs && bumper.arenaFor(9).shrinkMs < bumper.arenaFor(5).shrinkMs, "slow at first, faster in the final"); + + // Played through: a warning, then the step, and a car on the band falls. + const r2 = ring(2, [0, 1]); + const [you, bully] = r2.cars; + put(you, bumper.CX, bumper.CY); + put(bully, bumper.CX + bumper.RING_R - 1, bumper.CY); + bully.push = { x: 0, y: 0 }; + r2.clock = bumper.SHRINK_START_MS - bumper.SHRINK_WARN_MS - 10; + bumper.advance(r2, 20, calm); + assert.equal(bumpEvents(r2, "warn").length, 1); + bumper.advance(r2, bumper.SHRINK_WARN_MS, calm); + assert.equal(bumpEvents(r2, "shrink").length, 1); + assert.equal(r2.R, bumper.RING_R - bumper.SHRINK_STEP); + assert.equal(bully.alive, false, "caught on the band that dropped"); +}); + +test("Bumper Ring: rivals winding up a dash let go of the push first, then dash after WINDUP_MS at their sharpness", () => { + const round = ring(1, null, { still: false }); + const [you, bully] = round.cars; + put(you, bumper.CX, bumper.CY); + put(bully, bumper.CX, bumper.CY - 14, 0, 40); + bully.think = 0; + bully.charges = 1; + // A roll of 0 passes every chance, so the Bully at 14 units, closing, dashes. + bumper.advance(round, 4, () => 0); + assert.equal(bumpEvents(round, "windup").length, 1); + assert.ok(bully.windup > 0); + assert.deepEqual(bully.push, { x: 0, y: 0 }, "it lets go and revs"); + const wind = bumper.WINDUP_MS - (bumper.WINDUP_MS - 200) * bumper.ARENAS[1].smart; + bumper.advance(round, Math.floor(wind / 4) * 4 - 8, calm); + assert.equal(bumpEvents(round, "dash").length, 0, "not yet"); + bumper.advance(round, 16, calm); + assert.equal(bumpEvents(round, "dash").length, 1); + assert.equal(bumpEvents(round, "dash")[0].id, bully.id); + assert.equal(bully.charges, 0); +}); + +test("Bumper Ring: a sharp rival calls a wind-up off when it finds itself by the edge, keeping its charge", () => { + const round = ring(1); + const bully = round.cars[1]; + put(bully, bumper.CX + bumper.RING_R - 4, bumper.CY); + Object.assign(bully, { windup: 200, windDir: { x: -1, y: 0 }, charges: 1, blind: 0 }); + bumper.advance(round, 4, calm); + assert.equal(bully.windup, 0, "called off"); + assert.equal(bumpEvents(round, "dash").length, 0, "no dash"); + assert.equal(bully.charges, 1, "the charge is kept"); +}); + +test("Bumper Ring: a spent dash comes back after RECHARGE_MS, never past MAX_CHARGES, only in a fight, and a full car banks nothing", () => { + const round = ring(1, [0, 1]); + const [you, bully] = round.cars; + put(you, bumper.CX, bumper.CY + 10); + put(bully, bumper.CX, bumper.CY - 15); + assert.equal(bully.charges, 1, "a rival starts a heat with one"); + Object.assign(you, { charges: 1, recharge: 0 }); + bully.recharge = 0; + bumper.advance(round, bumper.RECHARGE_MS - 4, calm); + assert.equal(you.charges, 1, "not yet"); + assert.equal(bumpEvents(round, "charge").length, 0); + bumper.advance(round, 4, calm); + assert.equal(you.charges, 2); + assert.deepEqual(bumpEvents(round, "charge").map((e) => e.charges), [2], "one charge event, yours only"); + assert.equal(bully.charges, 2, "rivals recharge too, silently"); + + Object.assign(you, { charges: bumper.MAX_CHARGES, recharge: 0 }); + bumper.advance(round, bumper.RECHARGE_MS, calm); + assert.equal(you.charges, bumper.MAX_CHARGES, "never past the max"); + + // A Charge pad on a nearly refilled car: the bank empties at the max. + Object.assign(you, { charges: bumper.MAX_CHARGES - 1, recharge: bumper.RECHARGE_MS - 500 }); + bumper.applyPower(round, you, "charge"); + bumper.advance(round, 4, calm); + assert.equal(you.recharge, 0); + you.charges -= 1; + bumper.advance(round, 400, calm); + assert.equal(you.charges, bumper.MAX_CHARGES - 1, "the spent charge refills from empty"); + + round.phase = "ready"; + round.phaseMs = 1e9; + Object.assign(you, { charges: 1, recharge: 0 }); + bumper.advance(round, bumper.RECHARGE_MS, calm); + assert.equal(you.charges, 1, "no recharge before the heat starts"); +}); + +test("Bumper Ring: a heat where nobody pushes still ends, the ring shrinking through sudden death, in a plain arena and a busy one", () => { + for (const arena of [1, 8]) { + const round = ring(arena, [0, 1]); + const [you, rival] = round.cars; + put(you, bumper.CX, bumper.CY + 6); + put(rival, bumper.CX, bumper.CY - 6); + let ms = 0; + while (round.phase !== "done" && ms < 200000) { + bumper.advance(round, 16, calm); + ms += 16; + } + assert.equal(round.phase, "done", `arena ${arena} ended`); + assert.ok(["win", "lose", "draw"].includes(round.result), `arena ${arena}: ${round.result}`); + } +}); + +test("Bumper Ring: a Turtle at the middle with nobody near holds it, and no rival at sharpness 1 pushes off the edge with nothing near it", () => { + const round = ring(2, [0, 2], { still: false }); + const [you, turtle] = round.cars; + put(you, bumper.CX, bumper.CY + 38); + put(turtle, bumper.CX + 1, bumper.CY - 1); + assert.deepEqual([bumper.aim(round, turtle, calm).x, bumper.aim(round, turtle, calm).y], [0, 0], "nothing to do"); + for (let i = 0; i < 100; i++) bumper.advance(round, 20, calm); + assert.ok(Math.hypot(turtle.x - bumper.CX, turtle.y - bumper.CY) < 4, "it never leaves the middle"); + + const sharp = ring(9); + const [me] = sharp.cars; + for (const car of sharp.cars.slice(1)) { + for (let k = 0; k < 16; k++) { + const a = (k / 16) * Math.PI * 2; + for (const gap of [1, 4, 7]) { + for (const out of [0, 25]) { + put(car, bumper.CX + Math.cos(a) * (bumper.RING_R - gap), bumper.CY + Math.sin(a) * (bumper.RING_R - gap), Math.cos(a) * out, Math.sin(a) * out); + put(me, bumper.CX - Math.cos(a) * 30, bumper.CY - Math.sin(a) * 30); + car.echo = { x: Math.cos(a), y: Math.sin(a) }; + const others = sharp.cars.filter((c) => c !== car && c !== me); + for (const [i, o] of others.entries()) put(o, bumper.CX - Math.cos(a + 0.6 + i) * 25, bumper.CY - Math.sin(a + 0.6 + i) * 25); + const choice = bumper.aim(sharp, car, () => 0.99); + assert.ok(choice.x * Math.cos(a) + choice.y * Math.sin(a) <= 1e-9, `${car.kind} at gap ${gap} pushes back in`); + assert.equal(choice.dash, false); + } + } + } + } + assert.equal(bumper.aim(sharp, sharp.cars[1], () => 0).misjudge, false, "a sharp rival never misjudges"); + // Those places are all inside the panic band; played out, each sharp rival + // alone in the Grand Final (holes, magnet, turntable, square and all), with + // you a Ghost it cannot hit, is still on the ring when the shrink begins. + for (let i = 1; i < sharp.cars.length; i++) { + const heat = ring(9, [0, i], { still: false }); + const [ghost, rival] = heat.cars; + let ms = 0; + while (ms < bumper.SHRINK_START_MS - 1000 && heat.phase === "fight") { + ghost.fx.ghost = 1e9; + bumper.advance(heat, 16, calm); + ms += 16; + } + assert.equal(rival.alive, true, `the ${rival.kind} never drives itself off`); + } + const sloppy = ring(1); + assert.equal(bumper.aim(sloppy, sloppy.cars[1], () => 0).misjudge, true, "a sloppy one can"); +}); + +test("Bumper Ring: each arena brings its rivals and its floor, and past the ninth the Grand Final repeats, sharper", () => { + const kinds = (n) => ring(n).cars.map((c) => c.kind).slice(1); + assert.deepEqual(kinds(1), ["bully"]); + assert.deepEqual(kinds(2), ["bully", "turtle"]); + assert.deepEqual(kinds(3), ["bully", "turtle", "sniper"]); + assert.deepEqual(kinds(5), ["bully", "turtle", "sniper", "scrapper"]); + assert.deepEqual(kinds(8), ["bully", "turtle", "sniper", "scrapper", "mirror"]); + const has = (n) => { + const r = ring(n); + return { bumpers: r.bumpers.length > 0, ice: r.ice.length > 0, spin: r.spin > 0, holes: r.holes.length > 0, magnet: Boolean(r.magnet) }; + }; + assert.deepEqual(has(2), { bumpers: false, ice: false, spin: false, holes: false, magnet: false }); + assert.deepEqual(has(3), { bumpers: true, ice: false, spin: false, holes: false, magnet: false }); + assert.deepEqual(has(4), { bumpers: true, ice: true, spin: false, holes: false, magnet: false }); + assert.deepEqual(has(5), { bumpers: true, ice: true, spin: true, holes: false, magnet: false }); + assert.deepEqual(has(6), { bumpers: true, ice: true, spin: true, holes: true, magnet: false }); + assert.deepEqual(has(9), { bumpers: true, ice: true, spin: true, holes: true, magnet: true }); + for (let n = 2; n <= bumper.MAX_ARENA; n++) assert.ok(bumper.ARENAS[n].smart > bumper.ARENAS[n - 1].smart, `arena ${n} is sharper`); + assert.equal(bumper.arenaFor(10).title, "Final 2"); + assert.equal(bumper.arenaFor(12).title, "Final 4"); + assert.ok(bumper.arenaFor(12).shrinkMs < bumper.arenaFor(9).shrinkMs); + assert.ok(bumper.rivalPower(12).push > bumper.rivalPower(9).push); + assert.ok(bumper.rivalPower(1).push < 1 && bumper.rivalPower(9).push === 1, "the Training Mat Bully pushes softer than you"); + assert.equal(bumper.arenaName(4), "Ice Rink (arena 4 of 9)"); + assert.equal(bumper.arenaName(11), "Final 3 (arena 11)"); +}); + +test("Bumper Ring: the Turntable carries a car round, ice lets it slide, a bumper kicks it off, and the magnet pulls then pushes", () => { + const spin = alone(5); + const [you] = spin.cars; + put(you, bumper.CX + 20, bumper.CY); + bumper.advance(spin, 1000, calm); + assert.ok(you.y > bumper.CY + 3, "carried round with the floor"); + + const coast = (onIce) => { + const r = alone(4); + r.ice = onIce ? [{ x: bumper.CX, y: bumper.CY, r: 40 }] : []; + put(r.cars[0], bumper.CX - 20, bumper.CY, 40, 0); + bumper.advance(r, 400, calm); + return r.cars[0].x; + }; + assert.ok(coast(true) > coast(false) + 4, "ice slides further"); + + const kick = alone(3); + const b = kick.bumpers[0]; + put(kick.cars[0], b.x - b.r - bumper.CAR_R + 0.5, b.y, 20, 0); + bumper.advance(kick, 4, calm); + assert.ok(kick.cars[0].vx < -20, "kicked back harder than it came"); + assert.equal(bumpEvents(kick, "bumper").length, 1); + + const mag = alone(7); + put(mag.cars[0], bumper.CX + 30, bumper.CY); + bumper.advance(mag, 200, calm); + assert.ok(mag.cars[0].vx < 0, "pulled in"); + bumper.advance(mag, 5000, calm); + assert.equal(bumpEvents(mag, "magnetWarn").length, 1); + assert.equal(bumpEvents(mag, "magnet").length, 1); + assert.equal(mag.magnet.pull, -1); + put(mag.cars[0], bumper.CX + 30, bumper.CY); + bumper.advance(mag, 200, calm); + assert.ok(mag.cars[0].vx > 0, "then pushed out"); +}); + +test("Bumper Ring: holes swallow a car only while open, and the Hall of Mirrors' square has corners the round ring does not", () => { + const round = ring(6, [0, 1]); + const [you, bully] = round.cars; + const h = round.holes[0]; + h.ms = 0; + assert.equal(bumper.holeState(h), "shut"); + put(bully, h.x, h.y); + put(you, bumper.CX, bumper.CY + 40); + bumper.advance(round, 4, calm); + assert.equal(bully.alive, true, "a shut hole is floor"); + h.ms = 4000 + bumper.HOLE_WARN_MS - 8; + assert.equal(bumper.holeState(h), "warn"); + put(bully, h.x, h.y); + bumper.advance(round, 16, calm); + assert.equal(bumper.holeState(round.holes[0]), "open"); + assert.equal(bully.alive, false); + assert.equal(bumpEvents(round, "fall")[0].hole, true); + + const hall = alone(8); + const corner = { x: bumper.CX + bumper.RING_R * 0.85, y: bumper.CY + bumper.RING_R * 0.85 }; + assert.ok(bumper.edgeGap(hall, corner.x, corner.y) < 0, "off a round ring"); + hall.shape = "square"; + assert.ok(bumper.edgeGap(hall, corner.x, corner.y) > 0, "on the square"); + // The magnet, the turn and the holes kept still, so only the shape counts. + Object.assign(hall, { magnet: null, spin: 0, holes: [], shapeMs: 0 }); + put(hall.cars[0], bumper.CX, bumper.CY + 20); + bumper.advance(hall, 7000 - bumper.SHAPE_WARN_MS + 20, calm); + assert.equal(bumpEvents(hall, "shapeWarn").length, 1, "the corners flash first"); + assert.equal(hall.shape, "square"); + put(hall.cars[0], corner.x, corner.y); + bumper.advance(hall, bumper.SHAPE_WARN_MS, calm); + assert.equal(hall.shape, "round"); + assert.equal(hall.cars[0].alive, false, "left in a corner when it went round"); +}); + +test("Bumper Ring: pads turn up from arena 2 and every power does its thing", () => { + const plain = ring(1); + bumper.advance(plain, 20000, calm); + assert.equal(plain.pads.length, 0, "none on the Training Mat"); + const padded = alone(2); + put(padded.cars[0], bumper.CX, bumper.CY); + bumper.advance(padded, 4100, calm); + assert.equal(padded.pads.length, 1, "the first pad after FIRST_PAD_MS"); + assert.ok(bumper.edgeGap(padded, padded.pads[0].x, padded.pads[0].y) >= 6); + const pad = padded.pads[0]; + put(padded.cars[0], pad.x, pad.y); + bumper.advance(padded, 4, calm); + assert.equal(padded.pads.length, 0, "driven over, taken"); + assert.equal(bumpEvents(padded, "power").length, 1); + + const round = ring(2, [0, 1]); + const [you, bully] = round.cars; + bumper.applyPower(round, you, "heavy"); + assert.equal(bumper.massOf(you), 2); + bumper.applyPower(round, you, "grow"); + bumper.advance(round, 4, calm); + assert.ok(near(you.r, bumper.CAR_R * 1.4)); + you.charges = bumper.MAX_CHARGES; + bumper.applyPower(round, you, "charge"); + assert.equal(you.charges, bumper.MAX_CHARGES, "never past the max"); + bumper.applyPower(round, you, "ghost"); + put(you, 60, 50, 40, 0); + put(bully, 63, 50); + assert.equal(bumper.collide(you, bully), null, "a Ghost passes through"); + bumper.advance(round, bumper.POWERS.ghost.ms + 10, calm); + assert.equal(bumper.has(you, "ghost"), false, "and wears off"); + bumper.applyPower(round, you, "slick"); + put(you, bumper.CX, bumper.CY); + bumper.advance(round, 500, calm); + assert.ok(round.slicks.length > 0 && round.slicks.every((s) => s.owner === you.id), "oil left behind"); + assert.deepEqual(Object.keys(bumper.POWERS).sort(), ["charge", "ghost", "grow", "heavy", "shield", "slick", "spring"]); +}); + +test("Bumper Ring: the Mirror copies your dash MIRROR_MS later", () => { + const round = ring(8, [0, 5], { still: false }); + const [you, mirror] = round.cars; + assert.equal(mirror.kind, "mirror"); + put(you, bumper.CX, bumper.CY + 10); + put(mirror, bumper.CX, bumper.CY - 10); + mirror.charges = 1; + assert.equal(bumper.dash(round, you, { x: 1, y: 0 }), true); + round.events.length = 0; + bumper.advance(round, bumper.MIRROR_MS - 20, calm); + assert.equal(bumpEvents(round, "dash").length, 0); + bumper.advance(round, 40, calm); + const copy = bumpEvents(round, "dash"); + assert.equal(copy.length, 1); + assert.equal(copy[0].id, mirror.id); + assert.ok(near(copy[0].dx, 1) && near(copy[0].dy, 0), "the same way you went"); +}); + +test("Bumper Ring: no tick moves a car through another, however long", () => { + const round = ring(1); + const [you, bully] = round.cars; + put(you, bumper.CX - 20, bumper.CY, bumper.DASH_CAP, 0); + put(bully, bumper.CX, bumper.CY); + bumper.advance(round, 500, calm); + assert.ok(bully.x > you.x, "still ahead of you"); + assert.ok(bully.touch && bully.touch.by === 0, "it was hit"); + // A car sent flying by a Spring off a heavy dash goes some 600 units a + // second: still caught in one long advance, never passed through. + const fast = ring(1); + const [me, other] = fast.cars; + put(me, bumper.CX - 30, bumper.CY, 600, 0); + put(other, bumper.CX, bumper.CY); + bumper.advance(fast, 100, calm); + assert.ok(bumpEvents(fast, "hit").some((e) => e.a === 0 && e.b === other.id), "the hit was seen"); + assert.equal(other.touch.by, 0); +}); + +test("Bumper Ring: a rival you ram into another keeps your knockout, and a long lean never stretches the carry", () => { + const round = ring(3, [0, 1, 2]); + const [you, a, b] = round.cars; + round.bumpers = []; + // You ram A; it grazes B on its way out and falls. + put(you, bumper.CX + 17.8, bumper.CY, 90, 0); + put(a, bumper.CX + 26, bumper.CY); + put(b, bumper.CX + 30, bumper.CY + 7.6); + bumper.advance(round, 400, calm); + const hits = bumpEvents(round, "hit"); + assert.ok(hits.some((e) => e.a === 0 && e.b === a.id) && hits.some((e) => e.a === a.id && e.b === b.id), "you hit A, A hit B"); + const fall = bumpEvents(round, "fall").find((e) => e.id === a.id); + assert.ok(fall, "A fell"); + assert.equal(fall.by, 0, "your knockout, not B's"); + assert.ok(fall.points > 0); + + // Two rivals leaning on each other long after your hit: the carry runs out. + const lean = ring(3, [0, 1, 2]); + const [, c, d] = lean.cars; + lean.bumpers = []; + put(c, bumper.CX - 4, bumper.CY); + put(d, bumper.CX + 3.9, bumper.CY); + c.touch = { by: 0, via: null, at: lean.clock }; + c.push = { x: 1, y: 0 }; + d.push = { x: -1, y: 0 }; + bumper.advance(lean, 1200, calm); + assert.equal(c.touch.by, d.id); + assert.equal(c.touch.via, null, "no longer carrying your hit"); + assert.equal(bumper.creditKo(lean, c).by, d.id, "so it is the leaner's"); +}); + +test("Bumper Ring: a Shield saves a car a hole opens right under, sending it back toward the middle", () => { + const round = ring(6, [0, 1]); + const [you, bully] = round.cars; + Object.assign(round, { spin: 0, magnet: null }); + const h = round.holes[0]; + round.holes = [h]; + h.ms = 4000 + bumper.HOLE_WARN_MS - 4; + put(you, h.x, h.y); + put(bully, bumper.CX + 30, bumper.CY); + you.shield = true; + bumper.advance(round, 40, calm); + assert.equal(bumper.holeState(h), "open"); + assert.equal(you.alive, true, "saved"); + assert.equal(you.shield, false, "used up"); + assert.ok(Math.hypot(you.x - h.x, you.y - h.y) > h.r, "off the hole"); + assert.ok(Math.hypot(you.x - bumper.CX, you.y - bumper.CY) < Math.hypot(h.x - bumper.CX, h.y - bumper.CY), "on the side toward the middle"); + assert.deepEqual(bumpEvents(round, "saved").length, 1); + assert.equal(bumpEvents(round, "fall").length, 0); +}); + +test("Bumper Ring: an arena's numbers are built once, not on every slice", () => { + assert.equal(bumper.arenaFor(12), bumper.arenaFor(12), "the same Final 4"); + assert.equal(bumper.rivalPower(3), bumper.rivalPower(3)); + assert.equal(bumper.rivalPower(12), bumper.rivalPower(12)); + assert.ok(Object.isFrozen(bumper.arenaFor(12)) && Object.isFrozen(bumper.rivalPower(12)), "and nobody can change them"); +}); + +test("Bumper Ring: the pills never overlap or leave the board, even on the smallest board with every power held and sudden death", () => { + const h = Math.max(14 / bumper.MIN_CELL, 2.6); + const powers = ["HEAVY", "GROW", "GHOST", "SLICK", "SPRING", "SHIELD"].map((text) => ({ text, color: "#ffffff", fill: 1 })); + for (const countdown of [null, { text: "SUDDEN DEATH", color: "#ffffff" }, { text: "RING 3", color: "#ffffff" }]) { + for (let n = 0; n <= powers.length; n++) { + const pills = hudLayout(h, bumper.W, 3, { arena: "FINAL 12", charges: 1, maxCharges: 3, recharge: 0.5, left: 5, powers: powers.slice(0, n), ring: countdown }); + assert.equal(pills.length, 4 + n + (countdown ? 1 : 0)); + for (const p of pills) assert.ok(p.x >= 0 && p.x + p.w <= bumper.W, `${p.text} stays on the board`); + for (let i = 0; i < pills.length; i++) { + for (let j = i + 1; j < pills.length; j++) { + const [p, q] = [pills[i], pills[j]]; + const apart = p.x + p.w <= q.x || q.x + q.w <= p.x || p.y + h <= q.y || q.y + h <= p.y; + assert.ok(apart, `${p.text} and ${q.text} do not overlap (${n} powers, ${countdown ? countdown.text : "no ring"})`); + } + } + } + } +}); + +/* ------------------------------------------------------- Bumper Ring game */ + +test("Bumper Ring: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives, the dash and every power included, in light and dark under every highlight", () => { + checkPills(bumper.default, { + setup: (r) => { + const you = r.cars[0]; + Object.assign(you.fx, { heavy: 2000, grow: 2000, ghost: 1000, slick: 2000 }); + you.spring = true; + you.shield = true; + }, + expect: ["ARENA 1", "♥", "DASH", "~HEAVY", "SPRING", "SHIELD"], + }); +}); + +test("Bumper Ring game: held arrows push until let go, space dashes, a pause lets go of everything, and the board refuses a tiny window", () => { + const { canvas, calls } = stubCanvas(); + const g = bumper.default.create({ canvas }); + assert.equal(g.resize(bumper.W * bumper.MIN_CELL - 1, 2000), false, "too narrow to play"); + assert.equal(g.resize(800, 600), true); + assert.ok(calls.count > 0, "the start screen draws"); + assert.equal(typeof g.release, "function"); + g.key("action"); + assert.equal(g.state, "running"); + g.tick(400); + assert.equal(g.round.phase, "fight"); + const you = g.round.cars[0]; + const y = you.y; + g.key("up"); + g.tick(200); + assert.ok(you.y < y - 2, "held up pushes up"); + g.release("up"); + assert.equal(g.round.input.up, false); + g.key("left"); + g.key("action"); + assert.equal(you.charges, bumper.START_CHARGES - 1, "space dashes"); + assert.ok(you.vx < -bumper.MAX_SPEED * 0.5, "the way you push"); + g.pause(); + assert.deepEqual(g.round.input, { up: false, down: false, left: false, right: false }, "a pause holds nothing"); + g.key("action"); + assert.equal(g.state, "running", "space plays on from a pause"); + assert.equal(you.charges, bumper.START_CHARGES - 1, "and does not also dash"); +}); + +test("Bumper Ring game: a hard hit on you holds the action still a moment, and passing the best plays the fanfare once", () => { + const { canvas } = stubCanvas(); + const tones = []; + const g = bumper.default.create({ canvas, tone: (name) => tones.push(name), best: () => 5 }); + g.resize(800, 600); + g.key("action"); + g.tick(400); + const [you, bully] = g.round.cars; + put(you, bumper.CX - 8.5, bumper.CY, 50, 0); + put(bully, bumper.CX, bumper.CY, -50, 0); + g.tick(16); + assert.ok(tones.includes("ram"), "the hit sounds"); + const clock = g.round.clock; + g.tick(16); + assert.equal(g.round.clock, clock, "held still"); + g.tick(48); + assert.ok(g.round.clock > clock, "then on again"); + g.round.score = 6; + g.tick(16); + g.tick(16); + assert.equal(tones.filter((t) => t === "best").length, 1); +}); + +test("Bumper Ring game: the start screen reads the furthest arena, the memo only grows, and the round's end calls onScore once", () => { + const { canvas, calls } = stubCanvas(); + let saved = 3; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = bumper.default.create({ canvas, memo, onScore: (n) => scores.push(n) }); + g.resize(800, 600); + assert.ok(calls.count > 0); + assert.equal(saved, 3, "nothing is written by just opening it"); + const winHeat = () => { + for (const c of g.round.cars) if (c.id !== 0) put(c, bumper.CX + Math.cos(c.id * 1.3) * (bumper.RING_R + 6), bumper.CY + Math.sin(c.id * 1.3) * (bumper.RING_R + 6)); + g.tick(16); + g.tick(bumper.DONE_MS + 16); + g.tick(bumper.READY_MS + 16); + }; + g.key("action"); + g.tick(400); + winHeat(); + assert.equal(g.round.level, 2); + assert.equal(saved, 3, "arena 2 is not past arena 3"); + winHeat(); + winHeat(); + assert.equal(g.round.level, 4); + assert.equal(saved, 4, "a new furthest"); + const loseHeat = () => { + put(g.round.cars[0], bumper.CX, bumper.CY + bumper.RING_R + 3); + g.tick(16); + g.tick(bumper.DONE_MS + 16); + g.tick(bumper.READY_MS + 16); + }; + for (let i = 0; i < bumper.START_LIVES; i++) loseHeat(); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + g.tick(1000); + assert.equal(scores.length, 1, "once"); + g.key("action"); + g.tick(400); + for (let i = 0; i < bumper.START_LIVES; i++) loseHeat(); + assert.equal(saved, 4, "a shorter round leaves it"); + assert.equal(scores.length, 2); +}); + +test("Bumper Ring game: the opening banner sits in the board from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.32)"); + const g = bumper.default.create({ canvas }); + g.resize(900, 900); + openingBanner(g, shades, bumper.H); +}); + +/* ------------------------------------------------- shared random sources */ + +// A fixed random source: every call returns the same value, so a rival never +// guesses and a sharp one always notices a threat. +const steady = () => 0.5; + +// A seeded random source, so a long run plays the same every time. +function seeded(seed) { + let s = seed >>> 0; + return () => { + s = (Math.imul(s, 1103515245) + 12345) >>> 0; + return s / 4294967296; + }; +} + +/* ------------------------------------------------------- Hot Potato rules */ + +// A match at `venue`, past its hold, every rival standing still with no dash +// left (so none reacts) unless `still` is false. The bombs stay where +// newMatch lit them. +function potato(venue = 1, { still = true, random = calm } = {}) { + const round = fuse.newRound(random); + fuse.newMatch(round, venue, random, 0); + fuse.advance(round, 8, random); + assert.equal(round.phase, "play"); + if (still) for (const r of round.runners) if (r.id !== 0) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + round.events.length = 0; + return round; +} + +// Puts a runner somewhere, standing still. +const spot = (r, x, y) => Object.assign(r, { x, y, vx: 0, vy: 0 }); +// Takes a runner out of a test's match without a blast. +const sitOut = (r) => Object.assign(r, { alive: false, out: "blast", outMs: 0 }); +// Hands `bomb` to `r` with `fuseMs` left, passable at once. +const handTo = (r, bomb, fuseMs = 8000) => Object.assign(bomb, { lit: true, holder: r.id, lock: 0, fuse: fuseMs, max: Math.max(fuseMs, bomb.max), from: null, gap: 0 }); +const fuseEvents = (round, type) => round.events.filter((e) => e.type === type); +// The Break Room's top row (y 8) is open from wall to wall. +const ROW = 8; + +test("Hot Potato: a round opens in the Break Room with three lives, two dashes, three rivals and a 12 second fuse on one of them", () => { + const round = fuse.newRound(calm); + assert.equal(round.level, 1); + assert.equal(round.lives, fuse.START_LIVES); + assert.equal(round.phase, "ready"); + assert.equal(fuse.VENUES[1].title, "Break Room"); + assert.deepEqual(round.runners.map((r) => r.kind), ["planny", "sprinter", "hider", "trickster"]); + assert.equal(round.bombs.length, 1); + const [bomb] = round.bombs; + assert.ok(bomb.lit && bomb.holder !== 0, "a rival holds it"); + assert.equal(bomb.fuse, fuse.FUSE_MS); + const you = round.runners[0]; + assert.ok(you.y > fuse.AH / 2, "you start at the bottom"); + for (const r of round.runners) { + assert.equal(r.charges, fuse.START_CHARGES); + for (const b of round.blocks) { + const nx = Math.min(Math.max(r.x, b.x), b.x + b.w); + const ny = Math.min(Math.max(r.y, b.y), b.y + b.h); + assert.ok(Math.hypot(r.x - nx, r.y - ny) >= fuse.RUNNER_R, `${r.kind} starts clear of the ${b.kind}`); + } + } + const before = bomb.fuse; + fuse.advance(round, 200, calm); + assert.equal(bomb.fuse, before, "nothing burns during the hold"); +}); + +test("Hot Potato: the first fuse of a match never starts on you, in any venue, and Two Bombs lights two", () => { + for (let v = 1; v <= fuse.MAX_VENUE + 2; v++) { + for (let seed = 1; seed <= 40; seed++) { + const random = seeded(seed * 97 + v); + const round = fuse.newRound(random); + fuse.newMatch(round, v, random); + assert.equal(round.bombs.length, fuse.venueFor(v).bombs, `venue ${v}`); + for (const b of round.bombs) assert.notEqual(b.holder, 0, `venue ${v}, seed ${seed}`); + assert.equal(new Set(round.bombs.map((b) => b.holder)).size, round.bombs.length, "each bomb on its own rival"); + } + for (const random of [() => 0, () => 0.9999]) assert.ok(fuse.newMatch(fuse.newRound(random), v, random).bombs.every((b) => b.holder !== 0)); + } +}); + +test("Hot Potato: a touch by the holder passes the bomb, which then cannot move for NO_TAGBACK_MS, nor go straight back while three are left", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + const [bomb] = round.bombs; + handTo(a, bomb); + spot(a, 30, ROW); + spot(you, 35.8, ROW); + spot(b, 90, ROW); + spot(c, 10, 62); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0, "the touch passes it"); + assert.equal(bomb.lock, fuse.NO_TAGBACK_MS); + assert.equal(round.score, 0, "a rival's pass scores you nothing"); + assert.deepEqual(fuseEvents(round, "tag").map((e) => [e.from, e.to]), [[a.id, 0]]); + spot(b, you.x + 5.8, ROW); + spot(a, 10, 35); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0, "not inside NO_TAGBACK_MS"); + spot(b, 90, ROW); + fuse.advance(round, fuse.NO_TAGBACK_MS, calm); + spot(a, you.x + 5.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0, "no tag-back to the one who passed it"); + assert.ok(fuse.tagBack(round, bomb, a)); + assert.ok(fuse.tagSafe(round, a), "and it shows as safe"); + assert.equal(fuse.tagSafe(round, b), false, "nobody else is"); + spot(a, 10, 35); + spot(b, you.x + 5.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, b.id, "anyone else takes it"); + assert.equal(round.score, fuse.PASS_POINTS, "your pass scores"); + assert.equal(round.passes, 1); +}); + +test("Hot Potato: with two left, a tag-back is fine once NO_TAGBACK_MS is over", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + sitOut(b); + sitOut(c); + const [bomb] = round.bombs; + handTo(a, bomb); + spot(a, 30, ROW); + spot(you, 35.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0); + assert.equal(fuse.tagBack(round, bomb, a), false, "two left: no tag-back rule"); + fuse.advance(round, fuse.NO_TAGBACK_MS, calm); + spot(a, you.x + 5.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, a.id); +}); + +test("Hot Potato: a pass under HOT_MS is a hot pass, hot passes in a row step the streak up to MAX_STREAK, and a cold one ends it", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + const [bomb] = round.bombs; + const passTo = (r, fuseMs) => { + for (const o of [a, b, c]) spot(o, 10 + o.id * 25, 62); + handTo(you, bomb, fuseMs); + spot(you, 40, ROW); + spot(r, 45.8, ROW); + const score = round.score; + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, r.id); + return round.score - score; + }; + assert.equal(passTo(a, 900), fuse.PASS_POINTS + fuse.HOT_POINTS); + assert.equal(round.streak, 1); + assert.equal(passTo(b, 800), fuse.PASS_POINTS + fuse.HOT_POINTS * 2); + assert.equal(round.streak, 2); + assert.equal(passTo(c, 5000), fuse.PASS_POINTS, "a cold pass is only a pass"); + assert.equal(round.streak, 0, "and ends the streak"); + round.streak = fuse.MAX_STREAK; + assert.equal(passTo(a, 500), fuse.PASS_POINTS + fuse.HOT_POINTS * fuse.MAX_STREAK); + assert.equal(round.streak, fuse.MAX_STREAK, "never past MAX_STREAK"); + assert.equal(round.bestStreak, fuse.MAX_STREAK); + assert.equal(round.hotPasses, 3); +}); + +test("Hot Potato: a pass never leaves its new holder under PASS_FLOOR_MS (the no-pass window and a reaction margin), rivals' passes and yours, a hot pass still scores as hot, and each runner is lifted once a fuse", () => { + assert.equal(fuse.PASS_FLOOR_MS, fuse.NO_TAGBACK_MS + fuse.PASS_REACT_MS); + assert.ok(fuse.PASS_REACT_MS >= 700, "time enough to reach someone once the bomb can move"); + assert.ok(fuse.PASS_FLOOR_MS > fuse.HOT_MS, "a lifted fuse can still burn down into a hot pass"); + const round = potato(1); + const [you, a, b, c] = round.runners; + const [bomb] = round.bombs; + const apart = () => { + spot(a, 10, 62); + spot(b, 90, 62); + spot(c, 50, 62); + spot(you, 50, 35); + }; + // A rival hands it to you with 0.2 s left: you get the floor, not 0.2 s. + apart(); + handTo(a, bomb, 200); + spot(a, 30, ROW); + spot(you, 35.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0); + assert.ok(bomb.fuse >= fuse.PASS_FLOOR_MS - 8 && bomb.fuse <= fuse.PASS_FLOOR_MS, `lifted to the floor (${bomb.fuse})`); + fuse.advance(round, fuse.NO_TAGBACK_MS, calm); + assert.ok(you.alive && bomb.lit && bomb.holder === 0, "still yours once it can move"); + assert.ok(bomb.fuse >= fuse.PASS_REACT_MS - 16, `with PASS_REACT_MS left to pass it (${bomb.fuse})`); + // Your hot pass lifts the rival too, and still scores as hot. + spot(b, you.x + 5.8, you.y); + const score = round.score; + bomb.fuse = 300; + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, b.id); + assert.equal(round.score - score, fuse.PASS_POINTS + fuse.HOT_POINTS, "a hot pass"); + assert.ok(fuse.tagBack(round, bomb, you)); + assert.ok(bomb.fuse >= fuse.PASS_FLOOR_MS - 8, `the rival is lifted too (${bomb.fuse})`); + // A pass with more than the floor left is not touched. + apart(); + handTo(c, bomb, 5000); + spot(c, 30, ROW); + spot(a, 35.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, a.id); + assert.ok(bomb.fuse < 5000 && bomb.fuse >= 5000 - 8, `left as it was (${bomb.fuse})`); + // Handed the same fuse low a second time, you get what is left. + apart(); + handTo(c, bomb, 200); + spot(c, 30, ROW); + spot(you, 35.8, ROW); + fuse.advance(round, 8, calm); + assert.equal(bomb.holder, 0); + assert.ok(bomb.fuse <= 200, `lifted once a fuse (${bomb.fuse})`); + assert.deepEqual(bomb.lifted, [0, b.id]); +}); + +test("Hot Potato: the fuse at zero blows its holder out, and after RELIGHT_MS a survivor gets a shorter fuse, down to the floor", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + const [bomb] = round.bombs; + handTo(a, bomb, 40); + spot(a, 30, ROW); + spot(you, 52, 62); + spot(b, 90, ROW); + spot(c, 10, 62); + fuse.advance(round, 48, calm); + assert.equal(a.alive, false); + assert.equal(a.out, "blast"); + assert.deepEqual(fuseEvents(round, "blast").map((e) => e.id), [a.id]); + assert.equal(round.score, fuse.SURVIVE_POINTS, "you survived the fuse"); + assert.equal(bomb.lit, false); + assert.equal(round.phase, "play", "three are left"); + fuse.advance(round, fuse.RELIGHT_MS + 16, calm); + assert.ok(bomb.lit, "it lights again"); + assert.ok(round.runners[bomb.holder].alive); + assert.equal(bomb.max, fuse.FUSE_MS - fuse.FUSE_STEP_MS, "the second fuse is shorter"); + assert.equal(fuse.fuseFor(round, 0), fuse.FUSE_MS); + assert.equal(fuse.fuseFor(round, 4), fuse.FUSE_MS - 4 * fuse.FUSE_STEP_MS); + assert.equal(fuse.fuseFor(round, 20), fuse.FUSE_FLOOR_MS, "never under the floor"); + assert.equal(fuse.fuseFor({ level: 9 }, 20), fuse.VENUES[9].floor, "the Finale's floor is lower"); +}); + +test("Hot Potato: a match ends at one runner, a win moves on a venue, your blast costs a life and runs it again, and the last life ends the round", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + sitOut(b); + sitOut(c); + handTo(a, round.bombs[0], 30); + spot(a, 30, ROW); + spot(you, 80, ROW); + fuse.advance(round, 40, calm); + assert.equal(round.phase, "done"); + assert.equal(round.result, "win"); + assert.equal(round.score, fuse.SURVIVE_POINTS + fuse.WIN_POINTS, "the fuse survived and the match"); + assert.equal(round.matchesWon, 1); + fuse.advance(round, fuse.DONE_MS + 16, calm); + assert.equal(round.level, 2); + assert.equal(round.phase, "ready"); + assert.equal(fuseEvents(round, "level").length, 1); + assert.equal(round.runners.length, 4, "a fresh field"); + + const lost = potato(1); + handTo(lost.runners[0], lost.bombs[0], 30); + lost.streak = 3; + fuse.advance(lost, 40, calm); + assert.equal(lost.result, "lose"); + assert.equal(lost.lives, fuse.START_LIVES - 1); + assert.equal(lost.streak, 0, "a life lost ends the streak"); + fuse.advance(lost, fuse.DONE_MS + 16, calm); + assert.equal(lost.level, 1, "the same venue again"); + assert.ok(lost.bombs.every((bb) => bb.holder !== 0), "and its first fuse is not yours"); + assert.equal(fuseEvents(lost, "retry").length, 1); + lost.lives = 1; + fuse.advance(lost, fuse.READY_MS + 8, calm); + handTo(lost.runners[0], lost.bombs[0], 30); + fuse.advance(lost, 40, calm); + fuse.advance(lost, fuse.DONE_MS + 16, calm); + assert.equal(lost.over, true); +}); + +test("Hot Potato: Freeze stops every fuse burning, Extra Fuse adds to it, Sneakers speeds you up, and Swap trades places with the bomb staying put", () => { + const round = potato(2); + const [you, a] = round.runners; + const [bomb] = round.bombs; + handTo(a, bomb, 6000); + fuse.applyPower(round, you, "freeze"); + assert.equal(fuse.burn(round, 1500), false); + assert.equal(bomb.fuse, 6000, "frozen"); + fuse.burn(round, 1000); + assert.equal(bomb.fuse, 5500, "the freeze ran out half way"); + fuse.applyPower(round, you, "extra"); + assert.equal(bomb.fuse, 5500 + fuse.EXTRA_MS); + assert.ok(bomb.max >= bomb.fuse); + fuse.applyPower(round, you, "sneakers"); + assert.equal(you.fx.sneakers, fuse.SNEAKERS_MS); + assert.ok(Math.abs(fuse.speedOf(round, you) - fuse.SPEED * fuse.SNEAKERS) < 1e-9); + spot(you, 20, ROW); + spot(a, 80, ROW); + fuse.applyPower(round, a, "swap", () => 0); + assert.deepEqual([a.x, you.x], [20, 80], "places traded"); + assert.equal(bomb.holder, a.id, "the bomb goes with its holder"); + assert.equal(fuse.burn(round, 1e6), true, "a fuse that runs out says so"); + assert.equal(fuse.applyPower(round, you, "nope"), false); + handTo(you, bomb); + assert.ok(Math.abs(fuse.speedOf(round, you) - fuse.SPEED * fuse.SNEAKERS * fuse.HOLDER_SPEED) < 1e-9, "the holder runs HOLDER_SPEED times as fast"); +}); + +test("Hot Potato: a pickup turns up from venue 2, one at a time, and a runner over it takes it", () => { + const plain = potato(1); + plain.bombs[0].fuse = 1e6; + fuse.advance(plain, 12000, calm); + assert.equal(plain.pickups.length, 0, "none in the Break Room"); + const random = seeded(5); + const round = potato(2, { random }); + for (const r of round.runners) spot(r, 10 + r.id * 4, 62); + round.bombs[0].fuse = 1e6; + fuse.advance(round, 3100, random); + assert.equal(round.pickups.length, 1); + fuse.advance(round, 2000, random); + assert.equal(round.pickups.length, 1, "one at a time"); + const p = round.pickups[0]; + const you = round.runners[0]; + spot(you, p.x, p.y); + fuse.advance(round, 8, random); + assert.equal(round.pickups.length, 0); + assert.deepEqual(fuseEvents(round, "power").map((e) => [e.id, e.kind]), [[0, p.kind]]); +}); + +test("Hot Potato: a runner not holding flees the holder, and a holding rival chases", () => { + for (const v of [1, 3, 5, 8]) { + const round = potato(v); + const holder = round.runners[round.bombs[0].holder]; + const free = round.runners.filter((r) => r.id !== 0 && !fuse.holding(round, r)); + const r = free.reduce((x, y) => (Math.hypot(x.x - holder.x, x.y - holder.y) < Math.hypot(y.x - holder.x, y.y - holder.y) ? x : y)); + const before = Math.hypot(r.x - holder.x, r.y - holder.y); + Object.assign(r, { think: 0, charges: 0 }); + holder.charges = 0; + fuse.advance(round, 1500, calm); + const after = Math.hypot(r.x - holder.x, r.y - holder.y); + assert.ok(after > before + 6, `venue ${v}: the ${r.kind} runs from ${before.toFixed(1)} to ${after.toFixed(1)} away`); + } + const round = potato(1); + const [you, a, b, c] = round.runners; + handTo(a, round.bombs[0]); + spot(a, 20, ROW); + spot(you, 60, ROW); + spot(b, 10, 62); + spot(c, 94, 62); + const choice = fuse.think(round, a, calm); + assert.equal(choice.target, 0, "the nearest is you"); + assert.ok(choice.x > 0.9, "and it runs your way"); + const flee = fuse.think(round, you, calm); + assert.ok(flee.x > 0, "you, not holding, would run away from it"); +}); + +test("Hot Potato: a holding rival in range winds up its lunge, standing still, then dashes; a Trickster feints the wrong way first", () => { + for (const [kind, i] of [["sprinter", 1], ["trickster", 3]]) { + const round = potato(1); + const you = round.runners[0]; + const r = round.runners[i]; + assert.equal(r.kind, kind); + for (const o of round.runners) if (o !== r && o !== you) spot(o, 10 + o.id * 4, 62); + handTo(r, round.bombs[0]); + spot(r, 30, ROW); + spot(you, 38, ROW); + Object.assign(r, { think: 0, charges: 2 }); + fuse.advance(round, 8, () => 0); + if (kind === "sprinter") { + assert.ok(r.windup > 0, "it winds up"); + assert.deepEqual(r.push, { x: 0, y: 0 }, "standing still"); + assert.equal(fuseEvents(round, "windup").length, 1); + fuse.advance(round, fuse.rivalPower(1).windupMs, () => 0); + } else { + assert.ok(r.fake > 0, "it feints"); + assert.ok(r.push.x < 0, "the wrong way"); + fuse.advance(round, fuse.FAKE_MS, () => 0); + } + const lunge = fuseEvents(round, "dash").find((e) => e.id === r.id); + assert.ok(lunge && lunge.lunge && lunge.dx > 0.8, `${kind}: then lunges at you`); + assert.equal(r.charges, 1); + } +}); + +test("Hot Potato: a rival a lunge comes at dodges across it after its reaction time, once a lunge", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + handTo(you, round.bombs[0]); + spot(you, 30, ROW + 6); + spot(a, 54, ROW + 6); + spot(b, 10, 62); + spot(c, 94, 62); + Object.assign(a, { charges: 2 }); + round.input.right = true; + assert.ok(fuse.dash(round, you)); + assert.equal(you.charges, fuse.START_CHARGES - 1); + fuse.advance(round, 8, () => 0); + assert.equal(a.dashMs, 0, "not before its reaction time"); + for (let t = 0; t < 160 && !fuseEvents(round, "dodge").length; t += 8) fuse.advance(round, 8, () => 0); + assert.equal(fuseEvents(round, "dodge").length, 1, "it dodges"); + assert.ok(Math.abs(a.dashY) > 0.6, "across the lunge"); + assert.equal(a.charges, 1); + assert.equal(round.bombs[0].holder, 0, "and gets away"); + round.input.right = false; + fuse.advance(round, fuse.RECHARGE_MS, () => 0); + assert.equal(fuseEvents(round, "dodge").length, 1, "once a lunge"); +}); + +test("Hot Potato: a dash spends a charge for DASH_MS, one comes back every RECHARGE_MS up to MAX_CHARGES, and there is no dash before play", () => { + const round = fuse.newRound(calm); + const you = round.runners[0]; + assert.equal(fuse.dash(round, you), false, "the hold before the match"); + fuse.advance(round, fuse.READY_MS, calm); + for (const r of round.runners) if (r.id !== 0) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + round.input.left = true; + assert.ok(fuse.dash(round, you)); + assert.equal(you.dashMs, fuse.DASH_MS); + assert.equal(fuse.dash(round, you), false, "one at a time"); + fuse.advance(round, 8, calm); + assert.ok(Math.abs(you.vx + you.speed + fuse.DASH_SPEED) < 1e-6, "the way you run, at speed plus DASH_SPEED"); + round.bombs[0].fuse = 1e6; + fuse.advance(round, fuse.RECHARGE_MS, calm); + assert.equal(you.charges, fuse.START_CHARGES); + fuse.advance(round, fuse.RECHARGE_MS * 2, calm); + assert.equal(you.charges, fuse.MAX_CHARGES, "never past MAX_CHARGES"); +}); + +test("Hot Potato: the Rooftop has no wall at the bottom, a rival minds its edge unless it misjudges, and a holder off it takes the bomb along", () => { + const round = potato(4); + assert.equal(round.open, true); + const [you, a, b, c, d] = round.runners; + for (const o of [b, c, d]) spot(o, 10 + o.id * 20, 6); + handTo(b, round.bombs[0], 60000); + spot(a, 50, fuse.AH - 2); + Object.assign(a, { push: { x: 0, y: 1 }, vy: 30 }); + fuse.advance(round, 400, calm); + assert.ok(a.alive && a.y <= fuse.AH, "minding the edge, it stops"); + spot(a, 50, fuse.AH - 2); + Object.assign(a, { push: { x: 0, y: 1 }, vy: 30, blind: 1e9 }); + fuse.advance(round, 400, calm); + assert.equal(a.alive, false, "misjudging, it runs off"); + assert.equal(a.out, "fall"); + spot(b, 30, fuse.AH + 0.5); + b.blind = 1e9; + const score = round.score; + fuse.advance(round, 8, calm); + assert.equal(b.alive, false); + assert.equal(round.bombs[0].lit, false, "the bomb went with it"); + assert.equal(round.score - score, fuse.SURVIVE_POINTS * 4, "a fuse that ended on someone else"); + fuse.advance(round, fuse.RELIGHT_MS + 16, calm); + assert.ok(round.bombs[0].lit, "and lights again"); + spot(you, 60, fuse.AH - 1); + round.input.down = true; + fuse.advance(round, 400, calm); + assert.equal(you.alive, false, "you can run off too"); + assert.equal(round.result, "lose"); + const walled = potato(1); + spot(walled.runners[0], 60, fuse.AH - 4); + walled.input.down = true; + fuse.advance(walled, 400, calm); + assert.ok(walled.runners[0].alive && walled.runners[0].y <= fuse.AH - fuse.RUNNER_R + 1e-9, "a walled venue holds you in"); +}); + +test("Hot Potato: two bombs burn at once, never pass between two holders, and only one relights when three are left", () => { + const round = potato(8); + assert.equal(round.runners.length, 7); + const [b1, b2] = round.bombs; + const h1 = round.runners[b1.holder]; + const h2 = round.runners[b2.holder]; + assert.notEqual(h1, h2); + b1.lock = 0; + b2.lock = 0; + spot(h1, 40, 62); + spot(h2, 45.8, 62); + for (const r of round.runners) if (r !== h1 && r !== h2) spot(r, 6 + r.id * 14, 4); + fuse.advance(round, 8, calm); + assert.deepEqual([b1.holder, b2.holder], [h1.id, h2.id], "holder to holder passes nothing"); + // Leave you, the two holders and one more: a blast leaves three. + const extra = round.runners.find((r) => r.id !== 0 && r !== h1 && r !== h2); + for (const r of round.runners) if (r.id !== 0 && r !== h1 && r !== h2 && r !== extra) sitOut(r); + spot(h1, 10, 62); + spot(h2, 90, 62); + b1.fuse = 20; + b2.fuse = 1e6; + fuse.advance(round, 24, calm); + assert.equal(h1.alive, false); + fuse.advance(round, fuse.RELIGHT_MS + 16, calm); + assert.equal(round.bombs.filter((b) => b.lit).length, 1, "one bomb for three runners"); +}); + +test("Hot Potato: whole matches always end, every venue, with you left idle or run by the rivals' own think(), and the rivals pass the bomb about and catch each other", () => { + let rivalTags = 0; + let rivalBlasts = 0; + let fuses = 0; + let tags = 0; + for (let v = 1; v <= fuse.MAX_VENUE + 1; v++) { + for (let k = 0; k < 4; k++) { + const random = seeded(v * 13 + k); + const round = fuse.newRound(random); + fuse.newMatch(round, v, random, 0); + const you = round.runners[0]; + let t = 0; + for (; t < 120000 && round.phase !== "done"; t += 16) { + // Half the runs leave you idle; the rest steer you as a rival would. + if (k % 2 && t % 128 === 0 && you.alive && round.phase === "play") { + const c = fuse.think(round, you, random); + Object.assign(round.input, { left: c.x < -0.38, right: c.x > 0.38, up: c.y < -0.38, down: c.y > 0.38 }); + if (c.dash) fuse.dash(round, you, c); + } + fuse.advance(round, 16, random); + for (const e of round.events) { + if (e.type === "tag") tags += 1; + if (e.type === "tag" && e.from !== 0) rivalTags += 1; + if (e.type === "blast" && e.id !== 0) rivalBlasts += 1; + if (e.type === "lit") fuses += 1; + } + round.events.length = 0; + } + assert.equal(round.phase, "done", `venue ${v} ends (${t} ms)`); + assert.ok(t < 75000, `venue ${v} ends within a minute and a quarter (${t} ms)`); + } + } + assert.ok(rivalTags > 80, `rivals pass the bomb (${rivalTags})`); + assert.ok(rivalBlasts > 20, `and blow up too (${rivalBlasts})`); + assert.ok(tags / fuses > 1 && tags / fuses < 9, `a sane number of passes a fuse (${(tags / fuses).toFixed(2)})`); +}); + +test("Hot Potato: a venue's numbers are built once, not on every slice, and past the ninth the Finale repeats, sharper", () => { + assert.equal(fuse.venueFor(12), fuse.venueFor(12)); + assert.equal(fuse.rivalPower(3), fuse.rivalPower(3)); + assert.equal(fuse.rivalPower(12), fuse.rivalPower(12)); + assert.ok(Object.isFrozen(fuse.venueFor(12)) && Object.isFrozen(fuse.rivalPower(12)), "and nobody can change them"); + assert.equal(fuse.venueFor(11).title, "Finale 3"); + assert.ok(fuse.venueFor(11).fuse < fuse.VENUES[9].fuse); + assert.ok(fuse.rivalPower(11).speed > fuse.rivalPower(9).speed); + for (let v = 2; v <= fuse.MAX_VENUE; v++) assert.ok(fuse.VENUES[v].smart >= fuse.VENUES[v - 1].smart, `venue ${v} is no softer than ${v - 1}`); + assert.equal(fuse.VENUES[4].open, true); + assert.equal(fuse.VENUES[7].dark, true); + assert.ok(fuse.LAYOUTS[5].ice.length && fuse.LAYOUTS[6].belts.length, "ice in the Ice Machine, belts in the Conveyor Hall"); +}); + +test("Hot Potato: a belt carries a runner along, and ice lets it slide", () => { + const round = potato(6); + const you = round.runners[0]; + for (const r of round.runners) if (r !== you) spot(r, 10 + r.id * 12, 36); + round.bombs[0].fuse = 1e6; + spot(you, 40, 22); + fuse.advance(round, 500, calm); + assert.ok(you.x > 45, `the belt carried you right (${you.x.toFixed(1)})`); + const ice = potato(5); + const me = ice.runners[0]; + for (const r of ice.runners) if (r !== me) spot(r, 6 + r.id * 4, 66); + ice.bombs[0].fuse = 1e6; + spot(me, 31, 35); + me.vx = 40; + fuse.advance(ice, 100, calm); + const slid = me.x - 31; + const dry = potato(1); + const dme = dry.runners[0]; + for (const r of dry.runners) if (r !== dme) spot(r, 6 + r.id * 4, 66); + spot(dme, 40, ROW); + dme.vx = 40; + fuse.advance(dry, 100, calm); + assert.ok(slid > (dme.x - 40) * 1.4, `slides further on ice (${slid.toFixed(1)} against ${(dme.x - 40).toFixed(1)})`); +}); + +test("Hot Potato: a rival color too near your highlight gives way to a spare, so no highlight leaves a rival beside you", () => { + assert.deepEqual(fuse.rivalColors("#206cc3"), [...fuse.RIVAL_COLORS], "far from all of them: nothing changes"); + assert.deepEqual(fuse.rivalColors("not a color"), [...fuse.RIVAL_COLORS]); + const rgb = (h) => [1, 3, 5].map((k) => parseInt(h.slice(k, k + 2), 16)); + for (const [id, accent] of Object.entries(ACCENTS)) { + for (const you of [accent.light[0], accent.dark[0]]) { + const colors = fuse.rivalColors(you); + assert.equal(new Set(colors).size, colors.length, `${id}: no two rivals alike`); + for (const c of colors) { + const [a, b] = [rgb(c), rgb(you)]; + assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) >= fuse.NEAR_COLOR, `${id} ${you} beside ${c}`); + } + } + } +}); + +test("Hot Potato: the pills never overlap, leave the board or spill out of their strip, even on the smallest board with every pill wanted", () => { + const effects = [{ text: "SNEAKERS", color: "#fff", fill: 0.5 }, { text: "FROZEN", color: "#fff", fill: 0.5 }]; + for (const h of [Math.max(12 / fuse.MIN_CELL, 2.4), 2.4]) { + for (const fuseText of [null, "YOURS 12.0", "FUSE 0.4"]) { + for (let n = 0; n <= effects.length; n++) { + const hud = { venue: "FINALE 12", charges: 1, maxCharges: 2, recharge: 0.5, left: 7, effects: effects.slice(0, n), streak: 5, fuse: fuseText ? { text: fuseText, color: "#fff" } : null }; + const pills = fuseHudLayout(h, fuse.W, 3, hud, fuse.HUD_H); + assert.equal(pills.length, 5 + n + (fuseText ? 1 : 0)); + for (const p of pills) { + assert.ok(p.x >= 0 && p.x + p.w <= fuse.W, `${p.text} stays on the board`); + assert.ok(p.y >= 0 && p.y + p.h <= fuse.HUD_H, `${p.text} stays in the strip (h ${h})`); + } + for (let i = 0; i < pills.length; i++) { + for (let j = i + 1; j < pills.length; j++) { + const [p, q] = [pills[i], pills[j]]; + assert.ok(p.x + p.w <= q.x || q.x + q.w <= p.x || p.y + p.h <= q.y || q.y + q.h <= p.y, `${p.text} and ${q.text} apart`); + } + } + } + } + } +}); + +test("Hot Potato: a charred runner waddles to the nearest wall and stops there, never over the pills", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + handTo(a, round.bombs[0], 10); + spot(a, 40, 5); + spot(you, 60, 62); + spot(b, 90, 62); + spot(c, 10, 62); + fuse.advance(round, fuse.OUT_MS + 32, calm); + assert.equal(a.alive, false); + assert.ok(a.y >= fuse.RUNNER_R - 1e-9, `it stops at the top wall (y ${a.y.toFixed(1)})`); +}); + +test("Hot Potato: a rival holder low on fuse goes for a Freeze or an Extra Fuse, never for Sneakers or a Swap", () => { + for (const [kind, wanted] of [["freeze", true], ["extra", true], ["sneakers", false], ["swap", false]]) { + const round = potato(2); + const [you, a, b, c] = round.runners; + handTo(a, round.bombs[0], 3000); + spot(a, 40, ROW); + spot(you, 80, ROW); + spot(b, 94, 62); + spot(c, 90, 62); + round.pickups = [{ x: 30, y: ROW, kind, ttl: fuse.PICK_TTL_MS }]; + const choice = fuse.think(round, a, calm); + assert.equal(choice.x < 0, wanted, `${kind}: ${wanted ? "goes for it" : "chases you instead"}`); + } +}); + +/* -------------------------------------------------------- Hot Potato game */ + +// Starts a Hot Potato game past its hold with every rival standing still. +function potatoGame(opts = {}) { + const { canvas, calls } = stubCanvas(); + const g = fuse.default.create({ canvas, ...opts }); + g.resize(900, 700); + g.key("action"); + g.tick(400); + for (const r of g.round.runners) if (r.id !== 0) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + return { g, calls }; +} + +test("Hot Potato: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives, the dash, the fuse and the effects included, in light and dark under every highlight", () => { + checkPills(fuse.default, { + setup: (r) => { + r.runners[0].fx.sneakers = fuse.SNEAKERS_MS / 2; + r.freeze = fuse.FREEZE_MS / 2; + r.streak = 2; + }, + expect: ["VENUE 1", "♥", "DASH", "LEFT", "~SNEAKERS", "~FROZEN", "HOT x2"], + }); +}); + +test("Hot Potato game: held arrows run until let go, space dashes (its key repeat never), a pause lets go of everything, and the board refuses a tiny window", () => { + const { canvas, calls } = stubCanvas(); + const g = fuse.default.create({ canvas }); + assert.equal(g.resize(fuse.W * fuse.MIN_CELL - 1, 2000), false, "too narrow to play"); + assert.equal(g.resize(fuse.W * fuse.MIN_CELL, fuse.H * fuse.MIN_CELL), true, "just big enough"); + assert.equal(g.resize(900, 700), true); + assert.ok(calls.count > 0, "the start screen draws"); + assert.equal(typeof g.release, "function"); + g.key("action"); + assert.equal(g.state, "running"); + g.tick(400); + assert.equal(g.round.phase, "play"); + for (const r of g.round.runners) if (r.id !== 0) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + const you = g.round.runners[0]; + const y = you.y; + g.key("up"); + g.key("up", true); + g.tick(200); + assert.ok(you.y < y - 3, "held up runs up"); + g.release("up"); + assert.equal(g.round.input.up, false); + g.key("left"); + g.key("action", true); + assert.equal(you.charges, fuse.START_CHARGES, "a repeat of space never dashes"); + g.key("action"); + assert.equal(you.charges, fuse.START_CHARGES - 1, "space dashes"); + g.pause(); + assert.deepEqual(g.round.input, { up: false, down: false, left: false, right: false }, "a pause holds nothing"); + const clock = g.round.clock; + g.tick(1000); + assert.equal(g.round.clock, clock, "a paused game holds still"); + g.key("action"); + assert.equal(g.state, "running", "space plays on from a pause"); + assert.equal(you.charges, fuse.START_CHARGES - 1, "and does not also dash"); +}); + +test("Hot Potato game: the start screen reads the furthest venue, the memo only grows, and the round's end calls onScore once with its score big on the end screen", () => { + const texts = []; + let font = ""; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text), font]) : name in target ? target[name] : () => {}), + set: (target, name, value) => { if (name === "font") font = value; target[name] = value; return true; }, + }); + let saved = 3; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = fuse.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo, onScore: (n) => scores.push(n) }); + g.resize(900, 700); + assert.ok(texts.some(([t]) => t.includes("Furthest: Server Room (venue 3 of 9)")), "the start screen names the furthest venue"); + assert.equal(saved, 3, "nothing is written by just opening it"); + const winMatch = () => { + const r = g.round; + const holder = r.runners[r.bombs[0].holder]; + for (const o of r.runners) if (o.id !== 0 && o !== holder) sitOut(o); + for (const b of r.bombs) if (b !== r.bombs[0]) b.lit = false; + r.bombs[0].fuse = 1; + g.tick(16); + assert.equal(r.result, "win"); + g.tick(fuse.DONE_MS + 16); + g.tick(fuse.READY_MS + 16); + }; + g.key("action"); + g.tick(400); + winMatch(); + assert.equal(g.round.level, 2); + assert.equal(saved, 3, "venue 2 is not past venue 3"); + winMatch(); + winMatch(); + assert.equal(g.round.level, 4); + assert.equal(saved, 4, "a new furthest"); + const loseMatch = () => { + handTo(g.round.runners[0], g.round.bombs[0], 1); + g.tick(16); + g.tick(fuse.DONE_MS + 16); + g.tick(fuse.READY_MS + 16); + }; + for (let i = 0; i < fuse.START_LIVES; i++) loseMatch(); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + assert.ok(g.score > 0); + texts.length = 0; + g.tick(1000); + g.resize(900, 700); + assert.ok(texts.some(([t, f]) => t === String(g.score) && /\b7px/.test(f)), "the score, big"); + assert.equal(scores.length, 1, "once"); + g.key("action"); + g.tick(400); + for (let i = 0; i < fuse.START_LIVES; i++) loseMatch(); + assert.equal(saved, 4, "a shorter round leaves it"); + assert.equal(scores.length, 2); +}); + +test("Hot Potato game: the fuse ticks quicker as it burns down, a pass pops, passing the best plays the fanfare once, and every venue draws", () => { + const tones = []; + const { g, calls } = potatoGame({ tone: (name) => tones.push(name), best: () => 5 }); + const [bomb] = g.round.bombs; + const you = g.round.runners[0]; + for (const r of g.round.runners) if (r !== you) spot(r, 10 + r.id * 25, 62); + spot(you, 40, ROW); + bomb.fuse = fuse.FUSE_MS; + tones.length = 0; + for (let t = 0; t < 2000; t += 16) g.tick(16); + const slow = tones.filter((n) => n === "tick").length; + bomb.fuse = 2500; + tones.length = 0; + for (let t = 0; t < 1500; t += 16) g.tick(16); + const quick = tones.filter((n) => n === "tick").length; + assert.ok(slow >= 2, `the full fuse ticks (${slow} in 2 s)`); + assert.ok(quick / 1.5 > (slow / 2) * 2, `and twice as fast near the end (${quick} in 1.5 s)`); + handTo(you, bomb, 5000); + const a = g.round.runners[1]; + spot(a, you.x + 5.8, you.y); + g.tick(16); + assert.equal(bomb.holder, a.id); + assert.ok(tones.includes("pop"), "the pass pops"); + g.round.score = 6; + g.tick(16); + g.tick(16); + assert.equal(tones.filter((t) => t === "best").length, 1); + for (let n = 1; n <= fuse.MAX_VENUE + 1; n++) { + fuse.newMatch(g.round, n, steady, 0); + g.round.lives = 99; + const drawn = calls.count; + for (let k = 0; k < 60; k++) g.tick(50); + assert.ok(calls.count > drawn, `venue ${n} draws`); + } +}); + +test("Hot Potato game: handed the bomb at its last moment, your fuse pill, the countdown over the bomb and the tick all follow the lifted fuse", () => { + const texts = []; + const tones = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillText" ? (text) => texts.push(String(text)) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const g = fuse.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, tone: (name) => tones.push(name) }); + g.resize(900, 700); + g.key("action"); + g.tick(400); + const [you, a, b, c] = g.round.runners; + for (const r of [a, b, c]) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + const [bomb] = g.round.bombs; + spot(b, 90, 62); + spot(c, 10, 62); + handTo(a, bomb, 150); + spot(a, 30, ROW); + spot(you, 35.8, ROW); + texts.length = 0; + g.tick(16); + assert.equal(bomb.holder, 0); + assert.ok(texts.includes("YOURS 1.4"), `the pill reads the lifted fuse (${texts.filter((t) => t.startsWith("YOURS"))})`); + assert.ok(texts.includes("2"), "and the countdown over the bomb counts from it"); + spot(a, 10, 35); + tones.length = 0; + let t = 0; + for (; t < 3000 && you.alive; t += 16) g.tick(16); + assert.ok(t >= fuse.PASS_FLOOR_MS - 32, `the fuse burns its lifted time before it blows (${t} ms)`); + assert.ok(tones.filter((n) => n === "tick").length >= 5, "ticking all the way"); +}); + +// A 2D context that keeps the style each fill and stroke used, and counts +// every other call. +function styleCanvas() { + const fills = []; + const strokes = []; + const ctx = new Proxy({}, { + get: (target, name) => { + if (name === "fill" || name === "fillRect") return () => fills.push(target.fillStyle); + if (name === "stroke" || name === "strokeRect") return () => strokes.push(target.strokeStyle); + return name in target ? target[name] : () => {}; + }, + set: (target, name, value) => { target[name] = value; return true; }, + }); + return { canvas: { width: 0, height: 0, getContext: () => ctx }, fills, strokes }; +} + +test("Hot Potato: a fuse that runs out in the slice its holder touches someone blows on the holder, never on the one it touched", () => { + const round = potato(1); + const [you, a, b, c] = round.runners; + const [bomb] = round.bombs; + handTo(a, bomb, 4); + spot(a, 30, ROW); + spot(you, 35.8, ROW); + spot(b, 90, ROW); + spot(c, 10, 62); + fuse.advance(round, 8, calm); + assert.equal(fuseEvents(round, "tag").length, 0, "a spent bomb passes to nobody"); + assert.deepEqual(fuseEvents(round, "blast").map((e) => e.id), [a.id], "it blows on its holder"); + assert.equal(you.alive, true); + assert.equal(round.phase, "play"); +}); + +test("Hot Potato game: two bombs burning tick on one clock, no quicker than one bomb alone", () => { + const ticksIn = (bombs) => { + const tones = []; + const { g } = potatoGame({ tone: (name) => tones.push(name) }); + fuse.newMatch(g.round, 8, steady, 0); + g.tick(16); + for (const r of g.round.runners) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0, x: 6 + r.id * 14, y: 4, vx: 0, vy: 0 }); + g.round.bombs.forEach((b, i) => (b.lit = i < bombs)); + tones.length = 0; + for (let t = 0; t < 1200; t += 16) { + for (const b of g.round.bombs) b.fuse = 900; + g.tick(16); + } + return tones.filter((n) => n === "tick").length; + }; + const one = ticksIn(1); + const two = ticksIn(2); + assert.ok(one >= 4, `one bomb near its end ticks (${one} in 1.2 s)`); + assert.ok(two <= one, `two bombs tick no quicker (${two} against ${one})`); +}); + +test("Hot Potato game: blown up, you are still drawn as Planny, charred, with your star eye", () => { + const { canvas, fills } = styleCanvas(); + const g = fuse.default.create({ canvas }); + g.resize(900, 700); + g.key("action"); + g.tick(400); + const you = g.round.runners[0]; + Object.assign(you, { alive: false, out: "blast", outMs: fuse.OUT_MS / 2 }); + g.round.events.length = 0; + fills.length = 0; + g.resize(900, 700); + assert.ok(fills.includes(FUSE_CHAR), "a charred body"); + assert.ok(fills.includes("#206cc3"), "and the star eye in your highlight"); +}); + +test("Hot Potato: arms and feet on the floor stand out from every venue's tiles, light floors or dark, in either theme", () => { + for (let v = 1; v <= fuse.MAX_VENUE + 1; v++) { + const t = fuseTheme(v); + const ink = fuseLimbInk(v); + for (const tile of [t.a, t.b]) assert.ok(fuseContrast(ink, tile) >= 3, `venue ${v}: ${ink} on ${tile} (${fuseContrast(ink, tile).toFixed(2)})`); + } + assert.notEqual(fuseLimbInk(3), "#1d1a17", "the Server Room's dark floor gets the light ink"); + const { canvas, strokes } = styleCanvas(); + const g = fuse.default.create({ canvas }); + g.resize(900, 700); + g.key("action"); + g.tick(400); + fuse.newMatch(g.round, 3, steady, 0); + strokes.length = 0; + g.resize(900, 700); + assert.ok(strokes.includes(fuseLimbInk(3)), "and the drawing uses it there, whatever the page's ink"); +}); + +test("Hot Potato game: the safe-from-a-tag-back ring has a dark edge under its white, so it shows on the pale floors", () => { + const { canvas, strokes } = styleCanvas(); + const g = fuse.default.create({ canvas }); + g.resize(900, 700); + g.key("action"); + g.tick(400); + const [you, a] = g.round.runners; + Object.assign(g.round.bombs[0], { holder: you.id, from: { id: a.id, at: g.round.clock } }); + assert.ok(fuse.tagSafe(g.round, a)); + strokes.length = 0; + g.resize(900, 700); + const at = strokes.indexOf(FUSE_SAFE_EDGE); + assert.ok(at >= 0 && strokes[at + 1] === FUSE_SAFE_RING, "the edge, then the white ring"); +}); + +test("Hot Potato: the last seconds' number stays on the arena wherever the holder stands, under its feet when it hugs the top wall", () => { + for (let y = fuse.RUNNER_R; y <= fuse.AH - fuse.RUNNER_R; y += 0.5) { + for (const r of [1.7, 2.6]) { + const n = fuseCountY(y - 7.6, r, y); + assert.ok(n - 1.6 >= 0 && n + 1.6 <= fuse.AH, `holder at y ${y}: the number at ${n.toFixed(1)}`); + } + } + assert.ok(fuseCountY(3 - 7.6, 2.4, 3) > 3, "under the feet at the top wall"); + assert.ok(fuseCountY(40 - 7.6, 2.4, 40) < 40 - 7.6, "over the bomb in the open"); +}); + +test("Hot Potato game: the opening banner sits in the arena from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.32)"); + const g = fuse.default.create({ canvas }); + g.resize(900, 900); + openingBanner(g, shades, fuse.AH); +}); + +/* ---------------------------------------------------- Crossing Rush rules */ + +// A heat at `zone` from `seed`, past its hold, the rivals parked (they never +// choose) unless `still` is false, and no pickups. +function crossing(zone = 1, { seed = 7, still = true, random = calm } = {}) { + const round = hop.newRound(random); + round.seed = seed; + hop.newHeat(round, zone, random, 0); + hop.advance(round, 8, random); + assert.equal(round.phase, "play"); + if (still) for (const h of round.hoppers) if (h.id !== 0) parkHopper(h); + round.pickups = []; + round.events.length = 0; + return round; +} + +// Parks a rival where it stands: never choosing again, and no hop in the air +// whose landing would start it choosing. +const parkHopper = (h) => Object.assign(h, { hop: null, think: 1e9 }); + +const hopEvents = (round, type) => round.events.filter((e) => e.type === type); + +// Rebuilds a lane by hand: its kind, and cars or floats as [left edge, length] +// standing still unless `extra` says otherwise. +function setLane(round, row, kind, items = [], extra = {}) { + const lane = round.lanes[row]; + Object.assign(lane, { kind, speed: 0, shift: 0, drift: 0, dir: 1, span: hop.COLS + hop.MARGIN * 2 + 20, trees: new Array(hop.COLS).fill(0), icy: false, surge: 0, flip: 0, stop: 0 }, extra); + lane.items = items.map(([x, len, k]) => ({ kind: k || (kind === "river" ? "log" : "car"), p: x + hop.MARGIN, len, tint: 0, dive: false, phase: 0 })); + return lane; +} + +// Puts a hopper on a cell, standing. +const place = (h, row, x, face = "up") => Object.assign(h, { row, x, face, hop: null, back: null, daze: 0, queued: null, finished: false }); + +test("Crossing Rush: buildLanes builds the same lanes from the same seed, the pavement first and the finish last, grass between the groups and each zone's new thing first", () => { + const firstHazard = (lanes) => lanes.find((l) => !hop.isSafe(l)); + for (let z = 1; z <= hop.MAX_ZONE + 1; z++) { + const a = hop.buildLanes(z, 42); + assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(hop.buildLanes(z, 42))), `zone ${z}: the same seed, the same lanes`); + assert.notDeepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(hop.buildLanes(z, 43))), `zone ${z}: another seed, other lanes`); + for (const seed of [1, 2, 3, 99]) { + const lanes = hop.buildLanes(z, seed); + assert.equal(lanes.length, hop.zoneFor(z).rows); + assert.equal(lanes[0].kind, "start"); + assert.equal(lanes.at(-1).kind, "goal"); + lanes.forEach((l, i) => assert.equal(l.row, i)); + for (let i = 1; i < lanes.length - 1; i++) { + if (lanes[i].kind !== "grass") continue; + assert.notEqual(lanes[i + 1].kind, "grass", `zone ${z}: never two grass rows together`); + assert.ok(lanes[i].trees.filter((t) => !t).length >= 6, `zone ${z}: a grass row keeps at least six open cells`); + } + // No impossible lane: every gap between cars is at least the zone's, and + // the water always has something to stand on coming. + for (const l of lanes) { + if (l.kind !== "road" && l.kind !== "river") continue; + const its = l.items.slice().sort((p, q) => p.p - q.p); + for (let k = 0; k < its.length; k++) { + const next = k + 1 < its.length ? its[k + 1].p : its[0].p + l.span; + const gap = next - (its[k].p + its[k].len); + if (l.kind === "road") assert.ok(gap >= hop.zoneFor(z).gap - 1e-9, `zone ${z}: a gap of ${gap.toFixed(2)} between cars`); + else assert.ok(gap <= 3.2, `zone ${z}: a gap of ${gap.toFixed(2)} in the water`); + } + if (l.items.some((it) => it.kind === "turtle")) assert.ok(l.items.some((it) => !it.dive), `zone ${z}: a turtle lane always has turtles that stay up`); + } + } + const lanes = hop.buildLanes(z, 5); + const first = firstHazard(lanes); + if (z === 1) assert.equal(first.kind, "road"); + if (z === 2) assert.equal(first.kind, "river"); + if (z === 3) assert.equal(first.kind, "rail"); + if (z === 4) assert.ok(first.items.some((it) => it.dive), "Turtle Bay opens on diving turtles"); + if (z === 5) assert.ok(first.surge && lanes.some((l) => l.items.some((it) => it.kind === "truck")), "the Highway opens on a surging lane, with trucks"); + if (z === 7) assert.ok(first.flip, "Rapids opens on a river that turns round"); + if (z === 8) assert.ok(first.icy, "the Ice Road opens on ice"); + } + assert.equal(hop.ZONES[6].dark, true); +}); + +test("Crossing Rush: a hop onto a car sends you back to the last grass row, a car on you mid-lane does too, and the flight takes SENDBACK_MS", () => { + const round = crossing(1); + const you = round.hoppers[0]; + setLane(round, 1, "road", [[4.6, 1.2]]); + place(you, 0, 5); + assert.ok(hop.occupied(round, 1, 5), "the car is on column 5"); + assert.equal(hop.occupied(round, 1, 7), false); + assert.ok(hop.hop(round, you, "up")); + hop.advance(round, hop.HOP_MS / 2 - 8, calm); + assert.equal(you.back, null, "still in the cell it left for the first half"); + hop.advance(round, 16, calm); + assert.deepEqual(hopEvents(round, "back").map((e) => [e.id, e.cause]), [[0, "car"]]); + assert.equal(you.back.toRow, 0); + assert.equal(hop.hop(round, you, "up"), false, "no hops while flying back"); + hop.advance(round, hop.SENDBACK_MS, calm); + assert.deepEqual([you.back, you.row, you.x], [null, 0, 5]); + // Down, it stands dazed for DAZE_MS before it may hop again. + assert.ok(you.daze > hop.DAZE_MS - 50, "dazed on landing"); + assert.equal(hop.hop(round, you, "up"), false, "no hops while dazed"); + hop.advance(round, hop.DAZE_MS, calm); + assert.equal(you.daze, 0); + setLane(round, 1, "grass"); + assert.ok(hop.hop(round, you, "up"), "and then it may"); + // Higher up, back to the grass row under the road. + setLane(round, 3, "grass"); + setLane(round, 4, "road", [[6.5, 2]]); + place(you, 4, 7); + round.events.length = 0; + hop.advance(round, 8, calm); + assert.equal(you.back.toRow, 3); + assert.equal(round.clean, false, "a heat with a send-back is not clean"); +}); + +test("Crossing Rush: standing on a log carries you with it, the water with nothing to stand on sends you back, and so does riding off the edge", () => { + const round = crossing(2); + const you = round.hoppers[0]; + setLane(round, 1, "river", [[3.5, 3]], { speed: 2, dir: 1 }); + place(you, 0, 5); + hop.hop(round, you, "up"); + hop.advance(round, hop.HOP_MS, calm); + assert.equal(you.row, 1); + const x = you.x; + hop.advance(round, 500, calm); + assert.ok(Math.abs(you.x - (x + 1)) < 0.05, `the log carried you a cell in half a second (${you.x.toFixed(2)})`); + assert.equal(you.back, null); + hop.advance(round, 3000, calm); + assert.deepEqual(hopEvents(round, "back").map((e) => e.cause), ["swept"], "off the edge on the log"); + const wet = crossing(2); + setLane(wet, 1, "river", [[8, 2]]); + place(wet.hoppers[0], 0, 5); + assert.ok(hop.occupied(wet, 1, 5), "open water is no place to stand"); + hop.hop(wet, wet.hoppers[0], "up"); + hop.advance(wet, hop.HOP_MS / 2 + 8, calm); + assert.equal(wet.hoppers[0].back, null, "mid-hop over the water is fine"); + hop.advance(wet, hop.HOP_MS / 2, calm); + assert.deepEqual(hopEvents(wet, "back").map((e) => e.cause), ["splash"]); +}); + +test("Crossing Rush: pickups stack in the order you land on them, space uses the oldest first, a coin scores at once, and a new heat starts with none", () => { + const round = crossing(1); + const you = round.hoppers[0]; + setLane(round, 1, "grass"); + setLane(round, 2, "road"); + setLane(round, 3, "grass"); + place(you, 1, 5); + hop.applyPower(round, you, "horn"); + hop.applyPower(round, you, "coin"); + hop.applyPower(round, you, "shield"); + assert.deepEqual(you.powers, ["horn", "shield"], "the coin is not stacked"); + assert.equal(round.score, hop.COIN_POINTS); + assert.equal(you.shield, 0, "nothing goes off until space"); + assert.ok(hop.usePower(round, you)); + assert.deepEqual(you.powers, ["shield"], "the Horn went first"); + assert.equal(round.lanes[2].stop, hop.HORN_MS); + assert.ok(hop.usePower(round, you)); + assert.equal(you.shield, hop.SHIELD_MS); + assert.equal(hop.usePower(round, you), false, "an empty stack does nothing"); + assert.equal(round.powersUsed, 2); + // Mid-hop, the use waits for the landing. + hop.applyPower(round, you, "horn"); + assert.ok(hop.hop(round, you, "up")); + assert.ok(hop.usePower(round, you)); + assert.deepEqual([you.queued, you.powers.length], ["power", 1]); + hop.advance(round, hop.HOP_MS + 16, calm); + assert.deepEqual([you.queued, you.powers.length], [null, 0], "and goes off once down"); + // A rival uses a pickup the moment it lands on it. + const a = round.hoppers[1]; + hop.applyPower(round, a, "shield"); + assert.deepEqual([a.powers.length, a.shield], [0, hop.SHIELD_MS]); + // Nothing carries over to the next heat. + hop.applyPower(round, you, "spring"); + hop.newHeat(round, 2, calm, 0); + assert.deepEqual(round.hoppers[0].powers, []); +}); + +test("Crossing Rush: the first home wins; two home in the same slice finish by the moment each landed, a dead heat to you; zone 1 lets second place through, zone 3 does not", () => { + const race = (zone, rivalAhead) => { + const round = crossing(zone); + const [you, a] = round.hoppers; + const top = round.rows - 1; + setLane(round, top - 1, "grass"); + place(you, top - 1, 5); + place(a, top - 1, 2); + hop.hop(round, you, "up"); + hop.hop(round, a, "up"); + a.hop.ms = rivalAhead; + for (let t = 0; t < 400 && round.phase === "play"; t += 8) hop.advance(round, 8, calm); + return round; + }; + const tie = race(3, 0); + assert.equal(tie.result, "win", "a dead heat goes to you"); + assert.deepEqual(hopEvents(tie, "finish").map((e) => [e.id, e.place]), [[0, 1], [1, 2]]); + const beaten = race(3, 4); + assert.deepEqual(hopEvents(beaten, "finish").map((e) => e.id), [1, 0], "the rival landed 4 ms sooner, in the same slice"); + assert.equal(beaten.result, "lose"); + assert.equal(beaten.lives, hop.START_LIVES - 1); + const pass = race(1, 4); + assert.equal(pass.result, "pass", "second place gets through zone 1"); + assert.equal(pass.lives, hop.START_LIVES); + assert.equal(pass.heatsWon, 0, "but it is not a win"); +}); + +test("Crossing Rush: a lost heat runs again on the same lanes, a win moves on to new ones, and the last life ends the round", () => { + const round = crossing(3); + const shape = (r) => r.lanes.map((l) => `${l.kind}:${l.items.length}:${l.trees.join("")}`).join("|"); + const before = shape(round); + round.hoppers[1].finished = true; + round.finishers.push(round.hoppers[1]); + round.hoppers[1].place = 1; + hop.advance(round, 8, calm); + assert.equal(round.result, "lose"); + hop.advance(round, hop.DONE_MS + 16, calm); + assert.equal(round.level, 3); + assert.equal(shape(round), before, "the same lanes again"); + assert.equal(hopEvents(round, "retry").length, 1); + const won = crossing(3); + const top = won.rows - 1; + setLane(won, top - 1, "grass"); + place(won.hoppers[0], top - 1, 5); + hop.hop(won, won.hoppers[0], "up"); + hop.advance(won, hop.HOP_MS + hop.DONE_MS + 32, calm); + assert.equal(won.level, 4); + assert.equal(hopEvents(won, "level").length, 1); + const last = crossing(3); + last.lives = 1; + last.hoppers[1].finished = true; + last.finishers.push(last.hoppers[1]); + last.hoppers[1].place = 1; + hop.advance(last, hop.DONE_MS + 32, calm); + assert.equal(last.over, true); + assert.equal(hop.advance(last, 1000, calm), "over"); +}); + +test("Crossing Rush: points are a row higher, a win of 50 times the zone times the clean streak plus 3 a row of lead, and a close call", () => { + const winAt = (zone, { streak = 0, clean = true } = {}) => { + const round = crossing(zone); + const [you, a, b] = round.hoppers; + const top = round.rows - 1; + setLane(round, top - 1, "grass"); + place(you, top - 1, 5); + you.furthest = top; + place(a, 4, 2); + place(b, 6, 8); + Object.assign(round, { score: 0, streak, clean }); + hop.hop(round, you, "up"); + hop.advance(round, hop.HOP_MS + 8, calm); + assert.equal(round.result, "win"); + return round; + }; + const one = winAt(3); + assert.equal(one.score, hop.WIN_POINTS * 3 + hop.LEAD_POINTS * (one.rows - 1 - 6)); + assert.equal(one.streak, 1); + const two = winAt(3, { streak: 1 }); + assert.equal(two.score, hop.WIN_POINTS * 3 * 2 + hop.LEAD_POINTS * (two.rows - 1 - 6), "a second clean win in a row, times 2"); + const top = winAt(3, { streak: hop.MAX_STREAK }); + assert.equal(top.streak, hop.MAX_STREAK, "never past MAX_STREAK"); + assert.equal(top.score, hop.WIN_POINTS * 3 * hop.MAX_STREAK + hop.LEAD_POINTS * (top.rows - 1 - 6)); + const dirty = winAt(3, { streak: 2, clean: false }); + assert.equal(dirty.streak, 0, "a win after a send-back ends the streak"); + assert.equal(dirty.score, hop.WIN_POINTS * 3 + hop.LEAD_POINTS * (dirty.rows - 1 - 6)); + // A row higher than you had got, once. + const round = crossing(1); + const you = round.hoppers[0]; + setLane(round, 1, "grass"); + place(you, 0, 5); + hop.hop(round, you, "up"); + hop.advance(round, hop.HOP_MS + 8, calm); + assert.equal(round.score, hop.PROGRESS_POINTS); + hop.hop(round, you, "down"); + hop.advance(round, hop.HOP_MS + 8, calm); + hop.hop(round, you, "up"); + hop.advance(round, hop.HOP_MS + 8, calm); + assert.equal(round.score, hop.PROGRESS_POINTS, "a row already reached scores nothing more"); + // A car through the cell you just left. + const close = crossing(1); + const me = close.hoppers[0]; + setLane(close, 1, "road", [[5.7, 1.2]], { speed: 3, dir: -1 }); + setLane(close, 2, "grass"); + place(me, 1, 5); + me.furthest = 9; + hop.hop(close, me, "up"); + hop.advance(close, hop.HOP_MS + hop.CLOSE_MS, calm); + assert.equal(me.back, null, "it missed you"); + assert.deepEqual(hopEvents(close, "close").map((e) => e.points), [hop.CLOSE_POINTS]); + assert.equal(close.score, hop.CLOSE_POINTS); +}); + +test("Crossing Rush: a train lane warns for WARN_MS and then its train sends back whoever stands on it; a diving turtle under the water holds nobody up", () => { + const round = crossing(3); + const you = round.hoppers[0]; + setLane(round, 1, "rail", [], { phase: "idle", phaseMs: 100, nextIdle: 4000, dir: 1 }); + place(you, 1, 5); + assert.equal(hop.occupied(round, 1, 5), false); + assert.ok(hop.occupied(round, 1, 5, 100 + hop.WARN_MS + hop.PASS_MS / 2), "the train is on column 5 half way through its pass"); + hop.advance(round, 104, calm); + assert.deepEqual(hopEvents(round, "warn").map((e) => e.row), [1]); + assert.equal(you.back, null); + hop.advance(round, hop.WARN_MS, calm); + assert.equal(hopEvents(round, "train").length, 1); + hop.advance(round, hop.PASS_MS, calm); + assert.deepEqual(hopEvents(round, "back").map((e) => e.cause), ["train"]); + assert.equal(round.lanes[1].phase, "idle", "and the lane goes quiet again"); + const bay = crossing(4); + const lane = setLane(bay, 1, "river", [[4, 3, "turtle"]]); + assert.equal(hop.occupied(bay, 1, 5), false, "turtles up hold you"); + lane.items[0].dive = true; + lane.items[0].phase = hop.TURTLE_UP_MS + hop.TURTLE_SINK_MS + 100 - bay.clock; + assert.equal(hop.turtleState(lane.items[0], bay.clock), 2); + assert.ok(hop.occupied(bay, 1, 5), "under, they hold nobody"); +}); + +test("Crossing Rush: a Spring leaps two cells the way you face (kept when that cell is shut), a Shield lets cars through for SHIELD_MS, a Horn stops the nearest road, and an icy lane slides you a cell on", () => { + const round = crossing(1); + const you = round.hoppers[0]; + setLane(round, 1, "road", [[4.6, 1.2]]); + setLane(round, 2, "grass"); + place(you, 0, 5); + hop.applyPower(round, you, "spring"); + assert.ok(hop.usePower(round, you)); + assert.equal(you.hop.toRow, 2, "over the car"); + assert.equal(you.spring, false); + hop.advance(round, hop.SPRING_MS + 8, calm); + assert.deepEqual([you.row, you.back], [2, null]); + // Facing right, it leaps right; into a rock it stays in the stack. + place(you, 2, 5, "right"); + round.lanes[2].trees[7] = 2; + hop.applyPower(round, you, "spring"); + round.events.length = 0; + assert.equal(hop.usePower(round, you), false); + assert.deepEqual([you.powers, hopEvents(round, "bonk").length], [["spring"], 1]); + round.lanes[2].trees[7] = 0; + assert.ok(hop.usePower(round, you)); + assert.deepEqual([you.hop.toRow, you.hop.toX], [2, 7]); + // A slow truck rolling over you takes 2.3 s to pass: the Shield holds on + // until it has gone by, then runs out. + const shield = crossing(5); + const me = shield.hoppers[0]; + setLane(shield, 1, "road", [[2.5, 3, "truck"]], { speed: 1.2, dir: 1 }); + place(me, 1, 5); + hop.applyPower(shield, me, "shield"); + hop.usePower(shield, me); + hop.advance(shield, 8, calm); + assert.equal(hopEvents(shield, "shield").length, 1); + assert.equal(me.back, null); + hop.advance(shield, 2000, calm); + assert.equal(me.back, null, "nothing hits while the Shield is up"); + hop.advance(shield, hop.SHIELD_MS, calm); + assert.deepEqual([me.back, me.shield], [null, 0], "and it runs out once the truck has gone by"); + setLane(shield, 1, "road", [[4.6, 1.2]]); + hop.advance(shield, 8, calm); + assert.notEqual(me.back, null, "then the next car does send you back"); + const horn = crossing(1); + const road = setLane(horn, 2, "road", [[0, 1.2]], { speed: 2 }); + setLane(horn, 1, "grass"); + place(horn.hoppers[0], 1, 5); + hop.applyPower(horn, horn.hoppers[0], "horn"); + hop.usePower(horn, horn.hoppers[0]); + assert.equal(road.stop, hop.HORN_MS); + hop.advance(horn, 1000, calm); + assert.equal(road.shift, 0, "the cars stand still"); + hop.advance(horn, 1000, calm); + assert.ok(road.shift > 0.9, "and move on after HORN_MS"); + assert.equal(hop.applyPower(horn, horn.hoppers[0], "nope"), false); + const ice = crossing(8); + setLane(ice, 1, "road", [], { icy: true }); + setLane(ice, 2, "grass"); + place(ice.hoppers[0], 0, 5); + hop.hop(ice, ice.hoppers[0], "up"); + hop.advance(ice, hop.HOP_MS * 2 + 8, calm); + assert.equal(ice.hoppers[0].row, 2, "slid a cell on"); + assert.equal(hopEvents(ice, "slide").length, 1); +}); + +test("Crossing Rush: at full sharpness the planner never picks a hop onto a car, a train or the open water, in any zone, and rivals it drives are hardly ever sent back", () => { + let looks = 0; + let hops = 0; + let backs = 0; + const T = { row: 0, x: 0 }; + for (let z = 1; z <= hop.MAX_ZONE + 1; z++) { + // The boldest rival made sharp: the least room to spare. + const bold = { ...hop.rivalPower(z).daredevil, depth: 5, mistake: 0, noise: 0 }; + for (let k = 0; k < 2; k++) { + const random = seeded(z * 31 + k); + const round = crossing(z, { seed: z * 17 + k, random }); + for (let t = 0; t < 40000 && round.phase === "play"; t += 16) { + for (const h of round.hoppers) { + if (h.id === 0 || h.hop || h.back || h.finished || h.daze) continue; + // A rival whose own cell is hit within half a hop whatever it does + // has no safe choice to make. + if (hop.laneAt(round, h.row).kind !== "river" && hop.occupied(round, h.row, h.x, hop.HOP_MS / 2)) continue; + const dir = hop.plan(round, h, random, bold); + looks += 1; + if (!dir) continue; + hops += 1; + assert.ok(hop.target(round, h.row, h.x, dir, T), `zone ${z}: a hop the board allows`); + const into = hop.laneAt(round, T.row); + // The cell it lands on, when it lands and (off the water) from the + // moment it starts to count there. + assert.equal(hop.occupied(round, T.row, T.x, hop.HOP_MS), false, `zone ${z}: ${h.kind} hops ${dir} into ${into.kind} row ${T.row} at ${T.x.toFixed(2)}`); + if (into.kind !== "river") assert.equal(hop.occupied(round, T.row, T.x, hop.HOP_MS / 2), false, `zone ${z}: counted there at the half`); + hop.hop(round, h, dir); + } + hop.advance(round, 16, random); + backs += hopEvents(round, "back").filter((e) => e.id !== 0).length; + round.events.length = 0; + } + } + } + assert.ok(looks > 2000 && hops > 600, `the planner was asked enough (${looks} looks, ${hops} hops)`); + assert.ok(backs <= hops / 100, `and what it drove was hardly ever sent back (${backs} in ${hops} hops)`); +}); + +test("Crossing Rush: whole heats end in every zone, the rivals get home in 11 to 50 seconds, and a sharp hopper alone can cross every zone", () => { + for (let z = 1; z <= hop.MAX_ZONE + 1; z++) { + for (let k = 0; k < 2; k++) { + const random = seeded(z * 7 + k); + const race = crossing(z, { seed: z * 11 + k, still: false, random }); + let first = null; + let t = 0; + for (; t < 150000 && race.phase === "play"; t += 16) { + hop.advance(race, 16, random); + if (first === null && race.finishers.length) first = t; + race.events.length = 0; + } + assert.equal(race.phase, "done", `zone ${z} ends (${t} ms)`); + assert.ok(first >= 11000 && first <= 50000, `zone ${z}: the first rival home at ${(first / 1000).toFixed(1)} s`); + // Crossable: you alone, run by the planner, the rivals parked. + const solo = crossing(z, { seed: z * 11 + k, random }); + const you = solo.hoppers[0]; + for (t = 0; t < 90000 && !you.finished; t += 16) { + if (!you.hop && !you.back && !you.daze) { + const dir = hop.plan(solo, you, random, hop.SHARP_POWER); + if (dir) hop.hop(solo, you, dir); + } + hop.advance(solo, 16, random); + solo.events.length = 0; + } + assert.ok(you.finished, `zone ${z} seed ${z * 11 + k} can be crossed (${(t / 1000).toFixed(1)} s)`); + } + } +}); + +test("Crossing Rush: with a Spring, a sharp rival never takes the long hop from a cell a car reaches before its half", () => { + let chosen = 0; + for (let edge = -3; edge < 4.6; edge += 0.01) { + const round = crossing(9); + const h = round.hoppers[1]; + setLane(round, 0, "grass"); + setLane(round, 1, "road", [[edge, 1.2]], { speed: 4, dir: 1 }); + setLane(round, 2, "road"); + setLane(round, 3, "grass"); + place(h, 1, 5); + h.spring = true; + // A car on the cell before the long hop's half leaves no way out: with a + // Spring every hop is the long one. + if (hop.occupied(round, 1, 5, hop.SPRING_MS / 2)) continue; + const dir = hop.plan(round, h, calm, { ...hop.SHARP_POWER, margin: 0.02 }); + if (dir !== "up") continue; + chosen += 1; + assert.ok(hop.hop(round, h, dir) && h.hop.kind === "spring"); + h.think = 1e9; + hop.advance(round, hop.SPRING_MS + 16, calm); + assert.deepEqual(hopEvents(round, "back").map((e) => e.id), [], `a car ${edge.toFixed(2)} along caught the Spring hop in the cell it left`); + assert.equal(h.row, 3); + } + assert.ok(chosen > 100, `the Spring hop was taken (${chosen} times)`); +}); + +test("Crossing Rush: a rival sent back stands dazed for DAZE_MS too before its planner picks a hop", () => { + const round = crossing(1, { still: false }); + const a = round.hoppers[1]; + setLane(round, 1, "grass"); + setLane(round, 2, "grass"); + place(a, 2, 5); + hop.sendBack(round, a, "car"); + hop.advance(round, hop.SENDBACK_MS + 8, calm); + assert.equal(a.back, null); + assert.ok(a.daze > 0); + assert.equal(hop.plan(round, a, calm), null, "no plan while dazed"); + const at = [a.row, a.x]; + hop.advance(round, hop.DAZE_MS - 100, calm); + assert.deepEqual([a.row, a.x, a.hop], [...at, null], "it stands still"); +}); + +test("Crossing Rush: a Tagalong follows you up, sideways toward you rather than straight on", () => { + const round = crossing(7); + const [you, tag] = round.hoppers; + assert.equal(tag.kind, "tagalong"); + for (let r = 1; r < round.rows - 1; r++) setLane(round, r, "grass"); + const P = { ...hop.rivalPower(7).tagalong, mistake: 0, noise: 0 }; + place(you, 8, 9); + place(tag, 7, 1); + assert.equal(hop.plan(round, tag, calm, P), "right", "a row behind you and far across, it closes in on you"); + assert.equal(hop.plan(round, tag, calm, { ...P, tag: false }), "up", "where any other rival would climb"); +}); + +test("Crossing Rush: a careful rival in an end column beside a bush still hops onto a log that covers it", () => { + const round = crossing(2); + const h = round.hoppers[1]; + assert.equal(h.kind, "hopper"); + setLane(round, 1, "river"); + setLane(round, 2, "grass"); + round.lanes[2].trees[1] = 1; + setLane(round, 3, "river", [[-0.5, 11]]); + setLane(round, 4, "grass"); + place(h, 2, 0); + // Before the fix every hop onto the water looked unsafe from column 0, so + // a Hopper swept back there sat out the heat. + assert.equal(hop.plan(round, h, calm, { ...hop.rivalPower(2).hopper, mistake: 0, noise: 0 }), "up"); +}); + +test("Crossing Rush: shiftAt foresees exactly where a Rapids lane that flips, a Highway lane that surges and a lane a Horn holds will have flowed to", () => { + const lanesOf = (zone, test) => { + const round = crossing(zone, { seed: 5 }); + return [round, round.lanes.filter(test)]; + }; + const checks = [ + lanesOf(7, (l) => l.kind === "river" && l.flip), + lanesOf(5, (l) => l.kind === "road" && l.surge), + lanesOf(1, (l) => l.kind === "road"), + ]; + checks[2][1][0].stop = hop.HORN_MS; + for (const [round, lanes] of checks) { + assert.ok(lanes.length > 0); + for (const ms of [8, 640, hop.HORN_MS + 40, hop.FLIP_MS + 400, hop.FLIP_MS * 2 + hop.SURGE_MS]) { + const r = structuredClone({ lanes: round.lanes }); + const sample = lanes.map((l) => hop.shiftAt(r.lanes[l.row], ms)); + const copy = { ...round, lanes: r.lanes, hoppers: round.hoppers.map((h) => ({ ...h })), events: [] }; + for (const h of copy.hoppers) parkHopper(h); + hop.advance(copy, ms, calm); + lanes.forEach((l, i) => assert.ok(Math.abs(copy.lanes[l.row].shift - sample[i]) < 1e-6, `row ${l.row} at ${ms} ms`)); + } + } +}); + +test("Crossing Rush: a heat still on at HEAT_CAP_MS is lost, a life gone, and the banner says time", () => { + const round = crossing(3); + round.clock = hop.HEAT_CAP_MS - 8; + hop.advance(round, 16, calm); + assert.equal(round.result, "lose"); + assert.equal(round.lives, hop.START_LIVES - 1); + assert.deepEqual(hopEvents(round, "lose").map((e) => e.time), [true]); +}); + +test("Crossing Rush: a zone's numbers are built once, and past the ninth Rush Hour repeats, quicker", () => { + assert.equal(hop.zoneFor(12), hop.zoneFor(12)); + assert.equal(hop.rivalPower(3), hop.rivalPower(3)); + assert.equal(hop.rivalPower(12), hop.rivalPower(12)); + assert.ok(Object.isFrozen(hop.zoneFor(12)) && Object.isFrozen(hop.rivalPower(12)) && Object.isFrozen(hop.rivalPower(12).hopper), "and nobody can change them"); + assert.equal(hop.zoneFor(11).title, "Rush Hour 3"); + assert.ok(hop.zoneFor(11).car[1] > hop.ZONES[9].car[1]); + for (let z = 2; z <= hop.MAX_ZONE; z++) assert.ok(hop.ZONES[z].smart >= hop.ZONES[z - 1].smart, `zone ${z} is no softer than ${z - 1}`); + assert.ok(hop.rivalPower(9).daredevil.depth > hop.rivalPower(1).daredevil.depth, "sharper rivals look further ahead"); + assert.ok(hop.rivalPower(9).hopper.reactMs < hop.rivalPower(1).hopper.reactMs, "and wait less"); + assert.ok(hop.rivalPower(1).hopper.reactMs > hop.rivalPower(1).daredevil.reactMs, "the Hopper takes its time, the Daredevil does not"); +}); + +test("Crossing Rush: a rival color too near your highlight gives way to a spare, so no highlight leaves a rival beside you", () => { + assert.deepEqual(hop.rivalColors("#206cc3"), [...hop.RIVAL_COLORS]); + assert.deepEqual(hop.rivalColors("not a color"), [...hop.RIVAL_COLORS]); + const rgb = (h) => [1, 3, 5].map((k) => parseInt(h.slice(k, k + 2), 16)); + for (const [id, accent] of Object.entries(ACCENTS)) { + for (const you of [accent.light[0], accent.dark[0]]) { + const colors = hop.rivalColors(you); + assert.equal(new Set(colors).size, colors.length, `${id}: no two rivals alike`); + for (const c of colors) { + const [a, b] = [rgb(c), rgb(you)]; + assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) >= hop.NEAR_COLOR, `${id} ${you} beside ${c}`); + } + } + } +}); + +test("Crossing Rush: the pills never overlap, leave the board or spill out of their strip, even on the smallest board with every pill wanted", () => { + const effects = [{ text: "DAZED", color: "#fff", fill: 0.5 }, { text: "SHIELD", color: "#fff", fill: 0.5 }, { text: "SPACE: SHIELD", color: "#fff", fill: 1 }, { text: "+9", color: "#fff", fill: 1 }]; + for (const h of [Math.max(12 / hop.MIN_CELL, 2.4), 2.4]) { + for (const zone of ["ZONE 1", "ZONE 12", "ZONE 120"]) { + for (let n = 0; n <= effects.length; n++) { + { + const hud = { zone, effects: effects.slice(0, n), streak: hop.MAX_STREAK, place: "3RD", first: false }; + const pills = hopHudLayout(h, hop.W, 3, hud, hop.HUD_H); + assert.equal(pills.length, 4 + n); + for (const p of pills) { + assert.ok(p.x >= 0 && p.x + p.w <= hop.W, `${p.text} stays on the board`); + assert.ok(p.y >= 0 && p.y + p.h <= hop.HUD_H, `${p.text} stays in the strip (h ${h})`); + } + for (let i = 0; i < pills.length; i++) { + for (let j = i + 1; j < pills.length; j++) { + const [p, q] = [pills[i], pills[j]]; + assert.ok(p.x + p.w <= q.x || q.x + q.w <= p.x || p.y + p.h <= q.y || q.y + q.h <= p.y, `${p.text} and ${q.text} apart`); + } + } + } + } + } + } +}); + +test("Crossing Rush: every pill's text reads at 4.5:1 on its backing and its tint, lives, the daze and Shield running down and the pickup stack included, in light and dark under every highlight", () => { + checkPills(hop.default, { + setup: (r) => { + const you = r.hoppers[0]; + you.daze = hop.DAZE_MS / 2; + you.shield = hop.SHIELD_MS / 2; + you.powers = ["spring", "horn", "shield"]; + r.streak = 3; + }, + expect: ["ZONE 1", "♥", "~DAZED", "~SHIELD", "SPACE: SPRING", "+2", "CLEAN x3"], + }); +}); + +test("Crossing Rush: every word drawn on the field stays on it, wherever it starts and however long", () => { + for (const text of ["Dazed!", "Shield up!", "Daredevil made it!", "Tagalong: Shield", "A line much too long to fit across the field at all"]) { + for (const size of [2, 2.6, 3]) { + for (let x = -10; x <= hop.FIELD_W + 10; x += 7) { + for (let y = -10; y <= hop.FIELD_H + 10; y += 9) { + const at = hopLabelSpot(text, x, y, size, hop.FIELD_W, hop.FIELD_H); + assert.ok(at.x - at.max / 2 >= 0 && at.x + at.max / 2 <= hop.FIELD_W, `${text} across, at ${x}`); + assert.ok(at.y - size / 2 >= 0 && at.y + size / 2 <= hop.FIELD_H, `${text} down, at ${y}`); + } + } + } + } +}); + +test("Crossing Rush: arms and feet on a lane stand out from both of its tones, whatever the theme", () => { + for (const [look, t] of Object.entries(HOP_LANES)) { + const ink = hopLimbInk(look); + for (const tone of [t.a, t.b]) assert.ok(hopContrast(ink, tone) >= 3, `${look}: ${ink} on ${tone} (${hopContrast(ink, tone).toFixed(2)})`); + } + assert.notEqual(hopLimbInk("road"), hopLimbInk("grass"), "the dark road gets the light ink, the grass the dark"); +}); + +/* ----------------------------------------------------- Crossing Rush game */ + +// Starts a Crossing Rush game past its hold, the rivals parked and the first +// rows grass. +function crossingGame(opts = {}) { + const { canvas, calls } = stubCanvas(); + const g = hop.default.create({ canvas, ...opts }); + g.resize(900, 900); + g.key("action"); + g.tick(400); + for (const h of g.round.hoppers) if (h.id !== 0) place(parkHopper(h), 0, h.x); + for (let r = 1; r <= 6; r++) setLane(g.round, r, "grass"); + g.round.pickups = []; + return { g, calls }; +} + +test("Crossing Rush game: an arrow hops once a press (never on its key repeat, nor again until let go, nor with the press that plays on), one more press queues, a pause drops the queue, space uses the oldest pickup, a send-back leaves you dazed with presses dropped, and the board refuses a tiny window", () => { + const { canvas } = stubCanvas(); + const t = hop.default.create({ canvas }); + assert.equal(t.resize(hop.W * hop.MIN_CELL - 1, 2000), false, "too narrow to play"); + assert.equal(t.resize(hop.W * hop.MIN_CELL, hop.H * hop.MIN_CELL), true, "just big enough"); + const { g } = crossingGame(); + const you = g.round.hoppers[0]; + assert.equal(g.round.phase, "play"); + g.key("up"); + assert.equal(you.hop.toRow, 1, "a press hops"); + g.key("up", true); + g.tick(200); + assert.equal(you.row, 1, "its key repeat never hops again"); + g.key("up"); + g.tick(200); + assert.equal(you.row, 1, "nor a second press before it is let go"); + g.release("up"); + g.key("up"); + for (const k of ["up", "up", "up"]) { + g.release(k); + g.key(k); + } + g.release("up"); + assert.equal(you.queued, "up", "a press during the hop queues one more, and only one"); + for (let i = 0; i < 30; i++) g.tick(16); + assert.equal(you.row, 3, "the hop, then the queued one"); + g.key("left"); + g.key("up"); + g.pause(); + assert.equal(you.queued, null, "a pause drops the queue"); + g.resume(); + g.key("right"); + assert.equal(you.queued, null, "the press that plays on never hops or queues"); + for (let i = 0; i < 30; i++) g.tick(16); + const at = [you.row, you.x]; + g.release("right"); + g.key("right"); + assert.ok(you.hop, "the next one does"); + assert.deepEqual([you.hop.fromRow, you.hop.fromX], at); + for (let i = 0; i < 20; i++) g.tick(16); + you.powers = ["shield", "horn"]; + g.key("action", true); + assert.equal(you.powers.length, 2, "a repeat of space never uses a pickup"); + g.key("action"); + assert.deepEqual([you.powers, you.shield > 0], [["horn"], true], "space uses the oldest"); + g.release("right"); + hop.sendBack(g.round, you, "car"); + for (let i = 0; i < 30; i++) g.tick(16); + assert.ok(you.daze > 0, "down and dazed"); + g.key("up"); + g.release("up"); + g.key("action"); + assert.deepEqual([you.hop, you.queued, you.powers], [null, null, ["horn"]], "a press or space while dazed is dropped"); + for (let i = 0; i < 130; i++) g.tick(16); + assert.equal(you.daze, 0); + g.key("up"); + assert.ok(you.hop, "then an arrow hops again"); + g.pause(); + const clock = g.round.clock; + g.tick(1000); + assert.equal(g.round.clock, clock, "a paused game holds still"); + g.key("action"); + assert.equal(g.state, "running", "space plays on from a pause"); +}); + +test("Crossing Rush game: the start screen reads the furthest zone, the memo only grows, and the round's end calls onScore once with its score big on the end screen", () => { + const texts = []; + let font = ""; + const ctx = new Proxy({}, { + get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text), font]) : name in target ? target[name] : () => {}), + set: (target, name, value) => { if (name === "font") font = value; target[name] = value; return true; }, + }); + let saved = 3; + const memo = { get: () => saved, set: (n) => (saved = n) }; + const scores = []; + const g = hop.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, memo, onScore: (n) => scores.push(n) }); + g.resize(900, 900); + assert.ok(texts.some(([t]) => t.includes("Furthest: Rail Yard (zone 3 of 9)")), "the start screen names the furthest zone"); + assert.equal(saved, 3, "nothing is written by just opening it"); + const winHeat = () => { + const r = g.round; + const top = r.rows - 1; + setLane(r, top - 1, "grass"); + place(r.hoppers[0], top - 1, 5); + for (const h of r.hoppers) if (h.id !== 0) parkHopper(h); + g.key("up"); + g.release("up"); + g.tick(200); + assert.equal(r.result, "win"); + g.tick(hop.DONE_MS + 16); + g.tick(hop.READY_MS + 16); + }; + g.key("action"); + g.tick(400); + winHeat(); + assert.equal(g.round.level, 2); + assert.equal(saved, 3, "zone 2 is not past zone 3"); + winHeat(); + winHeat(); + assert.equal(g.round.level, 4); + assert.equal(saved, 4, "a new furthest"); + // Both rivals home first: a lost heat in any zone. + const loseHeat = () => { + const r = g.round; + for (const h of r.hoppers.slice(1)) { + parkHopper(h); + h.finished = true; + r.finishers.push(h); + h.place = r.finishers.length; + } + g.tick(16); + g.tick(hop.DONE_MS + 16); + g.tick(hop.READY_MS + 16); + }; + for (let i = 0; i < hop.START_LIVES; i++) loseHeat(); + assert.equal(g.state, "over"); + assert.deepEqual(scores, [g.score]); + assert.ok(g.score > 0); + texts.length = 0; + g.tick(1000); + g.resize(900, 900); + assert.ok(texts.some(([t, f]) => t === String(g.score) && /\b7px/.test(f)), "the score, big"); + assert.equal(scores.length, 1, "once"); + g.key("action"); + g.tick(400); + for (let i = 0; i < hop.START_LIVES; i++) loseHeat(); + assert.equal(saved, 4, "a shorter round leaves it"); + assert.equal(scores.length, 2); +}); + +test("Crossing Rush game: quick hops forward climb in pitch, a send-back boings, a coming train rings its bell, passing the best plays the fanfare once, and every zone draws", () => { + const tones = []; + const { g, calls } = crossingGame({ tone: (name, level, pitch) => tones.push([name, pitch || 1]), best: () => 5 }); + tones.length = 0; + for (let k = 0; k < 4; k++) { + g.key("up"); + g.release("up"); + for (let i = 0; i < 9; i++) g.tick(16); + } + const pitches = tones.filter(([n]) => n === "hop").map(([, p]) => p); + assert.equal(pitches.length, 4); + for (let i = 1; i < pitches.length; i++) assert.ok(pitches[i] > pitches[i - 1], `each quick hop higher (${pitches.join(", ")})`); + const you = g.round.hoppers[0]; + setLane(g.round, you.row + 1, "road", [[you.x - 0.6, 1.2]]); + g.key("up"); + g.release("up"); + for (let i = 0; i < 10; i++) g.tick(16); + assert.ok(tones.some(([n]) => n === "boing"), "a send-back boings"); + assert.ok(tones.some(([n]) => n === "crash")); + for (let i = 0; i < 40; i++) g.tick(16); + setLane(g.round, you.row + 1, "rail", [], { phase: "idle", phaseMs: 10, nextIdle: 4000, dir: 1 }); + tones.length = 0; + for (let i = 0; i < 50; i++) g.tick(16); + assert.ok(tones.filter(([n]) => n === "bell").length >= 2, "the bell rings while the train is coming"); + g.round.score = 6; + g.tick(16); + g.tick(16); + assert.equal(tones.filter(([n]) => n === "best").length, 1); + for (let z = 1; z <= hop.MAX_ZONE + 1; z++) { + hop.newHeat(g.round, z, steady, 0); + g.round.lives = 99; + const drawn = calls.count; + for (let k = 0; k < 40; k++) g.tick(50); + assert.ok(calls.count > drawn, `zone ${z} draws`); + } +}); + +test("Crossing Rush game: Planny keeps his star eye in your highlight standing, mid-hop, flying back and beaten", () => { + const frame = (setup) => { + const { canvas, fills } = styleCanvas(); + const g = hop.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(400); + setup(g.round); + fills.length = 0; + g.resize(900, 900); + return fills; + }; + const you = (r) => r.hoppers[0]; + // Two stars in your highlight: his eye, and his mark on the race bar. + const stars = (fills) => fills.filter((f) => f === "#206cc3").length; + assert.equal(stars(frame(() => {})), 2, "standing"); + assert.equal(stars(frame((r) => Object.assign(you(r), { hop: { kind: "hop", dir: "up", fromRow: 0, fromX: 5, toRow: 1, toX: 5, ms: 60, max: hop.HOP_MS, half: true } }))), 2, "mid-hop"); + assert.equal(stars(frame((r) => Object.assign(you(r), { back: { cause: "car", fromRow: 3, fromX: 5, toRow: 0, toX: 5, ms: 200, max: hop.SENDBACK_MS } }))), 2, "flying back"); + assert.equal(stars(frame((r) => Object.assign(r, { phase: "done", result: "lose" }))), 2, "beaten"); +}); + +test("Crossing Rush game: the opening banner sits in the field from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => { + const shades = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fillRect" ? (x, y) => t.fillStyle === "rgba(0, 0, 0, 0.32)" && shades.push(y) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const g = hop.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + shades.length = 0; + g.key("action"); + assert.equal(shades.length, 1, "the start paints its banner"); + const [first] = shades; + assert.ok(first - 7 >= 0 && first + 7 <= hop.FIELD_H, `inside the field, not at its top edge (${first})`); + shades.length = 0; + g.tick(16); + assert.deepEqual(shades, [first], "in the same place once play begins"); +}); + +test("Crossing Rush game: a rival's body is edged in its lane's limb ink, so a brown Tagalong on a log or a purple Bruiser on the water stands out", () => { + const seen = []; + const ctx = new Proxy({}, { + get: (t, name) => (name === "fill" ? () => seen.push(["fill", t.fillStyle]) : name === "stroke" ? () => seen.push(["stroke", t.strokeStyle, t.lineWidth]) : name in t ? t[name] : () => {}), + set: (t, name, value) => { t[name] = value; return true; }, + }); + const g = hop.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } }); + g.resize(900, 900); + g.key("action"); + g.tick(400); + const r = g.round; + const rival = r.hoppers[1]; + parkHopper(rival); + rival.kind = "tagalong"; + for (const look of ["road", "river", "rail"]) { + setLane(r, 2, look === "river" ? "river" : look, look === "river" ? [[3, 4]] : []); + place(rival, 2, 5); + seen.length = 0; + g.resize(900, 900); + const color = hop.rivalColors("#206cc3")[Object.keys(hop.RIVALS).indexOf(rival.kind)]; + // A fill in its color and then an edge: its dot on the race bar (a dark + // edge) and its body on the lane. + const edges = seen.flatMap(([kind, style], i) => (kind === "fill" && style === color && seen[i + 1] && seen[i + 1][0] === "stroke" ? [seen[i + 1]] : [])); + assert.ok(edges.some(([, ink, width]) => ink === hopLimbInk(look) && width >= 0.3), `${look}: the body is edged in the lane's limb ink, wide enough to see (${JSON.stringify(edges)})`); + } +}); + +test("Crossing Rush game: the Night Market's dark is one layer with the lights cut out when the page can draw off screen", () => { + const saved = globalThis.OffscreenCanvas; + const layers = []; + globalThis.OffscreenCanvas = class { + constructor(w, h) { + this.width = w; + this.height = h; + this.names = []; + layers.push(this); + const names = this.names; + this.ctx = new Proxy({}, { + get: (t, name) => (name in t ? t[name] : () => { + names.push(name); + return name === "createRadialGradient" ? { addColorStop() {} } : undefined; + }), + set: (t, n, v) => { t[n] = v; return true; }, + }); + } + getContext() { return this.ctx; } + }; + try { + const { canvas, names } = recordingCanvas(); + const g = hop.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + g.tick(400); + hop.newHeat(g.round, 6, steady, 0); + names.length = 0; + g.tick(16); + assert.equal(layers.length, 1, "one layer"); + const [layer] = layers; + assert.deepEqual([layer.width, layer.height], [Math.ceil(hop.FIELD_W * 3), Math.ceil(hop.FIELD_H * 3)], "at three a unit"); + assert.ok(layer.names.includes("fillRect"), "the dark is laid on it"); + assert.ok(layer.names.filter((n) => n === "fillRect").length >= 1 + g.round.hoppers.length, "with a light cut out round every hopper"); + assert.equal(layer.names.filter((n) => n === "createRadialGradient").length, 1, "from one light made with the layer"); + assert.ok(names.includes("drawImage"), "and the frame copies it over the field"); + layer.names.length = 0; + g.tick(16); + assert.equal(layers.length, 1, "kept from frame to frame"); + assert.ok(layer.names.filter((n) => n === "fillRect").length >= 1 + g.round.hoppers.length, "the lights cut again"); + assert.equal(layer.names.filter((n) => n === "createRadialGradient").length, 0, "and no new gradient a frame"); + } finally { + if (saved === undefined) delete globalThis.OffscreenCanvas; + else globalThis.OffscreenCanvas = saved; + } +}); + +/* ------------------------------------------------- lives and banners */ + +test("lives read at a glance: a heart per life up to five, a count past that, an empty heart at none, white on a solid pink pill", () => { + assert.equal(livesText(3), "♥♥♥"); + assert.equal(livesText(5), "♥".repeat(5)); + assert.equal(livesText(7), "♥ x7"); + assert.equal(livesText(0), "♡"); + assert.equal(livesText(-1), "♡"); + assert.ok(pillContrast(LIVES_INK, LIVES_BACK) >= 4.5, "white reads on the lives pill"); +}); + +test("every game with lives draws them in the lives pill, solid, with a heart per life", () => { + for (const [name, game] of [["trails", trails], ["bugs", bugs], ["bumper", bumper], ["fuse", fuse], ["hop", hop], ["bounce", bounce], ["rapids", rapids], ["ghoul", ghoul]]) { + const { canvas, pills, reset } = pillCanvas("#ffffff"); + const g = game.default.create({ canvas }); + g.resize(900, 900); + g.key("action"); + for (let k = 0; k < 5; k++) g.tick(16); + reset(); + g.tick(16); + const lives = pills().find((p) => p.text.startsWith("♥")); + assert.ok(lives, `${name}: a lives pill (${pills().map((p) => p.text)})`); + assert.equal(lives.text, livesText(g.round ? g.round.lives : 3), `${name}: a heart per life`); + assert.equal(lives.backing, LIVES_BACK, `${name}: on the solid lives backing`); + assert.equal(lives.ink, LIVES_INK, `${name}: in white`); + } + assert.equal(LIVES, bugs.POWERS.life.color, "the 1UP pickup keeps the lives pink"); +}); + +test("Bug Hunt: the banner's strip counts a diving bug or a bomb under it, and a bug in formation is not", () => { + const round = bugs.newRound(still); + round.bombs.length = 0; + for (const b of round.bugs) b.state = "form"; + assert.equal(bugs.underBanner(round), false, "nothing crossing"); + Object.assign(round.bugs[0], { state: "dive", y: bugs.H * 0.55 }); + assert.equal(bugs.underBanner(round), true, "a diving bug in the strip"); + round.bugs[0].state = "form"; + round.bombs.push({ x: 10, y: bugs.H * 0.55 + 1, vx: 0, vy: 10 }); + assert.equal(bugs.underBanner(round), true, "a bomb in the strip"); +}); + +test("Stack Deploy and Sunset Drive: the banner's strip counts the slider, and a road climbing into it", () => { + assert.equal(stack.underBanner(stack.H * 0.72 - 1), true, "the slider in the strip"); + assert.equal(stack.underBanner(stack.H * 0.4), false, "the slider up where the camera keeps it"); + assert.equal(drive.underBanner(drive.H / 2), false, "a flat road stays below the strip"); + assert.equal(drive.underBanner(drive.H * 0.36), true, "a hill into the strip"); +}); diff --git a/scripts/test-web-console-page-activities.mjs b/scripts/test-web-console-page-activities.mjs index d1b6780..1ef6e21 100644 --- a/scripts/test-web-console-page-activities.mjs +++ b/scripts/test-web-console-page-activities.mjs @@ -1,5 +1,6 @@ // Page tests for Activities: the die in the top bar on every screen, the -// window opening into Snake with the picker for Snake and Mini golf, the keys +// window opening on the picker (a card per game, walked by the arrows, one +// game at a time, All games back to it), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush in play, the keys // staying inside the window, Esc and P, and every pause rule (a new question, // a finish, a hidden page, a window blur), none of which ever resumes play by // itself. Mini golf in the real window: aim by mouse, two clicks to putt, @@ -90,10 +91,28 @@ const step = (s, n = 1, ms = 60) => const framesWaiting = (s) => s.page.evaluate(() => window.__frames.length); -async function openActivities(s) { +// Opens the window and, when it opens on the picker, picks `id` from it, +// and for a game with courses (Mini golf), `course` from its dashboard. A +// window that goes straight into a game (one game listed, or a round +// waiting) is left on that game. +async function openActivities(s, id = "snake", course = "pirate") { await s.page.click("#btn-activities"); await s.page.locator("#activities-modal[open]").waitFor(); - await until(async () => (await overlay(s)) !== "", 5000); + const picker = s.page.locator("#activities-picker"); + const board = s.page.locator("#activities-board"); + await until(async () => (await picker.isVisible()) || (await board.isVisible()), 5000); + if (await picker.isVisible()) { + await picker.locator(`.activities-card[data-activity="${id}"]`).click(); + if (id === "golf") await courseCard(s, course).click(); + } + await until(async () => (await board.isVisible()) && (await overlay(s)) !== "", 5000); +} + +// Opens the window onto its picker, which it shows when no round is waiting. +async function openPicker(s) { + await s.page.click("#btn-activities"); + await s.page.locator("#activities-modal[open]").waitFor(); + await s.page.locator("#activities-picker").waitFor(); } // Opens the window and starts a round: running, with a frame waiting. @@ -133,40 +152,77 @@ async function iconUsable(s, where) { assert.ok(await btn.isEnabled(), `the die is usable on ${where}`); } -test("the die sits right of the megaphone and opens into Snake on the dashboard, with the picker for both games", async (t) => { - savedLooks(t); +const cardTitles = (s) => s.page.locator("#activities-picker .activities-card-title").allInnerTexts(); +const card = (s, id) => s.page.locator(`#activities-picker .activities-card[data-activity="${id}"]`); +const focusedCard = (s) => s.page.evaluate(() => document.activeElement?.dataset?.activity || null); +const courseCard = (s, id) => s.page.locator(`#activities-picker .activities-course[data-course="${id}"]`); +const focusedCourse = (s) => s.page.evaluate(() => document.activeElement?.dataset?.course || null); + +test("the die sits right of the megaphone and opens on the picker, a card per game with its best, and a card opens its game", async (t) => { + savedLooks(t, { welcomeSeen: true, activityBestSnake: 12 }); const s = await openSession(await suite.browser(), { t, workflow: "dashboard" }); await pastTheIntro(s); await iconUsable(s, "the dashboard"); const next = await s.page.evaluate(() => document.getElementById("btn-feedback").nextElementSibling?.id); assert.equal(next, "btn-activities"); - await openActivities(s); - assert.equal(await overlay(s), "Press space to start"); - const picker = s.page.locator("#activities-picker"); - assert.ok(await picker.isVisible(), "two games listed: the picker shows"); - assert.deepEqual(await picker.locator("button").allInnerTexts(), ["Snake", "Mini golf"]); - assert.equal(await picker.locator('button[data-activity="snake"]').getAttribute("aria-pressed"), "true", "with no last pick, the first game"); - assert.ok(await s.page.locator("#activities-canvas").isVisible()); - const focused = await s.page.evaluate(() => document.activeElement?.id); - assert.equal(focused, "activities-board", "keys reach the game with no extra click"); + await openPicker(s); + assert.deepEqual(await cardTitles(s), ["Snake", "Mini golf", "Light Trails", "Bug Hunt", "Sunset Drive", "Stack Deploy", "Bumper Ring", "Rapids Run", "Hot Potato", "Crossing Rush", "Bounce Road", "Ghoul Rush"]); + assert.ok(await s.page.locator("#activities-board").isHidden(), "no board behind the picker"); + assert.ok(await s.page.locator("#activities-back").isHidden(), "nothing to go back to"); + assert.equal(await s.page.locator("#activities-title").innerText(), "Activities", "the header names no game"); + assert.match(await card(s, "snake").innerText(), /Best: 12/); + assert.match(await card(s, "golf").innerText(), /6 courses to play/); + assert.equal(await s.page.locator("#activities-picker svg").count(), (await cardTitles(s)).length, "each card has its cover"); + assert.equal(await focusedCard(s), "snake", "with no last pick, focus is on the first card"); + await card(s, "snake").click(); + await until(async () => (await overlay(s)) === "Press space to start", 5000); + assert.ok(await s.page.locator("#activities-picker").isHidden(), "the game takes the window"); + assert.ok(await s.page.locator("#activities-back").isVisible(), "All games shows with a game"); + assert.equal(await s.page.evaluate(() => document.activeElement?.id), "activities-board", "keys reach the game with no extra click"); }); -test("picking Mini golf shows it, saves it as the last activity, and keys reach it with no extra click", async (t) => { +test("the arrows walk the picker's cards, and space or Enter opens the one in focus", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await openPicker(s); + assert.equal(await focusedCard(s), "snake"); + await s.page.keyboard.press("ArrowRight"); + assert.equal(await focusedCard(s), "golf"); + for (let i = 0; i < 11; i++) await s.page.keyboard.press("ArrowRight"); + assert.equal(await focusedCard(s), "ghoul", "the last card stays put"); + for (let i = 0; i < 10; i++) await s.page.keyboard.press("ArrowLeft"); + assert.equal(await focusedCard(s), "golf"); + await s.page.keyboard.press("Enter"); + // Mini golf opens on its course dashboard, walked the same way. + await until(async () => (await focusedCourse(s)) === "pirate", 5000); + await s.page.keyboard.press("ArrowRight"); + assert.equal(await focusedCourse(s), "cave"); + await s.page.keyboard.press("Enter"); + await until(async () => (await overlay(s)) === "Press space or click to start", 5000); + assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf, Caves of Doom: no best yet"); + assert.equal(await s.page.locator("#activities-back").innerText(), "All courses"); + await s.page.click("#activities-back"); + await until(async () => (await focusedCourse(s)) === "cave", 5000); + assert.equal(await s.page.locator("#activities-back").innerText(), "All games"); + await s.page.click("#activities-back"); + await s.page.locator("#activities-picker .activities-card[data-activity]").first().waitFor(); + assert.equal(await focusedCard(s), "golf", "back on the picker, the game just left is in focus"); + await s.page.keyboard.press("ArrowRight"); + await s.page.keyboard.press(" "); + await until(async () => (await s.page.locator("#activities-title").innerText()) === "Activities · Light Trails: no best yet", 5000); +}); + +test("picking Mini golf shows it, saves it as the last played, and keys reach it with no extra click", async (t) => { savedLooks(t); const s = await openSession(await suite.browser(), { t, workflow: "dashboard" }); await pastTheIntro(s); await handTicks(s); - await openActivities(s); - const picker = s.page.locator("#activities-picker"); - await picker.locator('button[data-activity="golf"]').click(); - assert.equal(await picker.locator('button[data-activity="golf"]').getAttribute("aria-pressed"), "true"); - assert.equal(await picker.locator('button[data-activity="snake"]').getAttribute("aria-pressed"), "false"); - await until(async () => (await overlay(s)) === "Press space or click to start", 5000); - assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf: no best yet", "the header follows the pick"); + await openActivities(s, "golf"); + assert.equal(await overlay(s), "Press space or click to start"); + assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf, Pirate Cove: no best yet", "the header follows the pick"); // Golf's course is wider than tall: the canvas takes its shape, not Snake's square. const box = await s.page.locator("#activities-canvas").boundingBox(); assert.ok(Math.abs(box.width / box.height - 4 / 3) < 0.02, `a 4:3 board, not ${box.width} by ${box.height}`); - // Focus moved to the board, so space plays the pick instead of pressing the button again. assert.equal(await s.page.evaluate(() => document.activeElement?.id), "activities-board"); await s.page.keyboard.press(" "); assert.equal(await overlay(s), "", "space started the picked game"); @@ -174,29 +230,542 @@ test("picking Mini golf shows it, saves it as the last activity, and keys reach () => s.page.evaluate(async () => ((await (await fetch("/looks")).json()).looks || {}).lastActivity === "golf"), 5000, ); - // Back to Snake: golf's round waits, paused, and Snake's board is square again. - await picker.locator('button[data-activity="snake"]').click(); + // Back to Snake, by way of the course dashboard: its board is square again. + await s.page.click("#activities-back"); + await courseCard(s, "pirate").waitFor(); + await s.page.click("#activities-back"); + await card(s, "snake").click(); await until(async () => (await overlay(s)) === "Press space to start", 5000); const square = await s.page.locator("#activities-canvas").boundingBox(); assert.ok(Math.abs(square.width - square.height) < 1, "Snake's board is square"); - await picker.locator('button[data-activity="golf"]').click(); - await until(async () => (await overlay(s)) === "Paused. Press space, P or click to play", 5000); }); -test("a new session opens on the last pick, and a last pick that is no longer listed falls back to Snake", async (t) => { +test("one game at a time: All games keeps the round paused for its own card, and another pick lets it go", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await startGame(s); + await s.page.click("#activities-back"); + await s.page.locator("#activities-picker").waitFor(); + await step(s, 1); + assert.equal(await framesWaiting(s), 0, "the picker does not tick the game"); + assert.match(await card(s, "snake").innerText(), /Round paused, score 0/); + assert.match(await s.page.locator("#activities-picker").innerText(), /Picking a different game ends the paused round/); + // Closed and reopened with a round waiting: straight back into it. + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + await s.page.click("#btn-activities"); + await until(async () => (await overlay(s)).startsWith("Paused"), 5000); + // Its own card plays the same round on. + await s.page.click("#activities-back"); + await card(s, "snake").click(); + await until(async () => (await overlay(s)).startsWith("Paused"), 5000); + // Another game's card ends it: Snake starts fresh next time. + await s.page.click("#activities-back"); + await card(s, "trails").click(); + await until(async () => (await overlay(s)) === "Press space to start", 5000); + await s.page.click("#activities-back"); + assert.doesNotMatch(await s.page.locator("#activities-picker").innerText(), /Round paused/); + await card(s, "snake").click(); + await until(async () => (await overlay(s)) === "Press space to start", 5000); +}); + +test("a new session's picker marks the last played and puts focus on it, and a last pick no longer listed falls back to the first card", async (t) => { savedLooks(t, { welcomeSeen: true, lastActivity: "golf" }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); - await openActivities(s); - const picker = s.page.locator("#activities-picker"); - assert.equal(await overlay(s), "Press space or click to start", "it opens on Mini golf"); - assert.equal(await picker.locator('button[data-activity="golf"]').getAttribute("aria-pressed"), "true"); - assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf: no best yet"); + await openPicker(s); + assert.equal(await focusedCard(s), "golf"); + assert.match(await card(s, "golf").innerText(), /Last played/); + assert.doesNotMatch(await card(s, "snake").innerText(), /Last played/); fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, lastActivity: "chess" } })); const again = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); - await openActivities(again); - assert.equal(await overlay(again), "Press space to start", "an unknown pick opens on Snake"); - assert.equal(await again.page.locator('#activities-picker button[data-activity="snake"]').getAttribute("aria-pressed"), "true"); + await openPicker(again); + assert.equal(await focusedCard(again), "snake", "an unknown pick puts focus on the first card"); + assert.equal(await again.page.locator("#activities-picker .activities-card-tag").count(), 0); +}); + +test("Light Trails plays in the real window: a wide board, the rivals ride, and an arrow steers you", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await openActivities(s, "trails"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - 4 / 3) < 0.02, `a 4:3 board, not ${box.width} by ${box.height}`); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 20); + await s.page.keyboard.press("ArrowUp"); + await step(s, 20); + assert.equal(await overlay(s), "", "still riding"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + await s.page.keyboard.press("p"); + await pausedNow(s); +}); + +test("Bug Hunt plays in the real window: held space fires until let go, a held arrow slides the ship, and a pause lets go of both", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const hunt = (await import("/activities/bugs.js")).default; + const watched = { ...hunt, create: (opts) => (window.__bugs = hunt.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "bugs" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "bugs"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - 4 / 3) < 0.02, `a 4:3 board, not ${box.width} by ${box.height}`); + const shots = () => s.page.evaluate(() => window.__bugs.round.shots.length); + const input = () => s.page.evaluate(() => ({ ...window.__bugs.round.input })); + await s.page.keyboard.down(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 3, 60); + assert.ok((await shots()) > 0, "held space fires"); + await s.page.keyboard.up(" "); + assert.equal((await input()).fire, false, "let go, the firing stops"); + const x = await s.page.evaluate(() => window.__bugs.round.ship.x); + await s.page.keyboard.down("ArrowLeft"); + await step(s, 4, 60); + assert.ok((await s.page.evaluate(() => window.__bugs.round.ship.x)) < x, "a held arrow slides the ship"); + await s.page.keyboard.press("p"); + await pausedNow(s); + assert.deepEqual(await input(), { left: false, right: false, up: false, down: false, fire: false }, "a pause holds nothing"); + await s.page.keyboard.up("ArrowLeft"); +}); + +test("Sunset Drive plays in the real window: a wide board, held up drives until let go, a held arrow steers, space burns nitro, and a pause lets go of every key", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const road = (await import("/activities/drive.js")).default; + const watched = { ...road, create: (opts) => (window.__drive = road.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "drive" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "drive"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - 16 / 9) < 0.02, `a 16:9 board, not ${box.width} by ${box.height}`); + const round = () => s.page.evaluate(() => ({ ...window.__drive.round.input, speed: window.__drive.round.speed, x: window.__drive.round.x, nitro: window.__drive.round.nitro })); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await s.page.keyboard.down("ArrowUp"); + await step(s, 6, 60); + assert.ok((await round()).speed > 0, "held up drives"); + await s.page.keyboard.up("ArrowUp"); + assert.equal((await round()).up, false, "let go, the gas is off"); + const x = (await round()).x; + await s.page.keyboard.down("ArrowLeft"); + await step(s, 4, 60); + assert.ok((await round()).x < x, "a held arrow steers"); + await s.page.keyboard.press(" "); + assert.equal((await round()).nitro, 1, "space burns a nitro can"); + await s.page.keyboard.press("p"); + await pausedNow(s); + const held = await round(); + assert.deepEqual([held.left, held.right, held.up, held.down], [false, false, false, false], "a pause holds nothing"); + await s.page.keyboard.up("ArrowLeft"); +}); + +test("Stack Deploy plays in the real window: space and a click on the board drop the block, an arrow that plays on does not, and a miss saves the best and the highest floor", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const tower = (await import("/activities/stack.js")).default; + const watched = { ...tower, create: (opts) => (window.__stack = tower.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "stack" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "stack"); + assert.equal(await overlay(s), "Press space or click to start"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - 4 / 3) < 0.02, `a 4:3 board, not ${box.width} by ${box.height}`); + const round = () => s.page.evaluate(() => ({ floor: window.__stack.round.floor, streak: window.__stack.round.streak, x: window.__stack.round.slider?.x ?? null })); + // Puts the sliding block right over the top of the tower, or clear of it. + const aim = (off = 0) => + s.page.evaluate((off) => { + const r = window.__stack.round; + r.slider.x = r.blocks[r.blocks.length - 1].x + off; + }, off); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + assert.equal((await round()).floor, 0, "and drops nothing"); + await step(s, 2); + await aim(); + await s.page.keyboard.press(" "); + assert.deepEqual([(await round()).floor, (await round()).streak], [1, 1], "space drops, dead on is a perfect"); + await step(s, 2); + await aim(); + await s.page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + assert.equal((await round()).floor, 2, "a click on the board drops"); + await step(s, 2); + // A key repeat of up (say, up held through the countdown) never drops. + await aim(); + await s.page.evaluate(() => document.getElementById("activities-board").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", repeat: true, bubbles: true }))); + assert.equal((await round()).floor, 2, "a repeated up drops nothing"); + await step(s, 2); + await s.page.keyboard.press("p"); + await pausedNow(s); + const held = (await round()).x; + await s.page.keyboard.press("ArrowUp"); + assert.equal(await overlay(s), "", "an arrow plays on"); + assert.equal((await round()).floor, 2, "and drops nothing"); + assert.equal((await round()).x, held, "the block waits where it was"); + await step(s, 2); + assert.notEqual((await round()).x, held, "then slides on"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + await aim(1000); + await s.page.keyboard.press(" "); + await step(s, 10, 200); + await until(async () => (await overlay(s)).startsWith("Score:"), 5000); + const score = await s.page.evaluate(() => window.__stack.score); + assert.ok(score > 0); + await until(async () => { + const looks = await serverLooks(s); + return looks.activityBestStack === score && looks.activityMemoStack === 2; + }, 5000); +}); + +test("Bumper Ring plays in the real window: a 4:3 board, held arrows push until let go, space dashes, a pause lets go of every key, and the last fall saves the best and the furthest arena", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const ring = (await import("/activities/bumper.js")).default; + const watched = { ...ring, create: (opts) => (window.__bumper = ring.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "bumper" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "bumper"); + assert.equal(await overlay(s), "Press space to start"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - 4 / 3) < 0.02, `a 4:3 board, not ${box.width} by ${box.height}`); + const you = () => s.page.evaluate(() => { + const r = window.__bumper.round; + return { ...r.input, y: r.cars[0].y, charges: r.cars[0].charges, phase: r.phase, level: r.level }; + }); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 8); + assert.equal((await you()).phase, "fight", "past the hold before the heat"); + const y = (await you()).y; + await s.page.keyboard.down("ArrowUp"); + await step(s, 4); + assert.ok((await you()).y < y - 2, "held up pushes up"); + await s.page.keyboard.up("ArrowUp"); + assert.equal((await you()).up, false, "let go, the push stops"); + await s.page.keyboard.down("ArrowLeft"); + await s.page.keyboard.press(" "); + assert.equal((await you()).charges, 1, "space dashes"); + await s.page.keyboard.press("p"); + await pausedNow(s); + const held = await you(); + assert.deepEqual([held.left, held.right, held.up, held.down], [false, false, false, false], "a pause holds nothing"); + await s.page.keyboard.up("ArrowLeft"); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space plays on"); + assert.equal((await you()).charges, 1, "and does not also dash"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + // Knock the Bully off for a win (arena 2 is a new furthest), then fall + // off on your last life. + await s.page.evaluate(() => { + const bully = window.__bumper.round.cars[1]; + Object.assign(bully, { x: bully.x, y: -20, vx: 0, vy: 0 }); + }); + await step(s, 1); + await until(async () => (await you()).phase === "done", 5000); + await step(s, 40); + await until(async () => (await you()).level === 2, 5000); + await step(s, 30); + await s.page.evaluate(() => { + const r = window.__bumper.round; + r.lives = 1; + Object.assign(r.cars[0], { y: 200, vx: 0, vy: 0 }); + }); + await step(s, 40); + await until(async () => (await overlay(s)).startsWith("Score:"), 5000); + const score = await s.page.evaluate(() => window.__bumper.score); + assert.ok(score > 0); + await until(async () => { + const looks = await serverLooks(s); + return looks.activityBestBumper === score && looks.activityMemoBumper === 2; + }, 5000); +}); + +test("Hot Potato plays in the real window: a 106 by 76 unit board, held arrows run until let go, space dashes, a pause lets go of every key, and the last blast saves the best and the furthest venue", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const potato = (await import("/activities/fuse.js")).default; + const watched = { ...potato, create: (opts) => (window.__fuse = potato.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "fuse" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "fuse"); + assert.equal(await overlay(s), "Press space to start"); + const box = await s.page.locator("#activities-canvas").boundingBox(); + // fuse.js: W = AW + PAD * 2 = 106, H = HUD_H + AH + 1.5 = 76. + assert.ok(Math.abs(box.width / box.height - 106 / 76) < 0.02, `a 106:76 board, not ${box.width} by ${box.height}`); + const you = () => + s.page.evaluate(() => { + const r = window.__fuse.round; + return { ...r.input, y: r.runners[0].y, charges: r.runners[0].charges, phase: r.phase, level: r.level }; + }); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 8); + assert.equal((await you()).phase, "play", "past the hold before the match"); + // The rivals stand still, so nobody runs into you mid-test. + await s.page.evaluate(() => { + for (const r of window.__fuse.round.runners) if (r.id !== 0) Object.assign(r, { think: 1e9, push: { x: 0, y: 0 }, charges: 0 }); + }); + const y = (await you()).y; + await s.page.keyboard.down("ArrowUp"); + await step(s, 4); + assert.ok((await you()).y < y - 3, "held up runs up"); + await s.page.keyboard.up("ArrowUp"); + assert.equal((await you()).up, false, "let go, the running stops"); + await s.page.keyboard.down("ArrowLeft"); + await s.page.keyboard.press(" "); + assert.equal((await you()).charges, 1, "space dashes"); + await s.page.keyboard.press("p"); + await pausedNow(s); + const held = await you(); + assert.deepEqual([held.left, held.right, held.up, held.down], [false, false, false, false], "a pause holds nothing"); + await s.page.keyboard.up("ArrowLeft"); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space plays on"); + assert.equal((await you()).charges, 1, "and does not also dash"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + // Win the match (venue 2 is a new furthest): everyone but the holder sits + // out and its fuse runs out. Then the bomb blows on you on your last life. + await s.page.evaluate(() => { + const r = window.__fuse.round; + const holder = r.bombs[0].holder; + for (const o of r.runners) if (o.id !== 0 && o.id !== holder) Object.assign(o, { alive: false, outMs: 0 }); + r.bombs[0].fuse = 1; + }); + await step(s, 1); + await until(async () => (await you()).phase === "done", 5000); + await step(s, 40); + await until(async () => (await you()).level === 2, 5000); + await step(s, 30); + await s.page.evaluate(() => { + const r = window.__fuse.round; + r.lives = 1; + Object.assign(r.bombs[0], { holder: 0, fuse: 1, lock: 0 }); + }); + await step(s, 40); + await until(async () => (await overlay(s)).startsWith("Score:"), 5000); + const score = await s.page.evaluate(() => window.__fuse.score); + assert.ok(score > 0); + await until(async () => { + const looks = await serverLooks(s); + return looks.activityBestFuse === score && looks.activityMemoFuse === 2; + }, 5000); +}); + +test("Crossing Rush plays in the real window: its board's shape, an arrow hops once a press (a held one never again), space uses a pickup, a pause drops the queued hop, and the last heat lost saves the best and the furthest zone", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const rush = (await import("/activities/hop.js")).default; + const watched = { ...rush, create: (opts) => (window.__hop = rush.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "hop" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "hop"); + assert.equal(await overlay(s), "Press space to start"); + const { W, H } = await s.page.evaluate(async () => { + const { W, H } = await import("/activities/hop.js"); + return { W, H }; + }); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - W / H) < 0.02, `a ${W} by ${H} board, not ${box.width} by ${box.height}`); + const you = () => + s.page.evaluate(() => { + const r = window.__hop.round; + const me = r.hoppers[0]; + return { row: me.row, x: me.x, hopping: Boolean(me.hop), queued: me.queued, phase: r.phase, level: r.level }; + }); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 8); + assert.equal((await you()).phase, "play", "past the hold before the heat"); + // The rivals stand still and the first rows are grass, so nothing runs + // into you mid-test. + await s.page.evaluate(() => { + const r = window.__hop.round; + for (const h of r.hoppers) if (h.id !== 0) Object.assign(h, { hop: null, think: 1e9, row: 0 }); + for (let row = 1; row <= 4; row++) Object.assign(r.lanes[row], { kind: "grass", items: [], speed: 0, trees: new Array(11).fill(0) }); + r.pickups = []; + }); + await s.page.keyboard.press("ArrowUp"); + await step(s, 3); + assert.equal((await you()).row, 1, "a press hops a cell"); + await s.page.keyboard.down("ArrowUp"); + await s.page.keyboard.down("ArrowUp"); + await s.page.keyboard.down("ArrowUp"); + await step(s, 6); + assert.equal((await you()).row, 2, "a held arrow hops once, its repeats never"); + await s.page.keyboard.up("ArrowUp"); + await s.page.evaluate(() => { + window.__hop.round.hoppers[0].powers = ["shield"]; + }); + await s.page.keyboard.press(" "); + assert.equal(await s.page.evaluate(() => window.__hop.round.hoppers[0].shield > 0), true, "space uses the pickup"); + await step(s, 4); + await s.page.keyboard.press("ArrowLeft"); + await s.page.keyboard.press("ArrowUp"); + assert.equal((await you()).queued, "up", "a press during a hop waits its turn"); + await s.page.keyboard.press("p"); + await pausedNow(s); + assert.equal((await you()).queued, null, "a pause drops it"); + const held = await you(); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space plays on"); + await step(s, 6); + assert.equal((await you()).row, held.row, "and nothing hops on by itself"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + // Win the heat (zone 2 is a new furthest), then lose the last life with + // both rivals home first. + await s.page.evaluate(() => { + const r = window.__hop.round; + const top = r.rows - 1; + Object.assign(r.lanes[top - 1], { kind: "grass", items: [], speed: 0, trees: new Array(11).fill(0) }); + Object.assign(r.hoppers[0], { row: top - 1, x: 5, hop: null, daze: 0 }); + }); + await s.page.keyboard.press("ArrowUp"); + await step(s, 3); + await until(async () => (await you()).phase === "done", 5000); + await step(s, 40); + await until(async () => (await you()).level === 2, 5000); + await step(s, 30); + await s.page.evaluate(() => { + const r = window.__hop.round; + r.lives = 1; + for (const h of r.hoppers.slice(1)) { + Object.assign(h, { hop: null, think: 1e9, finished: true }); + r.finishers.push(h); + h.place = r.finishers.length; + } + }); + await step(s, 40); + await until(async () => (await overlay(s)).startsWith("Score:"), 5000); + const score = await s.page.evaluate(() => window.__hop.score); + assert.ok(score > 0); + await until(async () => { + const looks = await serverLooks(s); + return looks.activityBestHop === score && looks.activityMemoHop === 2; + }, 5000); +}); + +test("Bounce Road plays in the real window: its board's shape and cars big enough to read, held keys drive and steer until let go, space jumps once a press (never on its repeat, never with the press that plays on), a pause lets go of every key and holds a jump mid-air, and the last life lost saves the best and the furthest stage", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const bounce = (await import("/activities/bounce.js")).default; + const watched = { ...bounce, create: (opts) => (window.__bounce = bounce.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "bounce" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "bounce"); + assert.equal(await overlay(s), "Press space to start"); + const { W, H, CAR_L } = await s.page.evaluate(async () => { + const { W, H, CAR_L } = await import("/activities/bounce.js"); + return { W, H, CAR_L }; + }); + const box = await s.page.locator("#activities-canvas").boundingBox(); + assert.ok(Math.abs(box.width / box.height - W / H) < 0.02, `a ${W} by ${H} board, not ${box.width} by ${box.height}`); + const carPx = (box.width / W) * CAR_L; + assert.ok(carPx >= 24, `a car 24 px long or more in a 1280 by 800 window (${carPx.toFixed(1)} px)`); + const you = () => + s.page.evaluate(() => { + const r = window.__bounce.round; + const me = r.cars[0]; + return { ...r.input, v: me.v, x: me.x, air: me.air, phase: r.phase, stage: r.stage }; + }); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space starts a round"); + await step(s, 2, 16); + assert.equal((await you()).phase, "drive", "on the road at once after the window's 3, 2, 1"); + // No rivals, so nothing runs into you mid-test. + await s.page.evaluate(() => { + const r = window.__bounce.round; + r.cars.length = 1; + r.spawnMs = 1e9; + }); + await s.page.keyboard.down("ArrowUp"); + await step(s, 40, 16); + assert.ok((await you()).v > 30, "held up drives"); + const x = (await you()).x; + await s.page.keyboard.down("ArrowLeft"); + await step(s, 6, 16); + assert.ok((await you()).x < x, "held left steers"); + await s.page.keyboard.up("ArrowLeft"); + await s.page.keyboard.down(" "); + await step(s, 2, 16); + assert.ok((await you()).air > 0, "space jumps"); + await s.page.keyboard.down(" "); + await s.page.keyboard.down(" "); + await step(s, 80, 16); + assert.equal((await you()).air, 0, "a held space, its repeats included, jumps once"); + await s.page.keyboard.up(" "); + await s.page.keyboard.press(" "); + await step(s, 4, 16); + const air = (await you()).air; + assert.ok(air > 0, "a fresh press jumps again"); + await s.page.keyboard.down("ArrowRight"); + await s.page.keyboard.press("p"); + await pausedNow(s); + const held = await you(); + assert.deepEqual([held.up, held.right, held.jump], [false, false, 0], "a pause holds nothing"); + assert.equal(held.air, air, "and holds the jump mid-air"); + await s.page.keyboard.up("ArrowRight"); + await s.page.keyboard.up("ArrowUp"); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space plays on"); + await step(s, 2, 16); + const resumed = await you(); + assert.ok(resumed.air > 0 && resumed.air < air, "the jump carries on, and the press that played on started none"); + assert.match(await s.page.locator("#activities-score").innerText(), /^Score: \d+ · Best: 0$/); + // Cross into stage 2 (a new furthest), then lose the last life in a hole. + await s.page.evaluate(() => { + const r = window.__bounce.round; + const me = r.cars[0]; + Object.assign(me, { air: 0, d: r.road.stageAt[1] - 0.2 }); + const i = Math.floor(me.d / 2); + me.x = (r.road.L[i] + r.road.R[i]) / 2; + }); + await step(s, 4, 16); + await until(async () => (await you()).stage === 2, 5000); + await step(s, 10, 16); + await s.page.evaluate(() => { + const r = window.__bounce.round; + const me = r.cars[0]; + r.lives = 1; + const hole = r.road.holes.find((h) => h.d0 > me.d); + Object.assign(me, { air: 0, d: hole.d0 - 3, v: 20, bubble: false }); + }); + await step(s, 120, 16); + await until(async () => (await overlay(s)).startsWith("Score:"), 5000); + const score = await s.page.evaluate(() => window.__bounce.score); + assert.ok(score > 0); + await until(async () => { + const looks = await serverLooks(s); + return looks.activityBestBounce === score && looks.activityMemoBounce === 2; + }, 5000); }); test("the die works on a skill screen and on a finished screen", async (t) => { @@ -249,6 +818,179 @@ test("Esc closes the window with the game paused, and P toggles pause", async (t assert.ok((await overlay(s)).startsWith("Paused"), "reopening resumes the same round, paused"); }); +test("the endless-lives code typed on the board gives the round endless lives, from the start screen or mid-round, and a new round, a wrong key or closing the window takes it away", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const hunt = (await import("/activities/bugs.js")).default; + const watched = { ...hunt, create: (opts) => (window.__bugs = hunt.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "bugs" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "bugs"); + const CODE = ["ArrowUp", "ArrowDown", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "b", "a", " "]; + const type = async (keys) => { + for (const k of keys) await s.page.keyboard.press(k); + }; + const endless = () => s.page.evaluate(() => Boolean(window.__bugs.round.infinite)); + // From the start screen: the code's space starts the round, endless. + await type(CODE); + assert.equal(await endless(), true, "typed before the round, it holds for the round its space starts"); + await step(s, 8, 60); + assert.equal(await endless(), true, "and keeps holding"); + // R is a new round, without it. + await s.page.keyboard.press("r"); + await step(s, 8, 60); + assert.equal(await endless(), false, "a new round starts without it"); + // A wrong key on the way starts the code over. + await type([...CODE.slice(0, 6), "ArrowUp", ...CODE.slice(6)]); + assert.equal(await endless(), false, "a slip and it never takes"); + await type(CODE); + assert.equal(await endless(), true, "typed mid-round"); + // Closing the window lets it go. + await s.page.keyboard.press("Escape"); + assert.equal(await endless(), false, "closing the window lets it go"); +}); + +test("the stage code typed on Ghoul Rush's board opens its stage select, the arrows pick a stage and room there, and space goes straight into that room", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const ghoul = (await import("/activities/ghoul.js")).default; + const watched = { ...ghoul, create: (opts) => (window.__ghoul = ghoul.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "ghoul" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "ghoul"); + const CODE = ["ArrowUp", "ArrowDown", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "s"]; + const type = async (keys) => { + for (const k of keys) await s.page.keyboard.press(k); + }; + const now = () => s.page.evaluate(() => ({ state: window.__ghoul.state, phase: window.__ghoul.round.phase, select: window.__ghoul.round.select, stage: window.__ghoul.round.stage, at: window.__ghoul.round.stageAt })); + // A slip on the way and nothing opens. + await type([...CODE.slice(0, 5), "ArrowUp", ...CODE.slice(5)]); + assert.equal((await now()).state, "ready", "a slip and it never opens"); + await type(CODE); + let r = await now(); + assert.equal(r.state, "running"); + assert.equal(r.phase, "select", "the code opens the stage select from the start screen"); + await step(s, 4, 60); + assert.equal((await now()).phase, "select", "it waits on a choice"); + await type(["ArrowDown", "ArrowRight", "ArrowRight"]); + r = await now(); + assert.deepEqual(r.select, { at: 1, room: 2 }); + await s.page.keyboard.press(" "); + r = await now(); + assert.equal(r.phase, "ready"); + assert.equal(r.stage, "wing"); + assert.equal(r.at, 2, "straight into the room picked"); +}); + +test("Ghoul Rush's secondary weapon, with real keys in the window: a double tap of space uses it, a held key's repeats and a long hold never do, and held after the second tap the bolts carry on", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await s.page.evaluate(async () => { + const m = await import("/screens/activities.js"); + const { ACTIVITIES } = await import("/activities.js"); + const ghoul = (await import("/activities/ghoul.js")).default; + const watched = { ...ghoul, create: (opts) => (window.__ghoul = ghoul.create(opts)) }; + m.setActivityList(ACTIVITIES.map((e) => (e.id === "ghoul" ? { ...e, game: watched } : e))); + }); + await openActivities(s, "ghoul"); + // The stage code: a practice round in the Foyer, its bag full, straight in. + for (const k of ["ArrowUp", "ArrowDown", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "s"]) await s.page.keyboard.press(k); + await s.page.keyboard.press(" "); + const now = () => s.page.evaluate(() => { + const g = window.__ghoul; + const r = g.round; + return { phase: r.phase, kind: r.arms[0]?.kind, n: r.arms[0]?.n, balls: r.hazards.filter((h) => h.kind === "armBall").length, bolts: r.shots.filter((q) => !q.arm).length, hud: g.hud.arm && g.hud.arm.text }; + }); + for (let i = 0; i < 40 && (await now()).phase !== "play"; i++) await step(s, 1, 60); + await s.page.evaluate(() => { + const r = window.__ghoul.round; + r.you.safeMs = 1e9; + r.timeMs = 1e9; + }); + let r = await now(); + assert.equal(r.phase, "play"); + assert.equal(r.kind, "ball", "the stage's own on top"); + const full = r.n; + assert.equal(r.hud, `x${full} +3 TAP TAP`, "the HUD says so, and how"); + // A long hold, with the key's own repeats: bolts only. + await s.page.keyboard.down(" "); + await step(s, 1, 16); + await s.page.keyboard.down(" "); + await s.page.keyboard.down(" "); + await step(s, 10, 40); + await s.page.keyboard.up(" "); + r = await now(); + assert.equal(r.n, full, "a hold and its repeats spend nothing"); + await step(s, 10, 40); + // The double tap. + await s.page.keyboard.press(" "); + await step(s, 1, 16); + await s.page.keyboard.press(" "); + await step(s, 1, 16); + r = await now(); + assert.equal(r.n, full - 1, "two taps, one weapon"); + assert.equal(r.balls, 1, "and it is on the floor"); + assert.equal(r.hud, `x${full - 1} +3`, "the prompt has done its job"); + await step(s, 16, 40); + // Held after the second tap: used, then the blaster. + await s.page.keyboard.press(" "); + await step(s, 1, 16); + await s.page.keyboard.down(" "); + await step(s, 1, 16); + await s.page.evaluate(() => (window.__ghoul.round.shots.length = 0)); + r = await now(); + assert.equal(r.n, full - 2, "used on the second press"); + await step(s, 10, 40); + r = await now(); + assert.ok(r.bolts > 0, "held on, the bolts carry on"); + assert.equal(r.n, full - 2, "and no more spent"); + await s.page.keyboard.up(" "); +}); + +test("R starts the round over from the countdown, running or paused, and does nothing before a round has begun", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s, 100); + await openActivities(s); + const ready = await overlay(s); + await s.page.keyboard.press("r"); + assert.equal(await overlay(s), ready, "no round yet: R does nothing"); + await s.page.keyboard.press(" "); + await step(s, 8); + assert.equal(await overlay(s), "", "playing"); + await s.page.keyboard.press("r"); + assert.equal(await overlay(s), "3", "R: a new round, from the count"); + await step(s, 8); + await s.page.keyboard.press("p"); + assert.ok((await overlay(s)).startsWith("Paused")); + await s.page.keyboard.press("r"); + assert.equal(await overlay(s), "3", "and from a pause"); +}); + +test("in full screen the Music slider moves into the panel, and back under the board after", async (t) => { + savedLooks(t, { gameMusic: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await s.page.setViewportSize({ width: 1600, height: 900 }); + await handTicks(s); + await openActivities(s, "ghoul"); + const where = () => s.page.evaluate(() => (document.getElementById("activities-music").closest("#activities-rail") ? "rail" : "actions")); + assert.equal(await where(), "actions"); + await s.page.keyboard.press("f"); + await until(async () => (await where()) === "rail", 5000); + assert.equal(await s.page.locator("#activities-music-level").isVisible(), true, "shown in the panel"); + await s.page.keyboard.press("f"); + await until(async () => (await where()) === "actions", 5000); + assert.equal(await s.page.locator("#activities-music-level").isVisible(), true); +}); + test("starting and playing on count down 3, 2, 1 with the game held still, and P during the count pauses it", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await handTicks(s, 100); @@ -305,6 +1047,244 @@ test("a new question mid-game pauses it and shows the banner, and Go to it close assert.ok(await itemCard(s.page, "q2").isVisible(), "the question is on screen"); }); +// The full-screen stage's parts, measured: the stage, the board's canvas and +// the panel, and where the score line sits. +const fullParts = (s) => + s.page.evaluate(() => { + const rect = (id) => { + const r = document.getElementById(id).getBoundingClientRect(); + return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, w: r.width, h: r.height }; + }; + const stage = document.getElementById("activities-stage"); + const rail = document.getElementById("activities-rail"); + return { + full: stage.classList.contains("full"), + dock: stage.dataset.dock || null, + vw: innerWidth, + vh: innerHeight, + stage: rect("activities-stage"), + canvas: rect("activities-canvas"), + rail: rail.hidden ? null : rect("activities-rail"), + scoreInRail: rail.contains(document.getElementById("activities-score")), + railTitle: document.getElementById("activities-rail-title").textContent, + }; + }); + +// The canvas as big as the screen allows, centered with even black bars, +// and the panel on the screen: docked in a bar (never over the canvas) when +// one holds it, floating over the canvas's corner otherwise. +function assertLaidOut(p, what) { + const inside = (r) => r.left >= -1 && r.top >= -1 && r.right <= p.vw + 1 && r.bottom <= p.vh + 1; + assert.ok(inside(p.canvas), `${what}: the board is on the screen ${JSON.stringify(p.canvas)}`); + assert.ok(p.canvas.w >= p.vw * 0.92 || p.canvas.h >= p.vh * 0.92, `${what}: the board fills the screen one way ${JSON.stringify(p.canvas)}`); + assert.ok(Math.abs(p.canvas.left - (p.vw - p.canvas.right)) <= 2 && Math.abs(p.canvas.top - (p.vh - p.canvas.bottom)) <= 2, `${what}: centered between even bars ${JSON.stringify(p.canvas)}`); + assert.ok(p.rail && inside(p.rail), `${what}: the panel is on the screen ${JSON.stringify(p.rail)}`); + if (p.dock === "side") assert.ok(p.canvas.right <= p.rail.left + 1, `${what}: a docked panel never covers the board ${JSON.stringify({ canvas: p.canvas, rail: p.rail })}`); + else if (p.dock === "below") assert.ok(p.canvas.bottom <= p.rail.top + 1, `${what}: a docked panel never covers the board ${JSON.stringify({ canvas: p.canvas, rail: p.rail })}`); + else assert.equal(p.dock, "float", `${what}: the panel floats where no bar holds it`); +} + +test("Full screen gives the board the whole screen with a panel holding the score laid in its black bar, F and Esc put it back, and a new question mid-game puts it back too", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await s.page.setViewportSize({ width: 1600, height: 900 }); + await handTicks(s); + await openPicker(s); + const btn = s.page.locator("#activities-full"); + assert.ok(await btn.isHidden(), "no Full screen on the picker"); + await s.page.locator('.activities-card[data-activity="snake"]').click(); + await until(async () => (await overlay(s)) !== "", 5000); + const before = await fullParts(s); + assert.ok(!before.full && !before.rail && !before.scoreInRail, "the window opens at its own size, with no panel"); + + await btn.click(); + await until(async () => (await fullParts(s)).full, 5000); + const big = await fullParts(s); + assert.equal(Math.round(big.stage.w), big.vw, "the stage is as wide as the screen"); + assert.equal(Math.round(big.stage.h), big.vh, "and as tall"); + assert.ok(big.canvas.h >= big.vh - 40, `the board takes (nearly) the whole height: ${big.canvas.h} of ${big.vh}`); + assert.ok(big.canvas.w * big.canvas.h > before.canvas.w * before.canvas.h, "and grows"); + assertLaidOut(big, "Snake"); + assert.equal(big.dock, "side", "Snake's square on a wide screen docks the panel in the side bar"); + assert.ok(big.scoreInRail, "the score line moves into the panel"); + assert.equal(big.railTitle, "Snake", "which names the game"); + assert.equal(await s.page.locator("#activities-rail-best").innerText(), "No best yet"); + assert.equal(await s.page.evaluate(() => document.activeElement.id), "activities-board", "keys go back to the board"); + await s.page.keyboard.press(" "); + await step(s, 3); + assert.match(await s.page.locator("#activities-rail").innerText(), /Score: \d/, "the score shows in the panel while playing"); + await s.page.keyboard.press("p"); + + await s.page.keyboard.press("f"); + const back = await fullParts(s); + assert.ok(!back.full && !back.rail && !back.scoreInRail, "F puts it back, the score under the board again"); + await s.page.keyboard.press("f"); + assert.ok((await fullParts(s)).full, "and F fills it again"); + await s.page.click("#activities-rail-exit"); + assert.ok(!(await fullParts(s)).full, "the panel's Exit full screen puts it back"); + await s.page.keyboard.press("f"); + await s.page.keyboard.press("Escape"); + await until(async () => !(await fullParts(s)).full, 5000); + assert.ok(await s.page.locator("#activities-modal[open]").isVisible(), "Esc leaves full screen before it closes the window"); + + await s.page.keyboard.press("f"); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "a running game"); + await step(s, 3); + s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: "Who opens the export?" }], agent: { status: "waiting" } }); + await pausedNow(s); + assert.ok(!(await fullParts(s)).full, "the question puts the window back to its size"); + assert.equal(await btn.innerText(), "Full screen"); + assert.ok(await s.page.locator("#activities-banner").isVisible(), "with the banner showing"); +}); + +test("Full screen on a screen the board fills floats the panel over its corner, and a round in play with the pointer still shrinks it to the score line", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await s.page.setViewportSize({ width: 1600, height: 900 }); + await handTicks(s); + await openActivities(s, "ghoul"); + await s.page.keyboard.press("f"); + await until(async () => (await fullParts(s)).dock === "float", 5000); + assertLaidOut(await fullParts(s), "Ghoul Rush at 1600x900"); + const title = s.page.locator("#activities-rail-title"); + assert.ok(await title.isVisible(), "before a round the whole panel shows"); + await s.page.keyboard.press(" "); + await step(s, 1, 0); + for (let i = 0; i < 4; i++) await step(s, 1, 1000); + assert.equal(await overlay(s), "", "playing"); + await step(s, 3); + await until(async () => !(await title.isVisible()), 5000); + assert.ok(await s.page.locator("#activities-rail .activities-score").isVisible(), "the score line stays"); + await s.page.mouse.move(200, 200); + await s.page.mouse.move(220, 210); + await until(async () => await title.isVisible(), 5000); + await s.page.keyboard.press("p"); + assert.ok(await title.isVisible(), "a pause keeps the whole panel"); +}); + +test("Full screen lays every game out on wide, 16:10, ultrawide and tall screens: the board as big as the screen allows, the panel docked in a bar that holds it or floating over the board", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + const screens = [[1920, 1080], [1440, 900], [2560, 1080], [900, 1400]]; + const ids = (await s.page.evaluate(async () => (await import("/activities.js")).ACTIVITIES.map((a) => a.id))).filter((id) => id !== "golf"); + for (const id of [...ids, "golf"]) { + await s.page.setViewportSize({ width: 1600, height: 900 }); + await openActivities(s, id); + await s.page.keyboard.press("f"); + for (const [w, h] of screens) { + await s.page.setViewportSize({ width: w, height: h }); + // The resize event lays the game out a frame after the stage changes. + await until(async () => { + const p = await fullParts(s); + if (!p.full || Math.round(p.stage.w) !== w || Math.round(p.stage.h) !== h) return false; + try { + assertLaidOut(p, ""); + return true; + } catch { + return false; + } + }, 5000); + const p = await fullParts(s); + assertLaidOut(p, `${id} at ${w}x${h}`); + if (w === 2560) assert.equal(p.dock, "side", `${id} at ${w}x${h}: an ultrawide screen docks the panel at the side`); + } + await s.page.keyboard.press("Escape"); + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + } +}); + +// A stand-in AudioContext that counts the oscillators made, so a test can +// tell whether a sound played. +const COUNT_SOUNDS = () => { + window.__oscillators = 0; + const node = () => ({ connect() {}, start() {}, stop() {}, disconnect() {}, frequency: param(), gain: param(), Q: param(), type: "" }); + const param = () => ({ value: 0, setValueAtTime() {}, exponentialRampToValueAtTime() {}, linearRampToValueAtTime() {}, setTargetAtTime() {}, cancelScheduledValues() {} }); + window.AudioContext = class { + state = "running"; + currentTime = 0; + sampleRate = 44100; + destination = {}; + resume() { return Promise.resolve(); } + createOscillator() { window.__oscillators++; return node(); } + createGain() { return node(); } + createBiquadFilter() { return node(); } + createDynamicsCompressor() { return { ...node(), threshold: param(), knee: param(), ratio: param(), attack: param(), release: param() }; } + createBuffer() { return { getChannelData: () => new Float32Array(1) }; } + createBufferSource() { return { ...node(), buffer: null, playbackRate: param(), loop: false }; } + }; +}; + +test("Play game sounds in User Preferences silences the games and the countdown, Play sounds off grays it out, and Back to default turns it back on", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING, init: COUNT_SOUNDS }); + const played = () => s.page.evaluate(() => window.__oscillators); + // Starts a fresh round with the 3, 2, 1, which plays a blip, and closes it. + const countdown = async () => { + await handTicks(s, 50); + await openActivities(s); + const before = await played(); + await s.page.keyboard.press(" "); + await step(s, 3); + const after = await played(); + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + return after - before; + }; + assert.ok((await countdown()) > 0, "with game sounds on, the countdown plays"); + + await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-sounds"); + const box = s.page.locator("#looks-activity-sounds"); + assert.equal(await box.isChecked(), true, "on by default"); + await box.uncheck(); + await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activitySounds === false); + await s.page.locator("#looks-sound").uncheck(); + assert.equal(await box.isDisabled(), true, "Play sounds off grays it out"); + await s.page.locator("#looks-sound").check(); + assert.equal(await box.isDisabled(), false); + assert.equal(await box.isChecked(), false, "and it keeps its own tick"); + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("looks-modal").open); + assert.equal(await countdown(), 0, "with game sounds off, nothing plays"); + + await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-sounds"); + const tune = s.page.locator("#looks-game-music"); + assert.equal(await tune.isChecked(), false, "game music is off by default"); + await tune.check(); + await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).gameMusic === true); + await s.page.click("#looks-reset"); + await s.page.locator("#looks-activity-sounds:checked").waitFor(); + await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).gameMusic === false); + await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activitySounds === true); +}); + +test("a game with music has its own Music slider, at its default until moved, kept once moved, and dimmed while Play game music is off", async (t) => { + savedLooks(t, { gameMusic: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + const slider = s.page.locator("#activities-music-level"); + await openActivities(s, "snake"); + assert.equal(await s.page.locator("#activities-music").isVisible(), false, "Snake has no music, so no slider"); + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + await openActivities(s, "ghoul"); + assert.equal(await slider.isVisible(), true, "Ghoul Rush has one"); + assert.equal(await slider.inputValue(), "65", "at its default"); + assert.equal(await slider.isDisabled(), false); + await slider.fill("80"); + await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activityMusicGhoul === 80); + assert.equal((await pageLooks(s)).activityMusicDrive, 70, "another game keeps its own"); + await s.page.keyboard.press("Escape"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + await s.page.evaluate(async () => { + const { looks } = await import("/looks.js"); + looks.gameMusic = false; + }); + await openActivities(s, "ghoul"); + assert.equal(await slider.inputValue(), "80", "kept"); + assert.equal(await slider.isDisabled(), true, "Play game music off: dimmed"); + assert.match(await s.page.locator("#activities-music").getAttribute("title"), /Play game music/, "and says why"); +}); + test("the board is laid out again when the banner appears, so the canvas is never clipped", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await startGame(s); @@ -336,6 +1316,24 @@ test("a held P or space does not repeat", async (t) => { assert.ok((await overlay(s)).startsWith("Paused"), "a repeat of a held space does nothing"); }); +test("Enter starts a round, pauses it and plays on, and a held Enter acts once", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await handTicks(s); + await openActivities(s); + await s.page.keyboard.press("Enter"); + assert.equal(await overlay(s), "", "Enter starts a round"); + await step(s, 3); + await s.page.keyboard.press("Enter"); + await pausedNow(s); + await s.page.keyboard.press("Enter"); + assert.equal(await overlay(s), "", "Enter plays on"); + await s.page.keyboard.down("Enter"); + await pausedNow(s); + await s.page.keyboard.down("Enter"); + await s.page.keyboard.up("Enter"); + assert.ok((await overlay(s)).startsWith("Paused"), "a repeat of a held Enter does nothing"); +}); + test("a window too small to play shows the bigger-window note and pauses, and P cannot play it unseen", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await startGame(s); @@ -377,10 +1375,19 @@ test("playing on after a turn pause puts the banner away until the next new ques s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: "Who opens the export?" }], agent: { status: "waiting" } }); await pausedNow(s); const banner = s.page.locator("#activities-banner"); + const unpause = s.page.locator("#activities-unpause"); assert.ok(await banner.isVisible(), "the banner shows"); + assert.ok(await unpause.isVisible(), "with Unpause game beside Go to it"); await s.page.locator("#activities-board").focus(); - await s.page.keyboard.press(" "); - assert.equal(await overlay(s), "", "space plays again"); + for (const key of [" ", "p", "Enter", "ArrowUp", "d"]) { + await s.page.keyboard.press(key); + assert.ok((await overlay(s)).startsWith("Paused"), `${JSON.stringify(key)} does not play on while the turn holds the round`); + } + await s.page.click("#activities-overlay"); + assert.ok((await overlay(s)).startsWith("Paused"), "nor does a click on the overlay"); + assert.ok(await banner.isVisible(), "and the banner stays up"); + await unpause.click(); + assert.equal(await overlay(s), "", "Unpause game plays on"); assert.ok((await framesWaiting(s)) > 0); assert.ok(await banner.isHidden(), "playing on puts the banner away"); await step(s, 2); @@ -460,10 +1467,40 @@ test("a finish pauses the game and says Plan2Code is finished", async (t) => { await step(s, 5); assert.ok((await overlay(s)).startsWith("Paused"), "nothing resumes by itself"); await s.page.keyboard.press(" "); - assert.equal(await overlay(s), "", "space plays on"); + assert.ok((await overlay(s)).startsWith("Paused"), "space does not play on while the finish holds the round"); + await s.page.click("#activities-unpause"); + assert.equal(await overlay(s), "", "Unpause game plays on"); assert.ok(await s.page.locator("#activities-banner").isHidden(), "playing on puts the finish banner away too"); }); +test("after Go to it or a close, a round held by a question plays on from a game key when the window opens again", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await startGame(s); + s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: "Who opens the export?" }], agent: { status: "waiting" } }); + await pausedNow(s); + await s.page.click("#activities-goto"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + await s.page.click("#btn-activities"); + await s.page.locator("#activities-modal[open]").waitFor(); + await until(async () => (await overlay(s)).startsWith("Paused"), 5000); + assert.ok(await s.page.locator("#activities-unpause").isHidden(), "no Unpause game once the person went to it"); + await s.page.locator("#activities-board").focus(); + await s.page.keyboard.press(" "); + assert.equal(await overlay(s), "", "space plays on again"); + + s.post({ items: [{ id: "q3", kind: "text", title: "When it runs", body: "How often?" }] }); + await pausedNow(s); + assert.ok(await s.page.locator("#activities-unpause").isVisible(), "the next question holds the round again"); + await s.page.click("#activities-close"); + await s.page.waitForFunction(() => !document.getElementById("activities-modal").open); + await s.page.click("#btn-activities"); + await s.page.locator("#activities-modal[open]").waitFor(); + await until(async () => (await overlay(s)).startsWith("Paused"), 5000); + await s.page.locator("#activities-board").focus(); + await s.page.keyboard.press("ArrowUp"); + assert.equal(await overlay(s), "", "after a close, an arrow plays on"); +}); + test("a hidden page and a window blur each pause the game, and neither resumes it", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await startGame(s); @@ -586,6 +1623,9 @@ test("passing the best mid-round turns the line to a rainbow with sparks, once, assert.ok(sparks > 0, "the sparks fire"); await step(s, 3); assert.ok((await s.page.locator(".activities-spark").count()) <= sparks, "and only once a round"); + assert.match(await line.getAttribute("class"), /burst/, "the burst plays"); + await until(async () => !/burst/.test(await line.getAttribute("class")), 5000); + assert.match(await line.getAttribute("class"), /passed/, "then the line settles, still marked as a record"); await s.page.keyboard.press("ArrowUp"); assert.equal(await overlay(s), "Score: 9\nBest: 9\nPress space to play again", "the overlay's text is unchanged"); assert.match(await s.page.locator("#activities-overlay").getAttribute("class"), /record/, "the end screen marks the new best"); @@ -704,7 +1744,7 @@ test("a lowerIsBetter game saves a lower round over a higher best, and keeps the assert.equal((await pageLooks(s)).activityBestSnake, 5); }); -test("a drag on the board reaches a pointer game, a question mid-drag cancels it, and a press on the paused board plays on", async (t) => { +test("a drag on the board reaches a pointer game, a question mid-drag cancels it, and Unpause game, not a press on the board, plays on", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await handTicks(s); await listPointerGame(s, 3); @@ -738,7 +1778,9 @@ test("a drag on the board reaches a pointer game, a question mid-drag cancels it // The banner pushed the board down: measure the canvas again. const moved = await s.page.locator("#activities-canvas").boundingBox(); await s.page.mouse.click(moved.x + 8, moved.y + 8); - assert.equal(await overlay(s), "", "a press on the paused board plays on"); + assert.ok((await overlay(s)).startsWith("Paused"), "a press on the board does not play on while the question holds the round"); + await s.page.click("#activities-unpause"); + assert.equal(await overlay(s), "", "Unpause game plays on"); assert.ok(await s.page.locator("#activities-banner").isHidden(), "and puts the banner away"); assert.deepEqual( (await s.page.evaluate(() => window.__pointer)).filter((p) => p.type === "down" || p.type === "up"), @@ -771,8 +1813,7 @@ async function openGolf(s) { const watched = { ...golf, create: (opts) => (window.__golf = golf.create(opts)) }; m.setActivityList(ACTIVITIES.map((e) => (e.id === "golf" ? { ...e, game: watched } : e))); }); - await openActivities(s); - await s.page.locator('#activities-picker button[data-activity="golf"]').click(); + await openActivities(s, "golf"); await until(async () => (await overlay(s)) === "Press space or click to start", 5000); } @@ -824,6 +1865,45 @@ test("Mini golf: the aim follows the mouse, a click starts the meter, and a seco assert.ok(rolled.x > tee.x + 20, `aimed right, it rolls right (from ${tee.x} to ${rolled.x})`); }); +// Starts a round and drops the ball into the last hole's cup, so the round +// is over on the next frames. +async function finishGolf(s) { + await s.page.keyboard.press(" "); + await s.page.evaluate(async () => { + const { holesOf } = await import("/activities/golf.js"); + const r = window.__golf.round; + r.hole = holesOf(r).length - 1; + const { cup } = holesOf(r)[r.hole]; + Object.assign(r.ball, { x: cup.x, y: cup.y, vx: 1, vy: 0, moving: true }); + r.strokes = 1; + r.putts = 1; + r.phase = "rolling"; + }); + await step(s, 5, 16); + await until(async () => /pick a course/.test(await overlay(s)), 5000); +} + +test("Mini golf: once the round is over, space or a click goes back to the course dashboard rather than replaying the course, and the course picked there starts fresh", async (t) => { + savedLooks(t, { welcomeSeen: true }); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); + await openGolf(s); + await finishGolf(s); + assert.match(await overlay(s), /Press space or click to pick a course/); + await s.page.keyboard.press(" "); + await until(async () => (await courseCard(s, "pirate").count()) === 1, 5000); + assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf: pick a course"); + assert.equal(await s.page.locator("#activities-board").isVisible(), false, "the board is put away"); + assert.match(await courseCard(s, "pirate").innerText(), /Last played/); + await courseCard(s, "pirate").click(); + await until(async () => (await overlay(s)) === "Press space or click to start", 5000); + assert.equal((await s.page.evaluate(() => window.__golf.round.hole)), 0, "a fresh round from hole 1"); + + await finishGolf(s); + await s.page.locator("#activities-overlay").click(); + await until(async () => (await courseCard(s, "pirate").count()) === 1, 5000); + assert.equal(await s.page.locator("#activities-title").innerText(), "Activities · Mini golf: pick a course", "a click on the finish goes back too"); +}); + test("Mini golf: a held arrow turns the aim until it is let go, and holding space fast-forwards a roll until it is let go", async (t) => { savedLooks(t, { welcomeSeen: true }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); @@ -856,7 +1936,7 @@ test("Mini golf: a held arrow turns the aim until it is let go, and holding spac assert.equal((await golfRound(s)).strokes, 1, "and holding space putts nothing"); }); -test("Mini golf: a question mid-swing holds the meter with no stroke, one mid-roll stops the ball, and a click or an arrow plays on", async (t) => { +test("Mini golf: a question mid-swing holds the meter with no stroke, one mid-roll stops the ball, and only Unpause game plays on", async (t) => { savedLooks(t, { welcomeSeen: true }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await openGolf(s); @@ -875,10 +1955,13 @@ test("Mini golf: a question mid-swing holds the meter with no stroke, one mid-ro assert.equal(held.strokes, 0, "with no stroke"); assert.ok(await banner.isVisible()); - // The banner pushed the board down: a click on the board plays on. + // The banner pushed the board down: a click on the board stays paused, + // and Unpause game plays on. const box = await s.page.locator("#activities-canvas").boundingBox(); await s.page.mouse.click(box.x + 8, box.y + 8); - assert.equal(await overlay(s), "", "a click on the paused board plays on"); + assert.ok((await overlay(s)).startsWith("Paused"), "a click on the board waits for Unpause game"); + await s.page.click("#activities-unpause"); + assert.equal(await overlay(s), "", "Unpause game plays on"); assert.ok(await banner.isHidden(), "and puts the banner away"); const resumed = await golfRound(s); assert.equal(resumed.strokes, 0, "that click putts nothing"); @@ -896,26 +1979,27 @@ test("Mini golf: a question mid-swing holds the meter with no stroke, one mid-ro assert.deepEqual(await golfRound(s), stopped, "the ball holds still where the pause caught it"); assert.ok(await banner.isVisible(), "the next new question shows the banner again"); + await s.page.click("#activities-unpause"); await s.page.locator("#activities-board").focus(); - await s.page.keyboard.press("ArrowUp"); - assert.equal(await overlay(s), "", "an arrow plays on too"); + assert.equal(await overlay(s), "", "Unpause game plays on again"); assert.ok(await banner.isHidden()); await step(s, 5, 16); assert.notDeepEqual(await golfRound(s), stopped, "and the ball rolls on"); }); -test("Mini golf: a full round saves its total as the best, a lower one replaces it, a higher one does not, and Reset clears both games", async (t) => { +test("Mini golf: a full round saves its total as its course's best, a lower one replaces it, a higher one does not, each course keeps its own, and Reset clears them all", async (t) => { savedLooks(t, { welcomeSeen: true, activityBestSnake: 9 }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); await openGolf(s); const title = s.page.locator("#activities-title"); - assert.equal(await title.innerText(), "Activities · Mini golf: no best yet"); + assert.equal(await title.innerText(), "Activities · Mini golf, Pirate Cove: no best yet"); // Plays all eighteen holes through the game's own calls, each in `each` // strokes: the ball set down beside the cup, extra strokes counted first. const playRound = (each) => s.page.evaluate(async (each) => { - const { HOLES } = await import("/activities/golf-holes.js"); + const { courseById } = await import("/activities/golf-holes.js"); const g = window.__golf; + const HOLES = courseById(g.course).holes; if (g.state !== "running") g.key("action"); for (let h = 0; h < HOLES.length; h++) { const cup = HOLES[g.round.hole].cup; @@ -931,25 +2015,42 @@ test("Mini golf: a full round saves its total as the best, a lower one replaces } return g.state; }, each); - const golfBest = async () => (await serverLooks(s)).activityBestGolf; + const golfBest = async (course = "Pirate") => (await serverLooks(s))[`activityBestGolf${course}`]; assert.equal(await playRound(2), "over"); await until(async () => (await golfBest()) === 36, 5000); - assert.equal(await title.innerText(), "Activities · Mini golf best: 36", "a first round is the best"); + assert.equal(await title.innerText(), "Activities · Mini golf, Pirate Cove best: 36", "a first round is the best"); assert.equal(await playRound(1), "over"); await until(async () => (await golfBest()) === 18, 5000); - assert.equal(await title.innerText(), "Activities · Mini golf best: 18", "lower is better"); + assert.equal(await title.innerText(), "Activities · Mini golf, Pirate Cove best: 18", "lower is better"); assert.equal(await playRound(3), "over"); await step(s, 2); - assert.equal((await pageLooks(s)).activityBestGolf, 18, "a higher round keeps the best"); + assert.equal((await pageLooks(s)).activityBestGolfPirate, 18, "a higher round keeps the best"); assert.equal(await golfBest(), 18); - assert.equal(await title.innerText(), "Activities · Mini golf best: 18"); + assert.equal(await title.innerText(), "Activities · Mini golf, Pirate Cove best: 18"); + + // The dashboard shows each course's own best; another course starts with none. + await s.page.click("#activities-back"); + await courseCard(s, "pirate").waitFor(); + assert.match(await courseCard(s, "pirate").innerText(), /Best round: 18 \(-\d+\)/); + assert.match(await courseCard(s, "space").innerText(), /No best yet/); + assert.equal(await s.page.locator("#activities-picker .activities-course canvas").count(), 6, "each course card has its art"); + await courseCard(s, "space").click(); + await until(async () => (await overlay(s)) === "Press space or click to start", 5000); + assert.equal(await title.innerText(), "Activities · Mini golf, Cosmic Glow: no best yet"); + assert.equal(await playRound(2), "over"); + await until(async () => (await golfBest("Space")) === 36, 5000); + assert.equal(await golfBest(), 18, "Pirate Cove's best is its own"); + await s.page.click("#activities-back"); + await courseCard(s, "pirate").waitFor(); + await s.page.click("#activities-back"); + assert.match(await card(s, "golf").innerText(), /Best on 2 of 6 courses/); const reset = s.page.locator("#activities-reset"); await reset.click(); await reset.click(); - await until(async () => (await golfBest()) === 0 && (await serverLooks(s)).activityBestSnake === 0, 5000); - assert.equal(await title.innerText(), "Activities · Mini golf: no best yet"); + await until(async () => (await golfBest()) === 0 && (await golfBest("Space")) === 0 && (await serverLooks(s)).activityBestSnake === 0, 5000); + assert.match(await card(s, "golf").innerText(), /6 courses to play/); }); test("Mini golf running breaks no content-security rule and logs no error", async (t) => { @@ -994,6 +2095,7 @@ test("Back to default turns Show Activities back on and keeps the best scores", const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); assert.ok(await s.page.locator("#btn-activities").isHidden(), "the saved switch hides the die"); await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-sounds"); await s.page.locator("#looks-modal[open]").waitFor(); await s.page.click("#looks-reset"); await s.page.click("#looks-done"); @@ -1030,6 +2132,7 @@ test("Show Activities in User Preferences hides the die on the dashboard and on await pastTheIntro(dash); await iconUsable(dash, "the dashboard"); await dash.page.click("#btn-looks"); + await dash.page.click("#prefs-tab-sounds"); await dash.page.locator("#looks-modal[open]").waitFor(); const box = dash.page.locator("#looks-activities"); assert.ok(await box.isChecked(), "on by default"); @@ -1041,6 +2144,7 @@ test("Show Activities in User Preferences hides the die on the dashboard and on const skill = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); assert.ok(await skill.page.locator("#btn-activities").isHidden(), "and from a skill screen in a new session"); await skill.page.click("#btn-looks"); + await skill.page.click("#prefs-tab-sounds"); await skill.page.locator("#looks-modal[open]").waitFor(); assert.equal(await skill.page.locator("#looks-activities").isChecked(), false, "the switch shows what was saved"); await skill.page.locator("#looks-activities").check(); @@ -1105,10 +2209,304 @@ test("a running game breaks no content-security rule and logs no error", async ( assert.equal(styleTags, 0, "no