Add the new Activities games (bounce, bumper, fuse, drive, Ghoul Rush stages and more) with their suites and design notes

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-02 12:01:56 -08:00
1 parent 9c07ee5260
commit 2d6c7078ae
144 files changed
+120156 -971

No files matched your search

+24
View File
@@ -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);
@@ -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)));
});
@@ -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");
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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");
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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");
});
File diff suppressed because it is too large. Load diff
@@ -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);
});
@@ -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`);
}
});
@@ -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");
});
File diff suppressed because it is too large. Load diff
@@ -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);
}
});
@@ -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);
});
File diff suppressed because it is too large. Load diff
@@ -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/);
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff