From b8f52dd20cc54525151d6f3522e94f196d172f81 Mon Sep 17 00:00:00 2001 From: BrightBoost-Tech Date: Wed, 18 Nov 2026 19:17:20 -0600 Subject: [PATCH] =?UTF-8?q?feat:=20add=20Qubit=20Cove=20to=20the=20K?= =?UTF-8?q?=E2=80=932=20Quantum=20specialty?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/prisma/seedAdvanced.cjs | 43 + .../routes/__tests__/advancedProgress.test.ts | 2 +- prisma/seedAdvanced.cjs | 43 + prompts/2026-11-18-qubit-cove.md | 9 + scripts/__tests__/seedAdvanced.test.ts | 5 +- shared/progression/advanced.ts | 9 + src/components/games/QubitCoveActivity.tsx | 43 + .../__tests__/QubitCoveActivity.test.tsx | 85 ++ src/components/games/gameRegistry.ts | 4 +- .../games/qubitCove/QubitCoveGame.tsx | 538 +++++++++++++ src/components/games/qubitCove/ReadAloud.tsx | 47 ++ .../games/qubitCove/__tests__/engine.test.ts | 141 ++++ .../qubitCove/__tests__/gameFlow.test.tsx | 82 ++ src/components/games/qubitCove/coveHorizon.ts | 160 ++++ src/components/games/qubitCove/coveMesh.ts | 175 ++++ src/components/games/qubitCove/coveModels.ts | 249 ++++++ src/components/games/qubitCove/engine.ts | 206 +++++ src/components/games/qubitCove/qubitCove.css | 753 ++++++++++++++++++ src/components/games/qubitCove/readAloud.css | 20 + src/components/games/qubitCove/scene.ts | 674 ++++++++++++++++ src/components/games/qubitCove/useCovePlay.ts | 180 +++++ src/components/games/qubitCove/world.ts | 152 ++++ .../specialty/SpecialtyExperience.tsx | 63 +- .../__tests__/SpecialtyExperience.test.tsx | 9 +- src/lib/__tests__/specialty.test.ts | 9 + src/lib/specialty.ts | 6 +- src/locales/en/common.json | 77 +- src/locales/es/common.json | 77 +- src/locales/vi/common.json | 85 +- src/locales/zh-CN/common.json | 85 +- src/pages/dev/AdvancedPreview.tsx | 9 +- src/utils/localizedContent.ts | 15 + 32 files changed, 3991 insertions(+), 64 deletions(-) create mode 100644 prompts/2026-11-18-qubit-cove.md create mode 100644 src/components/games/QubitCoveActivity.tsx create mode 100644 src/components/games/__tests__/QubitCoveActivity.test.tsx create mode 100644 src/components/games/qubitCove/QubitCoveGame.tsx create mode 100644 src/components/games/qubitCove/ReadAloud.tsx create mode 100644 src/components/games/qubitCove/__tests__/engine.test.ts create mode 100644 src/components/games/qubitCove/__tests__/gameFlow.test.tsx create mode 100644 src/components/games/qubitCove/coveHorizon.ts create mode 100644 src/components/games/qubitCove/coveMesh.ts create mode 100644 src/components/games/qubitCove/coveModels.ts create mode 100644 src/components/games/qubitCove/engine.ts create mode 100644 src/components/games/qubitCove/qubitCove.css create mode 100644 src/components/games/qubitCove/readAloud.css create mode 100644 src/components/games/qubitCove/scene.ts create mode 100644 src/components/games/qubitCove/useCovePlay.ts create mode 100644 src/components/games/qubitCove/world.ts diff --git a/backend/prisma/seedAdvanced.cjs b/backend/prisma/seedAdvanced.cjs index 068931d8..08d8d53a 100644 --- a/backend/prisma/seedAdvanced.cjs +++ b/backend/prisma/seedAdvanced.cjs @@ -122,5 +122,48 @@ async function seedAdvanced(prisma, teacherId) { content: JSON.stringify({ gameKey: "sparbots" }), }, }); + const coveDetails = { + title: "Qubit Cove", + description: "Explore islands and measure a qubit to see a 0 or a 1.", + level: "K-2", + published: true, + }; + const cove = await prisma.module.upsert({ + where: { slug: "advanced-quantum-qubit-cove" }, + update: coveDetails, + create: { slug: "advanced-quantum-qubit-cove", ...coveDetails }, + }); + const coveUnitData = { + moduleId: cove.id, + title: "The quantum islands", + order: 1, + }; + const coveUnit = await prisma.unit.upsert({ + where: { id: "qubit-cove-islands" }, + update: coveUnitData, + create: { id: "qubit-cove-islands", teacherId, ...coveUnitData }, + }); + const coveLessonData = { + unitId: coveUnit.id, + title: "My first qubit", + order: 1, + }; + const coveLesson = await prisma.lesson.upsert({ + where: { id: "qubit-cove-expedition" }, + update: coveLessonData, + create: { id: "qubit-cove-expedition", ...coveLessonData }, + }); + const coveActivityData = { + lessonId: coveLesson.id, + title: coveDetails.title, + kind: "INTERACT", + order: 1, + content: JSON.stringify({ gameKey: "qubit_cove" }), + }; + await prisma.activity.upsert({ + where: { id: "qubit_cove" }, + update: coveActivityData, + create: { id: "qubit_cove", ...coveActivityData }, + }); } module.exports = { seedAdvanced }; diff --git a/backend/src/routes/__tests__/advancedProgress.test.ts b/backend/src/routes/__tests__/advancedProgress.test.ts index 103e1c0e..dd5b3191 100644 --- a/backend/src/routes/__tests__/advancedProgress.test.ts +++ b/backend/src/routes/__tests__/advancedProgress.test.ts @@ -130,7 +130,7 @@ describe.each(ADVANCED_ACTIVITIES)( expect(mocks.prisma.progress.upsert).toHaveBeenCalledTimes(1); mocks.prisma.avatar.findUnique.mockResolvedValue({ stage: "SPECIALIZED", - archetype: "QUANTUM", + archetype: advanced.specialty === "QUANTUM" ? "AI" : "QUANTUM", }); expect( (await request(app).post("/progress/checkpoint").send(checkpoint)) diff --git a/prisma/seedAdvanced.cjs b/prisma/seedAdvanced.cjs index 068931d8..08d8d53a 100644 --- a/prisma/seedAdvanced.cjs +++ b/prisma/seedAdvanced.cjs @@ -122,5 +122,48 @@ async function seedAdvanced(prisma, teacherId) { content: JSON.stringify({ gameKey: "sparbots" }), }, }); + const coveDetails = { + title: "Qubit Cove", + description: "Explore islands and measure a qubit to see a 0 or a 1.", + level: "K-2", + published: true, + }; + const cove = await prisma.module.upsert({ + where: { slug: "advanced-quantum-qubit-cove" }, + update: coveDetails, + create: { slug: "advanced-quantum-qubit-cove", ...coveDetails }, + }); + const coveUnitData = { + moduleId: cove.id, + title: "The quantum islands", + order: 1, + }; + const coveUnit = await prisma.unit.upsert({ + where: { id: "qubit-cove-islands" }, + update: coveUnitData, + create: { id: "qubit-cove-islands", teacherId, ...coveUnitData }, + }); + const coveLessonData = { + unitId: coveUnit.id, + title: "My first qubit", + order: 1, + }; + const coveLesson = await prisma.lesson.upsert({ + where: { id: "qubit-cove-expedition" }, + update: coveLessonData, + create: { id: "qubit-cove-expedition", ...coveLessonData }, + }); + const coveActivityData = { + lessonId: coveLesson.id, + title: coveDetails.title, + kind: "INTERACT", + order: 1, + content: JSON.stringify({ gameKey: "qubit_cove" }), + }; + await prisma.activity.upsert({ + where: { id: "qubit_cove" }, + update: coveActivityData, + create: { id: "qubit_cove", ...coveActivityData }, + }); } module.exports = { seedAdvanced }; diff --git a/prompts/2026-11-18-qubit-cove.md b/prompts/2026-11-18-qubit-cove.md new file mode 100644 index 00000000..d8009eee --- /dev/null +++ b/prompts/2026-11-18-qubit-cove.md @@ -0,0 +1,9 @@ +# Qubit Cove + +User request: “create the first game for k-2 using the quantum specialty. Should be based on super mario 64” + +Build an original exploration platformer for the Bright Boost Quantum specialty. +Use a lighthouse hub, three freely ordered beacon experiments, optional sparks, +and forgiving jumps. Let learners prepare and measure simulated qubits with +certain and equally likely outcomes. Keep the existing Set 3 specialty gate and +activity completion flow. diff --git a/scripts/__tests__/seedAdvanced.test.ts b/scripts/__tests__/seedAdvanced.test.ts index 7c6af4f5..a6bc56ce 100644 --- a/scripts/__tests__/seedAdvanced.test.ts +++ b/scripts/__tests__/seedAdvanced.test.ts @@ -7,7 +7,7 @@ describe.each([ "../../prisma/seedAdvanced.cjs", "../../backend/prisma/seedAdvanced.cjs", ])("advanced seed %s", (file) => { - it("seeds both canonical chains idempotently with the first specialty activity", async () => { + it("seeds all canonical chains idempotently with the first specialty activity", async () => { function table() { const rows = new Map>(); return { @@ -58,6 +58,7 @@ describe.each([ gameKey: advanced.activityId, }); } - for (const entity of Object.values(db)) expect(entity.rows.size).toBe(2); + for (const entity of Object.values(db)) + expect(entity.rows.size).toBe(ADVANCED_ACTIVITIES.length); }); }); diff --git a/shared/progression/advanced.ts b/shared/progression/advanced.ts index 1bdc5ca7..14f70a19 100644 --- a/shared/progression/advanced.ts +++ b/shared/progression/advanced.ts @@ -5,6 +5,9 @@ export const BIOTRAIL_LESSON_ID = "biotrail-field-lab"; export const SPARBOTS_SLUG = "advanced-ai-sparbots"; export const SPARBOTS_ACTIVITY_ID = "sparbots"; export const SPARBOTS_LESSON_ID = "sparbots-training-tower"; +export const QUBIT_COVE_SLUG = "advanced-quantum-qubit-cove"; +export const QUBIT_COVE_LESSON_ID = "qubit-cove-expedition"; +export const QUBIT_COVE_ACTIVITY_ID = "qubit_cove"; export const ADVANCED_ACTIVITIES = [ { slug: BIOTRAIL_SLUG, @@ -18,6 +21,12 @@ export const ADVANCED_ACTIVITIES = [ activityId: SPARBOTS_ACTIVITY_ID, specialty: "AI", }, + { + slug: QUBIT_COVE_SLUG, + lessonId: QUBIT_COVE_LESSON_ID, + activityId: QUBIT_COVE_ACTIVITY_ID, + specialty: "QUANTUM", + }, ] as const; export const ADVANCED_SPECIALTIES: Readonly> = Object.fromEntries( diff --git a/src/components/games/QubitCoveActivity.tsx b/src/components/games/QubitCoveActivity.tsx new file mode 100644 index 00000000..49621cfa --- /dev/null +++ b/src/components/games/QubitCoveActivity.tsx @@ -0,0 +1,43 @@ +import { lazy, Suspense } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { useAuth } from "@/contexts/AuthContext"; +import { useSpecialty } from "@/contexts/SpecialtyContext"; +import { Button } from "@/components/ui/button"; +import type { GameResult } from "./shared/GameShell"; +const QubitCoveGame = lazy(() => import("./qubitCove/QubitCoveGame")); +export default function QubitCoveActivity({ + onComplete, +}: { + onComplete?: (result: GameResult) => void; +}) { + const { t } = useTranslation(); + const { user } = useAuth(); + const { status, data, refresh } = useSpecialty(); + if (status === "loading") + return

{t("specialty.loading")}

