mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Add Activities with Snake and Mini golf to play through a wait, paused whenever it is your turn
AI Assisted
This commit is contained in:
1 parent
720758a7ee
commit
dbd31611b7
17 files changed
+8920
-7
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -644,16 +644,22 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
||||
/* ---------------------------------------------------------------- help */
|
||||
|
||||
|
||||
test("help: 18 tabs with unique ids", () => {
|
||||
assert.equal(HELP_TABS.length, 18);
|
||||
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 18);
|
||||
test("help: 19 tabs with unique ids", () => {
|
||||
assert.equal(HELP_TABS.length, 19);
|
||||
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 19);
|
||||
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
|
||||
const ids = HELP_TABS.map((t) => t.id);
|
||||
assert.equal(ids.indexOf("git"), ids.indexOf("build") + 1, "The git board comes right after Watching a build");
|
||||
assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board");
|
||||
assert.equal(helpTabFor({ workflow: "git" }), "git");
|
||||
assert.equal(ids.indexOf("activities"), ids.indexOf("ask") + 1, "Activities comes right after Ask a quick question");
|
||||
assert.equal(HELP_TABS[ids.indexOf("activities")].label, "Activities");
|
||||
const tpl = helpTemplate();
|
||||
for (const id of ids) assert.match(tpl, new RegExp(`<section class="help-panel" data-tab="${id}">`), `${id} has a section`);
|
||||
// The die sits right of the megaphone, so the megaphone is no longer the far-right button.
|
||||
assert.doesNotMatch(tpl, /far right/, "no line calls a top-bar button the far-right one");
|
||||
const around = tpl.match(/<section class="help-panel" data-tab="around">([\s\S]*?)<\/section>/)[1];
|
||||
assert.match(around, /<strong>die<\/strong>[\s\S]*?"Activities"/, "Finding your way around points the die at the Activities topic");
|
||||
});
|
||||
|
||||
test("help: the template's icons and panels match HELP_TABS in order, headed by their labels", () => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Plan2Code Web Console - the list of activities: the games the Activities window can open.
|
||||
//
|
||||
// The source of truth for which games exist. The window (screens/activities.js)
|
||||
// knows only this list; each game is its own module under activities/, loaded
|
||||
// with import() the first time it is opened, and answers the same calls:
|
||||
// create({ canvas, tone, onScore }) returning start, pause, resume, key, tick
|
||||
// and resize, plus score and state (scripts/test-web-console-activities.mjs
|
||||
// checks every listed game against it). create() is also handed best(), the
|
||||
// saved best, and memo, a number kept between sessions; a game may ignore
|
||||
// both. Three parts are optional: pointer(type,
|
||||
// x, y) for a game played by mouse, release(name) for a game that acts on a
|
||||
// key held down (handed the same names as key() when the key is let go), and
|
||||
// lowerIsBetter on the module's export for a game whose best is its lowest
|
||||
// round. Adding a game is one file and
|
||||
// one line here. No DOM access and no imports: the page and `node --test` both
|
||||
// import this file.
|
||||
|
||||
const entry = (id, title) => Object.freeze({ id, title, module: `/activities/${id}.js` });
|
||||
|
||||
export const ACTIVITIES = Object.freeze([entry("snake", "Snake"), entry("golf", "Mini golf")]);
|
||||
|
||||
// The looks.json key that holds a game's best score: activityBestSnake for
|
||||
// snake. Built the way soundKey() builds the per-sound switches, so every key
|
||||
// stays flat (cleanLooks() drops nested objects).
|
||||
export const bestKey = (id) => "activityBest" + id[0].toUpperCase() + id.slice(1);
|
||||
|
||||
// The looks.json key that holds a game's memo: one whole number the game may
|
||||
// keep between sessions (Snake keeps its tally of surprises found as bits).
|
||||
// Handed to create() as memo { get, set }; a game that has no use for it
|
||||
// leaves it at 0.
|
||||
export const memoKey = (id) => "activityMemo" + id[0].toUpperCase() + id.slice(1);
|
||||
@@ -0,0 +1,825 @@
|
||||
// Plan2Code Web Console - mini golf's scenery and props: the sharks, bats and torches round the course, the looks of what the ball hits, and the power-up icons.
|
||||
//
|
||||
// Drawing only, like golf-draw.js, which calls in here: no rules and no state.
|
||||
// Every piece is drawn in course units around its own point, and anything
|
||||
// that moves (a fin circling, a wing flapping, a flame) follows the round's
|
||||
// clock, never Math.random(), so a paused frame stays still. The palette `p`
|
||||
// is the hole's theme from golf-draw.js.
|
||||
|
||||
/* --------------------------------------------------------------- helpers */
|
||||
|
||||
export function polygon(ctx, points) {
|
||||
ctx.beginPath();
|
||||
points.forEach((q, i) => (i ? ctx.lineTo(q.x, q.y) : ctx.moveTo(q.x, q.y)));
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
export function circle(ctx, x, y, r) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, Math.max(0.01, r), 0, Math.PI * 2);
|
||||
}
|
||||
|
||||
export function ellipse(ctx, x, y, rx, ry, rot = 0) {
|
||||
ctx.beginPath();
|
||||
if (typeof ctx.ellipse === "function") ctx.ellipse(x, y, Math.max(0.01, rx), Math.max(0.01, ry), rot, 0, Math.PI * 2);
|
||||
else ctx.arc(x, y, Math.max(0.01, rx), 0, Math.PI * 2);
|
||||
}
|
||||
|
||||
// A radial gradient, or null where the context makes none (a stub in Node):
|
||||
// the caller then fills flat or skips the glow.
|
||||
export function radial(ctx, x, y, r0, r1, stops) {
|
||||
if (typeof ctx.createRadialGradient !== "function") return null;
|
||||
let g = null;
|
||||
try {
|
||||
g = ctx.createRadialGradient(x, y, r0, x, y, r1);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!g || typeof g.addColorStop !== "function") return null;
|
||||
for (const [at, color] of stops) g.addColorStop(at, color);
|
||||
return g;
|
||||
}
|
||||
|
||||
const fill = (ctx, color) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill();
|
||||
};
|
||||
|
||||
const stroke = (ctx, color, width) => {
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = width;
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
function line(ctx, x1, y1, x2, y2, color, width) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x1, y1);
|
||||
ctx.lineTo(x2, y2);
|
||||
stroke(ctx, color, width);
|
||||
}
|
||||
|
||||
function label(ctx, str, x, y, size, color, font) {
|
||||
ctx.font = `700 ${size}px ${font || "sans-serif"}`;
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillText(str, x, y);
|
||||
}
|
||||
|
||||
// Turns the context to draw along an angle around a point, for the callback.
|
||||
function turned(ctx, x, y, angle, draw) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.rotate(angle);
|
||||
draw();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
const t = (clock) => clock / 1000;
|
||||
|
||||
/* ---------------------------------------------------------------- props */
|
||||
|
||||
// The looks of a bumper, by `look` or the theme's own.
|
||||
export function drawBumperLook(ctx, p, b, clock) {
|
||||
const look = b.look || (p.theme === "cave" ? "mushroom" : "barrel");
|
||||
const { x, y, r } = b;
|
||||
circle(ctx, x + 1.5, y + 2, r);
|
||||
fill(ctx, p.shadow);
|
||||
if (look === "barrel") {
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#94602e");
|
||||
circle(ctx, x, y, r * 0.72);
|
||||
stroke(ctx, "#3a2a1c", 1.4);
|
||||
circle(ctx, x, y, r * 0.38);
|
||||
fill(ctx, "#6f4520");
|
||||
circle(ctx, x, y, r);
|
||||
stroke(ctx, "#3a2a1c", 1.6);
|
||||
} else if (look === "cannonball") {
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#25252c");
|
||||
circle(ctx, x - r * 0.35, y - r * 0.35, r * 0.3);
|
||||
fill(ctx, "#6d6d7a");
|
||||
} else if (look === "chest") {
|
||||
const s = r * 1.5;
|
||||
ctx.fillStyle = "#7a4a1e";
|
||||
ctx.fillRect(x - s / 2, y - s / 2, s, s);
|
||||
ctx.fillStyle = "#d9a520";
|
||||
ctx.fillRect(x - s / 2, y - 1.2, s, 2.4);
|
||||
ctx.fillRect(x - 1.5, y - 2.5, 3, 5);
|
||||
ctx.strokeStyle = "#3a2410";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
|
||||
} else if (look === "coin") {
|
||||
const shine = 0.5 + 0.5 * Math.sin(t(clock) * 3 + x);
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#e8b923");
|
||||
circle(ctx, x, y, r * 0.7);
|
||||
stroke(ctx, "#a87a0c", 1.3);
|
||||
label(ctx, "$", x, y + 0.5, r * 1.1, "#a87a0c");
|
||||
circle(ctx, x - r * 0.4, y - r * 0.4, r * 0.18 + shine * 0.6);
|
||||
fill(ctx, "#fff6c9");
|
||||
} else if (look === "mushroom") {
|
||||
const squish = 1 + Math.sin(t(clock) * 4 + y) * 0.04;
|
||||
circle(ctx, x, y, r * squish);
|
||||
fill(ctx, "#e0468a");
|
||||
for (const [dx, dy, s] of [[-0.4, -0.3, 0.22], [0.35, -0.2, 0.18], [0, 0.4, 0.2], [0.45, 0.35, 0.13]]) {
|
||||
circle(ctx, x + dx * r, y + dy * r, s * r);
|
||||
fill(ctx, "#ffe3f1");
|
||||
}
|
||||
} else if (look === "rock") {
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#5a5468");
|
||||
circle(ctx, x - r * 0.15, y - r * 0.15, r * 0.62);
|
||||
fill(ctx, "#77708a");
|
||||
circle(ctx, x - r * 0.25, y - r * 0.25, r * 0.25);
|
||||
fill(ctx, "#a49dba");
|
||||
} else if (look === "crystal") {
|
||||
const pts = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (i / 6) * Math.PI * 2 + Math.PI / 6;
|
||||
pts.push({ x: x + Math.cos(a) * r, y: y + Math.sin(a) * r });
|
||||
}
|
||||
polygon(ctx, pts);
|
||||
fill(ctx, "#8a66ee");
|
||||
polygon(ctx, [pts[0], pts[2], pts[4]]);
|
||||
fill(ctx, "#b59cff");
|
||||
circle(ctx, x - r * 0.25, y - r * 0.3, r * 0.2);
|
||||
fill(ctx, "#f1ebff");
|
||||
} else {
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#9c3327");
|
||||
}
|
||||
}
|
||||
|
||||
// A mover at its place this moment.
|
||||
export function drawMoverLook(ctx, p, m, clock) {
|
||||
const { x, y, r } = m;
|
||||
const look = m.look || "barrel";
|
||||
ellipse(ctx, x + 1.5, y + 2.5, r, r * 0.9);
|
||||
fill(ctx, p.shadow);
|
||||
if (look === "barrel") {
|
||||
// Rolls the way it travels: the hoops slide past.
|
||||
const roll = (m.y * 0.4 + m.x * 0.4) % 6;
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#a06a34");
|
||||
ctx.save();
|
||||
circle(ctx, x, y, r);
|
||||
ctx.clip();
|
||||
for (let k = -2; k <= 2; k++) line(ctx, x - r, y + k * 6 + roll - 3, x + r, y + k * 6 + roll - 3, "#3a2a1c", 1.5);
|
||||
ctx.restore();
|
||||
label(ctx, "TNT", x, y, r * 0.6, "#ffe9b0");
|
||||
} else if (look === "crab") {
|
||||
const wig = Math.sin(t(clock) * 14) * 1.5;
|
||||
for (const side of [-1, 1]) {
|
||||
for (let k = 0; k < 3; k++) line(ctx, x + side * r * 0.6, y - 2 + k * 2.5, x + side * (r + 3), y - 3 + k * 3 + wig * side, "#a8261b", 1.2);
|
||||
circle(ctx, x + side * (r + 1), y - r * 0.9 + wig, r * 0.42);
|
||||
fill(ctx, "#e1402d");
|
||||
}
|
||||
ellipse(ctx, x, y, r, r * 0.75);
|
||||
fill(ctx, "#e1402d");
|
||||
for (const side of [-1, 1]) {
|
||||
circle(ctx, x + side * 2.2, y - r * 0.55, 1.6);
|
||||
fill(ctx, "#ffffff");
|
||||
circle(ctx, x + side * 2.2, y - r * 0.55, 0.8);
|
||||
fill(ctx, "#111111");
|
||||
}
|
||||
} else if (look === "cart") {
|
||||
const s = r * 1.6;
|
||||
ctx.fillStyle = "#3d3a44";
|
||||
ctx.fillRect(x - s / 2 - 2, y - s / 2 + 1, 3, s - 2);
|
||||
ctx.fillRect(x + s / 2 - 1, y - s / 2 + 1, 3, s - 2);
|
||||
ctx.fillStyle = "#6b6373";
|
||||
ctx.fillRect(x - s / 2, y - s / 2, s, s);
|
||||
ctx.strokeStyle = "#2a2730";
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
|
||||
for (const [dx, dy, c] of [[-3, -2, "#f2c84b"], [3, 1, "#7fe6ff"], [-1, 3, "#f2c84b"], [2, -4, "#ff7ad9"]]) {
|
||||
circle(ctx, x + dx, y + dy, 2.2);
|
||||
fill(ctx, c);
|
||||
}
|
||||
} else if (look === "fireball") {
|
||||
const flick = 1 + Math.sin(t(clock) * 25) * 0.08;
|
||||
const glow = radial(ctx, x, y, 0, r * 2.4, [[0, "rgba(255,220,120,0.9)"], [0.4, "rgba(255,120,30,0.6)"], [1, "rgba(255,60,0,0)"]]);
|
||||
if (glow) {
|
||||
circle(ctx, x, y, r * 2.4);
|
||||
fill(ctx, glow);
|
||||
}
|
||||
circle(ctx, x, y, r * flick);
|
||||
fill(ctx, "#ff7a1a");
|
||||
circle(ctx, x - 1, y - 1, r * 0.55 * flick);
|
||||
fill(ctx, "#ffe08a");
|
||||
// A goofy face, because why not.
|
||||
circle(ctx, x - 2.5, y - 1, 1);
|
||||
fill(ctx, "#3a1200");
|
||||
circle(ctx, x + 2.5, y - 1, 1);
|
||||
fill(ctx, "#3a1200");
|
||||
}
|
||||
}
|
||||
|
||||
// A spinner's bar, with its look: a ship's wheel spoke, a kraken tentacle, a
|
||||
// dragon's tail, or a plain plank.
|
||||
export function drawSpinnerLook(ctx, p, s, clock) {
|
||||
const look = s.look || "plank";
|
||||
const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1);
|
||||
const arm = Math.hypot(s.x2 - s.x1, s.y2 - s.y1) / 2;
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, s.x1 + 1.5, s.y1 + 2, s.x2 + 1.5, s.y2 + 2, p.shadow, 6);
|
||||
if (look === "wheel") {
|
||||
line(ctx, s.x1, s.y1, s.x2, s.y2, "#7a4a22", 4.5);
|
||||
line(ctx, s.x1, s.y1, s.x2, s.y2, "#b07a43", 1.6);
|
||||
for (const [ex, ey] of [[s.x1, s.y1], [s.x2, s.y2]]) {
|
||||
circle(ctx, ex, ey, 3.2);
|
||||
fill(ctx, "#6b3f1d");
|
||||
}
|
||||
circle(ctx, s.x, s.y, 13);
|
||||
stroke(ctx, "#7a4a22", 3);
|
||||
circle(ctx, s.x, s.y, 5);
|
||||
fill(ctx, "#e0b030");
|
||||
} else if (look === "tentacle" || look === "tail") {
|
||||
const tentacle = look === "tentacle";
|
||||
turned(ctx, s.x, s.y, angle, () => {
|
||||
for (const dir of [-1, 1]) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i <= 12; i++) {
|
||||
const u = i / 12;
|
||||
const w = Math.sin(u * 6 + t(clock) * 5) * 2.2 * u;
|
||||
if (i === 0) ctx.moveTo(0, 0);
|
||||
else ctx.lineTo(dir * u * arm, w);
|
||||
}
|
||||
stroke(ctx, tentacle ? "#8e3fa8" : "#b5262a", 5.5);
|
||||
for (let i = 2; i < 11; i += 2) {
|
||||
const u = i / 12;
|
||||
circle(ctx, dir * u * arm, Math.sin(u * 6 + t(clock) * 5) * 2.2 * u + (tentacle ? 1.5 : -1.5), tentacle ? 1.2 : 1.6);
|
||||
fill(ctx, tentacle ? "#f0b7ff" : "#f2c84b");
|
||||
}
|
||||
}
|
||||
});
|
||||
circle(ctx, s.x, s.y, 6);
|
||||
fill(ctx, tentacle ? "#6c2a82" : "#7d1418");
|
||||
} else {
|
||||
line(ctx, s.x1, s.y1, s.x2, s.y2, p.spinner, 4);
|
||||
circle(ctx, s.x, s.y, 5);
|
||||
fill(ctx, p.hub);
|
||||
}
|
||||
}
|
||||
|
||||
// A power-up's icon, `r` across, centered on x, y.
|
||||
export function drawPowerIcon(ctx, kind, x, y, r) {
|
||||
if (kind === "doubloon") {
|
||||
circle(ctx, x, y, r);
|
||||
fill(ctx, "#f0c22c");
|
||||
circle(ctx, x, y, r * 0.7);
|
||||
stroke(ctx, "#a87a0c", r * 0.18);
|
||||
label(ctx, "1", x, y + r * 0.05, r * 1.1, "#a87a0c");
|
||||
} else if (kind === "cannon") {
|
||||
circle(ctx, x - r * 0.15, y + r * 0.15, r * 0.8);
|
||||
fill(ctx, "#25252c");
|
||||
line(ctx, x + r * 0.35, y - r * 0.35, x + r * 0.75, y - r * 0.85, "#c8a26a", r * 0.18);
|
||||
circle(ctx, x + r * 0.8, y - r * 0.9, r * 0.25);
|
||||
fill(ctx, "#ffb020");
|
||||
} else if (kind === "ghost") {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y - r * 0.15, r * 0.75, Math.PI, 0);
|
||||
ctx.lineTo(x + r * 0.75, y + r * 0.8);
|
||||
for (let i = 0; i < 4; i++) ctx.lineTo(x + r * 0.75 - (i + 0.5) * r * 0.375, y + (i % 2 ? r * 0.8 : r * 0.5));
|
||||
ctx.lineTo(x - r * 0.75, y + r * 0.8);
|
||||
ctx.closePath();
|
||||
fill(ctx, "#f4f7ff");
|
||||
for (const dx of [-0.28, 0.28]) {
|
||||
circle(ctx, x + dx * r, y - r * 0.2, r * 0.15);
|
||||
fill(ctx, "#1c1c2a");
|
||||
}
|
||||
} else if (kind === "magnet") {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y - r * 0.05, r * 0.6, Math.PI, 0, false);
|
||||
stroke(ctx, "#d4342a", r * 0.45);
|
||||
ctx.fillStyle = "#d9d9e3";
|
||||
ctx.fillRect(x - r * 0.83, y, r * 0.45, r * 0.55);
|
||||
ctx.fillRect(x + r * 0.38, y, r * 0.45, r * 0.55);
|
||||
} else if (kind === "bouncy") {
|
||||
ellipse(ctx, x, y + r * 0.25, r * 0.85, r * 0.55);
|
||||
fill(ctx, "#ffd43b");
|
||||
circle(ctx, x - r * 0.35, y - r * 0.35, r * 0.42);
|
||||
fill(ctx, "#ffd43b");
|
||||
polygon(ctx, [{ x: x - r * 0.75, y: y - r * 0.4 }, { x: x - r * 1.05, y: y - r * 0.25 }, { x: x - r * 0.72, y: y - r * 0.18 }]);
|
||||
fill(ctx, "#ff8a1f");
|
||||
circle(ctx, x - r * 0.42, y - r * 0.45, r * 0.1);
|
||||
fill(ctx, "#111111");
|
||||
} else if (kind === "bigcup") {
|
||||
ctx.fillStyle = "#efdcae";
|
||||
ctx.fillRect(x - r * 0.85, y - r * 0.7, r * 1.7, r * 1.4);
|
||||
ctx.strokeStyle = "#a7834c";
|
||||
ctx.lineWidth = r * 0.1;
|
||||
ctx.strokeRect(x - r * 0.85, y - r * 0.7, r * 1.7, r * 1.4);
|
||||
line(ctx, x - r * 0.35, y - r * 0.3, x + r * 0.35, y + r * 0.3, "#d4342a", r * 0.22);
|
||||
line(ctx, x + r * 0.35, y - r * 0.3, x - r * 0.35, y + r * 0.3, "#d4342a", r * 0.22);
|
||||
} else if (kind === "spyglass") {
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, x - r * 0.75, y + r * 0.55, x + r * 0.55, y - r * 0.45, "#a8792b", r * 0.42);
|
||||
line(ctx, x - r * 0.2, y + r * 0.12, x + r * 0.55, y - r * 0.45, "#d9a94a", r * 0.55);
|
||||
circle(ctx, x + r * 0.62, y - r * 0.5, r * 0.3);
|
||||
fill(ctx, "#bfe8ff");
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- scenery */
|
||||
|
||||
// Each kind of scenery: the layer it goes on ("low" under the walls, "high"
|
||||
// over the ball, "glow" over a cave's darkness) and how it is drawn. `light`
|
||||
// is the glow a cave casts around it, if any.
|
||||
const DECOR = {
|
||||
/* pirate */
|
||||
shark: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const a = t(clock) * 0.9 * (d.s > 0.85 ? 1 : -1) + d.x;
|
||||
const x = d.x + Math.cos(a) * 32 * d.s;
|
||||
const y = d.y + Math.sin(a) * 9 * d.s;
|
||||
const dir = Math.sign(-Math.sin(a) * (d.s > 0.85 ? 1 : -1)) || 1;
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, x - dir * 4, y + 4, x - dir * 18, y + 5, "rgba(255,255,255,0.55)", 1.2);
|
||||
polygon(ctx, [{ x: x - 5 * d.s, y: y + 4 }, { x: x + 5 * d.s, y: y + 4 }, { x: x - dir * 3 * d.s, y: y - 9 * d.s }]);
|
||||
fill(ctx, "#5d6b78");
|
||||
},
|
||||
},
|
||||
ship: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const bob = Math.sin(t(clock) * 1.6) * 1.5;
|
||||
const y = d.y + bob;
|
||||
polygon(ctx, [{ x: d.x - 22, y: y }, { x: d.x + 22, y: y }, { x: d.x + 15, y: y + 9 }, { x: d.x - 16, y: y + 9 }]);
|
||||
fill(ctx, "#5c3416");
|
||||
line(ctx, d.x, y, d.x, y - 30, "#3a2410", 1.6);
|
||||
polygon(ctx, [{ x: d.x - 13, y: y - 26 }, { x: d.x + 13, y: y - 26 }, { x: d.x + 11, y: y - 6 }, { x: d.x - 11, y: y - 6 }]);
|
||||
fill(ctx, "#f1ead6");
|
||||
ctx.fillStyle = "#111111";
|
||||
ctx.fillRect(d.x, y - 36, 9, 6);
|
||||
circle(ctx, d.x + 4.5, y - 33, 1.5);
|
||||
fill(ctx, "#ffffff");
|
||||
},
|
||||
},
|
||||
bottle: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const a = Math.sin(t(clock) * 2 + d.x) * 0.5;
|
||||
turned(ctx, d.x, d.y + Math.sin(t(clock) * 1.7) * 1.5, a, () => {
|
||||
ellipse(ctx, 0, 0, 7, 3);
|
||||
fill(ctx, "rgba(90,170,110,0.85)");
|
||||
ctx.fillStyle = "#f4ead0";
|
||||
ctx.fillRect(-3, -1.2, 5, 2.4);
|
||||
ctx.fillStyle = "#8a5a2b";
|
||||
ctx.fillRect(6, -1.3, 3, 2.6);
|
||||
});
|
||||
},
|
||||
},
|
||||
palm: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const s = d.s;
|
||||
ellipse(ctx, d.x, d.y + 4 * s, 16 * s, 8 * s);
|
||||
fill(ctx, "#ecd79c");
|
||||
const sway = Math.sin(t(clock) * 1.3 + d.x) * 0.12;
|
||||
line(ctx, d.x, d.y + 4 * s, d.x + 4 * s, d.y - 14 * s, "#8a5a2b", 2.5 * s);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const a = (i / 5) * Math.PI * 2 + sway;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(d.x + 4 * s, d.y - 14 * s);
|
||||
ctx.quadraticCurveTo(d.x + 4 * s + Math.cos(a) * 9 * s, d.y - 18 * s + Math.sin(a) * 6 * s, d.x + 4 * s + Math.cos(a) * 15 * s, d.y - 12 * s + Math.sin(a) * 8 * s);
|
||||
stroke(ctx, "#2f8f3c", 3 * s);
|
||||
}
|
||||
circle(ctx, d.x + 3 * s, d.y - 12 * s, 1.8 * s);
|
||||
fill(ctx, "#6b4a2a");
|
||||
},
|
||||
},
|
||||
wreck: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const tilt = -0.35 + Math.sin(t(clock) * 0.8) * 0.03;
|
||||
turned(ctx, d.x, d.y, tilt, () => {
|
||||
polygon(ctx, [{ x: -50, y: -6 }, { x: 40, y: -10 }, { x: 52, y: 4 }, { x: 30, y: 14 }, { x: -44, y: 12 }]);
|
||||
fill(ctx, "#5c3416");
|
||||
for (let x = -40; x < 40; x += 10) line(ctx, x, -6, x + 3, 12, "#3a2410", 1);
|
||||
polygon(ctx, [{ x: -8, y: -8 }, { x: 6, y: -9 }, { x: 0, y: 6 }]);
|
||||
fill(ctx, "#1b6d99");
|
||||
line(ctx, 10, -8, 22, -46, "#3a2410", 2);
|
||||
polygon(ctx, [{ x: 13, y: -40 }, { x: 34, y: -36 }, { x: 18, y: -24 }]);
|
||||
fill(ctx, "rgba(241,234,214,0.8)");
|
||||
});
|
||||
},
|
||||
},
|
||||
crab: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
drawMoverLook(ctx, p, { x: d.x + Math.sin(t(clock) * 1.5) * 10, y: d.y, r: 6 * d.s, look: "crab" }, clock);
|
||||
},
|
||||
},
|
||||
parrot: {
|
||||
layer: "high",
|
||||
draw(ctx, p, d, clock) {
|
||||
const bob = Math.abs(Math.sin(t(clock) * 3)) * -3;
|
||||
const y = d.y + bob;
|
||||
ellipse(ctx, d.x, y, 5, 8);
|
||||
fill(ctx, "#e4312b");
|
||||
ellipse(ctx, d.x + 3, y + 2, 3, 6, 0.3);
|
||||
fill(ctx, "#2f7fd8");
|
||||
circle(ctx, d.x, y - 8, 4);
|
||||
fill(ctx, "#e4312b");
|
||||
polygon(ctx, [{ x: d.x - 3, y: y - 8 }, { x: d.x - 7, y: y - 6 }, { x: d.x - 3, y: y - 5 }]);
|
||||
fill(ctx, "#f2c84b");
|
||||
circle(ctx, d.x - 1, y - 9, 1);
|
||||
fill(ctx, "#111111");
|
||||
polygon(ctx, [{ x: d.x - 2, y: y + 7 }, { x: d.x + 2, y: y + 7 }, { x: d.x + 1, y: y + 15 }]);
|
||||
fill(ctx, "#2e9e48");
|
||||
// Squawks now and then.
|
||||
if (Math.floor(t(clock) / 2.5) % 3 === 0) label(ctx, "SQUAWK!", d.x, y - 18, 6, "#fff6c9");
|
||||
},
|
||||
},
|
||||
island: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d) {
|
||||
ellipse(ctx, d.x, d.y, 18 * d.s, 9 * d.s);
|
||||
fill(ctx, "#ecd79c");
|
||||
line(ctx, d.x - 3, d.y - 3, d.x + 3, d.y + 3, "#d4342a", 1.6);
|
||||
line(ctx, d.x + 3, d.y - 3, d.x - 3, d.y + 3, "#d4342a", 1.6);
|
||||
},
|
||||
},
|
||||
cannon: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const dir = d.s < 0 ? -1 : 1;
|
||||
ctx.fillStyle = "#6b3f1d";
|
||||
ctx.fillRect(d.x - 8, d.y - 3, 16, 7);
|
||||
turned(ctx, d.x, d.y, dir * Math.PI / 2, () => {
|
||||
ctx.fillStyle = "#2b2b30";
|
||||
ctx.fillRect(-4, -4, 18, 8);
|
||||
circle(ctx, -4, 0, 5);
|
||||
fill(ctx, "#2b2b30");
|
||||
});
|
||||
// A puff of smoke every few seconds.
|
||||
const k = (t(clock) + d.x / 50) % 3;
|
||||
if (k < 0.8) {
|
||||
const r = 3 + k * 9;
|
||||
circle(ctx, d.x, d.y + dir * (16 + k * 10), r);
|
||||
fill(ctx, `rgba(230,230,230,${0.8 - k})`);
|
||||
if (k < 0.15) label(ctx, "BOOM!", d.x, d.y + dir * 30, 7, "#ffb020");
|
||||
}
|
||||
},
|
||||
},
|
||||
anchor: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d) {
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, d.x, d.y - 10, d.x, d.y + 8, "#5b6470", 2.2);
|
||||
line(ctx, d.x - 5, d.y - 6, d.x + 5, d.y - 6, "#5b6470", 2);
|
||||
ctx.beginPath();
|
||||
ctx.arc(d.x, d.y + 1, 7, 0.2, Math.PI - 0.2);
|
||||
stroke(ctx, "#5b6470", 2.2);
|
||||
circle(ctx, d.x, d.y - 12, 2.2);
|
||||
stroke(ctx, "#5b6470", 1.5);
|
||||
},
|
||||
},
|
||||
tentacle: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const s = d.s;
|
||||
ctx.lineCap = "round";
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
const u = i / 10;
|
||||
const x = d.x + Math.sin(u * 4 + t(clock) * 2 + d.y) * 6 * s * u;
|
||||
const y = d.y + 10 * s - u * 26 * s;
|
||||
if (i === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
}
|
||||
stroke(ctx, "#8e3fa8", 5 * s);
|
||||
ellipse(ctx, d.x, d.y + 10 * s, 7 * s, 2.5 * s);
|
||||
stroke(ctx, "rgba(255,255,255,0.5)", 1);
|
||||
},
|
||||
},
|
||||
kraken: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
ellipse(ctx, d.x, d.y + 6, 40, 16);
|
||||
fill(ctx, "#6c2a82");
|
||||
const blink = Math.floor(t(clock) * 10) % 40 === 0;
|
||||
for (const dx of [-16, 16]) {
|
||||
ellipse(ctx, d.x + dx, d.y - 2, 8, blink ? 1 : 7);
|
||||
fill(ctx, "#fff6c9");
|
||||
if (!blink) {
|
||||
circle(ctx, d.x + dx + Math.sin(t(clock)) * 2, d.y - 1, 3);
|
||||
fill(ctx, "#111111");
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
ghost: {
|
||||
layer: "high",
|
||||
draw(ctx, p, d, clock) {
|
||||
const y = d.y + Math.sin(t(clock) * 1.8 + d.x) * 5;
|
||||
const x = d.x + Math.sin(t(clock) * 0.7 + d.y) * 14;
|
||||
ctx.globalAlpha = 0.6 + Math.sin(t(clock) * 2.3) * 0.2;
|
||||
drawPowerIcon(ctx, "ghost", x, y, 12 * d.s);
|
||||
if (Math.floor(t(clock) / 3) % 2 === 0) label(ctx, "Booo!", x + 16 * d.s, y - 12 * d.s, 6, "#f4f7ff");
|
||||
ctx.globalAlpha = 1;
|
||||
},
|
||||
},
|
||||
jolly: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
const wave = Math.sin(t(clock) * 4) * 1.5;
|
||||
line(ctx, d.x, d.y + 14, d.x, d.y - 14, "#3a2410", 1.5);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(d.x, d.y - 14);
|
||||
ctx.quadraticCurveTo(d.x + 9, d.y - 16 + wave, d.x + 18, d.y - 14 + wave);
|
||||
ctx.lineTo(d.x + 18, d.y - 2 + wave);
|
||||
ctx.quadraticCurveTo(d.x + 9, d.y - 4 + wave, d.x, d.y - 2);
|
||||
ctx.closePath();
|
||||
fill(ctx, "#111111");
|
||||
circle(ctx, d.x + 9, d.y - 9 + wave * 0.6, 2.5);
|
||||
fill(ctx, "#f4f1ea");
|
||||
},
|
||||
},
|
||||
skullrock: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
ellipse(ctx, d.x, d.y + 40, 70, 20);
|
||||
fill(ctx, "#ecd79c");
|
||||
ellipse(ctx, d.x, d.y, 42, 38);
|
||||
fill(ctx, "#8a8478");
|
||||
ellipse(ctx, d.x, d.y - 4, 36, 30);
|
||||
fill(ctx, "#a29c8f");
|
||||
const glow = 0.5 + 0.5 * Math.sin(t(clock) * 2);
|
||||
for (const dx of [-14, 14]) {
|
||||
ellipse(ctx, d.x + dx, d.y - 6, 9, 10);
|
||||
fill(ctx, "#1d1a17");
|
||||
circle(ctx, d.x + dx, d.y - 5, 2 + glow);
|
||||
fill(ctx, `rgba(255,80,40,${0.5 + glow * 0.5})`);
|
||||
}
|
||||
polygon(ctx, [{ x: d.x, y: d.y + 2 }, { x: d.x - 4, y: d.y + 10 }, { x: d.x + 4, y: d.y + 10 }]);
|
||||
fill(ctx, "#1d1a17");
|
||||
for (let i = -3; i <= 3; i++) {
|
||||
ctx.fillStyle = "#f1ead6";
|
||||
ctx.fillRect(d.x + i * 5 - 2, d.y + 16, 4, 6);
|
||||
}
|
||||
},
|
||||
},
|
||||
chest: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
ctx.fillStyle = "#7a4a1e";
|
||||
ctx.fillRect(d.x - 12, d.y - 4, 24, 14);
|
||||
ctx.fillStyle = "#5c3416";
|
||||
ctx.fillRect(d.x - 12, d.y - 14, 24, 8);
|
||||
for (let i = 0; i < 6; i++) {
|
||||
circle(ctx, d.x - 9 + i * 3.6, d.y - 4 - (i % 2) * 2, 2.4);
|
||||
fill(ctx, "#f0c22c");
|
||||
}
|
||||
const sparkle = Math.floor(t(clock) * 4) % 6;
|
||||
circle(ctx, d.x - 8 + sparkle * 3, d.y - 8, 1.2);
|
||||
fill(ctx, "#ffffff");
|
||||
},
|
||||
},
|
||||
|
||||
/* cave */
|
||||
bat: {
|
||||
layer: "high",
|
||||
draw(ctx, p, d, clock) {
|
||||
const s = d.s;
|
||||
const a = t(clock) * 1.1 + d.x;
|
||||
const x = d.x + Math.sin(a) * 40 * s;
|
||||
const y = d.y + Math.sin(a * 2) * 12 * s;
|
||||
const flap = Math.sin(t(clock) * 18 + d.y) * 5 * s;
|
||||
for (const dir of [-1, 1]) {
|
||||
polygon(ctx, [{ x, y }, { x: x + dir * 6 * s, y: y - 4 * s - flap }, { x: x + dir * 13 * s, y: y - 1 * s - flap * 0.6 }, { x: x + dir * 9 * s, y: y + 2 * s }, { x: x + dir * 5 * s, y: y + 1 * s }]);
|
||||
fill(ctx, "#0b0910");
|
||||
}
|
||||
circle(ctx, x, y, 3 * s);
|
||||
fill(ctx, "#0b0910");
|
||||
for (const dir of [-1, 1]) {
|
||||
circle(ctx, x + dir * 1.2 * s, y - 0.6 * s, 0.7 * s);
|
||||
fill(ctx, "#ff4d4d");
|
||||
}
|
||||
},
|
||||
},
|
||||
stalactite: {
|
||||
layer: "high",
|
||||
draw(ctx, p, d) {
|
||||
const s = d.s;
|
||||
for (const [dx, h, w] of [[-14, 18, 6], [0, 30, 8], [12, 14, 5], [24, 22, 6]]) {
|
||||
polygon(ctx, [{ x: d.x + dx * s - w * s, y: d.y }, { x: d.x + dx * s + w * s, y: d.y }, { x: d.x + dx * s, y: d.y + h * s }]);
|
||||
fill(ctx, "#3d3747");
|
||||
polygon(ctx, [{ x: d.x + dx * s - w * s * 0.3, y: d.y }, { x: d.x + dx * s + w * s * 0.2, y: d.y }, { x: d.x + dx * s, y: d.y + h * s * 0.85 }]);
|
||||
fill(ctx, "#5d566a");
|
||||
}
|
||||
},
|
||||
},
|
||||
crystal: {
|
||||
layer: "glow",
|
||||
light: { r: 34, color: "rgba(150,110,255,0.45)" },
|
||||
draw(ctx, p, d, clock) {
|
||||
const s = d.s;
|
||||
const pulse = 0.8 + Math.sin(t(clock) * 2 + d.x) * 0.2;
|
||||
for (const [dx, h, a, c] of [[-6, 16, -0.4, "#7b5cf0"], [0, 22, 0, "#a68cff"], [6, 14, 0.45, "#5fd3ff"]]) {
|
||||
turned(ctx, d.x + dx * s, d.y, a, () => {
|
||||
polygon(ctx, [{ x: -3 * s, y: 0 }, { x: 3 * s, y: 0 }, { x: 2 * s, y: -h * s }, { x: 0, y: -(h + 4) * s }, { x: -2 * s, y: -h * s }]);
|
||||
ctx.globalAlpha = pulse;
|
||||
fill(ctx, c);
|
||||
ctx.globalAlpha = 1;
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
torch: {
|
||||
layer: "glow",
|
||||
light: { r: 60, color: "rgba(255,170,60,0.5)" },
|
||||
draw(ctx, p, d, clock) {
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, d.x, d.y + 10, d.x, d.y - 2, "#6b4a2a", 2.5);
|
||||
const f = Math.sin(t(clock) * 21 + d.x) * 1.2 + Math.sin(t(clock) * 13) * 0.8;
|
||||
polygon(ctx, [{ x: d.x - 4, y: d.y - 2 }, { x: d.x + 4, y: d.y - 2 }, { x: d.x + f * 0.6, y: d.y - 13 - f }]);
|
||||
fill(ctx, "#ff8a1f");
|
||||
polygon(ctx, [{ x: d.x - 2, y: d.y - 2 }, { x: d.x + 2, y: d.y - 2 }, { x: d.x + f * 0.3, y: d.y - 8 - f * 0.5 }]);
|
||||
fill(ctx, "#ffe08a");
|
||||
},
|
||||
},
|
||||
lantern: {
|
||||
layer: "glow",
|
||||
light: { r: 50, color: "rgba(255,210,110,0.45)" },
|
||||
draw(ctx, p, d, clock) {
|
||||
const swing = Math.sin(t(clock) * 1.5) * 4;
|
||||
line(ctx, d.x, 0, d.x + swing, d.y + 4, "#3d3747", 1);
|
||||
ctx.fillStyle = "#3d3747";
|
||||
ctx.fillRect(d.x + swing - 4, d.y + 4, 8, 10);
|
||||
ctx.fillStyle = "#ffd36b";
|
||||
ctx.fillRect(d.x + swing - 2.5, d.y + 6, 5, 6);
|
||||
},
|
||||
},
|
||||
eyes: {
|
||||
layer: "glow",
|
||||
draw(ctx, p, d, clock) {
|
||||
// Two eyes in the dark that blink, and now and then look at you.
|
||||
const k = Math.floor(t(clock) * 8 + d.x) % 30;
|
||||
const open = k > 1 ? 1 : 0.15;
|
||||
const look = Math.sin(t(clock) * 0.6 + d.y) * 1.5;
|
||||
for (const dx of [-5, 5]) {
|
||||
ellipse(ctx, d.x + dx * d.s, d.y, 3.2 * d.s, 2.2 * d.s * open);
|
||||
fill(ctx, "#ffe14d");
|
||||
if (open > 0.5) {
|
||||
ellipse(ctx, d.x + dx * d.s + look, d.y, 0.9 * d.s, 2 * d.s);
|
||||
fill(ctx, "#111111");
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
skeleton: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d, clock) {
|
||||
ctx.lineCap = "round";
|
||||
line(ctx, d.x - 9, d.y + 6, d.x + 9, d.y - 2, "#d8d2c2", 2.2);
|
||||
line(ctx, d.x - 9, d.y - 2, d.x + 9, d.y + 6, "#d8d2c2", 2.2);
|
||||
circle(ctx, d.x, d.y - 8, 6);
|
||||
fill(ctx, "#ece6d6");
|
||||
// The jaw chatters.
|
||||
const jaw = Math.abs(Math.sin(t(clock) * 6)) * 1.5;
|
||||
ctx.fillStyle = "#ece6d6";
|
||||
ctx.fillRect(d.x - 3.5, d.y - 3 + jaw, 7, 2.5);
|
||||
for (const dx of [-2.2, 2.2]) {
|
||||
circle(ctx, d.x + dx, d.y - 9, 1.6);
|
||||
fill(ctx, "#1d1a17");
|
||||
}
|
||||
},
|
||||
},
|
||||
rails: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d) {
|
||||
for (let y = d.y - 105; y <= d.y + 105; y += 9) {
|
||||
ctx.fillStyle = "#4a3a2a";
|
||||
ctx.fillRect(d.x - 10, y, 20, 3);
|
||||
}
|
||||
line(ctx, d.x - 6, d.y - 108, d.x - 6, d.y + 108, "#8b8796", 1.6);
|
||||
line(ctx, d.x + 6, d.y - 108, d.x + 6, d.y + 108, "#8b8796", 1.6);
|
||||
},
|
||||
},
|
||||
gems: {
|
||||
layer: "glow",
|
||||
light: { r: 26, color: "rgba(255,120,220,0.35)" },
|
||||
draw(ctx, p, d) {
|
||||
const s = d.s;
|
||||
for (const [dx, dy, c] of [[-6, 2, "#ff5bd6"], [4, 3, "#4de3ff"], [-1, -3, "#f2c84b"], [8, -2, "#5bff9a"], [-9, -4, "#f2c84b"]]) {
|
||||
polygon(ctx, [{ x: d.x + dx * s, y: d.y + (dy - 3) * s }, { x: d.x + (dx + 3) * s, y: d.y + dy * s }, { x: d.x + dx * s, y: d.y + (dy + 3) * s }, { x: d.x + (dx - 3) * s, y: d.y + dy * s }]);
|
||||
fill(ctx, c);
|
||||
}
|
||||
},
|
||||
},
|
||||
spider: {
|
||||
layer: "high",
|
||||
draw(ctx, p, d, clock) {
|
||||
const y = d.y + Math.sin(t(clock) * 1.2) * 18;
|
||||
line(ctx, d.x, 0, d.x, y, "rgba(220,220,230,0.6)", 0.6);
|
||||
for (const dir of [-1, 1]) {
|
||||
for (let k = 0; k < 4; k++) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(d.x, y);
|
||||
ctx.lineTo(d.x + dir * 5, y - 3 + k * 2);
|
||||
ctx.lineTo(d.x + dir * 8, y + k * 2.4);
|
||||
stroke(ctx, "#15121b", 1);
|
||||
}
|
||||
}
|
||||
circle(ctx, d.x, y, 3.5);
|
||||
fill(ctx, "#15121b");
|
||||
for (const dir of [-1, 1]) {
|
||||
circle(ctx, d.x + dir * 1.3, y - 1, 0.8);
|
||||
fill(ctx, "#ff4d4d");
|
||||
}
|
||||
},
|
||||
},
|
||||
web: {
|
||||
layer: "low",
|
||||
draw(ctx, p, d) {
|
||||
ctx.strokeStyle = "rgba(220,220,235,0.35)";
|
||||
ctx.lineWidth = 0.6;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const a = (i / 8) * Math.PI * 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(d.x, d.y);
|
||||
ctx.lineTo(d.x + Math.cos(a) * 26, d.y + Math.sin(a) * 26);
|
||||
ctx.stroke();
|
||||
}
|
||||
for (const r of [8, 15, 22]) {
|
||||
circle(ctx, d.x, d.y, r);
|
||||
ctx.stroke();
|
||||
}
|
||||
},
|
||||
},
|
||||
glowworms: {
|
||||
layer: "glow",
|
||||
light: { r: 40, color: "rgba(110,255,200,0.3)" },
|
||||
draw(ctx, p, d, clock) {
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const x = d.x - 40 + i * 10 + Math.sin(t(clock) + i) * 3;
|
||||
const y = d.y + Math.sin(t(clock) * 1.4 + i * 0.9) * 6;
|
||||
circle(ctx, x, y, 1.4 + (Math.sin(t(clock) * 3 + i) + 1) * 0.5);
|
||||
fill(ctx, "#8cffd9");
|
||||
}
|
||||
},
|
||||
},
|
||||
mushroom: {
|
||||
layer: "glow",
|
||||
light: { r: 30, color: "rgba(255,90,180,0.35)" },
|
||||
draw(ctx, p, d) {
|
||||
for (const [dx, dy, r] of [[-5, 3, 5], [4, -2, 6.5], [7, 6, 3.5]]) {
|
||||
circle(ctx, d.x + dx, d.y + dy, r);
|
||||
fill(ctx, "#e0468a");
|
||||
circle(ctx, d.x + dx - r * 0.3, d.y + dy - r * 0.3, r * 0.25);
|
||||
fill(ctx, "#ffe3f1");
|
||||
}
|
||||
},
|
||||
},
|
||||
dragon: {
|
||||
layer: "glow",
|
||||
light: { r: 70, color: "rgba(255,90,40,0.3)" },
|
||||
draw(ctx, p, d, clock) {
|
||||
// A sleeping dragon's head poking in from the right edge, snoring.
|
||||
const cx = d.x - 6;
|
||||
const breathe = Math.sin(t(clock) * 1.4) * 1.5;
|
||||
ellipse(ctx, cx, d.y, 44 + breathe, 32);
|
||||
fill(ctx, "#a3202a");
|
||||
for (let i = 0; i < 4; i++) {
|
||||
polygon(ctx, [{ x: cx - 26 + i * 12, y: d.y - 28 + i * 2 }, { x: cx - 20 + i * 12, y: d.y - 40 + i * 2 }, { x: cx - 14 + i * 12, y: d.y - 27 + i * 2 }]);
|
||||
fill(ctx, "#f2c84b");
|
||||
}
|
||||
// The closed eye, a sleepy curve.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx - 14, d.y - 12, 6, 0.2, Math.PI - 0.2);
|
||||
stroke(ctx, "#1d0608", 1.8);
|
||||
for (const dy of [-2, 6]) {
|
||||
circle(ctx, cx - 36 - breathe, d.y + dy, 2);
|
||||
fill(ctx, "#1d0608");
|
||||
}
|
||||
const k = (t(clock) % 3) / 3;
|
||||
label(ctx, "Z", cx - 46 - k * 14, d.y - 10 - k * 26, 7 + k * 5, `rgba(255,240,200,${1 - k})`);
|
||||
label(ctx, "z", cx - 52 - k * 8, d.y - 2 - k * 14, 5 + k * 3, `rgba(255,240,200,${0.8 - k * 0.8})`);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const DECOR_KINDS = Object.freeze(Object.keys(DECOR));
|
||||
|
||||
// Draws the hole's scenery that belongs on `layer`.
|
||||
export function drawDecor(ctx, p, decor, clock, layer) {
|
||||
for (const d of decor) {
|
||||
const kind = DECOR[d.kind];
|
||||
if (kind && kind.layer === layer) kind.draw(ctx, p, d, clock);
|
||||
}
|
||||
}
|
||||
|
||||
// The glows the scenery casts, for a cave's darkness: { x, y, r, color }.
|
||||
export function decorLights(decor) {
|
||||
const lights = [];
|
||||
for (const d of decor) {
|
||||
const kind = DECOR[d.kind];
|
||||
if (kind && kind.light) lights.push({ x: d.x, y: d.y - 4, r: kind.light.r * (d.s || 1), color: kind.light.color });
|
||||
if (d.kind === "eyes") lights.push({ x: d.x, y: d.y, r: 12, color: "rgba(255,225,80,0.25)" });
|
||||
}
|
||||
return lights;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,444 @@
|
||||
// Plan2Code Web Console - mini golf's course: the eighteen holes as data, in course units.
|
||||
//
|
||||
// Data only: no DOM and no imports, so the game (activities/golf.js) and the
|
||||
// unit suite both read it as it is. Every hole is drawn on a fixed course of
|
||||
// COURSE_W by COURSE_H units, scaled to the board like Snake's fixed grid, so
|
||||
// a resize never moves a ball.
|
||||
//
|
||||
// The front nine is Pirate Cove: greens afloat in a shark sea, wooden rails,
|
||||
// barrels and cannonballs. The back nine is the Caves of Doom: mossy stone in
|
||||
// the dark, glowing pools, lava, a bottomless pit, mine carts and crushers.
|
||||
//
|
||||
// A hole is { name, par, theme, quip, ground, liquid, tee, cup, outline,
|
||||
// walls, bumpers, sand, water, slopes, bridges, spinners, tunnels, movers,
|
||||
// gates, powerups, decor }:
|
||||
// theme "pirate" or "cave": the palette, the lighting and the gags
|
||||
// quip a line shown as the hole starts
|
||||
// ground how the green is drawn: "grass", "deck", "moss" or "stone"
|
||||
// liquid what the water is: "sea", "pool", "lava" or "chasm" (the rule
|
||||
// is the same, a stroke and back where the putt began)
|
||||
// tee, cup points { x, y }
|
||||
// outline the playing area as a polygon; its edges are the course edge,
|
||||
// and they lead the walls list
|
||||
// walls line segments { x1, y1, x2, y2 }
|
||||
// bumpers circles { x, y, r, look? } that kick the ball back faster
|
||||
// sand polygons that slow the ball several times over
|
||||
// water polygons that cost a stroke, unless the ball is on a bridge
|
||||
// slopes { points, push: { x, y } }: a polygon that pushes the ball each
|
||||
// moment it is inside, in units per second per second (ramps,
|
||||
// currents and updrafts too)
|
||||
// bridges rectangles { x, y, w, h }: safe ground over water
|
||||
// spinners { x, y, arm, speed, look? }: a windmill-style bar through its
|
||||
// center, arm units each way, turning speed radians a second
|
||||
// tunnels { a, b }: two mouths; entering one sends the ball out of the
|
||||
// other with its speed kept
|
||||
// movers { x, y, r, dx, dy, period, phase?, look? }: a bumper that swings
|
||||
// dx, dy units each way from x, y, once every period ms
|
||||
// gates { x1, y1, x2, y2, period, open, offset?, look? }: a wall that is
|
||||
// there for the last (1 - open) of every period ms
|
||||
// powerups { x, y, kind }: a pad the rolling ball picks up, for its next
|
||||
// putt (the kinds are POWERUPS in golf.js)
|
||||
// decor { kind, x, y, s? }: scenery that never touches the ball
|
||||
// A polygon is a list of points { x, y }.
|
||||
|
||||
export const COURSE_W = 400;
|
||||
export const COURSE_H = 300;
|
||||
|
||||
const pt = (x, y) => ({ x, y });
|
||||
|
||||
const rect = (x, y, w, h) => [pt(x, y), pt(x + w, y), pt(x + w, y + h), pt(x, y + h)];
|
||||
|
||||
const wall = (x1, y1, x2, y2) => ({ x1, y1, x2, y2 });
|
||||
|
||||
const bump = (x, y, r, look) => (look ? { x, y, r, look } : { x, y, r });
|
||||
|
||||
const pad = (x, y, kind) => ({ x, y, kind });
|
||||
|
||||
const deco = (kind, x, y, s = 1) => ({ kind, x, y, s });
|
||||
|
||||
// The outline's edges, closing back to its first point.
|
||||
const edges = (outline) => outline.map((p, i) => {
|
||||
const q = outline[(i + 1) % outline.length];
|
||||
return wall(p.x, p.y, q.x, q.y);
|
||||
});
|
||||
|
||||
function freezeDeep(value) {
|
||||
if (value && typeof value === "object") {
|
||||
Object.values(value).forEach(freezeDeep);
|
||||
Object.freeze(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Fills the empty lists and puts the outline's edges first among the walls.
|
||||
function hole(def) {
|
||||
const theme = def.theme || "pirate";
|
||||
return {
|
||||
name: def.name,
|
||||
par: def.par,
|
||||
theme,
|
||||
quip: def.quip || "",
|
||||
ground: def.ground || (theme === "cave" ? "moss" : "grass"),
|
||||
liquid: def.liquid || (theme === "cave" ? "pool" : "sea"),
|
||||
tee: def.tee,
|
||||
cup: def.cup,
|
||||
outline: def.outline,
|
||||
walls: [...edges(def.outline), ...(def.walls || [])],
|
||||
bumpers: def.bumpers || [],
|
||||
sand: def.sand || [],
|
||||
water: def.water || [],
|
||||
slopes: def.slopes || [],
|
||||
bridges: def.bridges || [],
|
||||
spinners: def.spinners || [],
|
||||
tunnels: def.tunnels || [],
|
||||
movers: def.movers || [],
|
||||
gates: def.gates || [],
|
||||
powerups: def.powerups || [],
|
||||
decor: def.decor || [],
|
||||
};
|
||||
}
|
||||
|
||||
const pirate = (def) => hole({ ...def, theme: "pirate" });
|
||||
const cave = (def) => hole({ ...def, theme: "cave" });
|
||||
|
||||
export const HOLES = freezeDeep([
|
||||
/* ------------------------------------------- front nine: Pirate Cove */
|
||||
|
||||
// 1: a straight plank over the sea, to learn the putt. The sharks wait.
|
||||
pirate({
|
||||
name: "Walk the Plank",
|
||||
par: 2,
|
||||
quip: "Arr! Straight down the plank, matey. The sharks be hungry.",
|
||||
ground: "deck",
|
||||
tee: pt(90, 150),
|
||||
cup: pt(310, 150),
|
||||
outline: rect(60, 110, 280, 80),
|
||||
decor: [deco("shark", 200, 62, 1), deco("shark", 140, 244, 0.8), deco("ship", 345, 52), deco("bottle", 40, 250), deco("palm", 30, 70, 0.8)],
|
||||
}),
|
||||
|
||||
// 2: an L that turns left; a barrel splits the lane, and a doubloon waits in
|
||||
// the corner for whoever banks it there.
|
||||
pirate({
|
||||
name: "Shipwreck Cove",
|
||||
par: 3,
|
||||
quip: "Bank it off the corner. That doubloon makes yer next putt free!",
|
||||
tee: pt(75, 228),
|
||||
cup: pt(268, 75),
|
||||
outline: [pt(40, 195), pt(232, 195), pt(232, 40), pt(305, 40), pt(305, 262), pt(40, 262)],
|
||||
bumpers: [bump(268, 142, 10, "barrel")],
|
||||
powerups: [pad(268, 228, "doubloon")],
|
||||
decor: [deco("wreck", 125, 110), deco("crab", 70, 282), deco("parrot", 345, 70), deco("shark", 355, 200, 0.7), deco("palm", 20, 175, 0.9)],
|
||||
}),
|
||||
|
||||
// 3: cannonballs across the straight line, a powder barrel rolling the
|
||||
// lane, and cannons firing from the shore.
|
||||
pirate({
|
||||
name: "Cannon Alley",
|
||||
par: 3,
|
||||
quip: "Fire in the hole! Grab the cannonball for a mighty blast.",
|
||||
tee: pt(70, 150),
|
||||
cup: pt(330, 150),
|
||||
outline: rect(40, 60, 320, 180),
|
||||
bumpers: [
|
||||
bump(160, 108, 12, "cannonball"),
|
||||
bump(160, 192, 12, "cannonball"),
|
||||
bump(222, 150, 14, "cannonball"),
|
||||
bump(278, 98, 10, "cannonball"),
|
||||
bump(278, 202, 10, "cannonball"),
|
||||
],
|
||||
movers: [{ x: 110, y: 150, r: 9, dx: 0, dy: 62, period: 2600, look: "barrel" }],
|
||||
powerups: [pad(92, 80, "cannon")],
|
||||
decor: [deco("cannon", 120, 42), deco("cannon", 280, 42), deco("cannon", 200, 262, -1), deco("anchor", 380, 270)],
|
||||
}),
|
||||
|
||||
// 4: two staggered traps; the straight line crosses both, a weave misses
|
||||
// them, and the treasure map waits beyond the second.
|
||||
pirate({
|
||||
name: "Treasure Beach",
|
||||
par: 3,
|
||||
quip: "X marks the spot! The map makes the next cup HUGE.",
|
||||
tee: pt(70, 150),
|
||||
cup: pt(330, 150),
|
||||
outline: rect(40, 70, 320, 160),
|
||||
sand: [
|
||||
rect(135, 112, 60, 118),
|
||||
rect(235, 70, 60, 118),
|
||||
],
|
||||
bumpers: [bump(215, 150, 9, "chest")],
|
||||
powerups: [pad(165, 195, "doubloon"), pad(265, 210, "bigcup")],
|
||||
decor: [deco("palm", 28, 52), deco("palm", 372, 252), deco("crab", 200, 254), deco("island", 350, 40), deco("bottle", 60, 262)],
|
||||
}),
|
||||
|
||||
// 5: the lagoon runs wall to wall; the bridge is the only dry way over, and
|
||||
// the kraken's tentacle sweeps the far bank. The ghost floats right across.
|
||||
pirate({
|
||||
name: "Kraken's Lagoon",
|
||||
par: 4,
|
||||
quip: "Release the kraken! Or grab the ghost ball and float over it.",
|
||||
tee: pt(65, 80),
|
||||
cup: pt(330, 80),
|
||||
outline: rect(30, 40, 340, 220),
|
||||
water: [rect(165, 40, 80, 220)],
|
||||
bridges: [{ x: 165, y: 190, w: 80, h: 40 }],
|
||||
spinners: [{ x: 305, y: 172, arm: 34, speed: -1.9, look: "tentacle" }],
|
||||
powerups: [pad(90, 240, "ghost")],
|
||||
decor: [deco("tentacle", 205, 95), deco("tentacle", 190, 150, 0.8), deco("kraken", 205, 280), deco("shark", 380, 140, 0.6)],
|
||||
}),
|
||||
|
||||
// 6: a ghost ship's deck with an open hold amidships; around it by the
|
||||
// rails, or a rubber duck's bounce off them.
|
||||
pirate({
|
||||
name: "Ghost Ship",
|
||||
par: 3,
|
||||
quip: "Ooooo, a haunted deck. Mind the hold, it goes straight to the sea.",
|
||||
ground: "deck",
|
||||
tee: pt(75, 150),
|
||||
cup: pt(330, 150),
|
||||
outline: [pt(40, 90), pt(280, 70), pt(370, 150), pt(280, 230), pt(40, 210)],
|
||||
water: [rect(150, 118, 90, 64)],
|
||||
powerups: [pad(105, 118, "bouncy"), pad(105, 182, "magnet")],
|
||||
decor: [deco("ghost", 200, 40), deco("ghost", 300, 262, 0.7), deco("tentacle", 195, 160), deco("jolly", 60, 40)],
|
||||
}),
|
||||
|
||||
// 7: a ship's wheel turns across the way to the cup; walls close the way
|
||||
// around it.
|
||||
pirate({
|
||||
name: "The Ship's Wheel",
|
||||
par: 3,
|
||||
quip: "Hard to starboard! Time yer putt through the spinning wheel.",
|
||||
tee: pt(70, 150),
|
||||
cup: pt(330, 150),
|
||||
outline: rect(40, 80, 320, 140),
|
||||
walls: [
|
||||
wall(240, 80, 240, 107),
|
||||
wall(240, 193, 240, 220),
|
||||
],
|
||||
spinners: [{ x: 240, y: 150, arm: 40, speed: 1.6, look: "wheel" }],
|
||||
powerups: [pad(130, 105, "bouncy")],
|
||||
decor: [deco("parrot", 240, 60), deco("anchor", 30, 260), deco("shark", 200, 262, 0.9), deco("island", 360, 45)],
|
||||
}),
|
||||
|
||||
// 8: a long U the slow way round, past a scuttling crab, or the skull's
|
||||
// tunnel straight across.
|
||||
pirate({
|
||||
name: "Skull Island",
|
||||
par: 3,
|
||||
quip: "Into the skull's mouth and out its ear. Totally normal.",
|
||||
tee: pt(75, 65),
|
||||
cup: pt(325, 125),
|
||||
outline: [pt(40, 40), pt(110, 40), pt(110, 195), pt(290, 195), pt(290, 40), pt(360, 40), pt(360, 262), pt(40, 262)],
|
||||
tunnels: [
|
||||
{ a: pt(75, 170), b: pt(325, 62) },
|
||||
],
|
||||
movers: [{ x: 200, y: 245, r: 8, dx: 60, dy: 0, period: 3000, look: "crab" }],
|
||||
powerups: [pad(160, 214, "magnet")],
|
||||
decor: [deco("skullrock", 200, 115), deco("shark", 200, 45, 0.7), deco("palm", 148, 175, 0.7), deco("palm", 255, 172, 0.8)],
|
||||
}),
|
||||
|
||||
// 9: up the ramp, over the bridge, through the gold to the cup.
|
||||
pirate({
|
||||
name: "Captain's Plunder",
|
||||
par: 4,
|
||||
quip: "The captain's own treasure! Ramp, bridge, gold. Go!",
|
||||
tee: pt(70, 240),
|
||||
cup: pt(340, 60),
|
||||
outline: rect(30, 30, 340, 240),
|
||||
// The ramp climbs to the bridge: too soft a putt rolls back down it.
|
||||
slopes: [
|
||||
{ points: rect(95, 55, 55, 50), push: pt(-110, 0) },
|
||||
],
|
||||
water: [
|
||||
rect(150, 30, 90, 240),
|
||||
],
|
||||
bridges: [
|
||||
{ x: 150, y: 55, w: 90, h: 50 },
|
||||
],
|
||||
bumpers: [
|
||||
bump(288, 118, 12, "coin"),
|
||||
bump(336, 132, 10, "coin"),
|
||||
bump(296, 200, 12, "coin"),
|
||||
bump(270, 40, 8, "coin"),
|
||||
],
|
||||
movers: [{ x: 320, y: 250, r: 7, dx: 30, dy: 0, period: 2400, look: "crab" }],
|
||||
powerups: [pad(60, 150, "spyglass"), pad(270, 160, "doubloon")],
|
||||
decor: [deco("tentacle", 195, 180), deco("tentacle", 210, 240, 0.7), deco("chest", 385, 80), deco("jolly", 385, 250)],
|
||||
}),
|
||||
|
||||
/* ---------------------------------------- back nine: Caves of Doom */
|
||||
|
||||
// 10: a winding passage into the dark past a glowing pool, a mushroom on
|
||||
// the bend.
|
||||
cave({
|
||||
name: "Into the Dark",
|
||||
par: 3,
|
||||
quip: "Welcome to the Caves of Doom. Your ball is the only light. Gulp.",
|
||||
tee: pt(60, 230),
|
||||
cup: pt(340, 80),
|
||||
outline: [pt(30, 200), pt(230, 200), pt(230, 40), pt(370, 40), pt(370, 120), pt(300, 120), pt(300, 260), pt(30, 260)],
|
||||
water: [rect(115, 236, 75, 24)],
|
||||
bumpers: [bump(265, 160, 9, "mushroom")],
|
||||
powerups: [pad(265, 232, "spyglass")],
|
||||
decor: [deco("bat", 110, 90), deco("bat", 160, 130, 0.8), deco("eyes", 90, 150), deco("torch", 30, 185), deco("stalactite", 330, 0), deco("crystal", 380, 200), deco("eyes", 345, 230, 0.7)],
|
||||
}),
|
||||
|
||||
// 11: a forest of stalagmites, with gaps a ball can thread.
|
||||
cave({
|
||||
name: "Stalagmite Forest",
|
||||
par: 3,
|
||||
quip: "Pointy rocks everywhere. Bounce through like a pinball.",
|
||||
ground: "stone",
|
||||
tee: pt(70, 150),
|
||||
cup: pt(335, 150),
|
||||
outline: rect(40, 50, 320, 200),
|
||||
bumpers: [
|
||||
bump(120, 90, 9, "rock"), bump(120, 150, 9, "rock"), bump(120, 210, 9, "rock"),
|
||||
bump(162, 120, 9, "rock"), bump(162, 180, 9, "rock"),
|
||||
bump(204, 90, 9, "rock"), bump(204, 150, 9, "rock"), bump(204, 210, 9, "rock"),
|
||||
bump(246, 120, 9, "rock"), bump(246, 180, 9, "rock"),
|
||||
bump(288, 90, 9, "rock"), bump(288, 210, 9, "rock"),
|
||||
],
|
||||
powerups: [pad(225, 236, "bouncy")],
|
||||
decor: [deco("bat", 100, 30), deco("bat", 300, 270, 0.8), deco("stalactite", 80, 0), deco("stalactite", 250, 0, 1.2), deco("crystal", 20, 270), deco("skeleton", 375, 40)],
|
||||
}),
|
||||
|
||||
// 12: a lava lake wall to wall, two thin stone bridges, and a fireball
|
||||
// bobbing up and down across both of them.
|
||||
cave({
|
||||
name: "Lava Lake",
|
||||
par: 4,
|
||||
quip: "The floor is lava. No, really. Fireball incoming!",
|
||||
liquid: "lava",
|
||||
ground: "stone",
|
||||
tee: pt(65, 150),
|
||||
cup: pt(335, 150),
|
||||
outline: rect(30, 40, 340, 220),
|
||||
water: [rect(130, 40, 140, 220)],
|
||||
bridges: [
|
||||
{ x: 130, y: 70, w: 140, h: 28 },
|
||||
{ x: 130, y: 205, w: 140, h: 28 },
|
||||
],
|
||||
movers: [{ x: 200, y: 150, r: 8, dx: 0, dy: 95, period: 3600, look: "fireball" }],
|
||||
powerups: [pad(85, 235, "ghost")],
|
||||
decor: [deco("torch", 20, 100), deco("torch", 380, 100), deco("skeleton", 375, 270), deco("stalactite", 200, 0, 0.8)],
|
||||
}),
|
||||
|
||||
// 13: three mine carts rattle up and down across the straight line.
|
||||
cave({
|
||||
name: "Mine Cart Madness",
|
||||
par: 3,
|
||||
quip: "Runaway mine carts! Time it... or blast through with the cannon.",
|
||||
ground: "stone",
|
||||
tee: pt(60, 150),
|
||||
cup: pt(345, 150),
|
||||
outline: rect(30, 40, 340, 220),
|
||||
movers: [
|
||||
{ x: 140, y: 150, r: 12, dx: 0, dy: 85, period: 2200, look: "cart" },
|
||||
{ x: 220, y: 150, r: 12, dx: 0, dy: 85, period: 2800, phase: 0.3, look: "cart" },
|
||||
{ x: 300, y: 150, r: 12, dx: 0, dy: 85, period: 2000, phase: 0.6, look: "cart" },
|
||||
],
|
||||
powerups: [pad(60, 70, "cannon")],
|
||||
decor: [deco("rails", 140, 150), deco("rails", 220, 150), deco("rails", 300, 150), deco("lantern", 20, 40), deco("gems", 385, 270), deco("bat", 200, 20)],
|
||||
}),
|
||||
|
||||
// 14: crystals everywhere and two slingshot walls: pure pinball.
|
||||
cave({
|
||||
name: "Crystal Pinball",
|
||||
par: 3,
|
||||
quip: "TILT! Crystals, bumpers and a big treasure-map cup.",
|
||||
tee: pt(70, 230),
|
||||
cup: pt(330, 70),
|
||||
outline: rect(40, 40, 320, 220),
|
||||
walls: [
|
||||
wall(300, 252, 350, 215),
|
||||
wall(48, 150, 85, 122),
|
||||
],
|
||||
bumpers: [
|
||||
bump(130, 110, 11, "crystal"),
|
||||
bump(200, 80, 11, "crystal"),
|
||||
bump(200, 170, 13, "crystal"),
|
||||
bump(270, 140, 11, "crystal"),
|
||||
bump(140, 200, 10, "crystal"),
|
||||
bump(330, 140, 9, "crystal"),
|
||||
],
|
||||
powerups: [pad(205, 238, "bigcup")],
|
||||
decor: [deco("crystal", 22, 210, 1.2), deco("crystal", 380, 280), deco("crystal", 385, 120, 0.8), deco("bat", 200, 280, 0.7)],
|
||||
}),
|
||||
|
||||
// 15: a bottomless pit wall to wall, one rope bridge over it, and an
|
||||
// updraft blowing across the bridge.
|
||||
cave({
|
||||
name: "The Bottomless Pit",
|
||||
par: 3,
|
||||
quip: "Don't look down. Seriously. There's an updraft on the bridge.",
|
||||
liquid: "chasm",
|
||||
ground: "stone",
|
||||
tee: pt(75, 150),
|
||||
cup: pt(325, 150),
|
||||
outline: rect(40, 50, 320, 200),
|
||||
water: [rect(150, 50, 100, 200)],
|
||||
bridges: [{ x: 150, y: 132, w: 100, h: 36 }],
|
||||
slopes: [{ points: rect(150, 132, 100, 36), push: pt(0, 70) }],
|
||||
powerups: [pad(100, 80, "magnet")],
|
||||
decor: [deco("spider", 330, 70), deco("web", 360, 230), deco("skeleton", 60, 230), deco("torch", 30, 150), deco("torch", 370, 150)],
|
||||
}),
|
||||
|
||||
// 16: a winding grotto; the glowworm current carries the ball up and over.
|
||||
cave({
|
||||
name: "Glowworm Grotto",
|
||||
par: 3,
|
||||
quip: "Ride the glowworm current. They're friendly. Probably.",
|
||||
tee: pt(70, 90),
|
||||
cup: pt(310, 200),
|
||||
outline: rect(30, 60, 340, 180),
|
||||
walls: [
|
||||
wall(130, 60, 130, 180),
|
||||
wall(250, 120, 250, 240),
|
||||
],
|
||||
slopes: [{ points: rect(140, 70, 100, 100), push: pt(0, -90) }],
|
||||
bumpers: [bump(190, 215, 10, "mushroom"), bump(310, 90, 10, "mushroom")],
|
||||
powerups: [pad(165, 195, "spyglass")],
|
||||
decor: [deco("glowworms", 200, 30), deco("glowworms", 100, 270), deco("mushroom", 20, 250), deco("mushroom", 385, 50), deco("eyes", 300, 270)],
|
||||
}),
|
||||
|
||||
// 17: a corridor of stone crushers slamming down in turn, lava in its
|
||||
// corners.
|
||||
cave({
|
||||
name: "Crusher Corridor",
|
||||
par: 4,
|
||||
quip: "SMASH! SMASH! SMASH! Run the crushers... if you dare.",
|
||||
ground: "stone",
|
||||
liquid: "lava",
|
||||
tee: pt(60, 150),
|
||||
cup: pt(345, 150),
|
||||
outline: rect(30, 90, 340, 120),
|
||||
water: [rect(160, 90, 30, 24), rect(240, 186, 30, 24)],
|
||||
gates: [
|
||||
{ x1: 130, y1: 90, x2: 130, y2: 210, period: 2400, open: 0.55, offset: 0, look: "crusher" },
|
||||
{ x1: 210, y1: 90, x2: 210, y2: 210, period: 2400, open: 0.55, offset: 0.33, look: "crusher" },
|
||||
{ x1: 290, y1: 90, x2: 290, y2: 210, period: 2400, open: 0.55, offset: 0.66, look: "crusher" },
|
||||
],
|
||||
powerups: [pad(95, 195, "cannon"), pad(250, 105, "doubloon")],
|
||||
decor: [deco("skeleton", 200, 245), deco("torch", 100, 70), deco("torch", 300, 70), deco("stalactite", 200, 0, 1.3), deco("bat", 60, 260, 0.8)],
|
||||
}),
|
||||
|
||||
// 18: the dragon's hoard: a lava lake, a portal over it, the dragon's tail
|
||||
// sweeping, gold everywhere, and the dragon himself asleep at the edge.
|
||||
cave({
|
||||
name: "The Dragon's Hoard",
|
||||
par: 5,
|
||||
quip: "SHHH! The dragon is sleeping. Grab the gold and sink it.",
|
||||
liquid: "lava",
|
||||
tee: pt(60, 240),
|
||||
cup: pt(305, 75),
|
||||
outline: rect(20, 45, 325, 230),
|
||||
water: [rect(130, 45, 80, 160)],
|
||||
tunnels: [{ a: pt(70, 80), b: pt(245, 70) }],
|
||||
spinners: [{ x: 275, y: 160, arm: 34, speed: 2.2, look: "tail" }],
|
||||
bumpers: [bump(300, 220, 9, "coin"), bump(235, 112, 9, "coin"), bump(95, 145, 9, "coin")],
|
||||
powerups: [pad(170, 240, "bigcup"), pad(65, 180, "ghost")],
|
||||
decor: [deco("dragon", 400, 160), deco("gems", 30, 290), deco("gems", 372, 270, 0.8), deco("torch", 10, 160), deco("stalactite", 200, 0)],
|
||||
}),
|
||||
]);
|
||||
|
||||
// Where the front nine ends: the scorecard after it heads into the caves.
|
||||
export const FRONT_NINE = 9;
|
||||
@@ -0,0 +1,954 @@
|
||||
// Plan2Code Web Console - Mini golf, the second activity: eighteen holes seen from above, rules, physics and the game contract.
|
||||
//
|
||||
// The Activities window (screens/activities.js) drives everything, as it does
|
||||
// for Snake: it ticks the game, hands it keys, key releases and pointer
|
||||
// events, and pauses it. Play is arcade quick: the aim follows the pointer
|
||||
// (or held arrows), one press starts the power meter and a second sets the
|
||||
// power, and a shot clock starts the meter for a player who dawdles. The
|
||||
// rules are plain functions over a round object (newRound, startSwing,
|
||||
// setPower, strike, advance and helpers), exported so the unit suite can play
|
||||
// exact shots without a canvas. Physics runs on a fixed sub-step and never reads the
|
||||
// clock or Math.random(), so the same shot always rolls the same way. The
|
||||
// course is data (golf-holes.js); the drawing lives in golf-draw.js and its
|
||||
// scenery in golf-decor.js.
|
||||
|
||||
import { COURSE_W, COURSE_H, FRONT_NINE, HOLES } from "./golf-holes.js";
|
||||
import { drawCourse, readColors } from "./golf-draw.js";
|
||||
|
||||
export { COURSE_W, COURSE_H, FRONT_NINE, HOLES };
|
||||
|
||||
// One physics step, in ms. tick() runs as many as the elapsed time holds and
|
||||
// carries the rest to the next tick.
|
||||
export const SUB_STEP_MS = 4;
|
||||
|
||||
// The most time one tick() plays, matching the window's own frame cap.
|
||||
export const MAX_TICK_MS = 250;
|
||||
|
||||
export const BALL_R = 4;
|
||||
export const CUP_R = 7;
|
||||
export const TUNNEL_R = 9;
|
||||
export const POWERUP_R = 9;
|
||||
|
||||
// The fastest a ball ever moves, in units a second. At SUB_STEP_MS it covers
|
||||
// 2.4 units a step, under BALL_R, so no step can carry it through a wall. A
|
||||
// cannon shot may go faster, still under BALL_R a step.
|
||||
export const MAX_SPEED = 600;
|
||||
export const CANNON_MAX = 900;
|
||||
|
||||
// A full-power putt's speed, in units a second. A MAX putt (MAX_BOOST) comes
|
||||
// to 598, just under MAX_SPEED.
|
||||
export const STRIKE_SPEED = 520;
|
||||
|
||||
// Rolling: a steady slowing plus a share of the speed, both multiplied in sand.
|
||||
const FRICTION = 40;
|
||||
const DRAG = 1.2;
|
||||
export const SAND_FACTOR = 4;
|
||||
|
||||
// Under this speed, off any slope, the ball has stopped. High enough to cut
|
||||
// the slow creep at the end of a roll.
|
||||
const STOP_SPEED = 8;
|
||||
|
||||
// Over the cup under this speed, the ball drops; faster, it rolls over.
|
||||
export const CAPTURE_SPEED = 130;
|
||||
|
||||
// The share of its speed into a wall the ball keeps coming off it.
|
||||
const WALL_KEEP = 0.7;
|
||||
|
||||
// The speed a bumper adds on top of a full bounce.
|
||||
const BUMPER_KICK = 60;
|
||||
|
||||
// A hit into a wall this fast or more gets the wall tone.
|
||||
const FIRM_HIT = 60;
|
||||
|
||||
export const MAX_STROKES = 8;
|
||||
|
||||
// How long the scorecard waits between holes before moving on by itself.
|
||||
export const CARD_MS = 1500;
|
||||
|
||||
// The power-ups: a pad the rolling ball runs over is held for the next putt,
|
||||
// and that putt alone gets its help. One is held at a time; a new pad
|
||||
// replaces the one held. A held power-up carries over to the next hole.
|
||||
export const POWERUPS = Object.freeze({
|
||||
doubloon: Object.freeze({ name: "Lucky Doubloon", blurb: "the next putt is free" }),
|
||||
cannon: Object.freeze({ name: "Cannonball", blurb: "the next putt fires 1.6x as hard" }),
|
||||
ghost: Object.freeze({ name: "Ghost Ball", blurb: "the next putt floats over water, sand and bumpers" }),
|
||||
magnet: Object.freeze({ name: "Parrot Magnet", blurb: "the next putt homes in on the cup" }),
|
||||
bouncy: Object.freeze({ name: "Rubber Duck", blurb: "the next putt bounces off walls at full speed" }),
|
||||
bigcup: Object.freeze({ name: "Treasure Map", blurb: "the next putt aims at a HUGE cup" }),
|
||||
spyglass: Object.freeze({ name: "Spyglass", blurb: "see where the next putt will roll" }),
|
||||
});
|
||||
|
||||
export const CANNON_BOOST = 1.6;
|
||||
export const BIG_CUP = 2.4;
|
||||
// The magnet turns the ball toward the cup inside this reach, by up to this
|
||||
// many radians a second, never adding speed, so a ball under it still stops.
|
||||
export const MAGNET_R = 110;
|
||||
const MAGNET_TURN = 7;
|
||||
// The magnet and the big cup let a faster ball drop.
|
||||
const HELPED_CAPTURE = 1.7;
|
||||
|
||||
// How far ahead the spyglass looks, in ms of rolling.
|
||||
const PREDICT_MS = 3000;
|
||||
|
||||
// The swing. A press starts the power meter and a second sets the power. The
|
||||
// needle runs from empty to past full and back once every METER_MS, slow at
|
||||
// the bottom and fast at the top (METER_CURVE), so a soft putt is easy to
|
||||
// catch and a full one is not. The MAX band, just under full, putts
|
||||
// MAX_BOOST as hard. Past full is the overswing: OVER_POWER, pulled off line
|
||||
// by up to OVER_PULL, the more the deeper into it.
|
||||
export const METER_MS = 1750;
|
||||
const METER_CURVE = 1.6;
|
||||
export const MAX_BAND = 0.12;
|
||||
export const MAX_BOOST = 1.15;
|
||||
export const OVER_BAND = 0.1;
|
||||
export const OVER_POWER = 0.7;
|
||||
const OVER_PULL = (14 * Math.PI) / 180;
|
||||
// The softest putt a press can set.
|
||||
const MIN_POWER = 0.03;
|
||||
|
||||
// The shot clock: a ball this long at rest starts the meter by itself, and a
|
||||
// meter left running METER_TRIPS trips dribbles the ball off at DRIBBLE_POWER.
|
||||
export const SHOT_CLOCK_MS = 6000;
|
||||
export const METER_TRIPS = 3;
|
||||
const DRIBBLE_POWER = 0.06;
|
||||
|
||||
// Holding the action key or the pointer down while the ball rolls plays the
|
||||
// roll this many times as fast.
|
||||
export const FAST_FORWARD = 3;
|
||||
|
||||
// Keyboard aiming: a press nudges the aim by AIM_NUDGE, and held, it turns
|
||||
// from TURN_SLOW up to TURN_FAST radians a second over TURN_RAMP_MS.
|
||||
const AIM_NUDGE = Math.PI / 180;
|
||||
const TURN_SLOW = (35 * Math.PI) / 180;
|
||||
const TURN_FAST = (220 * Math.PI) / 180;
|
||||
const TURN_RAMP_MS = 700;
|
||||
|
||||
// Below this many CSS pixels the course is too small to play.
|
||||
export const MIN_W = 320;
|
||||
export const MIN_H = 240;
|
||||
|
||||
// How many recent positions the rolling ball's trail keeps.
|
||||
const TRAIL = 12;
|
||||
|
||||
// How long a popped-up word stays on the board, in ms of the round's clock.
|
||||
const TOAST_MS = 1300;
|
||||
|
||||
/* --------------------------------------------------------------- geometry */
|
||||
|
||||
const dist = (ax, ay, bx, by) => Math.hypot(ax - bx, ay - by);
|
||||
|
||||
export function inPolygon(points, x, y) {
|
||||
let inside = false;
|
||||
for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
|
||||
const a = points[i];
|
||||
const b = points[j];
|
||||
if ((a.y > y) !== (b.y > y) && x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
const inRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
|
||||
|
||||
// The point on segment a-b closest to p.
|
||||
function closest(x1, y1, x2, y2, px, py) {
|
||||
const dx = x2 - x1;
|
||||
const dy = y2 - y1;
|
||||
const len = dx * dx + dy * dy;
|
||||
const t = len ? Math.max(0, Math.min(1, ((px - x1) * dx + (py - y1) * dy) / len)) : 0;
|
||||
return { x: x1 + t * dx, y: y1 + t * dy };
|
||||
}
|
||||
|
||||
// A spinner's bar as a segment at the round's clock.
|
||||
export function spinnerEnds(s, clockMs) {
|
||||
const a = s.speed * (clockMs / 1000);
|
||||
const cx = Math.cos(a) * s.arm;
|
||||
const cy = Math.sin(a) * s.arm;
|
||||
return { x1: s.x - cx, y1: s.y - cy, x2: s.x + cx, y2: s.y + cy };
|
||||
}
|
||||
|
||||
// A mover's center and velocity at the round's clock: a smooth swing either
|
||||
// side of where it rests.
|
||||
export function moverAt(m, clockMs) {
|
||||
const turn = (2 * Math.PI) / m.period;
|
||||
const a = turn * clockMs + 2 * Math.PI * (m.phase || 0);
|
||||
const s = Math.sin(a);
|
||||
const c = Math.cos(a) * turn * 1000;
|
||||
return { x: m.x + m.dx * s, y: m.y + m.dy * s, vx: m.dx * c, vy: m.dy * c, r: m.r };
|
||||
}
|
||||
|
||||
// How far through its period a gate is, 0 to 1, and whether it is shut.
|
||||
export const gatePhase = (g, clockMs) => (((clockMs / g.period + (g.offset || 0)) % 1) + 1) % 1;
|
||||
export const gateShut = (g, clockMs) => gatePhase(g, clockMs) >= g.open;
|
||||
|
||||
export const onSlope = (hole, x, y) => hole.slopes.some((s) => inPolygon(s.points, x, y));
|
||||
export const inSand = (hole, x, y) => hole.sand.some((p) => inPolygon(p, x, y));
|
||||
export const onBridge = (hole, x, y) => hole.bridges.some((r) => inRect(r, x, y));
|
||||
export const inWater = (hole, x, y) => hole.water.some((p) => inPolygon(p, x, y)) && !onBridge(hole, x, y);
|
||||
|
||||
/* ------------------------------------------------------------------ rules */
|
||||
|
||||
const parTotal = (upTo) => HOLES.slice(0, upTo).reduce((n, h) => n + h.par, 0);
|
||||
|
||||
// The ball at rest, waiting for a putt: the shot clock starts again and the
|
||||
// aim turns back toward the cup, so a straight putt needs no aiming at all.
|
||||
function atRest(round) {
|
||||
const hole = HOLES[round.hole];
|
||||
round.phase = "aim";
|
||||
round.restMs = 0;
|
||||
round.aimAngle = Math.atan2(hole.cup.y - round.ball.y, hole.cup.x - round.ball.x);
|
||||
}
|
||||
|
||||
function placeOnTee(round) {
|
||||
const hole = HOLES[round.hole];
|
||||
round.ball = { x: hole.tee.x, y: hole.tee.y, vx: 0, vy: 0, moving: false };
|
||||
round.from = { x: hole.tee.x, y: hole.tee.y };
|
||||
round.strokes = 0;
|
||||
round.putts = 0;
|
||||
round.tunnelLock = null;
|
||||
round.trail = [];
|
||||
round.active = null;
|
||||
round.taken = [];
|
||||
round.holeStart = round.clock;
|
||||
atRest(round);
|
||||
}
|
||||
|
||||
// Hole 1, the ball on its tee, nothing scored. `phase` is "aim" (the ball at
|
||||
// rest, waiting for a putt), "swing" (the power meter running), "rolling",
|
||||
// "card" (the scorecard between holes) or "done" (the round is over).
|
||||
// `restMs` is how long the ball has waited (the shot clock), `swingMs` how
|
||||
// long the meter has run, `swingAngle` the aim it locked, and `lastSwing`
|
||||
// where the needle stopped last time. `held` is the power-up waiting for the
|
||||
// next putt, `active` the one helping the putt in play, and `taken` the pads
|
||||
// this hole has used up.
|
||||
export function newRound() {
|
||||
const round = {
|
||||
hole: 0,
|
||||
card: [],
|
||||
clock: 0,
|
||||
cardMs: 0,
|
||||
sunk: null,
|
||||
swingMs: 0,
|
||||
swingAngle: 0,
|
||||
lastSwing: null,
|
||||
held: null,
|
||||
};
|
||||
placeOnTee(round);
|
||||
return round;
|
||||
}
|
||||
|
||||
// Every finished hole's strokes plus the hole in play.
|
||||
export const total = (round) => round.card.reduce((n, s) => n + s, 0) + (round.phase === "card" || round.phase === "done" ? 0 : round.strokes);
|
||||
|
||||
// Against par for the holes played so far, the one in play counted once it is
|
||||
// finished: negative is under par.
|
||||
export const toPar = (round) => round.card.reduce((n, s) => n + s, 0) - parTotal(round.card.length);
|
||||
|
||||
// Putts from where the ball rests: power 0 to MAX_BOOST of STRIKE_SPEED, at
|
||||
// an angle in radians (0 is along +x). A held power-up goes into this putt.
|
||||
// Returns whether a putt was taken (a Lucky Doubloon putt is taken but not
|
||||
// counted).
|
||||
export function strike(round, angle, power) {
|
||||
if ((round.phase !== "aim" && round.phase !== "swing") || round.ball.moving || !(power > 0)) return false;
|
||||
round.active = round.held;
|
||||
round.held = null;
|
||||
const boost = round.active === "cannon" ? CANNON_BOOST : 1;
|
||||
const speed = STRIKE_SPEED * Math.min(MAX_BOOST, power) * boost;
|
||||
const ball = round.ball;
|
||||
round.from = { x: ball.x, y: ball.y };
|
||||
ball.vx = Math.cos(angle) * speed;
|
||||
ball.vy = Math.sin(angle) * speed;
|
||||
ball.moving = true;
|
||||
round.putts += 1;
|
||||
if (round.active !== "doubloon") round.strokes += 1;
|
||||
round.phase = "rolling";
|
||||
round.trail = [];
|
||||
return true;
|
||||
}
|
||||
|
||||
// The needle `ms` into a swing: from 0 (empty) up to 1 + OVER_BAND (the top
|
||||
// of the overswing) and back, once every METER_MS.
|
||||
export function meterAt(ms) {
|
||||
const t = ((ms % METER_MS) + METER_MS) % METER_MS / METER_MS;
|
||||
const u = t < 0.5 ? t * 2 : 2 - t * 2;
|
||||
return (1 + OVER_BAND) * u ** METER_CURVE;
|
||||
}
|
||||
|
||||
export const meterZone = (pos) => (pos > 1 ? "over" : pos >= 1 - MAX_BAND ? "max" : "normal");
|
||||
|
||||
// What a press at needle `pos` puts on a ball aimed at `angle`: { zone,
|
||||
// angle, power }. An overswing pulls left and right on alternate putts (`n`),
|
||||
// so the same swing always goes the same way.
|
||||
export function swingShot(pos, angle, n) {
|
||||
const zone = meterZone(pos);
|
||||
if (zone === "max") return { zone, angle, power: MAX_BOOST };
|
||||
if (zone === "over") {
|
||||
const depth = Math.min(1, (pos - 1) / OVER_BAND);
|
||||
return { zone, angle: angle + (n % 2 ? 1 : -1) * (0.4 + 0.6 * depth) * OVER_PULL, power: OVER_POWER };
|
||||
}
|
||||
return { zone, angle, power: Math.max(MIN_POWER, pos) };
|
||||
}
|
||||
|
||||
// Starts the power meter on a ball at rest, the aim locked where it points.
|
||||
export function startSwing(round) {
|
||||
if (round.phase !== "aim" || round.ball.moving) return false;
|
||||
round.phase = "swing";
|
||||
round.swingMs = 0;
|
||||
round.swingAngle = round.aimAngle;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sets the power where the needle is and putts. Returns the shot swingShot()
|
||||
// made of it, or null when no meter was running.
|
||||
export function setPower(round) {
|
||||
if (round.phase !== "swing") return null;
|
||||
const pos = meterAt(round.swingMs);
|
||||
const shot = swingShot(pos, round.swingAngle, round.putts);
|
||||
if (!strike(round, shot.angle, shot.power)) return null;
|
||||
round.lastSwing = pos;
|
||||
return shot;
|
||||
}
|
||||
|
||||
// The scorecard for a finished hole, or the end of the round after the last.
|
||||
// A water penalty on the last stroke can take the count past the cap, so the
|
||||
// hole in play is capped too, not only its card entry. A hole always scores
|
||||
// at least 1, however many doubloons went into it.
|
||||
function finishHole(round, strokes, events) {
|
||||
round.strokes = Math.max(1, Math.min(round.strokes, MAX_STROKES));
|
||||
round.card.push(Math.max(1, Math.min(strokes, MAX_STROKES)));
|
||||
round.ball.vx = 0;
|
||||
round.ball.vy = 0;
|
||||
round.ball.moving = false;
|
||||
round.active = null;
|
||||
round.cardMs = 0;
|
||||
round.phase = round.hole === HOLES.length - 1 ? "done" : "card";
|
||||
if (round.phase === "done") events.push("done");
|
||||
}
|
||||
|
||||
// Leaves the scorecard for the next hole's tee.
|
||||
export function nextHole(round) {
|
||||
if (round.phase !== "card") return false;
|
||||
round.hole += 1;
|
||||
round.sunk = null;
|
||||
placeOnTee(round);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The ball off a fixed segment or a moving bar: pushed clear, and bounced
|
||||
// with `keep` of its speed into the surface. `sx`, `sy` is how fast the
|
||||
// surface itself moves at the contact (a spinner), 0 for a wall.
|
||||
function bounceOffSegment(ball, seg, events, keep = WALL_KEEP, sx = 0, sy = 0) {
|
||||
const p = closest(seg.x1, seg.y1, seg.x2, seg.y2, ball.x, ball.y);
|
||||
let nx = ball.x - p.x;
|
||||
let ny = ball.y - p.y;
|
||||
let d = Math.hypot(nx, ny);
|
||||
if (d >= BALL_R) return false;
|
||||
if (d === 0) {
|
||||
// Dead on the line: back out the way it came, or, at rest, square off it.
|
||||
const v = Math.hypot(ball.vx, ball.vy);
|
||||
const len = Math.hypot(seg.x2 - seg.x1, seg.y2 - seg.y1) || 1;
|
||||
nx = v ? -ball.vx / v : -(seg.y2 - seg.y1) / len;
|
||||
ny = v ? -ball.vy / v : (seg.x2 - seg.x1) / len;
|
||||
d = 1;
|
||||
} else {
|
||||
nx /= d;
|
||||
ny /= d;
|
||||
}
|
||||
ball.x = p.x + nx * BALL_R;
|
||||
ball.y = p.y + ny * BALL_R;
|
||||
const into = (ball.vx - sx) * nx + (ball.vy - sy) * ny;
|
||||
if (into < 0) {
|
||||
ball.vx -= (1 + keep) * into * nx;
|
||||
ball.vy -= (1 + keep) * into * ny;
|
||||
if (-into >= FIRM_HIT) events.push("wall");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// A ball off a round bumper, standing or moving at (bvx, bvy): a full bounce
|
||||
// plus a kick.
|
||||
function bounceOffRound(ball, b, events, bvx = 0, bvy = 0) {
|
||||
let nx = ball.x - b.x;
|
||||
let ny = ball.y - b.y;
|
||||
const d = Math.hypot(nx, ny);
|
||||
if (d >= b.r + BALL_R || d === 0) return false;
|
||||
nx /= d;
|
||||
ny /= d;
|
||||
ball.x = b.x + nx * (b.r + BALL_R);
|
||||
ball.y = b.y + ny * (b.r + BALL_R);
|
||||
const into = (ball.vx - bvx) * nx + (ball.vy - bvy) * ny;
|
||||
if (into < 0) {
|
||||
ball.vx -= 2 * into * nx;
|
||||
ball.vy -= 2 * into * ny;
|
||||
}
|
||||
ball.vx += nx * BUMPER_KICK;
|
||||
ball.vy += ny * BUMPER_KICK;
|
||||
events.push("bump");
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sets a resting ball that something knocked off rolling.
|
||||
function knocked(round) {
|
||||
const ball = round.ball;
|
||||
if (!ball.moving && Math.hypot(ball.vx, ball.vy) >= STOP_SPEED) {
|
||||
ball.moving = true;
|
||||
round.phase = "rolling";
|
||||
}
|
||||
}
|
||||
|
||||
// What moves by itself sweeps a resting ball too, so this runs on every step:
|
||||
// spinners' bars, movers and shut gates. A ghost ball slips through movers.
|
||||
function sweepers(round, hole, events) {
|
||||
const ball = round.ball;
|
||||
for (const s of hole.spinners) {
|
||||
const seg = spinnerEnds(s, round.clock);
|
||||
const p = closest(seg.x1, seg.y1, seg.x2, seg.y2, ball.x, ball.y);
|
||||
// The bar's own speed where it touches: the turn rate times the distance
|
||||
// from the center, at right angles to it.
|
||||
const sx = -s.speed * (p.y - s.y);
|
||||
const sy = s.speed * (p.x - s.x);
|
||||
if (bounceOffSegment(ball, seg, events, WALL_KEEP, sx, sy)) knocked(round);
|
||||
}
|
||||
if (round.active !== "ghost") {
|
||||
for (const m of hole.movers) {
|
||||
const at = moverAt(m, round.clock);
|
||||
if (bounceOffRound(ball, at, events, at.vx, at.vy)) knocked(round);
|
||||
}
|
||||
}
|
||||
for (const g of hole.gates) {
|
||||
if (gateShut(g, round.clock)) bounceOffSegment(ball, g, events, wallKeep(round));
|
||||
}
|
||||
}
|
||||
|
||||
const wallKeep = (round) => (round.active === "bouncy" ? 1 : WALL_KEEP);
|
||||
|
||||
function tunnels(round, hole, events) {
|
||||
const ball = round.ball;
|
||||
if (round.tunnelLock) {
|
||||
// Out of the mouth it came from before it can go in again.
|
||||
if (dist(ball.x, ball.y, round.tunnelLock.x, round.tunnelLock.y) < TUNNEL_R) return;
|
||||
round.tunnelLock = null;
|
||||
}
|
||||
for (const t of hole.tunnels) {
|
||||
for (const [from, to] of [[t.a, t.b], [t.b, t.a]]) {
|
||||
if (dist(ball.x, ball.y, from.x, from.y) < TUNNEL_R) {
|
||||
ball.x = to.x;
|
||||
ball.y = to.y;
|
||||
round.tunnelLock = to;
|
||||
round.trail = [];
|
||||
events.push("tunnel");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A pad the ball runs over is used up for the hole and held for the next putt.
|
||||
function powerups(round, hole, events) {
|
||||
const ball = round.ball;
|
||||
hole.powerups.forEach((p, i) => {
|
||||
if (round.taken.includes(i) || dist(ball.x, ball.y, p.x, p.y) >= POWERUP_R) return;
|
||||
round.taken.push(i);
|
||||
round.held = p.kind;
|
||||
events.push("powerup");
|
||||
});
|
||||
}
|
||||
|
||||
// The magnet bends the ball's path toward the cup without speeding it up.
|
||||
function magnet(round, hole, dt) {
|
||||
const ball = round.ball;
|
||||
const speed = Math.hypot(ball.vx, ball.vy);
|
||||
const dx = hole.cup.x - ball.x;
|
||||
const dy = hole.cup.y - ball.y;
|
||||
const d = Math.hypot(dx, dy);
|
||||
if (!speed || !d || d > MAGNET_R) return;
|
||||
const pull = MAGNET_TURN * dt * (1 - d / MAGNET_R) * speed;
|
||||
const vx = ball.vx + (dx / d) * pull;
|
||||
const vy = ball.vy + (dy / d) * pull;
|
||||
const v = Math.hypot(vx, vy) || 1;
|
||||
ball.vx = (vx / v) * speed;
|
||||
ball.vy = (vy / v) * speed;
|
||||
}
|
||||
|
||||
// The hole is over at MAX_STROKES without the ball in the cup: picked up.
|
||||
function pickUpAtCap(round, events) {
|
||||
if (round.strokes < MAX_STROKES) return;
|
||||
events.push("pickup");
|
||||
finishHole(round, MAX_STROKES, events);
|
||||
}
|
||||
|
||||
// How wide the cup is, and how slow a ball must be to drop, for this putt.
|
||||
export const cupReach = (round) => CUP_R * (round.active === "bigcup" ? BIG_CUP : 1);
|
||||
const captureSpeed = (round) => CAPTURE_SPEED * (round.active === "bigcup" || round.active === "magnet" ? HELPED_CAPTURE : 1);
|
||||
|
||||
// One physics step of `dtMs` (SUB_STEP_MS from tick()). Returns what happened,
|
||||
// as event names: "clock" (the shot clock started the meter), "dribble" (the
|
||||
// meter ran out), "wall", "bump", "tunnel", "powerup", "splash", "cup",
|
||||
// "ace", "stop", "pickup", "done", "hole".
|
||||
export function advance(round, dtMs) {
|
||||
const events = [];
|
||||
if (round.phase === "done") return events;
|
||||
round.clock += dtMs;
|
||||
if (round.phase === "card") {
|
||||
round.cardMs += dtMs;
|
||||
if (round.cardMs >= CARD_MS && nextHole(round)) events.push("hole");
|
||||
return events;
|
||||
}
|
||||
const hole = HOLES[round.hole];
|
||||
const ball = round.ball;
|
||||
const dt = dtMs / 1000;
|
||||
const ghost = round.active === "ghost";
|
||||
|
||||
sweepers(round, hole, events);
|
||||
if (!ball.moving) {
|
||||
if (round.phase === "aim") {
|
||||
round.restMs += dtMs;
|
||||
if (round.restMs >= SHOT_CLOCK_MS && startSwing(round)) events.push("clock");
|
||||
} else if (round.phase === "swing") {
|
||||
round.swingMs += dtMs;
|
||||
if (round.swingMs >= METER_TRIPS * METER_MS) {
|
||||
strike(round, round.swingAngle, DRIBBLE_POWER);
|
||||
events.push("dribble");
|
||||
return events;
|
||||
}
|
||||
}
|
||||
// A ball left on a slope rolls off it by itself.
|
||||
if (!onSlope(hole, ball.x, ball.y)) return events;
|
||||
ball.moving = true;
|
||||
round.phase = "rolling";
|
||||
}
|
||||
|
||||
for (const s of hole.slopes) {
|
||||
if (inPolygon(s.points, ball.x, ball.y)) {
|
||||
ball.vx += s.push.x * dt;
|
||||
ball.vy += s.push.y * dt;
|
||||
}
|
||||
}
|
||||
let speed = Math.hypot(ball.vx, ball.vy);
|
||||
const top = round.active === "cannon" ? CANNON_MAX : MAX_SPEED;
|
||||
if (speed > 0) {
|
||||
const slow = (FRICTION + DRAG * speed) * (!ghost && inSand(hole, ball.x, ball.y) ? SAND_FACTOR : 1) * dt;
|
||||
const next = Math.min(top, Math.max(0, speed - slow));
|
||||
ball.vx *= next / speed;
|
||||
ball.vy *= next / speed;
|
||||
speed = next;
|
||||
}
|
||||
if (round.active === "magnet") magnet(round, hole, dt);
|
||||
ball.x += ball.vx * dt;
|
||||
ball.y += ball.vy * dt;
|
||||
|
||||
for (const w of hole.walls) bounceOffSegment(ball, w, events, wallKeep(round));
|
||||
if (!ghost) for (const b of hole.bumpers) bounceOffRound(ball, b, events);
|
||||
sweepers(round, hole, events);
|
||||
speed = Math.hypot(ball.vx, ball.vy);
|
||||
if (speed > top) {
|
||||
ball.vx *= top / speed;
|
||||
ball.vy *= top / speed;
|
||||
speed = top;
|
||||
}
|
||||
tunnels(round, hole, events);
|
||||
powerups(round, hole, events);
|
||||
|
||||
round.trail.push({ x: ball.x, y: ball.y });
|
||||
if (round.trail.length > TRAIL) round.trail.shift();
|
||||
|
||||
if (dist(ball.x, ball.y, hole.cup.x, hole.cup.y) < cupReach(round) && speed < captureSpeed(round)) {
|
||||
events.push(round.putts === 1 ? "ace" : "cup");
|
||||
round.sunk = { x: ball.x, y: ball.y };
|
||||
ball.x = hole.cup.x;
|
||||
ball.y = hole.cup.y;
|
||||
finishHole(round, round.strokes, events);
|
||||
return events;
|
||||
}
|
||||
|
||||
const stopping = speed < STOP_SPEED && !onSlope(hole, ball.x, ball.y);
|
||||
// A ghost ball floats over water, but not once it runs out of puff there.
|
||||
if (inWater(hole, ball.x, ball.y) && (!ghost || stopping)) {
|
||||
events.push("splash");
|
||||
round.strokes += 1;
|
||||
ball.x = round.from.x;
|
||||
ball.y = round.from.y;
|
||||
ball.vx = 0;
|
||||
ball.vy = 0;
|
||||
ball.moving = false;
|
||||
atRest(round);
|
||||
round.active = null;
|
||||
round.tunnelLock = null;
|
||||
round.trail = [];
|
||||
pickUpAtCap(round, events);
|
||||
return events;
|
||||
}
|
||||
|
||||
if (stopping) {
|
||||
ball.vx = 0;
|
||||
ball.vy = 0;
|
||||
ball.moving = false;
|
||||
atRest(round);
|
||||
round.active = null;
|
||||
events.push("stop");
|
||||
pickUpAtCap(round, events);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
// Where a putt at `angle` and `power` would roll from the ball as it rests
|
||||
// now, as points along its path (null where a tunnel jumps it), for the
|
||||
// spyglass. Plays a copy of the round, so the round itself never changes.
|
||||
export function predictPath(round, angle, power) {
|
||||
const sim = structuredClone(round);
|
||||
// The spyglass itself goes into the putt and does nothing to the roll.
|
||||
if (sim.held === "spyglass") sim.held = null;
|
||||
if (!strike(sim, angle, power)) return [];
|
||||
const points = [{ x: sim.ball.x, y: sim.ball.y }];
|
||||
for (let t = 0, n = 0; t < PREDICT_MS && sim.phase === "rolling"; t += SUB_STEP_MS, n++) {
|
||||
const events = advance(sim, SUB_STEP_MS);
|
||||
if (events.includes("splash")) break;
|
||||
if (events.includes("tunnel")) points.push(null);
|
||||
if (n % 5 === 0 || sim.phase !== "rolling") points.push({ x: sim.ball.x, y: sim.ball.y });
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gags */
|
||||
|
||||
// The words that pop up on the board, picked by a count so the same round
|
||||
// always says the same things.
|
||||
const SPLASH_WORDS = Object.freeze({
|
||||
sea: ["SPLOOSH! Davy Jones says thanks", "Shark snack! Yum", "Man overboard!"],
|
||||
pool: ["Bloop!", "Glub glub glub", "Something down there liked that"],
|
||||
lava: ["SIZZLE! Extra crispy", "Toasty!", "Marshmallow, anyone?"],
|
||||
chasm: ["Aaaaaaaaa...", "Bye bye, ball!", "Still falling..."],
|
||||
});
|
||||
const BUMP_WORDS = Object.freeze({
|
||||
pirate: ["Bonk!", "Arr!", "Clunk!", "Yo ho!"],
|
||||
cave: ["Boing!", "Clang!", "Ping!", "Bwomp!"],
|
||||
});
|
||||
const TUNNEL_WORDS = ["Whoosh!", "Wheee!", "Where'd it go?!"];
|
||||
const MAX_WORDS = ["MAX POWER!", "CRUSHED IT!", "KA-BLAM!"];
|
||||
const SHANK_WORDS = ["Overswing! Shanked it", "Whoa, too hard!", "Wild swing!"];
|
||||
const DRIBBLE_WORDS = ["Too slow! Dribbled it", "Asleep at the tiller!", "Zzz... plop"];
|
||||
|
||||
const pick = (list, n) => list[n % list.length];
|
||||
|
||||
/* --------------------------------------------------------------- contract */
|
||||
|
||||
const TONE_FOR = Object.freeze({ wall: "wall", bump: "bump", cup: "cup", ace: "ace", tunnel: "tunnel", powerup: "power" });
|
||||
const SPLASH_TONE = Object.freeze({ sea: "splash", pool: "splash", lava: "sizzle", chasm: "fall" });
|
||||
|
||||
function create({ canvas, tone = () => {}, onScore = () => {} }) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
let colors = null;
|
||||
let round = newRound();
|
||||
let state = "ready";
|
||||
let scale = 1;
|
||||
let carry = 0;
|
||||
// How long each arrow has been held, in ms (0 is up), and whether the roll
|
||||
// is being fast-forwarded (the action key or the pointer held down).
|
||||
const held = { left: 0, right: 0 };
|
||||
let fast = false;
|
||||
// Words popped up on the board, and how many of each kind so far.
|
||||
let toasts = [];
|
||||
let said = 0;
|
||||
let lastBump = -Infinity;
|
||||
|
||||
// The ball is at rest on a hole and waiting for a putt.
|
||||
const aiming = () => state === "running" && round.phase === "aim";
|
||||
|
||||
const say = (text, x, y, big = false) => {
|
||||
toasts.push({ text, x, y, at: round.clock, big });
|
||||
said += 1;
|
||||
};
|
||||
|
||||
// A round on screen: running, or paused where it stood.
|
||||
const live = () => state === "running" || state === "paused";
|
||||
|
||||
// The aim in play, or null: { angle, needle, zone }, with the needle and
|
||||
// its zone only while the meter runs. Shown from the start of each hole, so
|
||||
// the first press is never blind.
|
||||
const currentAim = () => {
|
||||
if (!live()) return null;
|
||||
if (round.phase === "aim") return { angle: round.aimAngle, needle: null, zone: null };
|
||||
if (round.phase !== "swing") return null;
|
||||
const needle = meterAt(round.swingMs);
|
||||
return { angle: round.swingAngle, needle, zone: meterZone(needle) };
|
||||
};
|
||||
|
||||
// What the drawing needs of this moment, worked out here so golf-draw.js
|
||||
// decides nothing.
|
||||
const view = () => {
|
||||
const hole = HOLES[round.hole];
|
||||
const ball = round.ball;
|
||||
const aimView = currentAim();
|
||||
const card = round.phase === "card";
|
||||
// The ball waits for a putt: aimed, or the meter running.
|
||||
const waiting = round.phase === "aim" || round.phase === "swing";
|
||||
toasts = toasts.filter((t) => round.clock - t.at < TOAST_MS);
|
||||
// The spyglass follows the needle: the roll this press would make.
|
||||
const spyShot = aimView && aimView.needle !== null && round.held === "spyglass" ? swingShot(aimView.needle, aimView.angle, round.putts) : null;
|
||||
const spy = spyShot ? predictPath(round, spyShot.angle, spyShot.power) : null;
|
||||
return {
|
||||
course: { w: COURSE_W, h: COURSE_H },
|
||||
hole,
|
||||
holeNo: round.hole + 1,
|
||||
clock: round.clock,
|
||||
holeMs: round.clock - round.holeStart,
|
||||
spinners: hole.spinners.map((s) => ({ ...spinnerEnds(s, round.clock), x: s.x, y: s.y, look: s.look })),
|
||||
movers: hole.movers.map((m) => ({ ...moverAt(m, round.clock), look: m.look })),
|
||||
gates: hole.gates.map((g) => ({ ...g, shut: gateShut(g, round.clock), phase: gatePhase(g, round.clock) })),
|
||||
pads: hole.powerups.map((p, i) => ({ ...p, taken: round.taken.includes(i) })),
|
||||
ball,
|
||||
ballR: BALL_R,
|
||||
cupR: CUP_R,
|
||||
// The cup as this putt, or the one being aimed, will find it.
|
||||
cupDraw: round.active === "bigcup" || (round.held === "bigcup" && waiting) ? CUP_R * BIG_CUP : CUP_R,
|
||||
magnetR: round.active === "magnet" || (round.held === "magnet" && waiting) ? MAGNET_R : 0,
|
||||
tunnelR: TUNNEL_R,
|
||||
padR: POWERUP_R,
|
||||
trail: round.phase === "rolling" ? round.trail : [],
|
||||
aim: aimView,
|
||||
// The power meter while it runs: the needle, the top of the overswing,
|
||||
// where the MAX band starts, where the last swing stopped, and the
|
||||
// trips left before the ball dribbles.
|
||||
meter: aimView && aimView.needle !== null
|
||||
? { needle: aimView.needle, zone: aimView.zone, top: 1 + OVER_BAND, maxFrom: 1 - MAX_BAND, last: round.lastSwing, tripsLeft: METER_TRIPS - Math.floor(round.swingMs / METER_MS) }
|
||||
: null,
|
||||
// The shot clock's share left, 1 to 0, while the ball waits.
|
||||
shotClock: live() && round.phase === "aim" ? Math.max(0, 1 - round.restMs / SHOT_CLOCK_MS) : null,
|
||||
fast: fast && round.phase === "rolling" ? FAST_FORWARD : 0,
|
||||
spy,
|
||||
held: round.held ? { kind: round.held, ...POWERUPS[round.held] } : null,
|
||||
active: round.active,
|
||||
toasts: toasts.map((t) => ({ ...t, age: (round.clock - t.at) / TOAST_MS })),
|
||||
// A picked-up ball is simply gone; a sunk one shrinks into the cup.
|
||||
sinking: card ? (round.sunk ? Math.min(1, round.cardMs / 350) : 1) : null,
|
||||
phase: round.phase,
|
||||
cardMs: round.cardMs,
|
||||
card: HOLES.map((h, i) => ({ par: h.par, strokes: i < round.card.length ? round.card[i] : null })),
|
||||
frontNine: FRONT_NINE,
|
||||
// The card after the front nine heads into the caves.
|
||||
turn: card && round.hole === FRONT_NINE - 1,
|
||||
total: total(round),
|
||||
parTotal: parTotal(HOLES.length),
|
||||
toPar: toPar(round),
|
||||
strokes: round.strokes,
|
||||
pickedUp: card && !round.sunk,
|
||||
ace: card && round.sunk !== null && round.card.at(-1) === 1,
|
||||
state,
|
||||
colors,
|
||||
};
|
||||
};
|
||||
|
||||
const paint = () => {
|
||||
if (!ctx) return;
|
||||
colors ||= readColors(canvas);
|
||||
drawCourse(ctx, view());
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
colors = null;
|
||||
round = newRound();
|
||||
carry = 0;
|
||||
held.left = 0;
|
||||
held.right = 0;
|
||||
fast = false;
|
||||
toasts = [];
|
||||
said = 0;
|
||||
lastBump = -Infinity;
|
||||
state = "running";
|
||||
paint();
|
||||
};
|
||||
|
||||
const play = (events) => {
|
||||
const hole = HOLES[round.hole];
|
||||
const { x, y } = round.ball;
|
||||
for (const e of events) {
|
||||
if (e === "splash") {
|
||||
tone(SPLASH_TONE[hole.liquid] || "splash");
|
||||
say(`${pick(SPLASH_WORDS[hole.liquid] || SPLASH_WORDS.sea, said)} (+1)`, x, y);
|
||||
continue;
|
||||
}
|
||||
if (e === "clock") {
|
||||
tone("swing");
|
||||
say("Shot clock! Swing!", x, y - 14, true);
|
||||
}
|
||||
if (e === "dribble") {
|
||||
tone("shank");
|
||||
say(pick(DRIBBLE_WORDS, said), x, y - 12);
|
||||
}
|
||||
if (TONE_FOR[e]) tone(TONE_FOR[e]);
|
||||
if (e === "bump" && round.clock - lastBump > 450) {
|
||||
lastBump = round.clock;
|
||||
say(pick(BUMP_WORDS[hole.theme] || BUMP_WORDS.pirate, said), x, y - 8);
|
||||
}
|
||||
if (e === "tunnel") say(pick(TUNNEL_WORDS, said), x, y - 8);
|
||||
if (e === "powerup" && round.held) say(`${POWERUPS[round.held].name}!`, x, y - 10, true);
|
||||
// High, over the scorecard that is about to show.
|
||||
if (e === "ace") say(hole.theme === "cave" ? "HOLE IN ONE! The cave echoes: one... one... one..." : "SHIVER ME TIMBERS! HOLE IN ONE!", COURSE_W / 2, 54, true);
|
||||
}
|
||||
// A fast-forward ends with the roll.
|
||||
if (round.phase !== "rolling") fast = false;
|
||||
if (events.includes("done") && state === "running") {
|
||||
state = "over";
|
||||
onScore(total(round));
|
||||
}
|
||||
};
|
||||
|
||||
// The first press starts the meter, the second sets the power and putts.
|
||||
const swing = () => {
|
||||
if (round.phase === "aim") {
|
||||
if (!startSwing(round)) return false;
|
||||
tone("swing");
|
||||
paint();
|
||||
return true;
|
||||
}
|
||||
const shot = setPower(round);
|
||||
if (!shot) return false;
|
||||
const { x, y } = round.ball;
|
||||
tone(round.active === "cannon" ? "boom" : "putt", 0.4 + 0.6 * Math.min(1, shot.power));
|
||||
if (shot.zone === "max") {
|
||||
tone("max");
|
||||
say(pick(MAX_WORDS, said), x, y - 12, true);
|
||||
}
|
||||
if (shot.zone === "over") {
|
||||
tone("shank");
|
||||
say(pick(SHANK_WORDS, said), x, y - 12);
|
||||
}
|
||||
if (round.active && POWERUPS[round.active]) say(round.active === "doubloon" ? "Free putt!" : `${POWERUPS[round.active].name} away!`, x, y - (shot.zone === "normal" ? 12 : 26));
|
||||
paint();
|
||||
return true;
|
||||
};
|
||||
|
||||
const skipCard = () => {
|
||||
if (state !== "running" || round.phase !== "card") return false;
|
||||
nextHole(round);
|
||||
paint();
|
||||
return true;
|
||||
};
|
||||
|
||||
// Held arrows turn the aim, slowly at first and faster the longer they are
|
||||
// held.
|
||||
const turn = (ms) => {
|
||||
const dir = (held.right ? 1 : 0) - (held.left ? 1 : 0);
|
||||
const ramp = Math.min(1, Math.max(held.left, held.right) / TURN_RAMP_MS);
|
||||
if (held.left) held.left += ms;
|
||||
if (held.right) held.right += ms;
|
||||
if (!dir || round.phase !== "aim") return;
|
||||
round.aimAngle += dir * (TURN_SLOW + (TURN_FAST - TURN_SLOW) * ramp * ramp) * (ms / 1000);
|
||||
};
|
||||
|
||||
return {
|
||||
get score() {
|
||||
return total(round);
|
||||
},
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
// Not part of the contract: the round in play, so the unit suite can set
|
||||
// up a shot on any hole. The window never reads it.
|
||||
get round() {
|
||||
return round;
|
||||
},
|
||||
start,
|
||||
pause() {
|
||||
if (state !== "running") return;
|
||||
state = "paused";
|
||||
// Nothing held carries over a pause: its release may never arrive.
|
||||
held.left = 0;
|
||||
held.right = 0;
|
||||
fast = false;
|
||||
paint();
|
||||
},
|
||||
resume() {
|
||||
if (state === "paused") state = "running";
|
||||
},
|
||||
key(name) {
|
||||
if (name === "action") {
|
||||
if (state === "ready" || state === "over") start();
|
||||
else if (state === "paused") state = "running";
|
||||
else if (skipCard()) return true;
|
||||
else if (round.phase === "rolling") fast = true;
|
||||
else swing();
|
||||
return true;
|
||||
}
|
||||
if (name !== "left" && name !== "right") return false;
|
||||
if (!aiming()) return false;
|
||||
// A press nudges at once; the window's key repeats change nothing, as
|
||||
// the hold already turns the aim each tick.
|
||||
if (!held[name]) {
|
||||
held[name] = 1;
|
||||
round.aimAngle += (name === "left" ? -1 : 1) * AIM_NUDGE;
|
||||
paint();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
release(name) {
|
||||
if (name === "action") fast = false;
|
||||
else if (name === "left" || name === "right") held[name] = 0;
|
||||
else return false;
|
||||
return true;
|
||||
},
|
||||
pointer(type, x, y) {
|
||||
const cx = x / scale;
|
||||
const cy = y / scale;
|
||||
// The aim points from the ball at the pointer, wherever it is.
|
||||
const aimAt = () => {
|
||||
const { ball } = round;
|
||||
if (!aiming() || Math.hypot(cx - ball.x, cy - ball.y) < 1) return false;
|
||||
round.aimAngle = Math.atan2(cy - ball.y, cx - ball.x);
|
||||
return true;
|
||||
};
|
||||
if (type === "up" || type === "cancel") {
|
||||
fast = false;
|
||||
return true;
|
||||
}
|
||||
if (type === "move") {
|
||||
if (!aimAt()) return false;
|
||||
paint();
|
||||
return true;
|
||||
}
|
||||
if (type !== "down") return false;
|
||||
if (state === "ready" || state === "over") {
|
||||
start();
|
||||
return true;
|
||||
}
|
||||
if (state !== "running") return false;
|
||||
if (skipCard()) return true;
|
||||
if (round.phase === "rolling") {
|
||||
fast = true;
|
||||
return true;
|
||||
}
|
||||
aimAt();
|
||||
return swing();
|
||||
},
|
||||
tick(ms) {
|
||||
if (state !== "running") return;
|
||||
const step = Math.min(Math.max(0, ms), MAX_TICK_MS);
|
||||
turn(step);
|
||||
carry += step * (fast && round.phase === "rolling" ? FAST_FORWARD : 1);
|
||||
while (carry >= SUB_STEP_MS && state === "running") {
|
||||
carry -= SUB_STEP_MS;
|
||||
play(advance(round, SUB_STEP_MS));
|
||||
}
|
||||
paint();
|
||||
},
|
||||
resize(w, h) {
|
||||
if (!(w >= MIN_W && h >= MIN_H)) return false;
|
||||
scale = Math.min(w / COURSE_W, h / COURSE_H);
|
||||
colors = null;
|
||||
const ratio = (typeof devicePixelRatio === "number" && devicePixelRatio > 0) ? devicePixelRatio : 1;
|
||||
const cssW = COURSE_W * scale;
|
||||
const cssH = COURSE_H * scale;
|
||||
canvas.width = Math.round(cssW * ratio);
|
||||
canvas.height = Math.round(cssH * ratio);
|
||||
if (canvas.style) {
|
||||
canvas.style.width = `${cssW}px`;
|
||||
canvas.style.height = `${cssH}px`;
|
||||
}
|
||||
// Everything is drawn in course units.
|
||||
if (ctx && typeof ctx.setTransform === "function") ctx.setTransform(ratio * scale, 0, 0, ratio * scale, 0, 0);
|
||||
paint();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default Object.freeze({ id: "golf", title: "Mini golf", lowerIsBetter: true, create });
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,7 +22,7 @@ import {
|
||||
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
|
||||
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
|
||||
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
|
||||
wireHelp, wireLooks, wireNotepad, wireWorkspace,
|
||||
wireActivities, wireHelp, wireLooks, wireNotepad, wireWorkspace,
|
||||
} from "./screens/core.js";
|
||||
import { sound } from "./sound.js";
|
||||
|
||||
@@ -50,6 +50,7 @@ wireCleanup();
|
||||
wireDocs();
|
||||
wireAsk();
|
||||
wireNotepad();
|
||||
wireActivities();
|
||||
wireChrome();
|
||||
startClock();
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("git", "The git board", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("activities", "Activities", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("prefs", "Keyboard and preferences", false),
|
||||
tab("privacy", "Privacy and where things are saved", false),
|
||||
|
||||
@@ -9,6 +9,7 @@ import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
|
||||
import { bootData, hooks } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
import { tellApp } from "./app-bridge.js";
|
||||
import { ACTIVITIES, bestKey, memoKey } from "./activities.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -30,6 +31,13 @@ export const DEFAULT_LOOKS = {
|
||||
...soundPrefs(null),
|
||||
width: DEFAULT_CARD_WIDTH,
|
||||
hideUnavailable: true,
|
||||
// Activities: the top bar's die, the game last picked, and one best score
|
||||
// per listed game (activityBestSnake), each a flat key for cleanLooks().
|
||||
hideActivities: false,
|
||||
lastActivity: "",
|
||||
...Object.fromEntries(ACTIVITIES.map((a) => [bestKey(a.id), 0])),
|
||||
// And one memo per game (activityMemoSnake): Snake's surprises found.
|
||||
...Object.fromEntries(ACTIVITIES.map((a) => [memoKey(a.id), 0])),
|
||||
};
|
||||
|
||||
export let looks = { ...DEFAULT_LOOKS };
|
||||
@@ -46,6 +54,16 @@ export function adoptLooks(saved) {
|
||||
Object.assign(looks, soundPrefs(looks));
|
||||
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
|
||||
looks.width = cardWidth(looks.width);
|
||||
if (typeof looks.hideActivities !== "boolean") looks.hideActivities = DEFAULT_LOOKS.hideActivities;
|
||||
if (typeof looks.lastActivity !== "string") looks.lastActivity = DEFAULT_LOOKS.lastActivity;
|
||||
// A best score is a whole number of points, never below none.
|
||||
for (const a of ACTIVITIES) {
|
||||
const key = bestKey(a.id);
|
||||
const n = Number(looks[key]);
|
||||
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||
const memo = Number(looks[memoKey(a.id)]);
|
||||
looks[memoKey(a.id)] = Number.isFinite(memo) && memo > 0 ? Math.floor(memo) : 0;
|
||||
}
|
||||
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
|
||||
else delete looks.role;
|
||||
}
|
||||
@@ -212,10 +230,17 @@ export function renderSwatches() {
|
||||
box.disabled = !looks.sound;
|
||||
}
|
||||
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
|
||||
$("looks-activities").checked = !looks.hideActivities;
|
||||
}
|
||||
|
||||
// "Back to default": every look returns to its default, but the role is
|
||||
// marked as asked and the welcome stays seen.
|
||||
// marked as asked, the welcome stays seen, and the Activities' best scores
|
||||
// and last pick stay (only Reset best scores clears those).
|
||||
export function resetLooks() {
|
||||
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
|
||||
const kept = { lastActivity: looks.lastActivity };
|
||||
for (const a of ACTIVITIES) {
|
||||
kept[bestKey(a.id)] = looks[bestKey(a.id)];
|
||||
kept[memoKey(a.id)] = looks[memoKey(a.id)];
|
||||
}
|
||||
looks = { ...DEFAULT_LOOKS, ...kept, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
// Plan2Code Web Console - Activities: the top bar's die, its dialog, the frame timer, the keys and every pause rule.
|
||||
//
|
||||
// Small games for a long wait. The list of games is activities.js; each game
|
||||
// is its own module under activities/, loaded with import() the first time it
|
||||
// is opened, and answers the calls the list's header names. This file owns
|
||||
// everything around a game: the dialog, the one frame timer, the keys and the
|
||||
// pauses. A game never runs a timer of its own, so a paused game cannot move:
|
||||
// pausing is this file not ticking plus the game's own paused state. Nothing
|
||||
// here talks to the agent or the session; it only reads whose turn it is, so
|
||||
// a question, a sign-off or a finish always pauses play and says so.
|
||||
|
||||
import { page, redraw } from "../state.js";
|
||||
import { finish, myTurn } from "../selectors.js";
|
||||
import { looks, saveLooks } from "../looks.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { ACTIVITIES, bestKey, memoKey } from "../activities.js";
|
||||
import { tone, unlockTones } from "../tones.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const NOT_LOADED = "This activity could not be loaded. Close and open Activities to try again.";
|
||||
const NEED_KEYBOARD = "Activities need a keyboard.";
|
||||
const TOO_SMALL = "Make the window bigger to play.";
|
||||
const TURN_BANNER = "Plan2Code needs you: a question is waiting.";
|
||||
const FINISH_BANNER = "Plan2Code is finished.";
|
||||
const RESET_LABEL = "Reset best scores";
|
||||
const RESET_CONFIRM = "Reset? Click again";
|
||||
|
||||
// How long Reset waits for its second click before going back to its label.
|
||||
const RESET_CONFIRM_MS = 4000;
|
||||
|
||||
// A frame that arrives after a long gap (a slow machine, a debugger) is
|
||||
// counted as this much at most, so the snake never jumps several cells at once.
|
||||
const MAX_FRAME_MS = 250;
|
||||
|
||||
// Every start and every play-on counts down 3, 2, 1 before the game moves,
|
||||
// so a round never begins or picks up before the person is ready. The game
|
||||
// is already running while the count shows; this file just does not tick it.
|
||||
const COUNT_FROM = 3;
|
||||
|
||||
// The game keys: arrows and W/A/S/D steer, space is the game's action.
|
||||
const KEYS = Object.freeze({
|
||||
ArrowUp: "up",
|
||||
ArrowDown: "down",
|
||||
ArrowLeft: "left",
|
||||
ArrowRight: "right",
|
||||
w: "up",
|
||||
s: "down",
|
||||
a: "left",
|
||||
d: "right",
|
||||
" ": "action",
|
||||
});
|
||||
|
||||
// The list the window shows, and where frames come from. Both are swapped
|
||||
// only by the page tests (setActivityList, setTickSource).
|
||||
let list = ACTIVITIES;
|
||||
let tickSource = (fn) => requestAnimationFrame(fn);
|
||||
// How long each number of the countdown shows, in ms. Swapped only by the
|
||||
// page tests (setCountdownMs); 0 skips the countdown.
|
||||
let countStepMs = 700;
|
||||
|
||||
// One game object per listed game for the page's life, so a closed and
|
||||
// reopened window, or a skill change on the same page, resumes the same round.
|
||||
const games = new Map();
|
||||
// A load in flight per game id, so two quick opens share one import().
|
||||
const loading = new Map();
|
||||
let currentId = null;
|
||||
// The games that keep their lowest round as the best (their export says
|
||||
// lowerIsBetter), not their highest.
|
||||
const lowerIsBetter = new Set();
|
||||
|
||||
// The frame timer. `gen` counts starts and stops, so a frame asked for before
|
||||
// a stop does nothing when it arrives, whatever the tick source is.
|
||||
let gen = 0;
|
||||
let looping = false;
|
||||
let lastFrame = null;
|
||||
// The ms left of the countdown while one is showing, else 0. Game keys,
|
||||
// clicks and presses on the board wait for it; P and Esc still pause.
|
||||
let counting = 0;
|
||||
|
||||
// What renderActivities saw last time: the ids that were the person's to
|
||||
// answer, and whether a finish was up. Null until the first render.
|
||||
let seenTurn = null;
|
||||
let seenFinish = false;
|
||||
|
||||
// Set when the person plays on after a turn or finish pause: the banner stays
|
||||
// down until the next new question or finish.
|
||||
let bannerDismissed = false;
|
||||
|
||||
// Reset's confirm: the timer that puts its label back, while one is waiting.
|
||||
let resetTimer = null;
|
||||
|
||||
// Go to it closes the window onto a question, so the close must not hand
|
||||
// focus back to the die.
|
||||
let goingTo = false;
|
||||
|
||||
export function setTickSource(fn) {
|
||||
tickSource = fn;
|
||||
}
|
||||
|
||||
export function setCountdownMs(ms) {
|
||||
countStepMs = ms;
|
||||
}
|
||||
|
||||
export function setActivityList(next) {
|
||||
list = next;
|
||||
if (!list.some((e) => e.id === currentId)) currentId = null;
|
||||
}
|
||||
|
||||
const game = () => (currentId ? games.get(currentId) || null : null);
|
||||
|
||||
/* ----------------------------------------------------------- the notes */
|
||||
|
||||
function showNote(text) {
|
||||
const note = $("activities-note");
|
||||
note.textContent = text;
|
||||
note.hidden = !text;
|
||||
}
|
||||
|
||||
const hasKeyboard = () => typeof matchMedia !== "function" || matchMedia("(any-pointer: fine)").matches;
|
||||
|
||||
/* ------------------------------------------------------------ drawing */
|
||||
|
||||
const best = (id) => looks[bestKey(id)] || 0;
|
||||
|
||||
// The header's " · Snake best: 12" for the game on screen, or "no best yet"
|
||||
// before its first full round.
|
||||
function paintTitle() {
|
||||
const entry = list.find((e) => e.id === currentId);
|
||||
const n = entry ? best(entry.id) : 0;
|
||||
const text = entry ? (n ? ` · ${entry.title} best: ${n}` : ` · ${entry.title}: no best yet`) : "";
|
||||
const span = $("activities-title-best");
|
||||
if (span.textContent !== text) span.textContent = text;
|
||||
}
|
||||
|
||||
// The round on screen, for the best-score effects: which game, the state it
|
||||
// was last painted in, whether this round has passed the best (the sparks
|
||||
// fire once a round), and whether its end set a new best.
|
||||
const watched = { g: null, state: null, passed: false, record: false };
|
||||
|
||||
// A new round has begun when the game on screen changed, or went back to
|
||||
// running from anything but a pause.
|
||||
function watchRound(g) {
|
||||
if (g !== watched.g || (g && g.state === "running" && watched.state !== "running" && watched.state !== "paused")) {
|
||||
watched.passed = false;
|
||||
watched.record = false;
|
||||
}
|
||||
watched.g = g;
|
||||
watched.state = g ? g.state : null;
|
||||
}
|
||||
|
||||
const SPARK_COLORS = Object.freeze(["#ff4fa3", "#f5b301", "#1fb6d9", "#57b54a", "#a466ff", "#ff8a1f"]);
|
||||
const SPARKS = 22;
|
||||
const SPARK_MS = 1100;
|
||||
|
||||
const calm = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
// A fan of colored sparks up out of the score line's chips. They live on the
|
||||
// dialog, not the line, since the line is rebuilt at every new score. Nothing
|
||||
// under reduced motion; the colors alone mark the record there.
|
||||
function sparks(line) {
|
||||
const dialog = $("activities-modal");
|
||||
if (!line || !dialog || calm()) return;
|
||||
const chips = line.firstElementChild;
|
||||
const x = line.offsetLeft + (chips ? chips.offsetLeft + chips.offsetWidth / 2 : 40);
|
||||
const y = line.offsetTop + line.offsetHeight / 2;
|
||||
for (let i = 0; i < SPARKS; i++) {
|
||||
const a = Math.PI + (Math.PI * i) / (SPARKS - 1) + (Math.random() - 0.5) * 0.3;
|
||||
const d = 50 + Math.random() * 70;
|
||||
const s = el("span", "activities-spark");
|
||||
s.setAttribute("aria-hidden", "true");
|
||||
s.style.left = `${Math.round(x)}px`;
|
||||
s.style.top = `${Math.round(y)}px`;
|
||||
s.style.setProperty("--dx", `${Math.round(Math.cos(a) * d)}px`);
|
||||
s.style.setProperty("--dy", `${Math.round(Math.sin(a) * d)}px`);
|
||||
s.style.setProperty("--spin", `${Math.round((Math.random() - 0.5) * 720)}deg`);
|
||||
s.style.setProperty("--c", SPARK_COLORS[i % SPARK_COLORS.length]);
|
||||
dialog.append(s);
|
||||
setTimeout(() => s.remove(), SPARK_MS);
|
||||
}
|
||||
}
|
||||
|
||||
// Plays the burst again from its start, even mid-burst.
|
||||
function replay(node, cls) {
|
||||
node.classList.remove(cls);
|
||||
void node.offsetWidth;
|
||||
node.classList.add(cls);
|
||||
}
|
||||
|
||||
// The line under the board, once a round has started: a score chip, a meter
|
||||
// filling toward the best (for a game where the highest wins and a best is
|
||||
// saved), then a best chip. Reaching the best lights it; passing it turns the
|
||||
// line into a rainbow and fires the sparks, once a round. The chips are only
|
||||
// styling: the line still reads "Score: 3 · Best: 9". Set only when it
|
||||
// changes, since every frame asks. A lowest-wins game with no best yet says
|
||||
// so: "Best: 0" would read as a perfect round.
|
||||
function paintScore() {
|
||||
const g = game();
|
||||
watchRound(g);
|
||||
const line = $("activities-score");
|
||||
const running = Boolean(g && g.state !== "ready");
|
||||
const n = currentId ? best(currentId) : 0;
|
||||
const lower = lowerIsBetter.has(currentId);
|
||||
const score = running ? g.score : 0;
|
||||
// A lowest-wins game only knows it beat its best when the round ends.
|
||||
const chase = running && !lower && n > 0;
|
||||
const mood = !running ? "" : chase && score > n ? "passed" : chase && score === n ? "tied" : watched.record ? "passed" : "";
|
||||
const key = running ? `${score}|${n}|${lower}|${mood}` : "";
|
||||
if (line.dataset.key === key) return;
|
||||
line.dataset.key = key;
|
||||
line.classList.toggle("tied", mood === "tied");
|
||||
line.classList.toggle("passed", mood === "passed");
|
||||
if (!running) return line.replaceChildren();
|
||||
const chip = (cls, name, value) => {
|
||||
const c = el("span", `activities-chip ${cls}`, `${name}: `);
|
||||
c.append(el("b", null, value));
|
||||
return c;
|
||||
};
|
||||
const parts = [chip("score", "Score", String(score))];
|
||||
if (chase) {
|
||||
const meter = el("span", "activities-meter");
|
||||
meter.setAttribute("aria-hidden", "true");
|
||||
meter.style.setProperty("--fill", String(Math.min(1, score / n)));
|
||||
parts.push(meter);
|
||||
}
|
||||
parts.push(el("span", "activities-sep", " · "), chip("best", "Best", !n && lower ? "none yet" : String(n)));
|
||||
line.replaceChildren(...parts);
|
||||
if (mood === "passed" && !watched.passed) {
|
||||
watched.passed = true;
|
||||
replay(line, "burst");
|
||||
sparks(line);
|
||||
}
|
||||
}
|
||||
|
||||
function paintOverlay() {
|
||||
const g = game();
|
||||
const overlay = $("activities-overlay");
|
||||
// A game played by pointer also starts and plays on with a click.
|
||||
const click = g && typeof g.pointer === "function";
|
||||
let text = "";
|
||||
if (g && g.state === "running" && counting > 0) text = String(Math.ceil(counting / countStepMs));
|
||||
else if (g && g.state === "ready") text = click ? "Press space or click to start" : "Press space to start";
|
||||
else if (g && g.state === "paused") text = click ? "Paused. Press space, P or click to play" : "Paused. Press space or P to play";
|
||||
else if (g && g.state === "over") text = `Score: ${g.score}\nBest: ${best(currentId)}\n${click ? "Press space or click to play again" : "Press space to play again"}`;
|
||||
if (overlay.textContent !== text) overlay.textContent = text;
|
||||
overlay.classList.toggle("count", g !== null && g.state === "running" && counting > 0);
|
||||
paintScore();
|
||||
// Read after paintScore, which forgets the last round's record once a new one starts.
|
||||
overlay.classList.toggle("record", Boolean(g && g.state === "over" && watched.record));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ best scores */
|
||||
|
||||
// Called only when a round ends, so a half-played round is never saved. A
|
||||
// save that does not land stays in the page and its local copy, and the next
|
||||
// save carries it (looks.js sends every key it has not heard back about).
|
||||
// A best of 0 means none yet, so a lowerIsBetter game's first round always
|
||||
// counts.
|
||||
// A round that beats a best already saved is a record: the end screen says so
|
||||
// and, for a lowest-wins game (which could not tell mid-round), the sparks fire
|
||||
// now. A first best is only a best.
|
||||
function recordScore(id, score) {
|
||||
const was = best(id);
|
||||
if (!(lowerIsBetter.has(id) ? !was || score < was : score > was)) return;
|
||||
looks[bestKey(id)] = score;
|
||||
saveLooks();
|
||||
paintTitle();
|
||||
if (!was || id !== currentId) return;
|
||||
watched.record = true;
|
||||
if (lowerIsBetter.has(id)) {
|
||||
tone("best");
|
||||
watched.passed = true;
|
||||
replay($("activities-score"), "burst");
|
||||
sparks($("activities-score"));
|
||||
}
|
||||
}
|
||||
|
||||
function disarmReset() {
|
||||
clearTimeout(resetTimer);
|
||||
resetTimer = null;
|
||||
$("activities-reset").textContent = RESET_LABEL;
|
||||
}
|
||||
|
||||
// The first click asks, inside the window; a second within a few seconds
|
||||
// writes 0 to every listed game's best (the server refuses null).
|
||||
function resetBest() {
|
||||
if (!resetTimer) {
|
||||
$("activities-reset").textContent = RESET_CONFIRM;
|
||||
resetTimer = setTimeout(disarmReset, RESET_CONFIRM_MS);
|
||||
return;
|
||||
}
|
||||
disarmReset();
|
||||
for (const entry of list) looks[bestKey(entry.id)] = 0;
|
||||
saveLooks();
|
||||
paintOverlay();
|
||||
paintTitle();
|
||||
}
|
||||
|
||||
// Sizes the game to the board. A board too small to play, or a page with no
|
||||
// keyboard, shows its note in place of the board. A game that no longer fits
|
||||
// stops moving, since nobody can see it.
|
||||
function layout() {
|
||||
const board = $("activities-board");
|
||||
const g = game();
|
||||
if (!hasKeyboard()) {
|
||||
board.hidden = true;
|
||||
return showNote(NEED_KEYBOARD);
|
||||
}
|
||||
if (!g) return;
|
||||
board.hidden = false;
|
||||
if (g.resize(board.clientWidth, board.clientHeight) === false) {
|
||||
board.hidden = true;
|
||||
pauseAll("hidden");
|
||||
return showNote(TOO_SMALL);
|
||||
}
|
||||
showNote("");
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- frame timer */
|
||||
|
||||
function stopLoop() {
|
||||
gen++;
|
||||
looping = false;
|
||||
counting = 0;
|
||||
}
|
||||
|
||||
// Runs only while the dialog is open and the game is running, and stops
|
||||
// itself the moment either is no longer true.
|
||||
function startLoop() {
|
||||
const g = game();
|
||||
if (looping || !g || g.state !== "running" || !$("activities-modal").open) return;
|
||||
looping = true;
|
||||
lastFrame = null;
|
||||
counting = COUNT_FROM * countStepMs;
|
||||
if (counting > 0) tone("count");
|
||||
paintOverlay();
|
||||
const mine = ++gen;
|
||||
const frame = (now) => {
|
||||
if (mine !== gen) return;
|
||||
const t = typeof now === "number" ? now : performance.now();
|
||||
if (!$("activities-modal").open || g !== game() || g.state !== "running") {
|
||||
looping = false;
|
||||
counting = 0;
|
||||
return paintOverlay();
|
||||
}
|
||||
// The countdown's time is never handed to the game: its first tick comes
|
||||
// a frame after the count ends.
|
||||
if (counting > 0) {
|
||||
const shown = Math.ceil(counting / countStepMs);
|
||||
if (lastFrame !== null) counting -= Math.min(Math.max(0, t - lastFrame), MAX_FRAME_MS);
|
||||
lastFrame = t;
|
||||
if (counting <= 0) {
|
||||
counting = 0;
|
||||
tone("go");
|
||||
} else if (Math.ceil(counting / countStepMs) !== shown) tone("count");
|
||||
paintOverlay();
|
||||
return tickSource(frame);
|
||||
}
|
||||
if (lastFrame !== null) g.tick(Math.min(Math.max(0, t - lastFrame), MAX_FRAME_MS));
|
||||
lastFrame = t;
|
||||
paintScore();
|
||||
if (g.state !== "running") {
|
||||
looping = false;
|
||||
return paintOverlay();
|
||||
}
|
||||
tickSource(frame);
|
||||
};
|
||||
tickSource(frame);
|
||||
}
|
||||
|
||||
// After anything the person does: the timer follows the game's state.
|
||||
function follow() {
|
||||
const g = game();
|
||||
if (g && g.state === "running") startLoop();
|
||||
else stopLoop();
|
||||
paintOverlay();
|
||||
}
|
||||
|
||||
// Runs what the person did to the game; when it took a paused game back to
|
||||
// running, the banner goes away until the next new question or finish.
|
||||
function play(g, act) {
|
||||
const was = g.state;
|
||||
act();
|
||||
if (was === "paused" && g.state === "running") dismissBanner();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- pauses */
|
||||
|
||||
// Every pause goes through here: "turn", "finish", "hidden", "blur" and
|
||||
// "closed". None of them ever resumes or starts a round; only the person
|
||||
// does: space, P or any other game key, a click on the overlay, or for a
|
||||
// game that takes the pointer, a press on the board. A pause also drops a
|
||||
// drag in progress.
|
||||
function pauseAll(reason) {
|
||||
const g = game();
|
||||
if (g && g.state === "running") g.pause();
|
||||
dragging = false;
|
||||
if (g && typeof g.pointer === "function") g.pointer("cancel", 0, 0);
|
||||
stopLoop();
|
||||
paintOverlay();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ loading */
|
||||
|
||||
async function loadGame(entry) {
|
||||
if (games.has(entry.id)) return games.get(entry.id);
|
||||
if (!loading.has(entry.id)) {
|
||||
const made = (async () => {
|
||||
const def = entry.game || (await import(entry.module)).default;
|
||||
if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
|
||||
else lowerIsBetter.delete(entry.id);
|
||||
const onScore = (score) => {
|
||||
recordScore(entry.id, score);
|
||||
paintOverlay();
|
||||
};
|
||||
// The game's memo is saved like a best score: privately, in looks.json.
|
||||
const memo = {
|
||||
get: () => looks[memoKey(entry.id)] || 0,
|
||||
set: (n) => {
|
||||
if (looks[memoKey(entry.id)] === n) return;
|
||||
looks[memoKey(entry.id)] = n;
|
||||
saveLooks();
|
||||
},
|
||||
};
|
||||
const g = def.create({ canvas: $("activities-canvas"), tone, onScore, best: () => best(entry.id), memo });
|
||||
games.set(entry.id, g);
|
||||
return g;
|
||||
})();
|
||||
// A failed load is forgotten, so the next open tries again.
|
||||
loading.set(entry.id, made);
|
||||
made.finally(() => loading.delete(entry.id)).catch(() => {});
|
||||
}
|
||||
return loading.get(entry.id);
|
||||
}
|
||||
|
||||
// Makes `id` the game on screen: the one before it is paused, then the new
|
||||
// one is loaded, sized and drawn.
|
||||
async function showGame(id) {
|
||||
const entry = list.find((e) => e.id === id);
|
||||
if (!entry) return;
|
||||
if (currentId && currentId !== id) pauseAll("closed");
|
||||
currentId = id;
|
||||
drawPicker();
|
||||
paintTitle();
|
||||
try {
|
||||
await loadGame(entry);
|
||||
} catch {
|
||||
if (currentId !== id) return;
|
||||
$("activities-board").hidden = true;
|
||||
return showNote(NOT_LOADED);
|
||||
}
|
||||
if (currentId !== id) return;
|
||||
layout();
|
||||
paintOverlay();
|
||||
// Keys go to the game next, not to the picker button just pressed.
|
||||
if (!$("activities-board").hidden) $("activities-board").focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- picker */
|
||||
|
||||
// Shown only once two or more games are listed; with one, the window opens
|
||||
// straight into it.
|
||||
function drawPicker() {
|
||||
const picker = $("activities-picker");
|
||||
if (list.length < 2) {
|
||||
picker.hidden = true;
|
||||
picker.replaceChildren();
|
||||
return;
|
||||
}
|
||||
picker.hidden = false;
|
||||
picker.replaceChildren(
|
||||
...list.map((entry) => {
|
||||
const b = el("button", "btn small ghost", entry.title);
|
||||
b.type = "button";
|
||||
b.dataset.activity = entry.id;
|
||||
b.setAttribute("aria-pressed", String(entry.id === currentId));
|
||||
b.addEventListener("click", () => pick(entry.id));
|
||||
return b;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function pick(id) {
|
||||
if (looks.lastActivity !== id) {
|
||||
looks.lastActivity = id;
|
||||
saveLooks();
|
||||
}
|
||||
showGame(id);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ opening */
|
||||
|
||||
function startingId() {
|
||||
if (currentId && list.some((e) => e.id === currentId)) return currentId;
|
||||
if (list.length > 1 && list.some((e) => e.id === looks.lastActivity)) return looks.lastActivity;
|
||||
return list.length ? list[0].id : null;
|
||||
}
|
||||
|
||||
export async function openActivities() {
|
||||
unlockTones();
|
||||
const dlg = $("activities-modal");
|
||||
showNote("");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
renderBanner();
|
||||
paintTitle();
|
||||
$("activities-board").focus({ preventScroll: true });
|
||||
const id = startingId();
|
||||
if (id) await showGame(id);
|
||||
}
|
||||
|
||||
function closeActivities() {
|
||||
pauseAll("closed");
|
||||
const dlg = $("activities-modal");
|
||||
if (dlg.open) dlg.close();
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- keys */
|
||||
|
||||
function onKey(e) {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
|
||||
const onButton = document.activeElement instanceof HTMLButtonElement && e.currentTarget.contains(document.activeElement);
|
||||
// A window button keeps its own space and Enter.
|
||||
if (onButton && (key === " " || key === "Enter")) return;
|
||||
if (key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return closeActivities();
|
||||
}
|
||||
const g = game();
|
||||
const hidden = $("activities-board").hidden;
|
||||
if (key === "p") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// A held P would flicker between the two; and a board nobody can see
|
||||
// never plays.
|
||||
if (e.repeat) return;
|
||||
if (g && g.state === "running") pauseAll("key");
|
||||
else if (g && g.state === "paused" && !hidden) play(g, () => g.resume());
|
||||
return follow();
|
||||
}
|
||||
if (!Object.hasOwn(KEYS, key)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// A held space would restart a round the moment the last one ends; arrows
|
||||
// may repeat.
|
||||
if (e.repeat && KEYS[key] === "action") return;
|
||||
if (!g || hidden || counting > 0) return follow();
|
||||
if (g.state !== "paused") g.key(KEYS[key]);
|
||||
// Any game key plays on from a pause, a held one excepted. A direction is
|
||||
// passed on too, so one press resumes and steers; space only resumes, so it
|
||||
// never also starts a new round.
|
||||
else if (!e.repeat)
|
||||
play(g, () => {
|
||||
g.resume();
|
||||
if (KEYS[key] !== "action") g.key(KEYS[key]);
|
||||
});
|
||||
follow();
|
||||
}
|
||||
|
||||
// For a game with release(): a game key let go, so a game can act on a key
|
||||
// held down (Mini golf's fast-forward and its turning aim). Always passed on,
|
||||
// paused or not, so nothing is left held; a game's pause() drops whatever it
|
||||
// holds anyway, since a release can be lost to a blur.
|
||||
function onKeyUp(e) {
|
||||
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
|
||||
if (!Object.hasOwn(KEYS, key)) return;
|
||||
const g = game();
|
||||
if (g && typeof g.release === "function") g.release(KEYS[key]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ pointer */
|
||||
|
||||
const POINTER = Object.freeze({ pointerdown: "down", pointermove: "move", pointerup: "up", pointercancel: "cancel" });
|
||||
|
||||
// True from a down passed on to the game until its up, cancel or a pause, so
|
||||
// the release of a press that only played on, or of a drag a pause dropped,
|
||||
// never reaches the game.
|
||||
let dragging = false;
|
||||
|
||||
// For a game with pointer(): positions in CSS pixels from the canvas's
|
||||
// top-left. A press on a paused board plays on and starts nothing else; on a
|
||||
// ready or finished game it is passed on, so the game can start a round.
|
||||
function onPointer(e) {
|
||||
const g = game();
|
||||
if (!g || typeof g.pointer !== "function" || $("activities-board").hidden) return;
|
||||
const canvas = $("activities-canvas");
|
||||
const type = POINTER[e.type];
|
||||
// The countdown holds the board still: a press waits for it, and only the
|
||||
// release of a press made before it gets through.
|
||||
if (counting > 0 && type !== "up" && type !== "cancel") {
|
||||
if (type === "down") e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (type === "down") {
|
||||
if (e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
$("activities-board").focus({ preventScroll: true });
|
||||
if (g.state === "paused") {
|
||||
play(g, () => g.resume());
|
||||
return follow();
|
||||
}
|
||||
// A drag that leaves the canvas still ends here with an up.
|
||||
try {
|
||||
canvas.setPointerCapture(e.pointerId);
|
||||
} catch {}
|
||||
dragging = true;
|
||||
} else if (type === "up" || type === "cancel") {
|
||||
if (!dragging) return;
|
||||
dragging = false;
|
||||
}
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const used = g.pointer(type, e.clientX - r.left, e.clientY - r.top);
|
||||
if (type !== "move" || used) follow();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- whose turn */
|
||||
|
||||
// The banner takes height from the board, so the game is laid out again
|
||||
// whenever it comes or goes; otherwise the board would clip the canvas.
|
||||
function renderBanner() {
|
||||
const banner = $("activities-banner");
|
||||
const text = bannerDismissed ? "" : myTurn().length ? TURN_BANNER : finish() ? FINISH_BANNER : "";
|
||||
$("activities-banner-text").textContent = text;
|
||||
if (banner.hidden === !text) return;
|
||||
banner.hidden = !text;
|
||||
if ($("activities-modal").open) layout();
|
||||
}
|
||||
|
||||
// From the render pass: a question that was not the person's a render ago,
|
||||
// or a finish that was not up, pauses play. A stopped session or a dropped
|
||||
// connection is not a reason; only the person's turn is.
|
||||
export function renderActivities() {
|
||||
// The gear's Show Activities switch: off hides the die everywhere, and
|
||||
// closes a window left open, paused.
|
||||
$("btn-activities").hidden = looks.hideActivities;
|
||||
if (looks.hideActivities && $("activities-modal").open) closeActivities();
|
||||
const turn = new Set(myTurn().map((i) => i.id));
|
||||
const done = Boolean(finish());
|
||||
if (seenTurn) {
|
||||
if ([...turn].some((id) => !seenTurn.has(id))) {
|
||||
bannerDismissed = false;
|
||||
pauseAll("turn");
|
||||
}
|
||||
if (done && !seenFinish) {
|
||||
bannerDismissed = false;
|
||||
pauseAll("finish");
|
||||
}
|
||||
}
|
||||
seenTurn = turn;
|
||||
seenFinish = done;
|
||||
renderBanner();
|
||||
}
|
||||
|
||||
function dismissBanner() {
|
||||
if (bannerDismissed) return;
|
||||
bannerDismissed = true;
|
||||
renderBanner();
|
||||
}
|
||||
|
||||
// Closes the window and, for a question, lands on the first one that is the
|
||||
// person's, the way the page's own question list does.
|
||||
function goToIt() {
|
||||
const first = myTurn()[0];
|
||||
goingTo = Boolean(first);
|
||||
closeActivities();
|
||||
if (!first) return;
|
||||
page.selected = first.id;
|
||||
page.view = "questions";
|
||||
redraw();
|
||||
const m = $("main");
|
||||
m.focus();
|
||||
m.scrollTop = 0;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- wiring */
|
||||
|
||||
export function wireActivities() {
|
||||
const dlg = $("activities-modal");
|
||||
lightDismiss(dlg);
|
||||
$("btn-activities").addEventListener("click", openActivities);
|
||||
$("activities-close").addEventListener("click", closeActivities);
|
||||
$("activities-reset").addEventListener("click", resetBest);
|
||||
$("activities-goto").addEventListener("click", goToIt);
|
||||
$("activities-overlay").addEventListener("click", () => {
|
||||
const g = game();
|
||||
if (!g || counting > 0) return;
|
||||
play(g, () => g.key("action"));
|
||||
follow();
|
||||
$("activities-board").focus({ preventScroll: true });
|
||||
});
|
||||
dlg.addEventListener("keydown", onKey);
|
||||
dlg.addEventListener("keyup", onKeyUp);
|
||||
for (const type of Object.keys(POINTER)) $("activities-canvas").addEventListener(type, onPointer);
|
||||
// Esc, and any other way the browser cancels the dialog, takes the same
|
||||
// path as Close.
|
||||
dlg.addEventListener("cancel", (e) => {
|
||||
e.preventDefault();
|
||||
closeActivities();
|
||||
});
|
||||
dlg.addEventListener("close", () => {
|
||||
pauseAll("closed");
|
||||
disarmReset();
|
||||
if (!goingTo) $("btn-activities").focus();
|
||||
goingTo = false;
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) pauseAll("hidden");
|
||||
});
|
||||
window.addEventListener("blur", () => pauseAll("blur"));
|
||||
window.addEventListener("resize", () => {
|
||||
if (dlg.open) layout();
|
||||
});
|
||||
}
|
||||
@@ -515,6 +515,13 @@ export function wireLooks() {
|
||||
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
|
||||
if (preview) sound(preview);
|
||||
});
|
||||
$("looks-activities").addEventListener("change", (e) => {
|
||||
looks.hideActivities = !e.target.checked;
|
||||
saveLooks();
|
||||
// The die comes and goes with the next render, which also closes an open
|
||||
// Activities window, paused.
|
||||
redraw();
|
||||
});
|
||||
for (const box of document.querySelectorAll("input[data-sound]")) {
|
||||
box.addEventListener("change", () => {
|
||||
const event = box.dataset.sound;
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
/* Activities: the top bar's die, the dialog, the board, its overlay, the
|
||||
your-turn banner and the notes. The game draws its own board on the canvas. */
|
||||
|
||||
/* The top bar's die, drawn and lit like the megaphone and the gear beside it. */
|
||||
.icon-btn .dc-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
|
||||
.icon-btn .dc-pip { fill: var(--ink-2); stroke: none; }
|
||||
.icon-btn:hover .dc-body { stroke: var(--accent); }
|
||||
.icon-btn:hover .dc-pip { fill: var(--accent); }
|
||||
/* Show Activities off in User Preferences: .icon-btn's grid would beat the
|
||||
attribute's own display. */
|
||||
#btn-activities[hidden] { display: none; }
|
||||
|
||||
/* The dialog: Notebook-sized, with the board taking whatever height the
|
||||
title, the banner, the picker, the note and the actions leave. */
|
||||
.modal.activities {
|
||||
width: min(1200px, 90vw);
|
||||
height: min(900px, 85vh);
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
flex-direction: column;
|
||||
}
|
||||
.modal.activities[open] { display: flex; }
|
||||
.modal.activities h2,
|
||||
.modal.activities .modal-blurb,
|
||||
.modal.activities .modal-actions { flex: none; }
|
||||
.modal.activities .modal-blurb { margin-bottom: 12px; }
|
||||
|
||||
/* Plan2Code needs the person: an attention strip in the highlight color,
|
||||
above the board, that never covers it. */
|
||||
.activities-banner {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 8px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--ink);
|
||||
}
|
||||
.activities-banner[hidden] { display: none; }
|
||||
.activities-banner-text { flex: 1 1 auto; font-weight: 600; }
|
||||
.activities-banner .btn.primary { flex: none; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
|
||||
/* The picker: one button per game, shown only once two are listed. */
|
||||
.activities-picker {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.activities-picker[hidden] { display: none; }
|
||||
.activities-picker .btn[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--ink); }
|
||||
|
||||
/* The board: fills the free space and centers the canvas, with the state
|
||||
text laid over its middle. */
|
||||
.activities-board {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--rule-2);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.activities-board:focus { outline: none; }
|
||||
.activities-board:focus-visible { border-color: var(--accent-line); }
|
||||
.activities-board[hidden] { display: none; }
|
||||
.activities-board canvas { display: block; }
|
||||
|
||||
/* Mini golf's page colors (activities/golf-draw.js reads them off the
|
||||
canvas) for its ball, aim, pills and scorecard, all mixed from the page's
|
||||
tokens so they look right in light and dark and follow a picked highlight.
|
||||
The course itself (a pirate sea, a dark cave) keeps its own fixed colors.
|
||||
The canvas takes color-mix() as it is. */
|
||||
.activities-board canvas {
|
||||
--golf-shadow: color-mix(in srgb, black 24%, transparent);
|
||||
--golf-pole: color-mix(in srgb, white 90%, var(--stage));
|
||||
--golf-ball: color-mix(in srgb, white 96%, var(--stage));
|
||||
--golf-aim: var(--golf-ball);
|
||||
--golf-power: var(--accent);
|
||||
--golf-card: var(--panel);
|
||||
--golf-ink: var(--ink);
|
||||
--golf-ink2: var(--ink-2);
|
||||
--golf-under: var(--ok);
|
||||
--golf-over: var(--warn);
|
||||
--golf-burst: var(--stage);
|
||||
}
|
||||
.activities-overlay {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
max-width: 80%;
|
||||
padding: 10px 16px;
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--shadow);
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
white-space: pre-line;
|
||||
cursor: pointer;
|
||||
}
|
||||
/* The 3, 2, 1 before play: a big number, not a note, and nothing to click. */
|
||||
.activities-overlay.count {
|
||||
min-width: 2.4em;
|
||||
font-size: 48px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: default;
|
||||
}
|
||||
.activities-overlay:empty,
|
||||
.activities-overlay[hidden] { display: none; }
|
||||
|
||||
/* The header's best for the game on screen: quieter than the title. */
|
||||
.activities-title-best { font-weight: 400; color: var(--ink-2); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* The round's score beside the best, under the board, as colored chips with
|
||||
a meter between them (screens/activities.js builds them). Its height is
|
||||
fixed, empty or not, so the board does not jump the moment a round starts. */
|
||||
.activities-score {
|
||||
--score-gold: color-mix(in srgb, var(--stage) 80%, #f5b301);
|
||||
flex: none;
|
||||
height: 30px;
|
||||
margin: 8px 0 0;
|
||||
display: block;
|
||||
line-height: 30px;
|
||||
color: var(--ink-2);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.activities-chip {
|
||||
display: inline-block;
|
||||
padding: 0 12px;
|
||||
line-height: 26px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid;
|
||||
font-weight: 600;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.activities-chip b { font-weight: 800; font-size: 1.08em; }
|
||||
.activities-chip.score {
|
||||
border-color: var(--accent-line);
|
||||
background: linear-gradient(135deg, var(--accent-soft), color-mix(in srgb, var(--accent) 22%, var(--panel)));
|
||||
color: var(--ink);
|
||||
}
|
||||
.activities-chip.score b { color: var(--accent); }
|
||||
.activities-chip.best {
|
||||
border-color: color-mix(in srgb, var(--score-gold) 55%, transparent);
|
||||
background: linear-gradient(135deg, color-mix(in srgb, var(--score-gold) 14%, var(--panel)), color-mix(in srgb, var(--score-gold) 28%, var(--panel)));
|
||||
color: var(--ink);
|
||||
}
|
||||
.activities-chip.best b { color: var(--score-gold); }
|
||||
/* The " · " between them stays in the text (a plain inline span, so its
|
||||
spaces count) but takes no room; the best chip keeps its own gap. */
|
||||
.activities-sep { font-size: 0; }
|
||||
.activities-chip.best { margin-left: 8px; }
|
||||
/* The meter: how far the score has come toward the best. */
|
||||
.activities-meter {
|
||||
display: inline-block;
|
||||
width: 120px;
|
||||
height: 8px;
|
||||
margin: 0 2px 0 10px;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(90deg, var(--accent), var(--score-gold)) no-repeat var(--rule-2);
|
||||
background-size: calc(var(--fill, 0) * 100%) 100%;
|
||||
vertical-align: middle;
|
||||
transition: background-size 200ms ease-out;
|
||||
}
|
||||
/* Reaching the best: the best chip glows. */
|
||||
.activities-score.tied .activities-chip.best {
|
||||
border-color: var(--score-gold);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--score-gold) 30%, transparent);
|
||||
}
|
||||
/* Past it: a rainbow line and a NEW BEST tag (drawn by CSS, so the line still
|
||||
reads as its plain text). */
|
||||
.activities-score.passed .activities-chip,
|
||||
.activities-score.passed .activities-meter {
|
||||
background: linear-gradient(90deg, #ff4fa3, #f5b301, #57b54a, #1fb6d9, #a466ff, #ff4fa3);
|
||||
background-size: 300% 100%;
|
||||
border-color: transparent;
|
||||
color: #ffffff;
|
||||
}
|
||||
.activities-score.passed .activities-chip b { color: #ffffff; }
|
||||
.activities-score.passed .activities-chip { text-shadow: 0 1px 2px rgba(0, 0, 0, 0.45); }
|
||||
.activities-score.passed .activities-chip.score::after {
|
||||
content: "NEW BEST";
|
||||
margin-left: 8px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.28);
|
||||
font-size: 0.72em;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
/* The sparks fanning up out of the chips as the best is passed. */
|
||||
.activities-spark {
|
||||
position: absolute;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin: -4px 0 0 -4px;
|
||||
border-radius: 2px;
|
||||
background: var(--c);
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
z-index: 2;
|
||||
}
|
||||
/* The end of a round that set a new best: the overlay says so in rainbow. */
|
||||
.activities-overlay.record { border: 2px solid transparent; background: linear-gradient(var(--panel), var(--panel)) padding-box, linear-gradient(90deg, #ff4fa3, #f5b301, #57b54a, #1fb6d9, #a466ff) border-box; }
|
||||
.activities-overlay.record::before {
|
||||
content: "New best!";
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
background: linear-gradient(90deg, #ff4fa3, #f5b301, #1fb6d9, #a466ff);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.activities-score.tied .activities-chip.best { animation: activities-glow 900ms ease-in-out infinite alternate; }
|
||||
.activities-score.passed .activities-chip,
|
||||
.activities-score.passed .activities-meter { animation: activities-rainbow 2.4s linear infinite; }
|
||||
.activities-score.burst .activities-chip { animation: activities-rainbow 2.4s linear infinite, activities-pop 600ms cubic-bezier(0.3, 1.6, 0.5, 1); }
|
||||
.activities-spark { animation: activities-spark 1s cubic-bezier(0.2, 0.7, 0.4, 1) forwards; }
|
||||
.activities-overlay.record::before { animation: activities-pop 600ms cubic-bezier(0.3, 1.6, 0.5, 1); }
|
||||
}
|
||||
@keyframes activities-glow { to { box-shadow: 0 0 0 6px color-mix(in srgb, var(--score-gold) 12%, transparent), 0 0 16px color-mix(in srgb, var(--score-gold) 60%, transparent); } }
|
||||
@keyframes activities-rainbow { to { background-position: 300% 0; } }
|
||||
@keyframes activities-pop { 0% { transform: scale(0.8); } 60% { transform: scale(1.18); } 100% { transform: scale(1); } }
|
||||
@keyframes activities-spark {
|
||||
0% { opacity: 1; transform: translate(0, 0) rotate(0); }
|
||||
70% { opacity: 1; }
|
||||
100% { opacity: 0; transform: translate(var(--dx), calc(var(--dy) + 30px)) rotate(var(--spin)); }
|
||||
}
|
||||
|
||||
/* The keyboard, bigger-window and load-failure notes: shown in place of play. */
|
||||
.activities-note { flex: none; margin: 12px 0 0; color: var(--ink-2); }
|
||||
.activities-note[hidden] { display: none; }
|
||||
@@ -0,0 +1,122 @@
|
||||
// Plan2Code Web Console - the tones: short synthesized blips for the activities, silent when Play sounds is off; defines only.
|
||||
|
||||
import { looks } from "./looks.js";
|
||||
|
||||
/* ------------------------------------------------------------- tones
|
||||
|
||||
Blips made in the browser, so there is no audio file to fetch. They are
|
||||
not the main sounds in sound.js: the master Play sounds switch gates them,
|
||||
and they have no switch of their own and no queue. A browser will not
|
||||
make noise before the person has touched the page, so unlockTones() runs
|
||||
from the click that opens Activities. A tone asked for before that stays
|
||||
silent rather than throwing.
|
||||
|
||||
Every sound here is short (a quarter second at most) and quiet, so a cue
|
||||
never outlasts the moment it belongs to. A tone either sweeps from one
|
||||
pitch to another, or plays `notes` one after another in its time. */
|
||||
const TONES = Object.freeze({
|
||||
eat: Object.freeze({ type: "triangle", from: 660, to: 880, seconds: 0.12 }),
|
||||
crash: Object.freeze({ type: "sawtooth", from: 220, to: 80, seconds: 0.2 }),
|
||||
// The 3, 2, 1 before a round starts or plays on: a tick per number, then a
|
||||
// higher one as play begins.
|
||||
count: Object.freeze({ type: "sine", from: 440, to: 440, seconds: 0.08 }),
|
||||
go: Object.freeze({ type: "sine", from: 880, to: 880, seconds: 0.14 }),
|
||||
// Mini golf: the club on the ball, the ball off a wall or a bumper, into
|
||||
// the cup, a hole in one (a little three-note rise), and into the water.
|
||||
putt: Object.freeze({ type: "triangle", from: 520, to: 400, seconds: 0.06 }),
|
||||
wall: Object.freeze({ type: "triangle", from: 300, to: 200, seconds: 0.07 }),
|
||||
bump: Object.freeze({ type: "sine", from: 700, to: 1000, seconds: 0.09 }),
|
||||
cup: Object.freeze({ type: "triangle", from: 520, to: 1040, seconds: 0.16 }),
|
||||
ace: Object.freeze({ type: "triangle", notes: Object.freeze([523, 659, 784]), seconds: 0.24 }),
|
||||
splash: Object.freeze({ type: "sine", from: 420, to: 120, seconds: 0.2 }),
|
||||
// Mini golf's gags: a power-up grabbed (a sparkly rise), a tunnel's whoosh,
|
||||
// a cannonball putt, the ball into lava, and the ball down the pit.
|
||||
power: Object.freeze({ type: "square", notes: Object.freeze([784, 988, 1319]), seconds: 0.18 }),
|
||||
tunnel: Object.freeze({ type: "sine", from: 200, to: 900, seconds: 0.16 }),
|
||||
boom: Object.freeze({ type: "sawtooth", from: 160, to: 45, seconds: 0.22 }),
|
||||
sizzle: Object.freeze({ type: "sawtooth", from: 900, to: 300, seconds: 0.2 }),
|
||||
fall: Object.freeze({ type: "sine", from: 700, to: 60, seconds: 0.25 }),
|
||||
// Mini golf's swing: the meter starting, a putt caught in the MAX band (a
|
||||
// bright two-note hit), and an overswing's sour buzz.
|
||||
swing: Object.freeze({ type: "square", from: 620, to: 660, seconds: 0.04 }),
|
||||
max: Object.freeze({ type: "square", notes: Object.freeze([880, 1320]), seconds: 0.16 }),
|
||||
shank: Object.freeze({ type: "sawtooth", from: 240, to: 110, seconds: 0.18 }),
|
||||
// Snake's extras: a combo's quick chirp, a coin, a mystery box opening, a
|
||||
// new level (a four-note climb), a shield taking a hit, a comet cutting
|
||||
// the tail, and a new best mid-round. A grabbed power-up uses `power`, a
|
||||
// smashed rock `boom` and a portal `tunnel`.
|
||||
combo: Object.freeze({ type: "square", from: 880, to: 1320, seconds: 0.07 }),
|
||||
coin: Object.freeze({ type: "square", notes: Object.freeze([988, 1319]), seconds: 0.1 }),
|
||||
mystery: Object.freeze({ type: "triangle", notes: Object.freeze([392, 523, 466, 698]), seconds: 0.24 }),
|
||||
levelup: Object.freeze({ type: "square", notes: Object.freeze([523, 659, 784, 1047]), seconds: 0.25 }),
|
||||
shield: Object.freeze({ type: "sine", from: 1200, to: 500, seconds: 0.14 }),
|
||||
zap: Object.freeze({ type: "sawtooth", from: 1400, to: 200, seconds: 0.15 }),
|
||||
best: Object.freeze({ type: "triangle", notes: Object.freeze([784, 988, 1175, 1568]), seconds: 0.25 }),
|
||||
});
|
||||
|
||||
// Peak gain, kept modest so a blip sits under the page rather than over it.
|
||||
const PEAK = 0.08;
|
||||
|
||||
// A quick attack avoids a click at the start; the decay is exponential, which
|
||||
// needs a non-zero floor, so the envelope stops at a tiny value, not zero.
|
||||
const ATTACK = 0.01;
|
||||
const FLOOR = 0.0001;
|
||||
|
||||
let ctx = null;
|
||||
|
||||
// Made on first use, not at load, so importing this file in Node is harmless.
|
||||
// A missing AudioContext or a constructor that throws both give null.
|
||||
function audioContext() {
|
||||
if (ctx) return ctx;
|
||||
if (typeof globalThis.AudioContext === "undefined") return null;
|
||||
try {
|
||||
ctx = new globalThis.AudioContext();
|
||||
} catch {
|
||||
ctx = null;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// Called from the click that opens Activities. A browser keeps a new context
|
||||
// suspended until a gesture, and a rejected resume is not an error the page
|
||||
// can act on, so every failure is swallowed.
|
||||
export function unlockTones() {
|
||||
try {
|
||||
const c = audioContext();
|
||||
if (c) Promise.resolve(c.resume()).catch(() => {});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// One oscillator from t0 for `seconds`, sweeping from one pitch to another.
|
||||
function blip(c, type, from, to, t0, seconds, peak) {
|
||||
const end = t0 + seconds;
|
||||
const osc = c.createOscillator();
|
||||
const gain = c.createGain();
|
||||
osc.type = type;
|
||||
osc.frequency.setValueAtTime(from, t0);
|
||||
osc.frequency.exponentialRampToValueAtTime(to, end);
|
||||
gain.gain.setValueAtTime(FLOOR, t0);
|
||||
gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK);
|
||||
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
|
||||
osc.connect(gain);
|
||||
gain.connect(c.destination);
|
||||
osc.start(t0);
|
||||
osc.stop(end);
|
||||
}
|
||||
|
||||
// Plays one named blip, at `level` (0 to 1) of the usual loudness: a soft
|
||||
// putt sounds soft. An unknown name, Play sounds off, or a context that is
|
||||
// missing, suspended or closed all mean silence, not an error.
|
||||
export function tone(name, level = 1) {
|
||||
try {
|
||||
const spec = Object.hasOwn(TONES, name) ? TONES[name] : null;
|
||||
if (!spec || !looks.sound) return;
|
||||
const c = audioContext();
|
||||
if (!c || c.state !== "running") return;
|
||||
const peak = Math.max(FLOOR * 10, PEAK * Math.min(1, Number(level) || 0));
|
||||
const t0 = c.currentTime;
|
||||
if (!spec.notes) return blip(c, spec.type, spec.from, spec.to, t0, spec.seconds, peak);
|
||||
const each = spec.seconds / spec.notes.length;
|
||||
spec.notes.forEach((f, i) => blip(c, spec.type, f, f, t0 + i * each, each, peak));
|
||||
} catch {}
|
||||
}
|
||||
@@ -71,6 +71,14 @@ export const SERVABLE = new Set([
|
||||
"screens/workspace.js",
|
||||
"screens/ask.js",
|
||||
"screens/notepad.js",
|
||||
"screens/activities.js",
|
||||
"activities.js",
|
||||
"activities/snake.js",
|
||||
"activities/golf.js",
|
||||
"activities/golf-holes.js",
|
||||
"activities/golf-draw.js",
|
||||
"activities/golf-decor.js",
|
||||
"tones.js",
|
||||
"notepad-tabs.js",
|
||||
"net.js",
|
||||
"notepad.js",
|
||||
@@ -87,7 +95,7 @@ export const SERVABLE = new Set([
|
||||
// Layers first, then one file per screen, then responsive and print last so
|
||||
// its overrides still come after everything they override. The files are not
|
||||
// on SERVABLE: they reach the page only through /app.css.
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "git.css", "responsive.css"];
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
|
||||
|
||||
// The files joined with one newline between them (each file's own last newline
|
||||
// is that one), as the server serves them before the accent rules. The test
|
||||
|
||||
Reference in new issue
Block a user