; + if (status === "error") + return ( +
+

{t("specialty.loadError")}

+ +
+ ); + if (!user || !data?.unlocked || data.specialty !== "QUANTUM") + return ( +

+ + {t("specialty.qubitCove.gameLocked")} + +

+ ); + return ( + {t("specialty.loading")}

}> + +
+ ); +} diff --git a/src/components/games/__tests__/QubitCoveActivity.test.tsx b/src/components/games/__tests__/QubitCoveActivity.test.tsx new file mode 100644 index 00000000..f86eb0cb --- /dev/null +++ b/src/components/games/__tests__/QubitCoveActivity.test.tsx @@ -0,0 +1,85 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { expect, it, vi } from "vitest"; +import QubitCoveActivity from "../QubitCoveActivity"; +import type { GameResult } from "../shared/GameShell"; + +const state = vi.hoisted(() => ({ + user: { id: "learner" } as { id: string } | null, + status: "loading", + data: { unlocked: true, specialty: "QUANTUM" }, + refresh: vi.fn(), +})); +vi.mock("@/contexts/AuthContext", () => ({ + useAuth: () => ({ user: state.user }), +})); +vi.mock("@/contexts/SpecialtyContext", () => ({ useSpecialty: () => state })); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); +vi.mock("../qubitCove/QubitCoveGame", () => ({ + default: ({ + storageScope, + onComplete, + }: { + storageScope: string; + onComplete: (result: GameResult) => void; + }) => ( + + ), +})); + +it("checks the earned specialty, scopes the game to the student and forwards completion", async () => { + const onComplete = vi.fn(); + const activity = () => ( + + + + ); + const { rerender } = render(activity()); + expect(screen.getByRole("status")).toHaveTextContent("specialty.loading"); + state.status = "error"; + rerender(activity()); + fireEvent.click(screen.getByRole("button")); + expect(state.refresh).toHaveBeenCalledOnce(); + + state.status = "ready"; + for (const data of [ + { unlocked: true, specialty: "AI" }, + { unlocked: true, specialty: "BIOTECH" }, + { unlocked: false, specialty: "QUANTUM" }, + ]) { + state.data = data; + rerender(activity()); + expect(screen.getByRole("link")).toHaveAttribute( + "href", + "/student/specialty", + ); + } + state.data = { unlocked: true, specialty: "QUANTUM" }; + state.user = null; + rerender(activity()); + expect(screen.getByRole("link")).toBeInTheDocument(); + state.user = { id: "learner" }; + rerender(activity()); + fireEvent.click(await screen.findByRole("button", { name: "learner" })); + expect(onComplete).toHaveBeenCalledExactlyOnceWith({ + gameKey: "qubit_cove", + score: 3, + total: 3, + streakMax: 0, + roundsCompleted: 3, + }); +}); diff --git a/src/components/games/gameRegistry.ts b/src/components/games/gameRegistry.ts index 236dd153..70eaf67d 100644 --- a/src/components/games/gameRegistry.ts +++ b/src/components/games/gameRegistry.ts @@ -1,4 +1,5 @@ import BioTrailActivity from "./BioTrailActivity"; +import QubitCoveActivity from "./QubitCoveActivity"; import SparBotsActivity from "./SparBotsActivity"; import type { ComponentType } from "react"; import type { GameResult } from "./shared/GameShell"; @@ -46,7 +47,8 @@ export const GAME_COMPONENTS: Record> = { fast_lane: FastLaneGame, // "Fast Lane Signals" (Set 2) qualify_tune_race: QualifyTuneRaceGame, // "Qualify, Tune, Race" (Set 2) - // Advanced Biotech: independently gated by server specialty state. + // Advanced games are independently gated by server specialty state. + qubit_cove: QubitCoveActivity, biotrail: BioTrailActivity, sparbots: SparBotsActivity, diff --git a/src/components/games/qubitCove/QubitCoveGame.tsx b/src/components/games/qubitCove/QubitCoveGame.tsx new file mode 100644 index 00000000..cedb762e --- /dev/null +++ b/src/components/games/qubitCove/QubitCoveGame.tsx @@ -0,0 +1,538 @@ +import { useId, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import * as Dialog from "@radix-ui/react-dialog"; +import { + ArrowDown, + ArrowLeft, + ArrowRight, + ArrowUp, + Atom, + Check, + ChevronRight, + ChevronsUp, + CircleHelp, + Compass, + Flag, + FlaskConical, + Gem, + Keyboard, + Map, + Mountain, + RadioTower, + RotateCcw, + ScanLine, + Sparkles, + Sprout, + Telescope, + Waves, + X, +} from "lucide-react"; +import type { GameResult } from "../shared/GameShell"; +import { useReducedGameEffects } from "../shared/useReducedGameEffects"; +import { createGame, guideToBeacon, lightBeacon } from "./engine"; +import { beacons, type BeaconId } from "./world"; +import { useCovePlay, type Control } from "./useCovePlay"; +import ReadAloud from "./ReadAloud"; +import "./qubitCove.css"; + +type Props = { + storageScope: string; + onComplete?: (result: GameResult) => void | boolean | Promise; +}; +type Panel = "map" | "help" | BeaconId | null; +type Bit = 0 | 1; +type Readings = Record; +const freshReadings = (): Readings => ({ zero: [], one: [], mix: [] }); +const directionIcons = { + left: ArrowLeft, + up: ArrowUp, + down: ArrowDown, + right: ArrowRight, + jump: ChevronsUp, +}; +const places = { zero: Sprout, one: Mountain, mix: Waves }; +const symbols = { zero: "0", one: "1", mix: "0/1" }; + +function ReadingsStrip({ samples, count }: { samples: Bit[]; count: number }) { + const { t } = useTranslation(); + return ( +
+ {t("qubitCove.readings")} +
    + {Array.from({ length: count }, (_, i) => ( +
  1. + {samples[i] ?? } +
  2. + ))} +
+
+ ); +} + +function BeaconLab({ + id, + samples, + lit, + onSample, + onLight, + onClose, +}: { + id: BeaconId; + samples: Bit[]; + lit: boolean; + onSample: (value: Bit) => void; + onLight: () => void; + onClose: () => void; +}) { + const { t } = useTranslation(); + const [prepared, setPrepared] = useState(false); + const [incorrect, setIncorrect] = useState(false); + const target = id === "mix" ? 3 : 1; + const enough = samples.length >= target; + const last = samples.at(-1); + const name = t(`qubitCove.names.${id}`); + const setup = t(`qubitCove.setup.${id}`); + const insight = t(`qubitCove.insight.${id}`); + const status = prepared + ? t("qubitCove.ready") + : last === undefined + ? "" + : t("qubitCove.reading", { value: last }); + const question = t("qubitCove.prediction"); + const speech = lit + ? `${t("qubitCove.beaconLit", { name })} ${insight}` + : enough + ? [ + status, + question, + ...beacons.map((b) => t(`qubitCove.choices.${b.id}`)), + ].join(" ") + : [ + setup, + status, + t(prepared ? "qubitCove.measure" : "qubitCove.prepare"), + ].join(" "); + const Icon = places[id]; + + function sample() { + if (enough || !prepared) return; + onSample( + id === "mix" ? (Math.random() < 0.5 ? 0 : 1) : id === "one" ? 1 : 0, + ); + setPrepared(false); + } + function choose(choice: BeaconId) { + if (choice !== id) setIncorrect(true); + else { + setIncorrect(false); + onLight(); + } + } + + return ( +
+
+ + + {name} +
+
+ +
+ {lit ? insight : setup} + +
+
+ +

+ {lit ? t("qubitCove.beaconLit", { name }) : status} +

+ {lit ? ( + + ) : enough ? ( +
+

{question}

+
+ {beacons.map(({ id: choice }) => ( + + ))} +
+ {incorrect &&

{t("qubitCove.retry")}

} +
+ ) : ( + + )} +
+ ); +} + +export default function QubitCoveGame(props: Props) { + return ( + + ); +} + +function CoveAdventure({ onComplete }: Pick) { + const { t } = useTranslation(); + const [panel, setPanel] = useState(null); + const [readings, setReadings] = useState(freshReadings); + const [submission, setSubmission] = useState< + "idle" | "busy" | "saved" | "error" + >("idle"); + const latched = useRef(false); + const introId = useId(); + const victory = useRef(null); + const { reducedEffects, setReducedEffects } = useReducedGameEffects(); + const { canvas, region, world, hud, update, press, release, pulse } = + useCovePlay(panel !== null, reducedEffects, setPanel); + const won = hud.lit.length === 3; + const activeBeacon = + panel && panel !== "map" && panel !== "help" ? panel : null; + + function ride(id: BeaconId) { + update(guideToBeacon(world.current, id)); + setPanel(null); + } + function replay() { + if (submission === "busy") return; + update(createGame()); + setReadings(freshReadings()); + setSubmission("idle"); + latched.current = false; + canvas.current?.focus({ preventScroll: true }); + } + async function finish() { + if (latched.current || world.current.lit.length !== 3) return; + latched.current = true; + setSubmission("busy"); + try { + const ok = await onComplete?.({ + gameKey: "qubit_cove", + score: 3, + total: 3, + roundsCompleted: 3, + streakMax: 0, + starsEarned: 3, + }); + if (ok === false) throw new Error("Completion failed"); + setSubmission("saved"); + } catch { + latched.current = false; + setSubmission("error"); + } + } + + function controlButton(control: Control) { + const Icon = directionIcons[control]; + return ( + + ); + } + + return ( +
+
+
+ + +
+

{t("qubitCove.title")}

+

{t("qubitCove.goal")}

+
+
+
+ + +
+
+
+ canvas.current?.focus({ preventScroll: true })} + /> +
+ + + + +
+ {hud.near && ( + + )} +
+ {won && ( +
+
+ + +

+ {t("qubitCove.won")} +

+
+
+ + +
+ {submission === "error" && ( +

{t("qubitCove.saveError")}

+ )} +
+ )} +
+
+ {(["up", "left", "down", "right"] as const).map(controlButton)} +
+

+

+ {controlButton("jump")} +
+ { + if (!open) setPanel(null); + }} + > + + + { + event.preventDefault(); + const target = won ? victory.current : canvas.current; + target?.focus({ preventScroll: true }); + }} + > + + + {panel === "map" && ( + <> +
+ + + {t("qubitCove.map")} +
+ + {t("qubitCove.mapHint")} + +
+ {beacons.map(({ id }) => { + const Icon = places[id]; + const name = t(`qubitCove.names.${id}`); + const lit = hud.lit.includes(id); + return ( + + ); + })} +
+ + )} + {panel === "help" && ( + <> +
+ + + {t("qubitCove.help")} +
+ {t("qubitCove.goal")} +
+

+

+

+

+

+

+

+

+ t(`qubitCove.${key}`)) + .join(" ")} + /> + +
+ + )} + {activeBeacon && ( + + setReadings((old) => ({ + ...old, + [activeBeacon]: [...old[activeBeacon], value], + })) + } + onLight={() => update(lightBeacon(world.current, activeBeacon))} + onClose={() => setPanel(null)} + /> + )} +
+
+
+
+ ); +} diff --git a/src/components/games/qubitCove/ReadAloud.tsx b/src/components/games/qubitCove/ReadAloud.tsx new file mode 100644 index 00000000..7314679e --- /dev/null +++ b/src/components/games/qubitCove/ReadAloud.tsx @@ -0,0 +1,47 @@ +import { useEffect, useRef } from "react"; +import { Volume2 } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import "./readAloud.css"; + +export default function ReadAloud({ text }: { text: string }) { + const { t, i18n } = useTranslation(); + const language = i18n.resolvedLanguage || i18n.language; + const utterance = useRef(null); + const supported = + typeof window !== "undefined" && + "speechSynthesis" in window && + typeof window.SpeechSynthesisUtterance === "function"; + + useEffect(() => { + return () => { + if (utterance.current) { + window.speechSynthesis.cancel(); + utterance.current = null; + } + }; + }, [language, text]); + + if (!supported) return null; + + function read() { + const speech = window.speechSynthesis; + if (utterance.current) speech.cancel(); + const message = new SpeechSynthesisUtterance(text); + message.lang = language; + message.rate = 0.9; + utterance.current = message; + const clear = () => { + if (utterance.current === message) utterance.current = null; + }; + message.onend = clear; + message.onerror = clear; + speech.speak(message); + } + + return ( + + ); +} diff --git a/src/components/games/qubitCove/__tests__/engine.test.ts b/src/components/games/qubitCove/__tests__/engine.test.ts new file mode 100644 index 00000000..6c9aa132 --- /dev/null +++ b/src/components/games/qubitCove/__tests__/engine.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it } from "vitest"; +import { + createGame, + guideToBeacon, + lightBeacon, + nearbyBeacon, + stepGame, + type GameState, +} from "../engine"; +import { beaconLanding, spawn } from "../world"; + +function walk(state: GameState, frames: number, x = 0, z = 0, jump = false) { + for (let frame = 0; frame < frames; frame++) + state = stepGame(state, { x, z, jump }, 1 / 60); + return state; +} + +function hubCenter() { + return walk(createGame(), 27, 0, -1); +} + +describe("Qubit Cove", () => { + it("lets the explorer walk the pier, collect three different sparks and activate the west beacon", () => { + const west = walk(hubCenter(), 110, -1); + expect(nearbyBeacon(west)).toBe("zero"); + expect(west.collected).toEqual(["pier-1", "pier-2", "pier-3"]); + expect(west.rescues).toBe(0); + const lit = lightBeacon(west, "zero"); + expect(lit.lit).toEqual(["zero"]); + expect(lightBeacon(lit, "zero")).toBe(lit); + expect(lightBeacon(lit, "mix")).toBe(lit); + expect(walk(lit, 110, 1).collected).toEqual(west.collected); + }); + + it("makes the east terraces reachable using two running jumps", () => { + let east = walk(hubCenter(), 43, 1); + east = walk(east, 41, 1, 0, true); + expect(east.grounded).toBe(true); + east = walk(east, 25); + east = walk(east, 32, 1, 0, true); + expect(east.cometJump).toBe(false); + east = walk(east, 25); + expect(east.rescues).toBe(0); + expect(nearbyBeacon(east)).toBe("one"); + }); + + it("reaches the north island by jumping from the dock", () => { + let north = walk(hubCenter(), 54, 0, -1); + north = walk(north, 45, 0, -1, true); + north = walk(north, 12, 0, -1); + expect(north.rescues).toBe(0); + expect(nearbyBeacon(north)).toBe("mix"); + }); + + it("guides an explorer to any beacon without granting rewards for travel", () => { + let state = createGame(); + for (const id of ["mix", "zero", "one"] as const) { + const next = guideToBeacon(state, id); + expect(nearbyBeacon(next)).toBe(id); + expect(next.lit).toEqual(state.lit); + expect(next.collected).toEqual([]); + state = lightBeacon(next, id); + } + expect(state.lit).toEqual(["mix", "zero", "one"]); + expect(nearbyBeacon(createGame())).toBeNull(); + }); + + it.each(["hub", "one"] as const)( + "rescues a fall at the %s checkpoint with all earned progress intact", + (checkpoint) => { + const fromHub = checkpoint === "hub"; + let state = fromHub ? createGame() : guideToBeacon(createGame(), "one"); + if (!fromHub) state = lightBeacon(state, "one"); + if (fromHub) { + state = walk(hubCenter(), 36, -1); + expect(state.collected).toEqual(["pier-1"]); + } + for (let tick = 0; tick < 360 && state.rescues === 0; tick++) + state = stepGame(state, { x: 0, z: 1, jump: false }, 1 / 120); + expect(state.rescues).toBe(1); + expect(state.player).toEqual(fromHub ? spawn : beaconLanding("one")); + expect(state.lit).toEqual(fromHub ? [] : ["one"]); + expect(state.collected).toEqual(fromHub ? ["pier-1"] : []); + }, + ); + + it("launches a higher comet jump only on a timely moving follow-up", () => { + const regular = walk(hubCenter(), 1, 0, 0, true); + const regularPeak = walk(regular, 21).player.y; + const landed = walk(regular, 44); + expect(landed.grounded).toBe(true); + expect(walk(landed, 1, 0, 0, true).cometJump).toBe(false); + expect(walk(walk(landed, 24), 1, 1, 0, true).cometJump).toBe(false); + + const comet = walk(landed, 1, 1, 0, true); + expect(comet.cometJump).toBe(true); + expect(comet.cometTime).toBeGreaterThan(0); + expect(walk(comet, 24).player.y).toBeGreaterThan(regularPeak + 0.45); + const after = walk(comet, 56); + expect(after.grounded).toBe(true); + expect(after.cometTime).toBe(0); + expect(walk(after, 1, 1, 0, true).cometJump).toBe(false); + }); + + it("clears the comet and its landing bonus on guide or rescue", () => { + const landed = walk(walk(createGame(), 1, 0, 0, true), 44); + const comet = walk(landed, 1, 0, 1, true); + expect(comet.cometJump).toBe(true); + for (const state of [landed, comet]) { + const arrival = guideToBeacon(state, "one"); + expect(arrival.cometJump).toBe(false); + expect(arrival.cometTime).toBe(0); + expect(walk(walk(arrival, 1), 1, 1, 0, true).cometJump).toBe(false); + } + + let rescued = comet; + for (let tick = 0; tick < 250 && !rescued.rescues; tick++) + rescued = stepGame(rescued, { x: 0, z: 1, jump: false }, 1 / 120); + expect(rescued.rescues).toBe(1); + expect(rescued.cometTime).toBe(0); + expect(walk(rescued, 1, 1, 0, true).cometJump).toBe(false); + }); + + it("counts a held jump once and keeps movement consistent across frame rates", () => { + const initial = createGame(); + const held = walk(initial, 90, 0, 0, true); + expect(held.grounded).toBe(true); + expect(held.player).toEqual(spawn); + const released = walk(held, 1); + expect(walk(released, 1, 0, 0, true).grounded).toBe(false); + + const simulate = (fps: number) => { + let state = initial; + for (let f = 0; f < fps / 2; f++) + state = stepGame(state, { x: 1, z: -1, jump: true }, 1 / fps); + return state; + }; + expect(simulate(30).player).toEqual(simulate(144).player); + expect(initial.player).toEqual(spawn); + }); +}); diff --git a/src/components/games/qubitCove/__tests__/gameFlow.test.tsx b/src/components/games/qubitCove/__tests__/gameFlow.test.tsx new file mode 100644 index 00000000..45a2015f --- /dev/null +++ b/src/components/games/qubitCove/__tests__/gameFlow.test.tsx @@ -0,0 +1,82 @@ +import { fireEvent, render, screen, within } from "@testing-library/react"; +import { expect, it, vi } from "vitest"; +import { enMock } from "@/test/i18nMock"; +import QubitCoveGame from "../QubitCoveGame"; + +vi.mock("react-i18next", () => enMock()); +vi.mock("../scene", () => ({ + createCoveRenderer: () => ({ draw: () => {} }), +})); + +const button = (name: string | RegExp) => screen.getByRole("button", { name }); +const click = (name: string | RegExp) => fireEvent.click(button(name)); + +function visit(name: string) { + click("Island map"); + click(new RegExp(`Ride to ${name}`)); + click("Use beacon"); +} + +it("accepts repeated chance outcomes, requires all three discoveries and retries a failed save", async () => { + const finish = vi + .fn() + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true); + const random = vi.spyOn(Math, "random").mockReturnValue(0.2); + try { + render(); + visit("Chance Harbor"); + for (let round = 0; round < 3; round++) { + click(round ? "Prepare a fresh qubit" : "Prepare qubit"); + click("Measure"); + } + const readings = within(screen.getByRole("dialog")).getAllByRole( + "listitem", + ); + expect(readings.map((item) => item.textContent)).toEqual(["0", "0", "0"]); + click("Only 0"); + expect(screen.getByText(/Look at how you set up/)).toBeVisible(); + click("0 or 1"); + click("Back to the cove"); + expect( + screen.queryByRole("button", { name: "Finish adventure" }), + ).toBeNull(); + for (const [name, answer] of [ + ["One Peak", "Only 1"], + ["Zero Garden", "Only 0"], + ]) { + visit(name); + click("Prepare qubit"); + click("Measure"); + click(answer); + click("Back to the cove"); + } + expect( + screen.getByRole("heading", { name: "The lighthouse is shining!" }), + ).toBeVisible(); + expect(finish).not.toHaveBeenCalled(); + click("Finish adventure"); + expect(await screen.findByRole("alert")).toHaveTextContent( + /could not be saved/, + ); + click("Finish adventure"); + expect( + await screen.findByRole("button", { name: /Adventure complete/i }), + ).toBeDisabled(); + expect(finish).toHaveBeenCalledTimes(2); + expect(finish.mock.calls[1][0]).toMatchObject({ + gameKey: "qubit_cove", + score: 3, + total: 3, + roundsCompleted: 3, + }); + click("Play again"); + expect( + screen.queryByRole("button", { name: "Finish adventure" }), + ).toBeNull(); + visit("Chance Harbor"); + expect(button("Prepare qubit")).toBeVisible(); + } finally { + random.mockRestore(); + } +}); diff --git a/src/components/games/qubitCove/coveHorizon.ts b/src/components/games/qubitCove/coveHorizon.ts new file mode 100644 index 00000000..04aee640 --- /dev/null +++ b/src/components/games/qubitCove/coveHorizon.ts @@ -0,0 +1,160 @@ +// Painted distant coast. Coordinates stay in the sky layer, with subtle parallax. +export function drawHorizon( + ctx: CanvasRenderingContext2D, + w: number, + h: number, + pan: number, +) { + const sky = ctx.createLinearGradient(0, 0, 0, h); + sky.addColorStop(0, "#76cddf"); + sky.addColorStop(0.29, "#bdeada"); + sky.addColorStop(0.47, "#e5efd0"); + sky.addColorStop(0.48, "#9bdcce"); + sky.addColorStop(0.72, "#78c9c1"); + sky.addColorStop(1, "#55b5b0"); + ctx.fillStyle = sky; + ctx.fillRect(0, 0, w, h); + const sunX = w * 0.76 - pan * 1.2, + sunY = h * 0.19; + const glow = ctx.createRadialGradient( + sunX, + sunY, + h * 0.035, + sunX, + sunY, + h * 0.29, + ); + glow.addColorStop(0, "#fff7cdac"); + glow.addColorStop(1, "#fff7cd00"); + ctx.fillStyle = glow; + ctx.fillRect(0, 0, w, h * 0.5); + ctx.fillStyle = "#fff2bd"; + ctx.beginPath(); + ctx.arc(sunX, sunY, h * 0.058, 0, Math.PI * 2); + ctx.fill(); + + const cloud = (cx: number, cy: number, size: number, alpha: number) => { + ctx.save(); + ctx.translate(cx, cy); + ctx.scale(size, size); + ctx.globalAlpha = alpha; + ctx.fillStyle = "#f4f6de"; + ctx.beginPath(); + ctx.moveTo(-56, 5); + ctx.bezierCurveTo(-61, -2, -53, -10, -44, -10); + ctx.bezierCurveTo(-43, -24, -26, -28, -17, -19); + ctx.bezierCurveTo(-9, -41, 16, -38, 21, -21); + ctx.bezierCurveTo(34, -29, 49, -17, 48, -8); + ctx.bezierCurveTo(66, -7, 69, 3, 55, 5); + ctx.bezierCurveTo(14, 11, -35, 11, -56, 5); + ctx.fill(); + ctx.restore(); + }; + cloud(w * 0.13 - pan * 2, h * 0.19, w * 0.00115, 0.9); + cloud(w * 0.44 - pan, h * 0.14, w * 0.00065, 0.68); + cloud(w * 0.89 - pan, h * 0.29, w * 0.00086, 0.76); + // Layers of flat-topped headlands, each with an illuminated face. + const ridges = ( + base: number, + amplitude: number, + color: string, + shift: number, + step: number, + ) => { + ctx.fillStyle = color; + ctx.beginPath(); + ctx.moveTo(-step, h * base); + for (let i = -2; i < Math.ceil(w / step) + 3; i++) { + const x = i * step + shift; + const v = + Math.abs(Math.sin(i * 3.7 + base * 39) * Math.cos(i * 5.74)) + 0.18; + const y = h * (base - amplitude * v); + ctx.lineTo(x - step * 0.45, h * base - 3); + ctx.lineTo(x - step * 0.13, y + step * 0.13); + ctx.lineTo(x + step * 0.04, y); + ctx.lineTo(x + step * 0.26, y + step * 0.1); + ctx.lineTo(x + step * 0.53, h * base); + } + ctx.lineTo(w + step, h * base + 0.8); + ctx.lineTo(-step, h * base + 0.8); + ctx.fill(); + }; + ridges(0.452, 0.128, "#a8d2bc", -pan * 0.7, w * 0.093); + ridges(0.466, 0.082, "#82bfad", -pan * 1.3 + w * 0.053, w * 0.078); + ctx.fillStyle = "#d7e4bd"; + ctx.fillRect(0, h * 0.472, w, h * 0.004); + const mesa = (x: number, y: number, s: number) => { + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + ctx.fillStyle = "#6ca99e"; + ctx.beginPath(); + ctx.moveTo(-31, 0); + ctx.lineTo(-23, -6); + ctx.lineTo(-17, -23); + ctx.lineTo(-12, -27); + ctx.lineTo(5, -28); + ctx.lineTo(12, -22); + ctx.lineTo(17, -10); + ctx.lineTo(32, 0); + ctx.fill(); + ctx.fillStyle = "#9dc3a3"; + ctx.beginPath(); + ctx.moveTo(-17, -23); + ctx.lineTo(-12, -28); + ctx.lineTo(5, -29); + ctx.lineTo(11, -24); + ctx.lineTo(-3, -22); + ctx.fill(); + ctx.strokeStyle = "#d6eacb"; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(-44, 1); + ctx.lineTo(38, 1); + ctx.stroke(); + ctx.restore(); + }; + mesa(w * 0.17 - pan * 1.8, h * 0.53, h * 0.005); + mesa(w * 0.9 - pan * 1.9, h * 0.51, h * 0.0036); + mesa(w * 0.58 - pan * 1.5, h * 0.49, h * 0.0027); + for (let i = 0; i < 94; i++) { + const r = ((i * 181 + 39) % 997) / 997; + const y = h * (0.49 + r * r * 0.5); + const x = + ((((i * 83.71 - pan * (0.2 + r) * 2.5) % (w + 70)) + w + 70) % (w + 70)) - + 35; + ctx.strokeStyle = i % 4 === 0 ? "#e0f2d5a8" : "#bbe5d27c"; + ctx.lineWidth = ((0.65 + r * 1.1) * h) / 500; + const len = ((4 + ((i * 47) % 23) * (r + 0.4)) * w) / 800; + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x + len, y); + ctx.stroke(); + } + // A tiny survey balloon over the bay. + const bx = w * 0.22 - pan * 2.2, + by = h * 0.29, + b = h * 0.042; + ctx.save(); + ctx.translate(bx, by); + ctx.scale(b, b); + ctx.strokeStyle = "#887e68"; + ctx.lineWidth = 0.054; + for (const sign of [-1, 1]) { + ctx.beginPath(); + ctx.moveTo(sign * 0.41, 0.64); + ctx.lineTo(sign * 0.18, 1.05); + ctx.stroke(); + } + ctx.fillStyle = "#d88872"; + ctx.beginPath(); + ctx.ellipse(0, -0.04, 0.6, 0.73, 0, 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = "#f1c49a"; + ctx.beginPath(); + ctx.ellipse(-0.03, -0.04, 0.25, 0.73, 0, 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = "#99826a"; + ctx.fillRect(-0.21, 1.03, 0.42, 0.22); + ctx.restore(); +} diff --git a/src/components/games/qubitCove/coveMesh.ts b/src/components/games/qubitCove/coveMesh.ts new file mode 100644 index 00000000..f70bb295 --- /dev/null +++ b/src/components/games/qubitCove/coveMesh.ts @@ -0,0 +1,175 @@ +// Small, flat-shaded meshes share the same perspective projection as the play field. +import type { Point } from "./world"; + +export interface Face { + points: Point[]; + color: string; +} +export type Mesh = Face[]; +export const point = (x: number, y: number, z: number): Point => ({ x, y, z }); +const TAU = Math.PI * 2; + +const tones = new Map(); +export function tint(hex: string, brightness: number) { + const key = hex + brightness.toFixed(2); + const cached = tones.get(key); + if (cached) return cached; + const n = parseInt(hex.slice(1), 16); + const channel = (v: number) => + Math.max(0, Math.min(255, Math.round(v * brightness))); + const color = `rgb(${channel(n >> 16)},${channel((n >> 8) & 255)},${channel(n & 255)})`; + tones.set(key, color); + return color; +} + +export function ring( + x: number, + y: number, + z: number, + rx: number, + rz: number, + sides: number, + angle = 0, +) { + return Array.from({ length: sides }, (_, i) => { + const a = angle + (i * TAU) / sides; + return point(x + rx * Math.cos(a), y, z + rz * Math.sin(a)); + }); +} + +export function band(mesh: Mesh, bottom: Point[], top: Point[], color: string) { + for (let i = 0; i < bottom.length; i++) { + const j = (i + 1) % bottom.length; + const dx = top[j].x - top[i].x; + const dz = top[j].z - top[i].z; + const length = Math.hypot(dx, dz); + const gain = length ? 0.88 + (0.15 * (-dz + 0.6 * -dx)) / length : 1; + mesh.push({ + points: [bottom[i], bottom[j], top[j], top[i]], + color: tint(color, gain), + }); + } +} + +export function drum( + mesh: Mesh, + x: number, + y: number, + z: number, + bottomX: number, + bottomZ: number, + height: number, + topX: number, + topZ: number, + color: string, + sides = 12, + angle = 0, + capColor = color, +) { + const bottom = ring(x, y, z, bottomX, bottomZ, sides, angle); + const top = ring(x, y + height, z, topX, topZ, sides, angle); + band(mesh, bottom, top, color); + if (topX > 0 && topZ > 0) mesh.push({ points: top, color: capColor }); +} + +export function box( + mesh: Mesh, + x: number, + y: number, + z: number, + width: number, + height: number, + depth: number, + color: string, + bevel = 0, +) { + const shape = (h: number, w: number, d: number) => { + const b = Math.min(bevel, w / 3, d / 3); + const corners = b + ? [ + [-w + b, -d], + [w - b, -d], + [w, -d + b], + [w, d - b], + [w - b, d], + [-w + b, d], + [-w, d - b], + [-w, -d + b], + ] + : [ + [-w, -d], + [w, -d], + [w, d], + [-w, d], + ]; + return corners.map(([cx, cz]) => point(x + cx, h, z + cz)); + }; + const bottom = shape(y, width / 2, depth / 2); + const top = shape(y + height, width / 2, depth / 2); + band(mesh, bottom, top, color); + mesh.push({ points: top, color: tint(color, 1.07) }); +} + +export function gem( + mesh: Mesh, + x: number, + y: number, + z: number, + rx: number, + ry: number, + rz: number, + color: string, + sides = 7, +) { + drum(mesh, x, y - ry, z, 0, 0, ry * 0.87, rx, rz, color, sides, 0.18); + drum( + mesh, + x, + y - 0.13 * ry, + z, + rx, + rz, + ry * 0.7, + rx * 0.82, + rz * 0.82, + color, + sides, + 0.18, + ); + drum( + mesh, + x, + y + 0.57 * ry, + z, + rx * 0.82, + rz * 0.82, + ry * 0.43, + rx * 0.24, + rz * 0.24, + color, + sides, + 0.18, + ); +} + +export function place( + mesh: Mesh, + x: number, + y: number, + z: number, + angle = 0, + size = 1, +): Mesh { + const c = Math.cos(angle), + s = Math.sin(angle); + return mesh.map((face) => ({ + color: face.color, + points: face.points.map((p) => + point( + x + size * (p.x * c + p.z * s), + y + size * p.y, + z + size * (-p.x * s + p.z * c), + ), + ), + })); +} diff --git a/src/components/games/qubitCove/coveModels.ts b/src/components/games/qubitCove/coveModels.ts new file mode 100644 index 00000000..ddc90a39 --- /dev/null +++ b/src/components/games/qubitCove/coveModels.ts @@ -0,0 +1,249 @@ +import type { BeaconId, Platform } from "./world"; +import { band, box, drum, gem, point, ring, type Mesh } from "./coveMesh"; + +const grass = { + hub: "#91cc70", + zero: "#72c7a2", + one: "#cac973", + mix: "#a4c381", +}; +const navy = "#284c63"; +const cream = "#f7e8c1"; +const brass = "#e8b75a"; + +export function island(p: Platform): Mesh { + const m: Mesh = []; + const { rx, rz, kind, theme } = p; + if (kind === "bridge") { + const alongX = rx > rz, + length = alongX ? rx : rz, + width = alongX ? rz : rx; + const planks = Math.ceil(length * 3.5); + const board = (length * 2) / planks; + for (let i = 0; i < planks; i++) { + const distance = -length + board * (i + 0.5); + box( + m, + alongX ? distance : 0, + -0.24, + alongX ? 0 : distance, + alongX ? board - 0.035 : 2 * width, + 0.24, + alongX ? 2 * width : board - 0.035, + i % 3 === 0 ? "#e9b77b" : "#d6a66e", + 0.045, + ); + } + for (const side of [-1, 1]) { + box( + m, + alongX ? 0 : side * width * 0.69, + -0.43, + alongX ? side * width * 0.69 : 0, + alongX ? length * 2 : 0.19, + 0.19, + alongX ? 0.19 : length * 2, + "#775f58", + ); + } + return m; + } + + const n = kind === "stone" ? 9 : 24; + const rockDepth = kind === "stone" ? 1.32 : Math.min(3.6, rz * 0.9); + const layer = (height: number, radius: number) => + ring(0, height, 0, rx * radius, rz * radius, n, 0.13); + const tip = layer(-rockDepth, 0.24); + const ridge = layer(-rockDepth * 0.6, 0.79); + const bezel = layer(-0.63, 0.956); + // Varied cliff seams stay below the exact flat collision footprint. + for (let i = 0; i < n; i++) { + const v = Math.sin(i * 13 + 4) * Math.cos(i * 42 + 2); + tip[i].y += v * 0.24; + ridge[i].y += v * 0.36; + ridge[i].x *= 1 + v * 0.08; + bezel[i].y += v * 0.07; + } + const top = layer(0, 1), + lip = layer(-0.19, 1), + earth = layer(-0.41, 0.985); + const cliff = ["#779596", "#729296", "#87a09c", "#6d8790", "#7c9292"]; + for (let i = 0; i < n; i++) { + const j = (i + 1) % n; + m.push({ points: [tip[i], tip[j], ridge[i]], color: cliff[(i + 2) % 5] }); + m.push({ points: [tip[j], ridge[j], ridge[i]], color: cliff[i % 5] }); + m.push({ + points: [ridge[i], ridge[j], bezel[j]], + color: cliff[(i + 3) % 5], + }); + m.push({ + points: [ridge[i], bezel[j], bezel[i]], + color: cliff[(i + 4) % 5], + }); + } + band(m, bezel, earth, "#ac9379"); + band(m, earth, lip, "#dfc28f"); + band(m, lip, top, "#7daa64"); + m.push({ points: top, color: grass[theme] }); + return m; +} + +export function fern(): Mesh { + const m: Mesh = []; + for (let i = 0; i < 6; i++) { + const a = i * 2.4; + const x = Math.cos(a) * 0.38, + z = Math.sin(a) * 0.38; + m.push({ + points: [ + point(-z * 0.23, 0.02, x * 0.23), + point(x * 0.66, 0.36, z * 0.66), + point(x, 0.53 + (i % 2) * 0.16, z), + point(x * 0.7, 0.19, z * 0.7), + point(z * 0.2, 0.02, -x * 0.2), + ], + color: i % 2 ? "#349e70" : "#66b875", + }); + } + return m; +} + +export function tree(variant: number): Mesh { + const m: Mesh = []; + drum(m, 0, 0, 0, 0.14, 0.14, 1.04, 0.1, 0.1, "#966d51", 7); + if (variant === 0) { + gem(m, 0, 1.48, 0, 0.64, 0.79, 0.6, "#439f81", 7); + gem(m, -0.22, 1.81, 0.13, 0.44, 0.51, 0.42, "#63ba82"); + } else if (variant === 1) { + drum(m, 0, 0.6, 0, 0.65, 0.59, 1.05, 0.1, 0.1, "#338f82", 7); + drum(m, 0, 1.21, 0, 0.47, 0.46, 0.99, 0, 0, "#5db69a", 7); + } else { + gem(m, 0, 1.42, 0, 0.65, 0.65, 0.6, "#65af8b", 8); + gem(m, -0.35, 1.57, 0.12, 0.4, 0.44, 0.39, "#88c38c"); + gem(m, 0.17, 1.95, -0.03, 0.42, 0.52, 0.42, "#65b68b"); + } + return m; +} + +export function beaconBody(id: BeaconId, lit: boolean): Mesh { + const m: Mesh = []; + // Each beacon has a different silhouette and the same brass lamp housing. + if (id === "mix") { + drum(m, 0, 0, 0, 1.07, 0.96, 0.22, 1.02, 0.91, navy); + drum(m, 0, 0.22, 0, 0.86, 0.75, 0.88, 0.72, 0.64, cream); + drum(m, 0, 1.1, 0, 0.72, 0.64, 0.43, 0.65, 0.58, "#de7053"); + drum(m, 0, 1.53, 0, 0.65, 0.58, 0.96, 0.5, 0.46, cream); + drum(m, 0, 2.49, 0, 0.58, 0.54, 0.15, 0.63, 0.57, navy); + drum( + m, + 0, + 2.64, + 0, + 0.47, + 0.43, + 0.67, + 0.47, + 0.43, + lit ? "#fff09b" : "#87d9dc", + 8, + ); + for (const s of [-1, 1]) { + box(m, s * 0.38, 2.65, 0.22, 0.07, 0.67, 0.07, navy); + box(m, s * 0.38, 2.65, -0.22, 0.07, 0.67, 0.07, navy); + } + drum(m, 0, 3.31, 0, 0.77, 0.71, 0.52, 0.12, 0.1, "#db7950", 10); + gem(m, 0, 3.98, 0, 0.13, 0.2, 0.13, brass, 6); + box(m, 0, 0.24, 0.67, 0.43, 0.63, 0.15, navy, 0.06); + for (const side of [-1, 1]) { + box(m, side * 0.3, 1.85, 0.45, 0.15, 0.26, 0.09, navy, 0.025); + } + } else if (id === "zero") { + drum(m, 0, 0, 0, 0.85, 0.75, 0.2, 0.85, 0.75, navy); + drum(m, 0, 0.2, 0, 0.71, 0.62, 0.89, 0.56, 0.5, "#73c5b9", 10); + drum(m, 0, 1.09, 0, 0.69, 0.62, 0.16, 0.64, 0.58, cream, 10); + box(m, 0, 1.25, 0, 0.38, 0.64, 0.38, navy, 0.06); + for (const side of [-1, 1]) { + box(m, side * 0.51, 0.81, 0, 0.14, 1.08, 0.22, brass, 0.045); + gem(m, side * 0.51, 1.94, 0, 0.14, 0.19, 0.14, cream, 7); + } + gem(m, 0, 1.94, 0, 0.43, 0.51, 0.39, lit ? "#fff2a5" : "#72efdc", 8); + drum(m, 0, 2.38, 0, 0.13, 0.13, 0.15, 0.07, 0.07, brass, 8); + } else { + drum(m, 0, 0, 0, 0.94, 0.76, 0.2, 0.9, 0.73, navy, 9); + drum(m, 0, 0.2, 0, 0.71, 0.59, 0.65, 0.66, 0.57, "#e3ad76", 8); + drum(m, 0, 0.85, 0, 0.72, 0.6, 0.17, 0.72, 0.6, navy, 8); + drum(m, 0, 1.02, 0, 0.5, 0.45, 0.71, 0.4, 0.39, "#ec8059", 8); + drum(m, 0, 1.73, 0, 0.49, 0.44, 0.16, 0.52, 0.45, cream, 8); + gem(m, 0, 2.19, 0, 0.39, 0.51, 0.38, lit ? "#fff2a5" : "#ffcc69", 8); + for (const side of [-1, 1]) { + const x = side * 0.85; + box(m, x * 0.72, 0.4, -0.08, 0.1, 0.7, 0.13, navy); + box(m, x, 1.06, -0.08, 0.65, 0.13, 0.64, "#567f9a", 0.06); + for (const edge of [-0.24, 0, 0.24]) + box(m, x + edge, 1.193, -0.08, 0.025, 0.015, 0.6, "#c3dcce"); + } + } + return m; +} + +export function robot(walk: number, walking: boolean, air: boolean): Mesh { + const m: Mesh = []; + // Two boots and articulated arms make running legible at classroom-screen sizes. + const stride = walking && !air ? Math.sin(walk) : 0; + const bob = walking && !air ? Math.abs(Math.cos(walk)) * 0.055 : 0; + for (const s of [-1, 1]) { + const forward = stride * s * 0.23 + (air ? s * 0.09 : 0); + box( + m, + s * 0.22, + 0.025 + (air ? 0.1 : 0), + 0.05 + forward, + 0.34, + 0.24, + 0.46, + "#dc714c", + 0.07, + ); + box(m, s * 0.22, 0.21, forward * 0.6, 0.19, 0.28, 0.22, navy, 0.035); + const armY = 0.47 + bob + (air ? 0.36 : 0); + box(m, s * 0.54, armY, -forward * 0.74, 0.18, 0.36, 0.2, "#508587", 0.04); + gem( + m, + s * (air ? 0.63 : 0.55), + armY - 0.015, + -forward * 0.85 + 0.02, + 0.15, + 0.145, + 0.15, + "#dd9758", + 6, + ); + } + box(m, 0, 0.43 + bob, -0.23, 0.67, 0.6, 0.26, "#ab634a", 0.09); + box(m, 0, 0.53 + bob, -0.38, 0.42, 0.35, 0.13, brass, 0.04); + box(m, 0, 0.45 + bob, 0.02, 0.81, 0.67, 0.58, "#50adab", 0.12); + box(m, 0, 0.51 + bob, 0.3, 0.38, 0.36, 0.07, cream, 0.04); + box(m, 0, 0.71 + bob, 0.34, 0.18, 0.07, 0.04, "#e1a858"); + box(m, 0, 0.98 + bob, 0.025, 0.8, 0.13, 0.58, "#e78354", 0.1); + box(m, 0.31, 0.76 + bob, 0.23, 0.17, 0.26, 0.13, "#e78354", 0.03); + box(m, 0, 1.14 + bob, 0, 1.11, 0.65, 0.78, cream, 0.13); + box(m, 0, 1.23 + bob, 0.395, 0.86, 0.42, 0.11, "#254b5c", 0.06); + for (const side of [-1, 1]) { + box(m, side * 0.214, 1.39 + bob, 0.455, 0.12, 0.16, 0.03, "#aff8e5", 0.014); + box( + m, + side * 0.555, + 1.32 + bob, + -0.015, + 0.105, + 0.23, + 0.31, + "#338b94", + 0.03, + ); + } + box(m, 0, 1.78 + bob, -0.04, 0.75, 0.08, 0.56, "#81c4b6", 0.09); + box(m, 0.28, 1.82 + bob, -0.1, 0.066, 0.25, 0.066, navy); + gem(m, 0.28, 2.08 + bob, -0.1, 0.117, 0.135, 0.117, "#ffd065", 7); + return m; +} diff --git a/src/components/games/qubitCove/engine.ts b/src/components/games/qubitCove/engine.ts new file mode 100644 index 00000000..63de1067 --- /dev/null +++ b/src/components/games/qubitCove/engine.ts @@ -0,0 +1,206 @@ +import { + beaconLanding, + beacons, + contains, + pickups, + platforms, + spawn, + type BeaconId, + type Point, + type Platform, +} from "./world"; + +export interface GameInput { + x: number; + z: number; + jump: boolean; +} + +export interface GameState { + player: Point; + facing: number; + grounded: boolean; + moving: boolean; + collected: readonly string[]; + lit: readonly BeaconId[]; + checkpoint: "hub" | BeaconId; + rescues: number; + verticalSpeed: number; + jumpHeld: boolean; + jumpBuffer: number; + normalJump: boolean; + cometJump: boolean; + cometTime: number; + cometWindow: number; + coyote: number; + remainder: number; +} + +const TICK = 1 / 120; +const WALK_SPEED = 5.9; +const GRAVITY = 24; +const JUMP_SPEED = 8.9; +const COMET_SPEED = 10.5; +const COMET_WINDOW = 0.3; +const LEDGE_GRACE = 0.15; +const STEP_HEIGHT = 0.14; + +export function createGame(): GameState { + return { + player: { ...spawn }, + facing: 0, + grounded: true, + moving: false, + collected: [], + lit: [], + checkpoint: "hub", + rescues: 0, + verticalSpeed: 0, + jumpHeld: false, + jumpBuffer: 0, + normalJump: false, + cometJump: false, + cometTime: 0, + cometWindow: 0, + coyote: LEDGE_GRACE, + remainder: 0, + }; +} + +function placePlayer(state: GameState, checkpoint: GameState["checkpoint"]) { + state.player = + checkpoint === "hub" ? { ...spawn } : beaconLanding(checkpoint); + state.checkpoint = checkpoint; + state.facing = checkpoint === "hub" ? 0 : Math.PI; + state.grounded = true; + state.moving = false; + state.verticalSpeed = 0; + state.jumpBuffer = 0; + state.normalJump = false; + state.cometJump = false; + state.cometTime = 0; + state.cometWindow = 0; + state.coyote = LEDGE_GRACE; +} + +export function guideToBeacon(state: GameState, id: BeaconId): GameState { + const next = { ...state, remainder: 0 }; + placePlayer(next, id); + return next; +} + +export function nearbyBeacon(state: GameState): BeaconId | null { + if (!state.grounded) return null; + const { x, y, z } = state.player; + return ( + beacons.find( + (beacon) => + Math.abs(y - beacon.y) < STEP_HEIGHT && + Math.hypot(x - beacon.x, z - beacon.z) <= 1.85, + )?.id ?? null + ); +} + +export function lightBeacon(state: GameState, id: BeaconId): GameState { + if (state.lit.includes(id) || nearbyBeacon(state) !== id) return state; + return { ...state, lit: [...state.lit, id] }; +} + +function tick(state: GameState, dx: number, dz: number) { + const p = state.player; + const previousY = p.y; + if (state.grounded) state.coyote = LEDGE_GRACE; + if (state.jumpBuffer > 0 && state.coyote > 0) { + state.cometJump = state.cometWindow > 0 && (dx !== 0 || dz !== 0); + state.normalJump = !state.cometJump; + state.verticalSpeed = state.cometJump ? COMET_SPEED : JUMP_SPEED; + state.cometWindow = 0; + state.grounded = false; + state.jumpBuffer = 0; + state.coyote = 0; + } + state.cometWindow = Math.max(0, state.cometWindow - TICK); + if (state.cometJump) state.cometTime += TICK; + state.coyote = Math.max(0, state.coyote - TICK); + state.jumpBuffer = Math.max(0, state.jumpBuffer - TICK); + state.verticalSpeed -= GRAVITY * TICK; + const nextY = p.y + state.verticalSpeed * TICK; + const maxStep = state.grounded ? STEP_HEIGHT : 0.001; + const canEnter = (x: number, z: number) => + !platforms.some( + (surface) => + surface.y > Math.max(previousY, nextY) + maxStep && + contains(surface, x, z) && + !contains(surface, p.x, p.z), + ); + + // Resolve axes separately so a diagonal approach can slide along a ledge. + const previousX = p.x; + const previousZ = p.z; + if (dx && canEnter(p.x + dx, p.z)) p.x += dx; + if (dz && canEnter(p.x, p.z + dz)) p.z += dz; + state.moving = previousX !== p.x || previousZ !== p.z; + if (dx || dz) state.facing = Math.atan2(dx, dz); + + let floor: Platform | undefined; + if (state.verticalSpeed <= 0) { + for (const surface of platforms) { + if ( + contains(surface, p.x, p.z) && + surface.y <= previousY + maxStep && + surface.y >= nextY && + (!floor || floor.y < surface.y) + ) + floor = surface; + } + } + state.grounded = Boolean(floor); + if (floor) { + if (state.normalJump) state.cometWindow = COMET_WINDOW; + state.normalJump = false; + state.cometJump = false; + state.cometTime = 0; + p.y = floor.y; + state.verticalSpeed = 0; + if (floor.kind === "island") state.checkpoint = floor.theme; + } else { + p.y = nextY; + } + + if (p.y < -3.5) { + state.rescues += 1; + placePlayer(state, state.checkpoint); + return; + } + + for (const pickup of pickups) { + if ( + Math.abs(p.y + 0.6 - pickup.y) < 1.0 && + Math.hypot(p.x - pickup.x, p.z - pickup.z) < 0.72 && + !state.collected.includes(pickup.id) + ) { + state.collected = [...state.collected, pickup.id]; + } + } +} + +/** Simulate elapsed seconds on fixed ticks. Clamp a resumed/background frame. */ +export function stepGame( + state: GameState, + input: GameInput, + dt: number, +): GameState { + if (!Number.isFinite(dt) || dt <= 0) return state; + const next: GameState = { ...state, player: { ...state.player } }; + const strength = Math.max(1, Math.hypot(input.x, input.z)); + const dx = (input.x / strength) * WALK_SPEED * TICK; + const dz = (input.z / strength) * WALK_SPEED * TICK; + if (input.jump && !state.jumpHeld) next.jumpBuffer = 0.14; + next.jumpHeld = input.jump; + next.remainder += Math.min(dt, 0.1); + while (next.remainder + 1e-10 >= TICK) { + tick(next, dx, dz); + next.remainder = Math.max(0, next.remainder - TICK); + } + return next; +} diff --git a/src/components/games/qubitCove/qubitCove.css b/src/components/games/qubitCove/qubitCove.css new file mode 100644 index 00000000..80eb17b3 --- /dev/null +++ b/src/components/games/qubitCove/qubitCove.css @@ -0,0 +1,753 @@ +.qc-game, +.qc-dialog { + --qc-ink: #162f47; + --qc-night: #0d293f; + --qc-mint: #60e3c6; + --qc-paper: #fff9e8; + --qc-accent: #ffca65; + color: var(--qc-ink); + font-family: "Nunito", ui-rounded, "Trebuchet MS", system-ui, sans-serif; + line-height: 1.35; +} +.qc-game { + max-width: 1010px; + margin: 0 auto; + padding: clamp(8px, 1.3vw, 15px); + border: 2px solid #0e2637; + border-radius: 26px; + background: linear-gradient(120deg, #193c50, #112b3e 55%, #103548); + box-shadow: + 0 7px 0 #0a2131, + 0 14px 25px #16354124; +} +.qc-game button, +.qc-dialog button { + cursor: pointer; + font-family: inherit; + font-weight: 800; + -webkit-tap-highlight-color: transparent; +} +.qc-game button:focus-visible, +.qc-dialog button:focus-visible, +.qc-game canvas:focus-visible, +.qc-dialog input:focus-visible { + outline: 3px solid #f0983c; + outline-offset: 2px; +} +.qc-game button:disabled { + opacity: 0.65; + cursor: default; +} +.qc-header, +.qc-wordmark, +.qc-tools, +.qc-controls, +.qc-hud, +.qc-counter, +.qc-interact, +.qc-victory-title, +.qc-victory-actions, +.qc-dialog-title, +.qc-dialog .qc-primary, +.qc-victory .qc-primary, +.qc-replay, +.qc-readings, +.qc-readings ol, +.qc-choices, +.qc-map-button { + display: flex; + align-items: center; +} +.qc-header { + justify-content: space-between; + gap: 12px; + padding: 2px 4px 13px; + color: var(--qc-paper); +} +.qc-wordmark, +.qc-tools { + gap: 10px; +} +.qc-wordmark { + min-width: 0; +} +.qc-emblem, +.qc-place-icon, +.qc-map-token, +.qc-victory-title > span { + display: grid; + place-items: center; + flex: none; +} +.qc-emblem { + width: 46px; + height: 46px; + color: #ffe290; + background: #214758; + border: 1px solid #9dbbae66; + box-shadow: inset 0 0 0 3px #17364b; + border-radius: 16px; +} +.qc-emblem svg { + width: 30px; + height: 30px; +} +.qc-wordmark h2 { + margin: 0; + font-size: clamp(23px, 3vw, 34px); + font-weight: 900; + line-height: 1.04; + letter-spacing: -0.04em; +} +.qc-wordmark p { + margin: 4px 0 0; + color: #d3e8e7; + font-size: clamp(14px, 1.4vw, 17px); + font-weight: 600; +} +.qc-tools { + flex-shrink: 0; + gap: 6px; +} +.qc-tools button, +.qc-interact { + height: auto; + min-height: 44px; + padding: 8px 14px; + border: 1px solid #ffffff20; + border-radius: 13px; +} +.qc-map-button { + gap: 8px; + color: #153747; + background: var(--qc-accent); + box-shadow: inset 0 -3px 0 #84522235; +} +.qc-tools .qc-help-button { + display: grid; + place-items: center; + width: 44px; + padding: 0; + color: #fff9e8; + background: #235064; +} +.qc-map-button:hover, +.qc-interact:hover, +.qc-dialog .qc-primary:hover { + filter: brightness(1.06); +} +.qc-stage { + position: relative; + isolation: isolate; + overflow: hidden; + width: 100%; + border: 2px solid #0b2434; + border-radius: 17px; + background: #7ad8e6; +} +.qc-stage canvas { + display: block; + width: 100%; + height: auto; + aspect-ratio: 1.9; + border-radius: inherit; +} +.qc-game canvas:focus-visible { + outline-offset: -5px; +} +.qc-hud { + position: absolute; + top: 12px; + left: 12px; + gap: 6px; + pointer-events: none; +} +.qc-counter { + gap: 5px; + min-height: 34px; + padding: 4px 10px; + border: 1px solid #fff6; + border-radius: 12px; + background: #102d45e8; + color: #fff; + font-size: 19px; + font-variant-numeric: tabular-nums; +} +.qc-counter svg { + width: 21px; + height: 21px; + color: #fcd173; + stroke-width: 2.4; +} +.qc-crystals svg { + color: #83f8dd; +} +.qc-counter small { + font-size: 0.75em; + color: #dfeded; +} +.qc-interact { + position: absolute; + bottom: 12px; + left: 50%; + transform: translateX(-50%); + gap: 8px; + white-space: nowrap; + font-size: 17px; + color: #113947; + background: #fff5d0; + box-shadow: + 0 3px 0 #314a53, + 0 5px 15px #20394e45; +} +.qc-interact kbd { + padding: 1px 5px; + font-size: 0.8em; + border-radius: 4px; + border: 1px solid #86979c; +} +.qc-controls { + justify-content: space-between; + gap: 10px; + padding: 10px 9px 0; + color: var(--qc-paper); +} +.qc-pad { + display: grid; + flex: none; + grid-template: repeat(2, 44px) / repeat(3, 46px); + gap: 2px; +} +.qc-control { + display: grid; + place-items: center; + min-width: 44px; + min-height: 44px; + user-select: none; + touch-action: none; + border: 1px solid #ffffff40; + border-radius: 11px; + color: #fffefa; + background: #2c5466; + box-shadow: inset 0 -3px 0 #162b3d80; +} +.qc-control svg { + width: 20px; + height: 20px; + stroke-width: 3; +} +.qc-control:active { + background: #45798a; + box-shadow: inset 0 2px 0 #162b3d80; +} +.qc-up { + grid-area: 1 / 2; +} +.qc-left { + grid-area: 2 / 1; +} +.qc-down { + grid-area: 2 / 2; +} +.qc-right { + grid-area: 2 / 3; +} +.qc-control.qc-jump { + display: flex; + justify-content: center; + align-items: center; + gap: 5px; + min-height: 52px; + min-width: 88px; + max-width: 45%; + padding: 10px 15px; + border: 2px solid #beeedd; + border-radius: 20px; + font-size: 18px; + line-height: 1.1; + color: #103b43; + background: #7ae8c8; + box-shadow: + inset 0 -4px 0 #155a603b, + 0 3px 0 #092637; +} +.qc-jump:active { + transform: translateY(2px); +} +.qc-key-hint { + display: flex; + align-items: center; + gap: 10px; + max-width: 320px; + margin: 0; + color: #d5e7e8; + font-size: 15px; + font-weight: 600; +} +.qc-key-hint svg { + width: 26px; + flex: none; + color: #83dcca; +} +.qc-victory { + padding: 14px; + margin-top: 8px; + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: space-between; + background: var(--qc-paper); + border-radius: 14px; +} +.qc-victory-title { + gap: 8px; +} +.qc-victory-title > span { + color: #176755; +} +.qc-victory h3 { + font-size: clamp(19px, 2.5vw, 25px); + font-weight: 900; + letter-spacing: -0.025em; + margin: 0; +} +.qc-victory p { + width: 100%; + margin: 0; + color: #9b321e; +} +.qc-victory-actions { + flex-wrap: wrap; + gap: 8px; +} +.qc-primary, +.qc-replay { + justify-content: center; + gap: 8px; + min-height: 48px; + padding: 10px 15px; + border-radius: 12px; + font-size: 17px; +} +.qc-primary { + background: #126453; + color: white; + box-shadow: inset 0 -3px 0 #073b3450; +} +.qc-primary svg, +.qc-replay svg { + width: 20px; + height: 20px; +} +.qc-replay { + border: 1px solid #829c91; + background: white; + color: #21494a; +} +.qc-scrim { + position: fixed; + inset: 0; + z-index: 60; + background: #061e32ae; +} +.qc-dialog { + position: fixed; + z-index: 61; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: min(440px, calc(100vw - 24px)); + max-height: min(86dvh, 720px); + overflow-y: auto; + overscroll-behavior: contain; + padding: clamp(17px, 4vw, 26px); + background: var(--qc-paper); + border: 2px solid #173a47; + border-radius: 24px; + box-shadow: + 0 7px 0 #173a47, + 0 14px 60px #071c3366; +} +.qc-dialog-title { + min-height: 45px; + gap: 10px; + padding-right: 36px; +} +.qc-dialog-title h2 { + margin: 0; + color: var(--qc-ink); + font-size: clamp(22px, 4.2vw, 30px); + font-weight: 900; + line-height: 1.12; + letter-spacing: -0.045em; +} +.qc-dialog p { + color: #345263; + font-size: 17px; + font-weight: 650; + margin: 10px 0; +} +.qc-dialog .qc-x { + position: absolute; + top: 10px; + right: 10px; + width: 44px; + height: 44px; + display: grid; + place-items: center; + color: #304957; + border-radius: 14px; +} +.qc-dialog .qc-x:hover { + background: #e3e6d9; +} +.qc-place-icon, +.qc-map-token { + width: 43px; + height: 43px; + border-radius: 13px; + background: #d3ede1; + color: #197050; +} +[data-beacon="one"] .qc-place-icon, +[data-beacon="one"] .qc-map-token { + background: #ffe1ad; + color: #94511e; +} +[data-beacon="mix"] .qc-place-icon, +[data-beacon="mix"] .qc-map-token { + background: #e8defd; + color: #694194; +} +.qc-itinerary { + display: grid; + gap: 8px; + margin-top: 18px; +} +.qc-itinerary button { + display: flex; + align-items: center; + gap: 10px; + min-height: 66px; + padding: 6px 12px 6px 8px; + border: 1px solid #b0c2b6; + border-radius: 14px; + background: white; + color: #1c4250; + text-align: start; + font-size: 18px; +} +.qc-itinerary button:hover, +.qc-choices button:hover { + background: #f1f6e9; + border-color: #215e58; +} +.qc-map-mark { + display: grid; + place-items: center; + margin-left: auto; + font-size: 15px; + color: #316651; +} +.qc-itinerary button > svg { + width: 16px; + flex: none; +} +.qc-help-body p { + display: flex; + align-items: flex-start; + gap: 10px; + margin: 14px 0; +} +.qc-help-body p svg { + width: 20px; + flex: none; + margin-top: 2px; + color: #286859; +} +.qc-help-body label { + display: flex; + align-items: center; + gap: 10px; + min-height: 48px; + margin-top: 12px; + font-size: 17px; + font-weight: 800; + border-top: 1px solid #b7c6ba; +} +.qc-help-body input { + width: 20px; + height: 20px; + accent-color: #176953; +} +.qc-instrument { + margin-top: 16px; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 13px; + padding: 15px; + border-radius: 16px; + color: #fff; + background: radial-gradient(ellipse at top left, #2d6671, #194458 66%); +} +.qc-lab-copy { + flex: 1 1 150px; +} +.qc-dialog .qc-instrument p { + margin: 0 0 6px; + color: white; + font-size: 18px; + font-weight: 750; +} +.qc-instrument-rim { + display: grid; + place-items: center; + position: relative; + width: 74px; + height: 74px; + flex: none; + border-radius: 50%; + background: #113448; + border: 2px solid #64b4ad; + box-shadow: 0 0 0 3px #183f51; +} +.qc-instrument-rim i { + position: absolute; + inset: 10px; + border: 1px solid #64d6c5; + border-radius: 50%; + transform: rotate(28deg) scaleX(0.57); +} +.qc-instrument-rim i:nth-child(2) { + transform: rotate(-28deg) scaleX(0.57); +} +.qc-instrument-rim i:nth-child(3) { + transform: rotate(90deg) scaleX(0.57); +} +.qc-instrument-rim b { + z-index: 1; + text-shadow: 0 2px 5px #113044; + font: + 900 26px/1 ui-rounded, + system-ui, + sans-serif; + color: #ffdf89; +} +.qc-instrument[data-ready="true"] b { + color: #98ffe4; +} +.qc-instrument[data-lit="true"] b { + color: #ffe38a; +} +.qc-instrument[data-ready="true"] .qc-instrument-rim { + animation: qc-ready 1.5s ease-in-out infinite alternate; +} +@keyframes qc-ready { + to { + box-shadow: 0 0 0 4px #a8f2d743; + } +} +.qc-readings { + justify-content: space-between; + flex-wrap: wrap; + gap: 8px; + margin-top: 12px; + font-size: 17px; + font-weight: 800; +} +.qc-readings ol { + list-style: none; + padding: 0; + margin: 0; + gap: 5px; +} +.qc-readings li { + display: grid; + place-items: center; + min-width: 35px; + height: 36px; + font-size: 22px; + border-radius: 10px; + background: #eaece2; + border: 1px dashed #7c9c94; +} +.qc-readings li[data-full="true"] { + background: #d7efdf; + color: #184d44; + border: 1px solid #9bb9a8; +} +.qc-dialog .qc-lab-status { + margin: 8px 0; + font-weight: 800; + color: #165e50; +} +.qc-lab .qc-primary { + width: 100%; + margin-top: 12px; +} +.qc-question h3 { + font-size: 19px; + font-weight: 850; + line-height: 1.25; + margin: 14px 0 8px; +} +.qc-choices { + flex-wrap: wrap; + gap: 6px; +} +.qc-choices button { + flex: 1 1 85px; + min-height: 48px; + color: var(--qc-ink); + border: 1px solid #98ad9f; + background: white; + border-radius: 12px; + padding: 6px; + font-size: 17px; +} +.qc-question p { + color: #843e1a; +} +.qc-dialog[data-reduced="true"] * { + animation-duration: 0s !important; +} +@media (max-width: 660px) { + .qc-wordmark { + gap: 8px; + } + .qc-emblem { + width: 37px; + height: 37px; + border-radius: 12px; + } + .qc-emblem svg { + width: 25px; + height: 25px; + } + .qc-key-hint { + display: none; + } + .qc-stage canvas { + aspect-ratio: 1.43; + } + .qc-hud { + left: 7px; + top: 7px; + } + .qc-controls { + padding: 8px 3px 0; + } + .qc-header { + flex-wrap: wrap; + gap: 8px; + padding: 2px 2px 9px; + } + .qc-tools { + margin-left: auto; + } +} +@media (max-width: 520px) { + .qc-game { + margin-inline: -15px; + border-radius: 20px; + } + .qc-header { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: start; + } + .qc-wordmark { + display: contents; + } + .qc-wordmark > div { + display: contents; + } + .qc-wordmark h2 { + grid-column: 1; + grid-row: 1; + align-self: center; + padding-left: 3px; + } + .qc-wordmark p { + grid-column: 1 / -1; + grid-row: 2; + margin: 0 3px; + line-height: 1.25; + } + .qc-emblem { + display: none; + } + .qc-tools { + grid-column: 2; + grid-row: 1; + gap: 4px; + } + .qc-tools button { + padding-inline: 8px; + font-size: 14px; + } + .qc-tools svg { + width: 18px; + height: 18px; + } + .qc-tools .qc-help-button { + width: 44px; + } + .qc-map-button { + gap: 4px; + max-width: 127px; + } + .qc-stage { + border-radius: 12px; + } + .qc-stage canvas { + aspect-ratio: 1.12; + } + .qc-interact kbd { + display: none; + } + .qc-counter { + min-height: 29px; + font-size: 15px; + padding: 3px 6px; + } + .qc-counter svg { + width: 16px; + height: 16px; + } + .qc-victory-actions { + width: 100%; + } +} +@media (max-width: 365px) { + .qc-tools { + max-width: 143px; + } + .qc-wordmark h2 { + font-size: 21px; + } + .qc-header { + column-gap: 3px; + } + .qc-control.qc-jump { + min-width: 70px; + padding-inline: 5px; + } +} +@media (prefers-reduced-motion: reduce) { + .qc-dialog * { + animation-duration: 0s !important; + } +} + +.qc-game[data-reduced="false"] .qc-spark-gain { + animation: qc-pickup 0.35s ease-out; +} +@keyframes qc-pickup { + 40% { + transform: scale(1.42) rotate(-12deg); + color: #fff4bd; + } +} diff --git a/src/components/games/qubitCove/readAloud.css b/src/components/games/qubitCove/readAloud.css new file mode 100644 index 00000000..a5be4abc --- /dev/null +++ b/src/components/games/qubitCove/readAloud.css @@ -0,0 +1,20 @@ +.qubit-read-aloud { + display: inline-flex; + min-height: 44px; + align-items: center; + justify-content: center; + gap: 0.4em; + padding: 0.4em 0.8em; + border: 1px solid #94b6bc; + border-radius: 999px; + color: #194d56; + background: #f2fcfa; + font: inherit; + font-weight: 700; + cursor: pointer; +} + +.qubit-read-aloud:focus-visible { + outline: 3px solid #1a6977; + outline-offset: 2px; +} diff --git a/src/components/games/qubitCove/scene.ts b/src/components/games/qubitCove/scene.ts new file mode 100644 index 00000000..84cfbd49 --- /dev/null +++ b/src/components/games/qubitCove/scene.ts @@ -0,0 +1,674 @@ +import type { GameState } from "./engine"; +import { + beacons, + contains, + pickups, + platforms, + spawn, + type Beacon, + type Platform, + type Point, +} from "./world"; +import { box, gem, place, point, type Mesh } from "./coveMesh"; +import { beaconBody, fern, island, robot, tree } from "./coveModels"; +import { drawHorizon } from "./coveHorizon"; + +const TAU = Math.PI * 2; +const flatten = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.z - b.z); +interface ScenicObject { + mesh: Mesh; + anchor: Point; + radius: number; +} + +function buildGarden() { + const objects: ScenicObject[] = []; + const add = ( + mesh: Mesh, + x: number, + y: number, + z: number, + scale: number, + angle: number, + radius: number, + ) => { + objects.push({ + mesh: place(mesh, x, y, z, angle, scale), + anchor: point(x, y, z), + radius: radius * scale, + }); + }; + for (const p of platforms.filter((p) => p.kind === "island")) { + const plants = + p.theme === "hub" + ? [ + [-0.75, -0.47, 0.9], + [0.72, -0.51, 1.06], + [-0.75, 0.45, 0.62], + [0.69, 0.56, 0.7], + ] + : [ + [-0.63, -0.46, 0.8], + [0.66, -0.45, 0.92], + [0.7, 0.35, 0.56], + ]; + plants.forEach(([x, z, s], i) => + add( + tree((i + (p.theme === "one" ? 1 : 0)) % 3), + p.x + x * p.rx, + p.y, + p.z + z * p.rz, + s, + i, + 0.5, + ), + ); + for (let i = 0; i < 13; i++) { + const a = i * 2.4 + 0.35; + const x = p.x + Math.cos(a) * p.rx * 0.84, + z = p.z + Math.sin(a) * p.rz * 0.84; + if (p.theme === "hub" && (Math.abs(z) < 0.76 || Math.abs(x) < 0.73)) + continue; + const m: Mesh = []; + if (i % 4 === 0) { + gem(m, 0, 0.14, 0, 0.29, 0.18, 0.21, "#a7b4a3", 6); + gem(m, 0.25, 0.08, 0.09, 0.15, 0.1, 0.14, "#bdc6af", 6); + } else if (i % 3 === 0) m.push(...fern()); + else { + for (let j = 0; j < 3; j++) { + const xx = Math.cos(j * 2.4 + i) * 0.14, + zz = Math.sin(j * 2.4) * 0.16; + box(m, xx, 0, zz, 0.035, 0.14, 0.035, "#47875e"); + gem( + m, + xx, + 0.18, + zz, + 0.085, + 0.07, + 0.08, + i % 2 === 0 ? "#fff2bc" : "#f99985", + 5, + ); + } + } + add(m, x, p.y, z, 0.91 + (i % 4) * 0.1, a, 0.21); + } + } + return objects; +} + +export function createCoveRenderer(canvas: HTMLCanvasElement) { + const ctx = canvas.getContext("2d", { alpha: false }); + if (!ctx) return { draw: () => {} }; + const g = ctx; + const terrain = platforms.map((p) => ({ + p, + mesh: place(island(p), p.x, p.y, p.z), + })); + const decor = buildGarden(); + const stations = beacons.map((b) => ({ + b, + unlit: place(beaconBody(b.id, false), b.x, b.y, b.z), + lit: place(beaconBody(b.id, true), b.x, b.y, b.z), + })); + const standingRobot = robot(0, false, false); + const airborneRobot = robot(0, false, true); + const crystal: Mesh = []; + gem(crystal, 0, 0, 0, 0.24, 0.37, 0.24, "#ffce59", 5); + const tilt = 0.52, + cs = Math.cos(tilt), + sn = Math.sin(tilt); + let width = 0, + height = 0, + dpr = 0, + focal = 0, + trackX = spawn.x, + trackZ = 0; + let cameraZ = 0, + cameraY = 0, + lastSeconds: number | undefined, + walkPhase = 0; + let heading = 0; + const projected = (p: Point) => { + const vz = cameraZ - p.z, + vy = cameraY - p.y; + const depth = Math.max(1, cs * vz + sn * vy); + const scale = focal / depth; + return { + x: width * 0.5 + (p.x - trackX) * scale, + y: height * 0.58 + (cs * vy - sn * vz) * scale, + depth, + scale, + }; + }; + + let cameraRevision = 0, + steadyFrames = 0; + const sprites = new WeakMap< + Mesh, + { + revision: number; + image: HTMLCanvasElement; + x: number; + y: number; + width: number; + height: number; + } + >(); + function mesh(faces: Mesh, stationary = false) { + const reuse = stationary && steadyFrames >= 2; + if (reuse) { + const sprite = sprites.get(faces); + if (sprite?.revision === cameraRevision) { + g.drawImage( + sprite.image, + sprite.x, + sprite.y, + sprite.width, + sprite.height, + ); + return; + } + } + let left = Infinity, + right = -Infinity, + top = Infinity, + bottom = -Infinity; + // Sort the faces of each small solid in camera space. Shared vertices across + // adjacent facets project to identical positions, keeping seams very fine. + const ordered = faces + .map((f) => { + let depth = 0; + const points = f.points.map((p) => { + const v = projected(p); + depth += v.depth; + return v; + }); + // Back-facing facets of the opaque solids need no paint. + let area = 0; + for (let i = 0; i < points.length; i++) { + const p = points[i], + q = points[(i + 1) % points.length]; + area += p.x * q.y - q.x * p.y; + if (reuse) { + left = Math.min(left, p.x); + right = Math.max(right, p.x); + top = Math.min(top, p.y); + bottom = Math.max(bottom, p.y); + } + } + return { points, color: f.color, depth: depth / points.length, area }; + }) + .filter((f) => f.area > 0.024); + ordered.sort((a, b) => b.depth - a.depth); + let target: CanvasRenderingContext2D = g; + let sprite: HTMLCanvasElement | undefined; + if (reuse && ordered.length) { + left = Math.floor(left) - 1; + top = Math.floor(top) - 1; + right = Math.ceil(right) + 1; + bottom = Math.ceil(bottom) + 1; + sprite = document.createElement("canvas"); + sprite.width = Math.max(1, Math.ceil((right - left) * dpr)); + sprite.height = Math.max(1, Math.ceil((bottom - top) * dpr)); + const context = sprite.getContext("2d"); + if (context) { + target = context; + target.setTransform(dpr, 0, 0, dpr, -left * dpr, -top * dpr); + } else sprite = undefined; + } + for (const face of ordered) { + target.beginPath(); + face.points.forEach((p, i) => + i ? target.lineTo(p.x, p.y) : target.moveTo(p.x, p.y), + ); + target.closePath(); + target.fillStyle = face.color; + target.fill(); + // Fractional overdraw closes anti-aliasing seams between adjacent faces. + target.strokeStyle = face.color; + target.lineWidth = 0.48; + target.lineJoin = "round"; + target.stroke(); + } + if (sprite) { + const entry = { + revision: cameraRevision, + image: sprite, + x: left, + y: top, + width: sprite.width / dpr, + height: sprite.height / dpr, + }; + sprites.set(faces, entry); + g.drawImage(sprite, entry.x, entry.y, entry.width, entry.height); + } + } + function ellipse( + x: number, + y: number, + z: number, + rx: number, + rz: number, + color: string, + stroke?: string, + ) { + g.beginPath(); + for (let i = 0; i <= 24; i++) { + const a = (i / 24) * TAU; + const p = projected(point(x + Math.cos(a) * rx, y, z + Math.sin(a) * rz)); + if (i) g.lineTo(p.x, p.y); + else g.moveTo(p.x, p.y); + } + g.closePath(); + g.fillStyle = color; + g.fill(); + if (stroke) { + g.strokeStyle = stroke; + g.lineWidth = 1.15; + g.stroke(); + } + } + function polygon(points: Point[], color: string) { + g.beginPath(); + points.forEach((v, i) => { + const p = projected(v); + if (i) g.lineTo(p.x, p.y); + else g.moveTo(p.x, p.y); + }); + g.closePath(); + g.fillStyle = color; + g.fill(); + } + function line(points: Point[], color: string, thickness: number) { + g.beginPath(); + points.forEach((v, i) => { + const p = projected(v); + if (i) g.lineTo(p.x, p.y); + else g.moveTo(p.x, p.y); + }); + g.strokeStyle = color; + g.lineWidth = thickness; + g.lineJoin = "round"; + g.lineCap = "round"; + g.stroke(); + } + function groundArt(p: Platform) { + const y = p.y + 0.018; + if (p.kind === "stone") { + ellipse( + p.x, + y, + p.z, + p.rx * 0.68, + p.rz * 0.65, + p.theme === "mix" ? "#b4c99b" : "#d2cf8e", + ); + return; + } + if (p.kind !== "island") return; + if (p.theme === "hub") { + for (const [dx, dz, length] of [ + [-1, 0, p.rx], + [1, 0, p.rx], + [0, -1, p.rz], + ]) { + const a = point(-dz * 0.55, y, dx * 0.55), + b = point(dz * 0.55, y, -dx * 0.55); + polygon( + [ + a, + b, + point(b.x + dx * (length - 0.13), y, b.z + dz * (length - 0.13)), + point(a.x + dx * (length - 0.13), y, a.z + dz * (length - 0.13)), + ], + "#cbd18a", + ); + for (let i = 0; i < 3; i++) { + const d = 1.62 + i * 0.85; + const cx = dx * d, + cz = dz * d; + // Arrow-shaped stone inlays point toward each trail. + polygon( + [ + point(cx - dz * 0.23, y, cz + dx * 0.23), + point(cx + dx * 0.2, y, cz + dz * 0.2), + point(cx + dz * 0.23, y, cz - dx * 0.23), + point(cx + dx * 0.035, y, cz + dz * 0.035), + ], + "#f2e7b4", + ); + } + } + ellipse(0, y, 0, 1.42, 1.34, "#d4d49d"); + ellipse(0, y + 0.005, 0, 1.08, 1.02, "#789e93", "#e6ddb2"); + ellipse(0, y + 0.008, 0, 0.82, 0.77, "#94b5a3"); + polygon( + [ + point(0, y + 0.01, -0.67), + point(0.23, y + 0.01, -0.14), + point(0.63, y + 0.01, 0), + point(0.14, y + 0.01, 0.14), + point(0, y + 0.01, 0.64), + point(-0.18, y + 0.01, 0.14), + point(-0.58, y + 0.01, 0), + point(-0.18, y + 0.01, -0.13), + ], + "#f3db93", + ); + } else { + ellipse(p.x, y, p.z - 0.2, 1.44, 1.18, "#ddd19b"); + ellipse(p.x, y + 0.01, p.z - 0.2, 1.21, 0.99, "#91a694", "#fff0c5"); + } + } + function mark(b: Beacon, lit: boolean, seconds: number) { + const wp = point(b.x, b.y + 0.57, b.z + (b.id === "mix" ? 0.86 : 0.77)); + const s = projected(wp), + r = Math.max(7, s.scale * (b.id === "mix" ? 0.42 : 0.37)); + g.save(); + g.translate(s.x, s.y); + g.beginPath(); + g.arc(0, 0, r, 0, TAU); + g.fillStyle = "#243e50"; + g.fill(); + g.strokeStyle = lit ? "#ffe69a" : "#eee3bc"; + g.lineWidth = Math.max(1.4, r * 0.15); + g.stroke(); + g.fillStyle = "#fff7db"; + g.font = `900 ${r * (b.id === "mix" ? 1.04 : 1.59)}px system-ui,sans-serif`; + g.textBaseline = "middle"; + g.textAlign = "center"; + g.fillText( + b.id === "zero" ? "0" : b.id === "one" ? "1" : "0·1", + 0, + r * 0.06, + ); + g.restore(); + const top = projected( + point( + b.x, + b.y + (b.id === "mix" ? 3.02 : b.id === "one" ? 2.18 : 1.91), + b.z, + ), + ); + const rad = top.scale * (lit ? 1.14 : 0.59); + const glow = g.createRadialGradient( + top.x, + top.y, + 0, + top.x, + top.y, + Math.max(1, rad), + ); + glow.addColorStop(0, lit ? "#fff9bdc4" : "#fff4c591"); + glow.addColorStop(1, "#ffffcf00"); + g.fillStyle = glow; + g.fillRect(top.x - rad, top.y - rad, rad * 2, rad * 2); + if (lit) { + for (let i = 0; i < 3; i++) { + const a = seconds * 1.4 + (i * TAU) / 3; + sparkle( + top.x + Math.cos(a) * rad * 0.74, + top.y + Math.sin(a) * rad * 0.44, + rad * 0.1, + ); + } + } + } + function sparkle(x: number, y: number, r: number) { + g.fillStyle = "#fff5bc"; + g.beginPath(); + for (let i = 0; i < 8; i++) { + const a = (i * Math.PI) / 4, + radius = i % 2 ? r * 0.26 : r; + const sx = x + Math.sin(a) * radius, + sy = y + Math.cos(a) * radius; + if (i) g.lineTo(sx, sy); + else g.moveTo(sx, sy); + } + g.closePath(); + g.fill(); + } + + function flag( + x: number, + y: number, + z: number, + seconds: number, + color: string, + size = 1, + ) { + const a = projected(point(x, y, z)); + line( + [point(x, y, z), point(x, y + 1.5 * size, z)], + "#795b4a", + Math.max(1, a.scale * 0.065), + ); + const wave = Math.sin(seconds * 2 + x) * 0.07; + polygon( + [ + point(x, y + 1.48 * size, z), + point(x + 0.4 * size, y + (1.5 + wave) * size, z + 0.035), + point(x + 0.82 * size, y + (1.36 + wave) * size, z), + point(x + 0.43 * size, y + (1.24 + wave) * size, z), + point(x, y + 1.15 * size, z), + ], + color, + ); + } + // The broad sky and opaque terrain do not change while the camera rests. + const ground = document.createElement("canvas"); + const groundContext = ground.getContext("2d"); + let cachedX = NaN, + cachedZ = NaN; + return { + draw(state: GameState, seconds: number, reducedMotion = false) { + const w = canvas.clientWidth, + h = canvas.clientHeight; + if (!w || !h) return; + const ratio = Math.min(window.devicePixelRatio || 1, 1.8); + if (w !== width || h !== height || ratio !== dpr) { + width = w; + height = h; + dpr = ratio; + canvas.width = Math.round(w * ratio); + canvas.height = Math.round(h * ratio); + ground.width = canvas.width; + ground.height = canvas.height; + cachedX = NaN; + g.setTransform(ratio, 0, 0, ratio, 0, 0); + focal = Math.min(h * 1.23, w * 0.95); + } + const dt = + lastSeconds === undefined + ? 0 + : Math.max(0, Math.min(0.1, seconds - lastSeconds)); + const first = lastSeconds === undefined; + lastSeconds = seconds; + const follow = first || reducedMotion ? 1 : 1 - Math.exp(-4.8 * dt); + const desiredX = state.player.x * 0.8, + desiredZ = (state.player.z - spawn.z) * 0.74; + trackX += (desiredX - trackX) * follow; + trackZ += (desiredZ - trackZ) * follow; + if (Math.abs(trackX - desiredX) < 0.008) trackX = desiredX; + if (Math.abs(trackZ - desiredZ) < 0.008) trackZ = desiredZ; + cameraZ = 19.2 + trackZ; + cameraY = 11.45; + const t = reducedMotion ? 0 : seconds; + if (state.moving && !reducedMotion) walkPhase += dt * 11.5; + // Rotate by the shortest arc. The robot keeps facing its last travel direction. + heading += + Math.atan2( + Math.sin(state.facing - heading), + Math.cos(state.facing - heading), + ) * (first || reducedMotion ? 1 : 1 - Math.exp(-15 * dt)); + + if (!groundContext || cachedX !== trackX || cachedZ !== trackZ) { + steadyFrames = 0; + cameraRevision++; + drawHorizon(g, width, height, trackX); + for (const { p } of terrain.filter(({ p }) => p.kind === "island")) { + ellipse( + p.x + 0.63, + -4.65, + p.z + 0.43, + p.rx * 0.9, + p.rz * 0.76, + "#398f9629", + ); + ellipse( + p.x + 0.6, + -4.65, + p.z + 0.4, + p.rx * 0.68, + p.rz * 0.5, + "#438c8c23", + ); + } + const sorted = [...terrain].sort( + (a, b) => a.p.z - b.p.z || (a.p.kind === "bridge" ? 1 : -1), + ); + for (const { p, mesh: surface } of sorted) { + mesh(surface); + groundArt(p); + } + for (const obj of decor) + ellipse( + obj.anchor.x, + obj.anchor.y + 0.025, + obj.anchor.z, + obj.radius, + obj.radius * 0.72, + "#4a7a6e33", + ); + for (const b of beacons) + ellipse(b.x + 0.18, b.y + 0.024, b.z + 0.12, 1.04, 0.71, "#507c6e42"); + if (groundContext) { + groundContext.drawImage(canvas, 0, 0); + cachedX = trackX; + cachedZ = trackZ; + } + } else { + steadyFrames++; + g.drawImage(ground, 0, 0, width, height); + } + + const p = state.player; + const below = platforms + .filter((is) => contains(is, p.x, p.z) && is.y <= p.y + 0.1) + .sort((a, b) => b.y - a.y)[0]; + const actors: { z: number; draw: () => void }[] = []; + if (below) { + const altitude = Math.max(0, p.y - below.y); + const size = 0.52 / (1 + 0.12 * altitude); + ellipse( + p.x, + below.y + 0.032, + p.z, + size, + size * 0.73, + `rgba(38,76,74,${0.34 / (1 + 0.35 * altitude)})`, + ); + } + for (const obj of decor) { + const pos = projected(obj.anchor); + if (pos.x < -60 || pos.x > width + 60) continue; + actors.push({ + z: obj.anchor.z, + draw: () => { + const inFront = + obj.anchor.z > p.z && + Math.abs(obj.anchor.x - p.x) < 0.77 && + flatten(obj.anchor, p) < 2.5; + g.globalAlpha = inFront ? 0.55 : 1; + mesh(obj.mesh, true); + g.globalAlpha = 1; + }, + }); + } + for (const station of stations) { + const { b } = station; + actors.push({ + z: b.z, + draw: () => { + const lit = state.lit.includes(b.id); + const inFront = + b.z > p.z && Math.abs(b.x - p.x) < 0.85 && flatten(b, p) < 2.45; + g.globalAlpha = inFront ? 0.58 : 1; + mesh(lit ? station.lit : station.unlit, true); + mark(b, lit, t); + g.globalAlpha = 1; + }, + }); + } + for (const [i, item] of pickups.entries()) { + if (state.collected.includes(item.id)) continue; + const y = item.y + 0.13 * Math.sin(t * 2.7 + i); + actors.push({ + z: item.z, + draw: () => { + const top = projected(point(item.x, y, item.z)); + const shine = 0.5 + 0.5 * Math.sin(t * 3.1 + i); + mesh(place(crystal, item.x, y, item.z, 0.48 + t * 1.28 + i)); + if (shine > 0.64) + sparkle( + top.x + top.scale * 0.14, + top.y - top.scale * 0.24, + top.scale * 0.11 * shine, + ); + }, + }); + } + const flags = [ + [-3.98, 0, -1.15, "#e57e5b"], + [-8.47, 0.08, 1.13, "#47aaa1"], + [1.32, 0, -3.61, "#e79357"], + [-1.26, 0.82, -9.48, "#a98ad8"], + ] as const; + for (const [x, y, z, color] of flags) + actors.push({ z, draw: () => flag(x, y, z, t, color, 0.87) }); + actors.push({ + z: p.z, + draw: () => { + let spin = 0; + if (state.cometJump) { + const arc = Math.min(1, state.cometTime / 0.66); + spin = reducedMotion ? 0 : TAU * (arc * arc * (3 - 2 * arc)); + const backX = -Math.sin(heading), + backZ = -Math.cos(heading); + for (const side of [-1, 1]) { + const streak = Array.from({ length: 5 }, (_, i) => { + const d = i / 4; + return point( + p.x + + backX * d * 0.95 + + Math.cos(heading) * side * (0.19 + 0.14 * d), + p.y + 0.29 - d * 0.64, + p.z + + backZ * d * 0.95 - + Math.sin(heading) * side * (0.19 + 0.14 * d), + ); + }); + line( + streak, + side > 0 ? "#ffe39a" : "#b7fff3", + Math.max(2, projected(p).scale * 0.09), + ); + const tail = projected(streak[4]); + sparkle(tail.x, tail.y, Math.max(2, tail.scale * 0.095)); + } + } + const body = !state.grounded + ? airborneRobot + : state.moving && !reducedMotion + ? robot(walkPhase, true, false) + : standingRobot; + mesh(place(body, p.x, p.y, p.z, heading + spin)); + }, + }); + actors.sort((a, b) => a.z - b.z); + actors.forEach((actor) => actor.draw()); + }, + }; +} diff --git a/src/components/games/qubitCove/useCovePlay.ts b/src/components/games/qubitCove/useCovePlay.ts new file mode 100644 index 00000000..732ff4ae --- /dev/null +++ b/src/components/games/qubitCove/useCovePlay.ts @@ -0,0 +1,180 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { createGame, nearbyBeacon, stepGame, type GameState } from "./engine"; +import { createCoveRenderer } from "./scene"; +import type { BeaconId } from "./world"; + +export type Control = "left" | "right" | "up" | "down" | "jump"; + +const keyControls: Partial> = { + ArrowLeft: "left", + KeyA: "left", + ArrowRight: "right", + KeyD: "right", + ArrowUp: "up", + KeyW: "up", + ArrowDown: "down", + KeyS: "down", + Space: "jump", +}; + +function status(state: GameState) { + return { + near: nearbyBeacon(state), + lit: state.lit, + sparks: state.collected.length, + }; +} + +export function useCovePlay( + paused: boolean, + reduced: boolean, + onUse: (beacon: BeaconId) => void, +) { + const canvas = useRef(null); + const region = useRef(null); + const [world] = useState(() => ({ current: createGame() })); + const [hud, setHud] = useState(() => status(world.current)); + const previous = useRef(hud); + const inputs = useRef(new Map()); + const pulses = useRef(new Set()); + const options = useRef({ paused, reduced, onUse }); + + const resetInputs = useCallback(() => { + inputs.current.clear(); + pulses.current.clear(); + }, []); + + useEffect(() => { + options.current = { paused, reduced, onUse }; + if (paused) resetInputs(); + }, [paused, reduced, onUse, resetInputs]); + + const update = useCallback( + (next: GameState) => { + world.current = next; + const current = status(next); + const old = previous.current; + if ( + old.near !== current.near || + old.lit !== current.lit || + old.sparks !== current.sparks + ) { + previous.current = current; + setHud(current); + } + }, + [world], + ); + + useEffect(() => { + if (!canvas.current) return; + const scene = createCoveRenderer(canvas.current); + const held = inputs.current; + const tapped = pulses.current; + let last = performance.now(); + let elapsed = 0; + let animation = 0; + let lastPaint = -Infinity; + + function frame(now: number) { + const dt = Math.min(Math.max(0, (now - last) / 1000), 0.08); + last = now; + if (!options.current.paused) { + const active = new Set([...held.values(), ...tapped]); + update( + stepGame( + world.current, + { + x: Number(active.has("right")) - Number(active.has("left")), + z: Number(active.has("down")) - Number(active.has("up")), + jump: active.has("jump"), + }, + dt, + ), + ); + tapped.clear(); + elapsed += dt; + } + // The map and beacon panels pause the world. Repaint occasionally for resizing. + if (!options.current.paused || now - lastPaint >= 250) { + scene.draw(world.current, elapsed, options.current.reduced); + lastPaint = now; + } + animation = requestAnimationFrame(frame); + } + + function keyDown(event: KeyboardEvent) { + if ( + options.current.paused || + event.ctrlKey || + event.altKey || + event.metaKey + ) + return; + const target = event.target; + if (!(target instanceof HTMLElement)) return; + if (target !== document.body && !region.current?.contains(target)) return; + if ( + target.isContentEditable || + target.closest("input, select, textarea, [role=textbox]") + ) + return; + if (event.code === "KeyE") { + const beacon = nearbyBeacon(world.current); + if (!event.repeat && beacon) { + event.preventDefault(); + options.current.onUse(beacon); + } + return; + } + const control = keyControls[event.code]; + if ( + !control || + (control === "jump" && target.closest("button,a,summary")) + ) + return; + event.preventDefault(); + held.set(event.code, control); + if (!event.repeat) tapped.add(control); + } + + const keyUp = (event: KeyboardEvent) => { + held.delete(event.code); + }; + const visibility = () => { + resetInputs(); + last = performance.now(); + }; + window.addEventListener("keydown", keyDown); + window.addEventListener("keyup", keyUp); + window.addEventListener("blur", resetInputs); + document.addEventListener("visibilitychange", visibility); + animation = requestAnimationFrame(frame); + return () => { + cancelAnimationFrame(animation); + window.removeEventListener("keydown", keyDown); + window.removeEventListener("keyup", keyUp); + window.removeEventListener("blur", resetInputs); + document.removeEventListener("visibilitychange", visibility); + resetInputs(); + }; + }, [resetInputs, update, world]); + + function press(id: number, control: Control) { + inputs.current.set(String(id), control); + pulses.current.add(control); + } + function release(id: number) { + inputs.current.delete(String(id)); + } + return { + canvas, + region, + world, + hud, + update, + press, + release, + pulse: (c: Control) => pulses.current.add(c), + }; +} diff --git a/src/components/games/qubitCove/world.ts b/src/components/games/qubitCove/world.ts new file mode 100644 index 00000000..c4263ec2 --- /dev/null +++ b/src/components/games/qubitCove/world.ts @@ -0,0 +1,152 @@ +/** Heights mark the walking surface. The camera looks toward negative z. */ +export interface Point { + x: number; + y: number; + z: number; +} + +export type BeaconId = "zero" | "one" | "mix"; + +export interface Platform extends Point { + id: string; + kind: "island" | "stone" | "bridge"; + theme: "hub" | BeaconId; + rx: number; + rz: number; +} + +export interface Beacon extends Point { + id: BeaconId; +} + +export interface Pickup extends Point { + id: string; +} + +export const spawn: Point = { x: 0, y: 0, z: 2.65 }; + +// The west pier can be walked. The two other trails teach jumping with broad +// landing areas at successively higher elevations. +export const platforms: readonly Platform[] = [ + { + id: "harbor", + kind: "island", + theme: "hub", + x: 0, + y: 0, + z: 0, + rx: 4.8, + rz: 4.2, + }, + { + id: "pier", + kind: "bridge", + theme: "zero", + x: -6.65, + y: 0.04, + z: 0, + rx: 2.65, + rz: 1.03, + }, + { + id: "west", + kind: "island", + theme: "zero", + x: -11, + y: 0.08, + z: 0, + rx: 3.05, + rz: 2.95, + }, + { + id: "east-step", + kind: "stone", + theme: "one", + x: 5.95, + y: 0.38, + z: 0.2, + rx: 1.12, + rz: 1.18, + }, + { + id: "east-shelf", + kind: "stone", + theme: "one", + x: 8.02, + y: 0.67, + z: -0.05, + rx: 1.05, + rz: 1.3, + }, + { + id: "east", + kind: "island", + theme: "one", + x: 11.55, + y: 0.97, + z: 0, + rx: 2.95, + rz: 2.85, + }, + { + id: "north-dock", + kind: "bridge", + theme: "mix", + x: 0, + y: 0.04, + z: -4.85, + rx: 1.12, + rz: 1.2, + }, + { + id: "north-step", + kind: "stone", + theme: "mix", + x: 0.05, + y: 0.52, + z: -7.14, + rx: 1.62, + rz: 1.05, + }, + { + id: "north", + kind: "island", + theme: "mix", + x: 0, + y: 0.82, + z: -10.97, + rx: 3.35, + rz: 2.86, + }, +]; + +export const beacons: readonly Beacon[] = [ + { id: "zero", x: -11, y: 0.08, z: -0.46 }, + { id: "one", x: 11.62, y: 0.97, z: -0.46 }, + { id: "mix", x: 0, y: 0.82, z: -11.3 }, +]; + +export const pickups: readonly Pickup[] = [ + { id: "pier-1", x: -3.5, y: 0.65, z: 0 }, + { id: "pier-2", x: -5.85, y: 0.69, z: 0 }, + { id: "pier-3", x: -8.25, y: 0.73, z: 0 }, + { id: "east-1", x: 3.75, y: 0.65, z: 0.1 }, + { id: "east-2", x: 5.95, y: 1.2, z: 0.2 }, + { id: "east-3", x: 8.02, y: 1.49, z: -0.05 }, + { id: "north-1", x: 0, y: 0.69, z: -3.4 }, + { id: "north-2", x: 0, y: 0.69, z: -5.42 }, + { id: "north-3", x: 0.05, y: 1.34, z: -7.14 }, +]; + +export function contains(platform: Platform, x: number, z: number) { + const dx = (x - platform.x) / platform.rx; + const dz = (z - platform.z) / platform.rz; + return platform.kind === "bridge" + ? Math.abs(dx) <= 1 && Math.abs(dz) <= 1 + : dx * dx + dz * dz <= 1; +} + +export function beaconLanding(id: BeaconId): Point { + const beacon = beacons.find((entry) => entry.id === id)!; + return { x: beacon.x, y: beacon.y, z: beacon.z + 1.0 }; +} diff --git a/src/components/specialty/SpecialtyExperience.tsx b/src/components/specialty/SpecialtyExperience.tsx index e0527025..b29a9d70 100644 --- a/src/components/specialty/SpecialtyExperience.tsx +++ b/src/components/specialty/SpecialtyExperience.tsx @@ -22,6 +22,7 @@ import { SPECIALTIES, BIOTRAIL_PATH, SPARBOTS_PATH, + QUBIT_COVE_PATH, type Specialty, type SpecialtyStatus, } from "@/lib/specialty"; @@ -29,6 +30,12 @@ import "./specialty.css"; import { SPECIALTY_ICONS } from "./specialtyIcons"; +const FIRST_GAMES: Record = { + AI: { key: "sparbots", path: SPARBOTS_PATH }, + QUANTUM: { key: "specialty.qubitCove", path: QUBIT_COVE_PATH }, + BIOTECH: { key: "biotrail", path: BIOTRAIL_PATH }, +}; + export function SpecialtyExperience({ data, onChoose, @@ -48,12 +55,7 @@ export function SpecialtyExperience({ const active = data.specialty ?? preview; const Icon = SPECIALTY_ICONS[active]; const chosen = data.unlocked && data.specialty !== null; - const game = - active === "AI" - ? { key: "sparbots", path: SPARBOTS_PATH } - : active === "BIOTECH" - ? { key: "biotrail", path: BIOTRAIL_PATH } - : null; + const game = FIRST_GAMES[active]; async function commit() { if (saving) return; setSaving(true); @@ -191,40 +193,27 @@ export function SpecialtyExperience({ {t(`specialty.tracks.${active}.name`)}

-

{t(game ? `${game.key}.title` : "specialty.comingTitle")}

-

- {t(game ? `${game.key}.tagline` : "specialty.comingDescription")} -

- {game ? ( - <> -
- {t(`${game.key}.tag1`)} - {t(`${game.key}.tag2`)} - {t(`${game.key}.tag3`)} -
- {onPlay ? ( - - ) : ( - - {t("specialty.play")} - - - )} - - ) : !onPlay ? ( +

{t(`${game.key}.title`)}

+

{t(`${game.key}.tagline`)}

+
+ {t(`${game.key}.tag1`)} + {t(`${game.key}.tag2`)} + {t(`${game.key}.tag3`)} +
+ {onPlay ? ( + + ) : ( - {t("specialty.revisit")} + {t("specialty.play", { title: t(`${game.key}.title`) })} + - ) : null} + )}