From 3e0af15a86057a850894cdcc217eced1aabf380f Mon Sep 17 00:00:00 2001 From: Michi Date: Thu, 26 Nov 2026 13:46:53 +0100 Subject: [PATCH 1/6] feat(web): billiards easter egg on a triple-click of the Ari Code logo Solo 8-ball time race on a 9:16 Canvas 2D table, lazy-loaded so startup is unchanged. Fouls add seconds, the first miss is free, and a bubble shows threads that finish or need you while playing. --- .../components/billiards/BilliardsOverlay.tsx | 251 ++++++++++ .../components/billiards/billiardsAudio.ts | 106 ++++ .../components/billiards/billiardsPhysics.ts | 167 +++++++ .../components/billiards/billiardsRender.ts | 458 ++++++++++++++++++ .../billiards/billiardsRules.test.ts | 166 +++++++ .../components/billiards/billiardsRules.ts | 228 +++++++++ .../components/billiards/billiardsSession.ts | 277 +++++++++++ .../components/billiards/billiardsTable.ts | 82 ++++ .../billiards/billiardsThreadAlerts.test.ts | 57 +++ .../billiards/billiardsThreadAlerts.ts | 73 +++ .../src/components/sidebar/SidebarChrome.tsx | 42 +- apps/web/src/i18n/translations/de.json | 20 + apps/web/src/i18n/translations/en.json | 20 + apps/web/src/i18n/translations/es.json | 20 + apps/web/src/i18n/translations/fr.json | 20 + apps/web/src/i18n/translations/ja.json | 20 + apps/web/src/i18n/translations/ko.json | 20 + apps/web/src/i18n/translations/pt-BR.json | 20 + apps/web/src/i18n/translations/ru.json | 20 + apps/web/src/i18n/translations/sv.json | 20 + apps/web/src/i18n/translations/zh.json | 20 + 21 files changed, 2095 insertions(+), 12 deletions(-) create mode 100644 apps/web/src/components/billiards/BilliardsOverlay.tsx create mode 100644 apps/web/src/components/billiards/billiardsAudio.ts create mode 100644 apps/web/src/components/billiards/billiardsPhysics.ts create mode 100644 apps/web/src/components/billiards/billiardsRender.ts create mode 100644 apps/web/src/components/billiards/billiardsRules.test.ts create mode 100644 apps/web/src/components/billiards/billiardsRules.ts create mode 100644 apps/web/src/components/billiards/billiardsSession.ts create mode 100644 apps/web/src/components/billiards/billiardsTable.ts create mode 100644 apps/web/src/components/billiards/billiardsThreadAlerts.test.ts create mode 100644 apps/web/src/components/billiards/billiardsThreadAlerts.ts diff --git a/apps/web/src/components/billiards/BilliardsOverlay.tsx b/apps/web/src/components/billiards/BilliardsOverlay.tsx new file mode 100644 index 0000000000..38cf072d9a --- /dev/null +++ b/apps/web/src/components/billiards/BilliardsOverlay.tsx @@ -0,0 +1,251 @@ +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; +import { CircleCheckIcon, MessageCircleQuestionIcon, XIcon } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; + +import { cn } from "../../lib/utils"; +import { useThreadShells } from "../../state/entities"; +import { FOUL_PENALTY_SECONDS } from "./billiardsRules"; +import { BilliardsSession, type BilliardsHud } from "./billiardsSession"; +import { snapshotThreads, threadAlerts, type ThreadAlert } from "./billiardsThreadAlerts"; + +const MAX_ALERTS = 3; + +function formatClock(ms: number, tenths = false): string { + const seconds = Math.floor(ms / 1000); + const clock = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + return tenths ? `${clock}.${Math.floor((ms % 1000) / 100)}` : clock; +} + +function alertId(alert: ThreadAlert): string { + return `${alert.key}:${alert.kind}:${alert.thread.latestRun?.completedAt ?? ""}`; +} + +/** The billiards easter egg: a full-window table, opened by triple-clicking the Ari Code logo. */ +export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { + const gt = useGT(); + const navigate = useNavigate(); + const dialogRef = useRef(null); + const canvasRef = useRef(null); + const sessionRef = useRef(null); + const [hud, setHud] = useState(null); + const threads = useThreadShells(); + const [baseline] = useState(() => snapshotThreads(threads)); + const [dismissed, setDismissed] = useState>(new Set()); + const alerts = threadAlerts(baseline, threads) + .filter((alert) => !dismissed.has(alertId(alert))) + .slice(0, MAX_ALERTS); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- runs the canvas game session while mounted and reports its HUD + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + const session = new BilliardsSession(canvas, setHud); + sessionRef.current = session; + dialogRef.current?.focus(); + return () => { + session.dispose(); + sessionRef.current = null; + }; + }, []); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a window Escape listener that closes the game while it is open + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + if (!sessionRef.current?.cancelCharge()) onClose(); + }; + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); + }, [onClose]); + + const openThread = (alert: ThreadAlert) => { + onClose(); + void navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: alert.thread.environmentId, threadId: alert.thread.id }, + }); + }; + + const status = (() => { + if (!hud) return { text: "", tone: "quiet" }; + if (hud.blocked) return { text: gt("Call a pocket for the 8 first: click it."), tone: "warn" }; + switch (hud.foul) { + case "scratch": + return { + text: gt("Scratch. +{seconds} s", { seconds: FOUL_PENALTY_SECONDS.scratch }), + tone: "warn", + }; + case "noContact": + return hud.forgiven + ? { + text: gt("No ball hit. Free this once, after that it costs {seconds} s.", { + seconds: FOUL_PENALTY_SECONDS.noContact, + }), + tone: "call", + } + : { + text: gt("No ball hit. +{seconds} s", { seconds: FOUL_PENALTY_SECONDS.noContact }), + tone: "warn", + }; + case "early8": + return { + text: gt("The 8 went in too early and is back on its spot. +{seconds} s", { + seconds: FOUL_PENALTY_SECONDS.early8, + }), + tone: "warn", + }; + case "wrong8": + return { + text: gt("Wrong pocket. The 8 is back on its spot. +{seconds} s", { + seconds: FOUL_PENALTY_SECONDS.wrong8, + }), + tone: "warn", + }; + case "scratch8": + return { + text: gt("Scratch on the 8. It is back on its spot. +{seconds} s", { + seconds: FOUL_PENALTY_SECONDS.scratch8, + }), + tone: "warn", + }; + case null: + break; + } + if (hud.needsCall) { + return hud.calledPocket === null + ? { text: gt("Only the 8 is left. Click the pocket you call."), tone: "call" } + : { text: gt("8 called. Click another pocket to change it."), tone: "call" }; + } + if (hud.isBreak) { + return { + text: gt("The clock starts after the break. Hold to charge, release to shoot."), + tone: "quiet", + }; + } + return { + text: gt("Move to aim, hold to charge, release to shoot. Shift aims finer, Esc closes."), + tone: "quiet", + }; + })(); + + return createPortal( +
+
+ +
+
+ {gt("Shots {shots}", { shots: hud?.shots ?? 0 })} + {hud && hud.penaltySeconds > 0 ? ( + + {gt("Penalties +{seconds} s", { seconds: hud.penaltySeconds })} + + ) : null} + {formatClock(hud?.totalMs ?? 0)} + +
+

+ {status.text} +

+
+ {alerts.length > 0 ? ( +
+ {alerts.map((alert) => ( +
+ {alert.kind === "done" ? ( + + ) : ( + + )} + + {alert.kind === "done" + ? gt("{title} is done", { title: alert.thread.title }) + : gt("{title} needs you", { title: alert.thread.title })} + + + +
+ ))} +
+ ) : null} + {hud?.phase === "cleared" ? ( +
+
+

{gt("Table cleared")}

+

+ {formatClock(hud.totalMs, true)} +

+

+ {gt("{clock} played, +{seconds} s penalties, {shots} shots", { + clock: formatClock(hud.totalMs - hud.penaltySeconds * 1000, true), + seconds: hud.penaltySeconds, + shots: hud.shots, + })} +

+
+ + +
+
+
+ ) : null} +
+
, + document.body, + ); +} diff --git a/apps/web/src/components/billiards/billiardsAudio.ts b/apps/web/src/components/billiards/billiardsAudio.ts new file mode 100644 index 0000000000..e91882c79c --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAudio.ts @@ -0,0 +1,106 @@ +// Every sound is synthesised, so the game ships no audio files. + +const clamp01 = (value: number) => Math.max(0, Math.min(1, value)); + +export class BilliardsAudio { + private context: AudioContext | null = null; + private master: GainNode | null = null; + private noise: AudioBuffer | null = null; + + /** Starts audio; call from a user gesture. */ + unlock(): void { + if (!this.context) { + const context = new AudioContext(); + const master = context.createGain(); + master.gain.value = 0.55; + master.connect(context.destination); + const noise = context.createBuffer( + 1, + Math.floor(context.sampleRate * 0.4), + context.sampleRate, + ); + const data = noise.getChannelData(0); + for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1; + this.context = context; + this.master = master; + this.noise = noise; + } + if (this.context.state === "suspended") void this.context.resume(); + } + + dispose(): void { + void this.context?.close(); + this.context = null; + } + + /** Ball on ball: a bright click whose pitch and level follow the impact. */ + click(speed: number): void { + const v = clamp01(speed / 5); + if (v < 0.01) return; + this.tone("sine", 2300 + Math.random() * 900 + v * 600, 1900, v * 0.45, 0.05); + this.hiss("bandpass", 3600, 1.4, v * 0.55, 0.02); + } + + /** Ball on cushion: a low, soft thud. */ + cushion(speed: number): void { + const v = clamp01(speed / 4); + if (v < 0.02) return; + this.tone("sine", 150, 70, v * 0.6, 0.12); + this.hiss("lowpass", 700, 0.7, v * 0.35, 0.07); + } + + /** Ball into a pocket: a hollow drop, then a rattle in the pocket. */ + pocket(): void { + this.tone("triangle", 240, 85, 0.35, 0.28); + this.hiss("bandpass", 950, 2, 0.22, 0.05, 0.09); + this.hiss("bandpass", 780, 2, 0.14, 0.05, 0.17); + } + + /** Cue tip on the cue ball. */ + cue(power: number): void { + const p = clamp01(power); + this.hiss("bandpass", 1500 + p * 900, 0.9, 0.25 + p * 0.5, 0.03); + this.tone("sine", 700 + p * 300, 500, 0.15 + p * 0.2, 0.04); + } + + private tone(type: OscillatorType, from: number, to: number, gain: number, decay: number): void { + const { context, master } = this; + if (!context || !master) return; + const at = context.currentTime; + const oscillator = context.createOscillator(); + const envelope = context.createGain(); + oscillator.type = type; + oscillator.frequency.setValueAtTime(from, at); + oscillator.frequency.exponentialRampToValueAtTime(to, at + decay); + envelope.gain.setValueAtTime(gain, at); + envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay); + oscillator.connect(envelope).connect(master); + oscillator.start(at); + oscillator.stop(at + decay + 0.02); + } + + private hiss( + type: BiquadFilterType, + frequency: number, + q: number, + gain: number, + decay: number, + delay = 0, + ): void { + const { context, master, noise } = this; + if (!context || !master || !noise) return; + const at = context.currentTime + delay; + const source = context.createBufferSource(); + const filter = context.createBiquadFilter(); + const envelope = context.createGain(); + source.buffer = noise; + filter.type = type; + filter.frequency.value = frequency; + filter.Q.value = q; + envelope.gain.setValueAtTime(gain, at); + envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay); + source.connect(filter).connect(envelope).connect(master); + source.start(at, Math.random() * 0.3); + source.stop(at + decay + 0.02); + } +} diff --git a/apps/web/src/components/billiards/billiardsPhysics.ts b/apps/web/src/components/billiards/billiardsPhysics.ts new file mode 100644 index 0000000000..317bd62e25 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsPhysics.ts @@ -0,0 +1,167 @@ +import { + BALL_RADIUS, + CUSHION_SEGMENTS, + POCKETS, + TABLE_LENGTH, + TABLE_WIDTH, + type Pocket, +} from "./billiardsTable.ts"; + +export interface Ball { + /** 0 is the cue ball, 1 to 15 the object balls. */ + readonly id: number; + x: number; + y: number; + vx: number; + vy: number; + onTable: boolean; +} + +export type PhysicsEvent = + | { readonly kind: "ball"; readonly a: number; readonly b: number; readonly speed: number } + | { + readonly kind: "cushion"; + readonly ball: number; + readonly speed: number; + readonly x: number; + readonly y: number; + } + | { + readonly kind: "pocket"; + readonly ball: number; + readonly pocket: number; + readonly x: number; + readonly y: number; + }; + +/** One fixed simulation step. Small enough that a break-speed ball can't pass through another. */ +export const STEP_SECONDS = 1 / 480; +/** The fastest shot, in table widths per second. */ +export const MAX_SHOT_SPEED = 8; + +const ROLL_DECEL = 0.5; +const DRAG = 0.12; +const SLEEP_SPEED = 0.012; +const BALL_RESTITUTION = 0.94; +const CUSHION_RESTITUTION = 0.72; +const CUSHION_GRIP = 0.94; +const DIAMETER = BALL_RADIUS * 2; +const OUT_MARGIN = BALL_RADIUS * 1.2; + +export function makeBall(id: number, x: number, y: number): Ball { + return { id, x, y, vx: 0, vy: 0, onTable: true }; +} + +export function anyMoving(balls: ReadonlyArray): boolean { + return balls.some((ball) => ball.onTable && (ball.vx !== 0 || ball.vy !== 0)); +} + +function nearestPocket(x: number, y: number): Pocket { + let best = POCKETS[0] as Pocket; + let bestDistance = Infinity; + for (const pocket of POCKETS) { + const distance = Math.hypot(pocket.x - x, pocket.y - y); + if (distance < bestDistance) { + best = pocket; + bestDistance = distance; + } + } + return best; +} + +/** Advances every ball by one fixed step, appending what happened to `events`. Deterministic. */ +export function stepPhysics(balls: Ball[], events: PhysicsEvent[]): void { + const dt = STEP_SECONDS; + + for (const ball of balls) { + if (!ball.onTable || (ball.vx === 0 && ball.vy === 0)) continue; + const speed = Math.hypot(ball.vx, ball.vy); + const loss = (ROLL_DECEL + DRAG * speed) * dt; + if (speed - loss < SLEEP_SPEED) { + ball.vx = 0; + ball.vy = 0; + continue; + } + const scale = (speed - loss) / speed; + ball.vx *= scale; + ball.vy *= scale; + ball.x += ball.vx * dt; + ball.y += ball.vy * dt; + } + + for (let i = 0; i < balls.length; i++) { + const a = balls[i]; + if (!a?.onTable) continue; + for (let j = i + 1; j < balls.length; j++) { + const b = balls[j]; + if (!b?.onTable) continue; + const dx = b.x - a.x; + const dy = b.y - a.y; + const distanceSquared = dx * dx + dy * dy; + if (distanceSquared >= DIAMETER * DIAMETER || distanceSquared === 0) continue; + const distance = Math.sqrt(distanceSquared); + const nx = dx / distance; + const ny = dy / distance; + const push = (DIAMETER - distance) / 2; + a.x -= nx * push; + a.y -= ny * push; + b.x += nx * push; + b.y += ny * push; + const approach = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny; + if (approach <= 0) continue; + const impulse = ((1 + BALL_RESTITUTION) / 2) * approach; + a.vx -= impulse * nx; + a.vy -= impulse * ny; + b.vx += impulse * nx; + b.vy += impulse * ny; + events.push({ kind: "ball", a: a.id, b: b.id, speed: approach }); + } + } + + for (const ball of balls) { + if (!ball.onTable) continue; + for (const { a, b } of CUSHION_SEGMENTS) { + const sx = b.x - a.x; + const sy = b.y - a.y; + const t = Math.max( + 0, + Math.min(1, ((ball.x - a.x) * sx + (ball.y - a.y) * sy) / (sx * sx + sy * sy)), + ); + const cx = a.x + sx * t; + const cy = a.y + sy * t; + const dx = ball.x - cx; + const dy = ball.y - cy; + const distanceSquared = dx * dx + dy * dy; + if (distanceSquared >= BALL_RADIUS * BALL_RADIUS || distanceSquared === 0) continue; + const distance = Math.sqrt(distanceSquared); + const nx = dx / distance; + const ny = dy / distance; + ball.x += nx * (BALL_RADIUS - distance); + ball.y += ny * (BALL_RADIUS - distance); + const normalSpeed = ball.vx * nx + ball.vy * ny; + if (normalSpeed >= 0) continue; + const tx = ball.vx - normalSpeed * nx; + const ty = ball.vy - normalSpeed * ny; + ball.vx = tx * CUSHION_GRIP - normalSpeed * CUSHION_RESTITUTION * nx; + ball.vy = ty * CUSHION_GRIP - normalSpeed * CUSHION_RESTITUTION * ny; + events.push({ kind: "cushion", ball: ball.id, speed: -normalSpeed, x: cx, y: cy }); + } + } + + for (const ball of balls) { + if (!ball.onTable) continue; + const pocket = nearestPocket(ball.x, ball.y); + const inPocket = Math.hypot(pocket.x - ball.x, pocket.y - ball.y) < pocket.radius; + // Cushions close every gap but the pocket mouths, so a ball off the cloth went into one. + const offCloth = + ball.x < -OUT_MARGIN || + ball.x > TABLE_WIDTH + OUT_MARGIN || + ball.y < -OUT_MARGIN || + ball.y > TABLE_LENGTH + OUT_MARGIN; + if (!inPocket && !offCloth) continue; + events.push({ kind: "pocket", ball: ball.id, pocket: pocket.id, x: ball.x, y: ball.y }); + ball.onTable = false; + ball.vx = 0; + ball.vy = 0; + } +} diff --git a/apps/web/src/components/billiards/billiardsRender.ts b/apps/web/src/components/billiards/billiardsRender.ts new file mode 100644 index 0000000000..e9fba68eb9 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRender.ts @@ -0,0 +1,458 @@ +import type { Ball } from "./billiardsPhysics.ts"; +import { EIGHT, type BilliardsGame } from "./billiardsRules.ts"; +import { + BALL_RADIUS, + CUSHIONS, + FOOT_SPOT, + HEAD_SPOT, + POCKETS, + RAIL_WIDTH, + TABLE_LENGTH, + TABLE_WIDTH, + type Pocket, +} from "./billiardsTable.ts"; + +// The canvas is a 9:16 frame around the table, in table units. +export const FRAME_WIDTH = 1.4; +const FRAME_HEIGHT = (FRAME_WIDTH * 16) / 9; +export const TABLE_ORIGIN = { + x: (FRAME_WIDTH - TABLE_WIDTH) / 2, + y: (FRAME_HEIGHT - TABLE_LENGTH) / 2, +}; + +const R = BALL_RADIUS; +const BALL_COLORS = [ + "#f4f1e8", + "#f2c230", + "#2160d4", + "#d8322b", + "#6c3fa3", + "#f07a1f", + "#1d8a4a", + "#8c2233", + "#151515", +]; +const CLOTH_CENTER = "#1d6896"; +const CLOTH_EDGE = "#0f3b5c"; +const CUSHION = "#164f78"; +const SINK_SECONDS = 0.22; +const CALL = "255, 200, 80"; + +export interface Sinking { + readonly ball: number; + readonly x: number; + readonly y: number; + readonly pocket: Pocket; + readonly start: number; +} + +export interface SceneView { + readonly game: BilliardsGame; + readonly aimAngle: number; + /** 0 to 1 while charging a shot, null otherwise. */ + readonly power: number | null; + readonly hoverPocket: number | null; + readonly sinking: ReadonlyArray; + /** Seconds, for pulses and animations. */ + readonly now: number; +} + +export { SINK_SECONDS }; + +function frameTransform(ctx: CanvasRenderingContext2D, scale: number): void { + ctx.setTransform(scale, 0, 0, scale, TABLE_ORIGIN.x * scale, TABLE_ORIGIN.y * scale); +} + +/** Everything that never moves, drawn once per resize. */ +export function drawStaticLayer(layer: HTMLCanvasElement, scale: number): void { + const ctx = layer.getContext("2d"); + if (!ctx) return; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, layer.width, layer.height); + frameTransform(ctx, scale); + + const backdrop = ctx.createRadialGradient(0.5, 1, 0.2, 0.5, 1, 1.6); + backdrop.addColorStop(0, "#141b24"); + backdrop.addColorStop(1, "#06080c"); + ctx.fillStyle = backdrop; + ctx.fillRect(-TABLE_ORIGIN.x, -TABLE_ORIGIN.y, FRAME_WIDTH, FRAME_HEIGHT); + + // Rail wood, with a soft drop shadow under the whole table. + ctx.save(); + ctx.shadowColor = "rgba(0, 0, 0, 0.6)"; + ctx.shadowBlur = 0.06 * scale; + ctx.shadowOffsetY = 0.02 * scale; + const wood = ctx.createLinearGradient(-RAIL_WIDTH, 0, 1 + RAIL_WIDTH, 0); + wood.addColorStop(0, "#2a1810"); + wood.addColorStop(0.5, "#3d2416"); + wood.addColorStop(1, "#2a1810"); + ctx.fillStyle = wood; + ctx.beginPath(); + ctx.roundRect(-RAIL_WIDTH, -RAIL_WIDTH, 1 + RAIL_WIDTH * 2, 2 + RAIL_WIDTH * 2, 0.045); + ctx.fill(); + ctx.restore(); + ctx.strokeStyle = "rgba(255, 255, 255, 0.07)"; + ctx.lineWidth = 0.003; + ctx.stroke(); + + // Cloth, under the cushions too. + const cloth = ctx.createRadialGradient(0.5, 1, 0.1, 0.5, 1, 1.2); + cloth.addColorStop(0, CLOTH_CENTER); + cloth.addColorStop(1, CLOTH_EDGE); + ctx.fillStyle = cloth; + ctx.fillRect(-0.045, -0.045, 1.09, 2.09); + ctx.save(); + ctx.globalAlpha = 0.07; + ctx.fillStyle = noisePattern(ctx, scale); + ctx.fillRect(-0.045, -0.045, 1.09, 2.09); + ctx.restore(); + + for (const cushion of CUSHIONS) { + ctx.beginPath(); + for (const [i, point] of cushion.entries()) { + if (i === 0) ctx.moveTo(point.x, point.y); + else ctx.lineTo(point.x, point.y); + } + ctx.closePath(); + ctx.fillStyle = CUSHION; + ctx.fill(); + const [, noseStart, noseEnd] = cushion; + if (noseStart && noseEnd) { + ctx.beginPath(); + ctx.moveTo(noseStart.x, noseStart.y); + ctx.lineTo(noseEnd.x, noseEnd.y); + ctx.strokeStyle = "rgba(255, 255, 255, 0.1)"; + ctx.lineWidth = 0.003; + ctx.stroke(); + } + } + + for (const pocket of POCKETS) { + const hole = ctx.createRadialGradient(pocket.x, pocket.y, 0, pocket.x, pocket.y, pocket.radius); + hole.addColorStop(0, "#000"); + hole.addColorStop(0.75, "#050505"); + hole.addColorStop(1, "#1b1b1b"); + ctx.fillStyle = hole; + ctx.beginPath(); + ctx.arc(pocket.x, pocket.y, pocket.radius, 0, Math.PI * 2); + ctx.fill(); + } + + // Diamonds on the rails, spots and the head string on the cloth. + ctx.fillStyle = "rgba(236, 224, 196, 0.75)"; + const railMid = RAIL_WIDTH * 0.6; + for (const t of [0.25, 0.5, 0.75]) { + for (const [x, y] of [ + [t, -railMid], + [t, TABLE_LENGTH + railMid], + [-railMid, t], + [-railMid, 1 + t], + [1 + railMid, t], + [1 + railMid, 1 + t], + ] as const) { + ctx.beginPath(); + ctx.arc(x, y, 0.006, 0, Math.PI * 2); + ctx.fill(); + } + } + ctx.strokeStyle = "rgba(255, 255, 255, 0.06)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.moveTo(0, HEAD_SPOT.y); + ctx.lineTo(1, HEAD_SPOT.y); + ctx.stroke(); + ctx.fillStyle = "rgba(255, 255, 255, 0.18)"; + for (const spot of [HEAD_SPOT, FOOT_SPOT]) { + ctx.beginPath(); + ctx.arc(spot.x, spot.y, 0.005, 0, Math.PI * 2); + ctx.fill(); + } + + // The tray the potted balls line up in. + ctx.fillStyle = "rgba(255, 255, 255, 0.04)"; + ctx.beginPath(); + ctx.roundRect(-0.01, TRAY_Y - 0.032, 1.02, 0.064, 0.032); + ctx.fill(); +} + +const TRAY_Y = TABLE_LENGTH + RAIL_WIDTH + 0.07; + +function noisePattern(ctx: CanvasRenderingContext2D, scale: number): CanvasPattern | string { + const size = 128; + const tile = document.createElement("canvas"); + tile.width = size; + tile.height = size; + const tileContext = tile.getContext("2d"); + if (!tileContext) return "transparent"; + const image = tileContext.createImageData(size, size); + for (let i = 0; i < image.data.length; i += 4) { + const value = Math.random() * 255; + image.data[i] = value; + image.data[i + 1] = value; + image.data[i + 2] = value; + image.data[i + 3] = 255; + } + tileContext.putImageData(image, 0, 0); + const pattern = ctx.createPattern(tile, "repeat"); + if (!pattern) return "transparent"; + pattern.setTransform(new DOMMatrix().scale(1 / scale)); + return pattern; +} + +export function drawScene( + ctx: CanvasRenderingContext2D, + staticLayer: HTMLCanvasElement, + scale: number, + view: SceneView, +): void { + const { game } = view; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(staticLayer, 0, 0); + frameTransform(ctx, scale); + + const cue = game.ball(0); + const aiming = game.phase === "aiming" && cue?.onTable; + if (game.needsCall()) drawPocketCalls(ctx, view); + if (aiming && cue) drawAimGuide(ctx, game, cue, view.aimAngle); + + for (const ball of game.balls) if (ball.onTable) drawShadow(ctx, ball.x, ball.y, 1); + for (const ball of game.balls) if (ball.onTable) drawBall(ctx, ball.id, ball.x, ball.y, 1); + for (const sinking of view.sinking) drawSinking(ctx, sinking, view.now); + + if (aiming && cue) drawCue(ctx, cue, view.aimAngle, view.power ?? 0); + if (view.power !== null) drawPowerMeter(ctx, view.power); + + for (const [i, id] of game.pottedOrder.entries()) { + drawBall(ctx, id, 0.035 + i * 0.066, TRAY_Y, 1); + } +} + +function drawShadow(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void { + const shadow = ctx.createRadialGradient( + x + R * 0.3, + y + R * 0.45, + 0, + x + R * 0.3, + y + R * 0.45, + R * 1.25 * size, + ); + shadow.addColorStop(0, "rgba(0, 0, 0, 0.45)"); + shadow.addColorStop(0.6, "rgba(0, 0, 0, 0.25)"); + shadow.addColorStop(1, "rgba(0, 0, 0, 0)"); + ctx.fillStyle = shadow; + ctx.beginPath(); + ctx.arc(x + R * 0.3, y + R * 0.45, R * 1.25 * size, 0, Math.PI * 2); + ctx.fill(); +} + +function drawBall( + ctx: CanvasRenderingContext2D, + id: number, + x: number, + y: number, + size: number, +): void { + const r = R * size; + const color = BALL_COLORS[id > EIGHT ? id - EIGHT : id] ?? "#fff"; + ctx.save(); + ctx.beginPath(); + ctx.arc(x, y, r, 0, Math.PI * 2); + ctx.clip(); + ctx.fillStyle = id > EIGHT ? "#f4f1e8" : color; + ctx.fillRect(x - r, y - r, r * 2, r * 2); + if (id > EIGHT) { + ctx.fillStyle = color; + ctx.fillRect(x - r, y - r * 0.55, r * 2, r * 1.1); + } + if (id !== 0) { + ctx.fillStyle = "#f7f4ea"; + ctx.beginPath(); + ctx.arc(x, y, r * 0.47, 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = "#151515"; + ctx.font = `700 ${r * 0.62}px ui-sans-serif, system-ui, sans-serif`; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(String(id), x, y + r * 0.04); + } + const shade = ctx.createRadialGradient(x - r * 0.35, y - r * 0.4, r * 0.05, x, y, r); + shade.addColorStop(0, "rgba(255, 255, 255, 0.6)"); + shade.addColorStop(0.22, "rgba(255, 255, 255, 0.12)"); + shade.addColorStop(0.65, "rgba(0, 0, 0, 0)"); + shade.addColorStop(1, "rgba(0, 0, 0, 0.42)"); + ctx.fillStyle = shade; + ctx.fillRect(x - r, y - r, r * 2, r * 2); + ctx.restore(); +} + +function drawSinking(ctx: CanvasRenderingContext2D, sinking: Sinking, now: number): void { + const t = Math.min(1, (now - sinking.start) / SINK_SECONDS); + const ease = t * t; + const x = sinking.x + (sinking.pocket.x - sinking.x) * ease; + const y = sinking.y + (sinking.pocket.y - sinking.y) * ease; + const size = 1 - 0.45 * ease; + ctx.save(); + ctx.globalAlpha = 1 - ease * 0.85; + drawBall(ctx, sinking.ball, x, y, size); + ctx.restore(); +} + +interface AimHit { + readonly x: number; + readonly y: number; + readonly ball: Ball | null; +} + +/** Where the cue ball would first touch a ball, or the cushion line, along `angle`. */ +function castAim(game: BilliardsGame, cue: Ball, angle: number): AimHit { + const dx = Math.cos(angle); + const dy = Math.sin(angle); + let best = Infinity; + let hit: Ball | null = null; + for (const ball of game.balls) { + if (!ball.onTable || ball === cue) continue; + const fx = cue.x - ball.x; + const fy = cue.y - ball.y; + const b = fx * dx + fy * dy; + const c = fx * fx + fy * fy - 4 * R * R; + const disc = b * b - c; + if (disc < 0) continue; + const t = -b - Math.sqrt(disc); + if (t > 0 && t < best) { + best = t; + hit = ball; + } + } + const wallX = dx > 0 ? (1 - R - cue.x) / dx : dx < 0 ? (R - cue.x) / dx : Infinity; + const wallY = dy > 0 ? (2 - R - cue.y) / dy : dy < 0 ? (R - cue.y) / dy : Infinity; + const wall = Math.max(0, Math.min(wallX, wallY)); + if (wall < best) { + best = wall; + hit = null; + } + return { x: cue.x + dx * best, y: cue.y + dy * best, ball: hit }; +} + +function drawAimGuide( + ctx: CanvasRenderingContext2D, + game: BilliardsGame, + cue: Ball, + angle: number, +): void { + const hit = castAim(game, cue, angle); + ctx.save(); + ctx.lineCap = "round"; + ctx.setLineDash([0.01, 0.012]); + ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"; + ctx.lineWidth = 0.0035; + ctx.beginPath(); + ctx.moveTo(cue.x, cue.y); + ctx.lineTo(hit.x, hit.y); + ctx.stroke(); + ctx.setLineDash([]); + ctx.strokeStyle = "rgba(255, 255, 255, 0.55)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.arc(hit.x, hit.y, R, 0, Math.PI * 2); + ctx.stroke(); + if (hit.ball) { + const nx = (hit.ball.x - hit.x) / (2 * R); + const ny = (hit.ball.y - hit.y) / (2 * R); + ctx.strokeStyle = "rgba(255, 255, 255, 0.6)"; + ctx.lineWidth = 0.004; + ctx.beginPath(); + ctx.moveTo(hit.ball.x + nx * R, hit.ball.y + ny * R); + ctx.lineTo(hit.ball.x + nx * 0.3, hit.ball.y + ny * 0.3); + ctx.stroke(); + // The cue ball leaves at right angles to the object ball. + const dx = Math.cos(angle); + const dy = Math.sin(angle); + const along = dx * nx + dy * ny; + const tx = dx - along * nx; + const ty = dy - along * ny; + const length = Math.hypot(tx, ty); + if (length > 0.05) { + ctx.strokeStyle = "rgba(255, 255, 255, 0.22)"; + ctx.beginPath(); + ctx.moveTo(hit.x, hit.y); + ctx.lineTo(hit.x + (tx / length) * 0.12, hit.y + (ty / length) * 0.12); + ctx.stroke(); + } + } + ctx.restore(); +} + +const CUE_LENGTH = 1.15; + +function drawCue(ctx: CanvasRenderingContext2D, cue: Ball, angle: number, power: number): void { + const dx = Math.cos(angle); + const dy = Math.sin(angle); + const back = R + 0.012 + power * 0.14; + const tipX = cue.x - dx * back; + const tipY = cue.y - dy * back; + const buttX = tipX - dx * CUE_LENGTH; + const buttY = tipY - dy * CUE_LENGTH; + const px = -dy; + const py = dx; + const outline = (offset: number) => { + ctx.beginPath(); + ctx.moveTo(tipX + px * 0.0065 + offset, tipY + py * 0.0065 + offset * 1.4); + ctx.lineTo(buttX + px * 0.013 + offset, buttY + py * 0.013 + offset * 1.4); + ctx.lineTo(buttX - px * 0.013 + offset, buttY - py * 0.013 + offset * 1.4); + ctx.lineTo(tipX - px * 0.0065 + offset, tipY - py * 0.0065 + offset * 1.4); + ctx.closePath(); + }; + outline(0.012); + ctx.fillStyle = "rgba(0, 0, 0, 0.3)"; + ctx.fill(); + const body = ctx.createLinearGradient(tipX, tipY, buttX, buttY); + for (const [stop, color] of [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f3efe4"], + [0.025, "#f3efe4"], + [0.026, "#e0c69c"], + [0.62, "#b8875a"], + [0.621, "#d4af37"], + [0.63, "#d4af37"], + [0.631, "#2a1810"], + [1, "#120a06"], + ] as const) { + body.addColorStop(stop, color); + } + outline(0); + ctx.fillStyle = body; + ctx.fill(); +} + +function drawPowerMeter(ctx: CanvasRenderingContext2D, power: number): void { + const x = 1 + RAIL_WIDTH + 0.04; + const top = 0.6; + const height = 0.8; + ctx.fillStyle = "rgba(255, 255, 255, 0.08)"; + ctx.beginPath(); + ctx.roundRect(x, top, 0.018, height, 0.009); + ctx.fill(); + const fill = ctx.createLinearGradient(0, top + height, 0, top); + fill.addColorStop(0, "#5ad19a"); + fill.addColorStop(0.6, "#ffc850"); + fill.addColorStop(1, "#ff5a4f"); + ctx.fillStyle = fill; + ctx.beginPath(); + ctx.roundRect(x, top + height * (1 - power), 0.018, height * power, 0.009); + ctx.fill(); +} + +function drawPocketCalls(ctx: CanvasRenderingContext2D, view: SceneView): void { + const pulse = 0.35 + 0.25 * Math.sin(view.now * 4); + for (const pocket of POCKETS) { + const called = view.game.calledPocket === pocket.id; + const hovered = view.hoverPocket === pocket.id; + ctx.strokeStyle = `rgba(${CALL}, ${called || hovered ? 0.95 : pulse})`; + ctx.lineWidth = called ? 0.008 : 0.005; + ctx.beginPath(); + ctx.arc(pocket.x, pocket.y, pocket.radius * 1.3, 0, Math.PI * 2); + ctx.stroke(); + if (called) drawBall(ctx, EIGHT, pocket.x, pocket.y, 0.6); + } +} diff --git a/apps/web/src/components/billiards/billiardsRules.test.ts b/apps/web/src/components/billiards/billiardsRules.test.ts new file mode 100644 index 0000000000..5000774fc1 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRules.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { makeBall, MAX_SHOT_SPEED, type Ball, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { BilliardsGame, EIGHT, rackBalls, seededRandom } from "./billiardsRules.ts"; +import { BALL_RADIUS, FOOT_SPOT, HEAD_SPOT, POCKETS } from "./billiardsTable.ts"; + +function settle(game: BilliardsGame): PhysicsEvent[] { + const events: PhysicsEvent[] = []; + for (let frame = 0; frame < 60 * 60 && game.phase === "rolling"; frame++) { + game.advance(1 / 60, events); + } + return events; +} + +function angleTo(from: Ball, x: number, y: number): number { + return Math.atan2(y - from.y, x - from.x); +} + +function overlaps(balls: ReadonlyArray): number { + let count = 0; + const onTable = balls.filter((ball) => ball.onTable); + for (let i = 0; i < onTable.length; i++) { + for (let j = i + 1; j < onTable.length; j++) { + const a = onTable[i] as Ball; + const b = onTable[j] as Ball; + if (Math.hypot(a.x - b.x, a.y - b.y) < BALL_RADIUS * 2 - 1e-6) count++; + } + } + return count; +} + +const topLeft = POCKETS[0]!; +const topRight = POCKETS[1]!; + +describe("rackBalls", () => { + it("racks 15 balls without overlap and the 8 in the middle", () => { + const balls = rackBalls(seededRandom(7)); + expect(balls).toHaveLength(16); + expect(new Set(balls.map((ball) => ball.id)).size).toBe(16); + expect(overlaps(balls)).toBe(0); + const eight = balls.find((ball) => ball.id === EIGHT)!; + expect(eight.x).toBeCloseTo(FOOT_SPOT.x); + }); + + it("racks the same way for the same seed", () => { + expect(rackBalls(seededRandom(42))).toEqual(rackBalls(seededRandom(42))); + }); +}); + +describe("the break", () => { + it("spreads the rack at full power and comes to rest on the table", () => { + const game = new BilliardsGame({ random: seededRandom(3) }); + const cue = game.ball(0)!; + expect(game.shoot(angleTo(cue, FOOT_SPOT.x, FOOT_SPOT.y) + 0.004, MAX_SHOT_SPEED)).toBe(true); + settle(game); + expect(game.phase).toBe("aiming"); + expect(game.shots).toBe(0); + expect(game.penaltySeconds).toBe(0); + expect(overlaps(game.balls)).toBe(0); + for (const ball of game.balls.filter((b) => b.onTable)) { + expect(ball.x).toBeGreaterThan(0); + expect(ball.x).toBeLessThan(1); + expect(ball.y).toBeGreaterThan(0); + expect(ball.y).toBeLessThan(2); + } + const moved = game.balls.filter((b) => b.id !== 0 && Math.abs(b.y - FOOT_SPOT.y) > 0.2); + expect(moved.length).toBeGreaterThan(5); + }); + + it("is the same every time for the same rack and shot", () => { + const run = () => { + const game = new BilliardsGame({ random: seededRandom(11) }); + game.shoot(-Math.PI / 2 + 0.01, MAX_SHOT_SPEED); + settle(game); + return game.balls.map((ball) => [ball.id, ball.x, ball.y, ball.onTable]); + }; + expect(run()).toEqual(run()); + }); +}); + +describe("rules", () => { + // Cue and 8 on the diagonal to the top-left corner, so a straight shot pots the 8 there. + const eightShot = (extra: Ball[] = []) => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.4, 0.4), makeBall(EIGHT, 0.2, 0.2), ...extra], + }); + return { game, angle: angleTo(game.ball(0)!, topLeft.x, topLeft.y) }; + }; + + it("needs a called pocket before shooting the 8", () => { + const { game, angle } = eightShot(); + expect(game.needsCall()).toBe(true); + expect(game.shoot(angle, 2)).toBe(false); + }); + + it("clears the table when the 8 drops in the called pocket", () => { + const { game, angle } = eightShot(); + game.callPocket(topLeft.id); + expect(game.shoot(angle, 2)).toBe(true); + settle(game); + expect(game.phase).toBe("cleared"); + expect(game.shots).toBe(1); + expect(game.penaltySeconds).toBe(0); + }); + + it("respots the 8 with a penalty when it drops in another pocket", () => { + const { game, angle } = eightShot(); + game.callPocket(topRight.id); + game.shoot(angle, 2); + settle(game); + expect(game.phase).toBe("aiming"); + expect(game.lastShot?.foul).toBe("wrong8"); + expect(game.penaltySeconds).toBe(15); + expect(game.ball(EIGHT)).toMatchObject({ onTable: true, x: FOOT_SPOT.x }); + }); + + it("respots the 8 with a penalty when it drops before the other balls", () => { + const { game, angle } = eightShot([makeBall(3, 0.8, 1.6)]); + expect(game.needsCall()).toBe(false); + game.shoot(angle, 2); + settle(game); + expect(game.lastShot?.foul).toBe("early8"); + expect(game.penaltySeconds).toBe(15); + expect(game.ball(EIGHT)?.onTable).toBe(true); + }); + + it("puts a scratched cue ball back on the head spot with a penalty", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.3, 0.3), makeBall(3, 0.8, 1.6)], + }); + game.shoot(angleTo(game.ball(0)!, topLeft.x, topLeft.y), 2); + settle(game); + expect(game.lastShot?.foul).toBe("scratch"); + expect(game.penaltySeconds).toBe(10); + expect(game.ball(0)).toMatchObject({ onTable: true, x: HEAD_SPOT.x, y: HEAD_SPOT.y }); + }); + + it("forgives the first miss of a game, then adds seconds for each miss", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.5, 1.5), makeBall(3, 0.8, 0.3)], + }); + game.shoot(Math.PI / 2, 0.6); + settle(game); + expect(game.lastShot).toMatchObject({ foul: "noContact", forgiven: true }); + expect(game.penaltySeconds).toBe(0); + game.shoot(-Math.PI / 2, 0.6); + settle(game); + expect(game.lastShot).toMatchObject({ foul: "noContact", forgiven: false }); + expect(game.penaltySeconds).toBe(5); + }); + + it("counts a clean pot as one shot", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.4, 0.4), makeBall(3, 0.2, 0.2), makeBall(EIGHT, 0.5, 1.2)], + }); + game.shoot(angleTo(game.ball(0)!, topLeft.x, topLeft.y), 2); + settle(game); + expect(game.lastShot).toEqual({ foul: null, forgiven: false, potted: [3] }); + expect(game.penaltySeconds).toBe(0); + expect(game.needsCall()).toBe(true); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsRules.ts b/apps/web/src/components/billiards/billiardsRules.ts new file mode 100644 index 0000000000..c130d6991e --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRules.ts @@ -0,0 +1,228 @@ +import { + anyMoving, + makeBall, + stepPhysics, + STEP_SECONDS, + type Ball, + type PhysicsEvent, +} from "./billiardsPhysics.ts"; +import { BALL_RADIUS, FOOT_SPOT, HEAD_SPOT, TABLE_LENGTH, type Point } from "./billiardsTable.ts"; + +// Solo 8-ball: pot the other 14 in any order, then the 8 into a pocket you call. +// It's a race: the clock starts once the break settles, and fouls add seconds to it. + +export type Foul = "scratch" | "noContact" | "early8" | "wrong8" | "scratch8"; + +/** Seconds each foul adds to the clock. */ +export const FOUL_PENALTY_SECONDS: Readonly> = { + scratch: 10, + noContact: 5, + early8: 15, + wrong8: 15, + scratch8: 15, +}; +export const EIGHT = 8; + +export type Phase = "aiming" | "rolling" | "cleared"; + +/** A shot that runs longer than this is stopped where it is. */ +const MAX_ROLL_SECONDS = 40; + +/** Same seed, same sequence: the daily rack depends on it. */ +export function seededRandom(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** The cue ball on the head spot and 15 balls racked on the foot spot, the 8 in the middle. */ +export function rackBalls(random: () => number): Ball[] { + const others = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]; + for (let i = others.length - 1; i > 0; i--) { + const j = Math.floor(random() * (i + 1)); + [others[i], others[j]] = [others[j] as number, others[i] as number]; + } + const spacing = BALL_RADIUS * 2 + 0.0004; + const rowStep = spacing * (Math.sqrt(3) / 2); + const balls: Ball[] = [makeBall(0, HEAD_SPOT.x, HEAD_SPOT.y)]; + let next = 0; + for (let row = 0; row < 5; row++) { + for (let i = 0; i <= row; i++) { + const id = row === 2 && i === 1 ? EIGHT : (others[next++] as number); + balls.push(makeBall(id, FOOT_SPOT.x + (i - row / 2) * spacing, FOOT_SPOT.y - row * rowStep)); + } + } + return balls; +} + +export interface ShotResult { + readonly foul: Foul | null; + /** The game's first miss is free: likely a slip, so it only warns. */ + readonly forgiven: boolean; + readonly potted: ReadonlyArray; +} + +export interface BilliardsGameOptions { + readonly random?: () => number; + /** A custom layout, for tests. */ + readonly balls?: Ball[]; + readonly skipBreak?: boolean; +} + +export class BilliardsGame { + readonly balls: Ball[]; + phase: Phase = "aiming"; + isBreak: boolean; + shots = 0; + penaltySeconds = 0; + calledPocket: number | null = null; + lastShot: ShotResult | null = null; + /** Ball ids in the order they dropped. */ + readonly pottedOrder: number[] = []; + + private accumulator = 0; + private rollSeconds = 0; + private firstContact: number | null = null; + private pottedThisShot: Array<{ ball: number; pocket: number }> = []; + private objectBallsAtShotStart = 0; + private missForgiven = false; + + constructor(options: BilliardsGameOptions = {}) { + this.balls = options.balls ?? rackBalls(options.random ?? Math.random); + this.isBreak = !options.skipBreak; + } + + ball(id: number): Ball | undefined { + return this.balls.find((ball) => ball.id === id); + } + + /** Object balls still on the table, not counting the 8. */ + objectBallsLeft(): number { + return this.balls.filter((ball) => ball.onTable && ball.id !== 0 && ball.id !== EIGHT).length; + } + + /** Only the 8 is left, so a pocket has to be called before shooting. */ + needsCall(): boolean { + return this.phase === "aiming" && this.objectBallsLeft() === 0 && !!this.ball(EIGHT)?.onTable; + } + + callPocket(pocket: number): void { + if (this.needsCall()) this.calledPocket = pocket; + } + + /** Strikes the cue ball. False when it isn't time to shoot, or the 8 needs a called pocket. */ + shoot(angle: number, speed: number): boolean { + const cue = this.ball(0); + if (this.phase !== "aiming" || !cue?.onTable) return false; + if (this.needsCall() && this.calledPocket === null) return false; + cue.vx = Math.cos(angle) * speed; + cue.vy = Math.sin(angle) * speed; + this.firstContact = null; + this.pottedThisShot = []; + this.objectBallsAtShotStart = this.objectBallsLeft(); + this.rollSeconds = 0; + this.accumulator = 0; + this.phase = "rolling"; + return true; + } + + /** Runs the simulation for `seconds` in fixed steps; settles the shot once every ball stops. */ + advance(seconds: number, events: PhysicsEvent[]): void { + if (this.phase !== "rolling") return; + this.accumulator += seconds; + while (this.accumulator >= STEP_SECONDS) { + this.accumulator -= STEP_SECONDS; + this.rollSeconds += STEP_SECONDS; + const from = events.length; + stepPhysics(this.balls, events); + for (let i = from; i < events.length; i++) { + const event = events[i]; + if (event?.kind === "ball" && this.firstContact === null) { + if (event.a === 0) this.firstContact = event.b; + else if (event.b === 0) this.firstContact = event.a; + } else if (event?.kind === "pocket") { + this.pottedThisShot.push({ ball: event.ball, pocket: event.pocket }); + if (event.ball !== 0) this.pottedOrder.push(event.ball); + } + } + if (this.rollSeconds > MAX_ROLL_SECONDS) { + for (const ball of this.balls) { + ball.vx = 0; + ball.vy = 0; + } + } + if (!anyMoving(this.balls)) { + this.settle(); + return; + } + } + } + + private settle(): void { + const scratched = this.pottedThisShot.some((pot) => pot.ball === 0); + const eight = this.pottedThisShot.find((pot) => pot.ball === EIGHT); + let foul: Foul | null = null; + let forgiven = false; + let cleared = false; + + if (this.isBreak) { + this.isBreak = false; + } else { + this.shots += 1; + if (eight) { + if (this.objectBallsAtShotStart > 0) foul = "early8"; + else if (scratched) foul = "scratch8"; + else if (eight.pocket !== this.calledPocket) foul = "wrong8"; + else cleared = true; + } else if (scratched) { + foul = "scratch"; + } else if (this.firstContact === null) { + foul = "noContact"; + } + if (foul === "noContact" && !this.missForgiven) { + this.missForgiven = true; + forgiven = true; + } else if (foul) { + this.penaltySeconds += FOUL_PENALTY_SECONDS[foul]; + } + } + + if (eight && !cleared) this.respot(EIGHT, FOOT_SPOT, -1); + if (scratched) this.respot(0, HEAD_SPOT, 1); + this.lastShot = { + foul, + forgiven, + potted: this.pottedThisShot.map((pot) => pot.ball).filter((id) => id !== 0), + }; + this.phase = cleared ? "cleared" : "aiming"; + } + + /** Puts a ball back on `spot`, sliding along the table (`direction` first) until it's clear. */ + private respot(id: number, spot: Point, direction: 1 | -1): void { + const ball = this.ball(id); + if (!ball) return; + const potted = this.pottedOrder.lastIndexOf(id); + if (potted !== -1) this.pottedOrder.splice(potted, 1); + const step = BALL_RADIUS * 0.5; + for (let i = 0; i < 400; i++) { + const offset = (i % 2 === 1 ? 1 : -1) * Math.ceil(i / 2) * step * direction; + const y = spot.y + offset; + if (y < BALL_RADIUS || y > TABLE_LENGTH - BALL_RADIUS) continue; + const free = this.balls.every( + (other) => + other === ball || + !other.onTable || + Math.hypot(other.x - spot.x, other.y - y) >= BALL_RADIUS * 2 + 0.001, + ); + if (free) { + Object.assign(ball, { x: spot.x, y, vx: 0, vy: 0, onTable: true }); + return; + } + } + } +} diff --git a/apps/web/src/components/billiards/billiardsSession.ts b/apps/web/src/components/billiards/billiardsSession.ts new file mode 100644 index 0000000000..c583b5fa5a --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSession.ts @@ -0,0 +1,277 @@ +import { observeResize } from "~/lib/observeResize"; + +import { BilliardsAudio } from "./billiardsAudio.ts"; +import { MAX_SHOT_SPEED, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { + drawScene, + drawStaticLayer, + FRAME_WIDTH, + SINK_SECONDS, + TABLE_ORIGIN, + type Sinking, +} from "./billiardsRender.ts"; +import { BilliardsGame, type Foul, type Phase } from "./billiardsRules.ts"; +import { POCKETS, type Point } from "./billiardsTable.ts"; + +/** What the overlay shows around the canvas. */ +export interface BilliardsHud { + readonly phase: Phase; + readonly isBreak: boolean; + readonly shots: number; + readonly penaltySeconds: number; + /** Clock plus penalties: the race time. */ + readonly totalMs: number; + readonly needsCall: boolean; + readonly calledPocket: number | null; + readonly foul: Foul | null; + /** The foul was the game's free first miss. */ + readonly forgiven: boolean; + /** The player tried to shoot the 8 without calling a pocket. */ + readonly blocked: boolean; +} + +const CHARGE_MS = 1100; +const MIN_SHOT_SPEED = 0.3; +const FINE_AIM = 0.12; +const POCKET_PICK_RADIUS = 0.1; +const HUD_INTERVAL_MS = 250; + +function wrapAngle(angle: number): number { + return Math.atan2(Math.sin(angle), Math.cos(angle)); +} + +/** Runs one game on a canvas: input, simulation, sound and drawing. */ +export class BilliardsSession { + private readonly canvas: HTMLCanvasElement; + private readonly context: CanvasRenderingContext2D; + private readonly staticLayer = document.createElement("canvas"); + private readonly onHud: (hud: BilliardsHud) => void; + private readonly audio = new BilliardsAudio(); + private readonly stopObservingResize: () => void; + private game = new BilliardsGame(); + private scale = 1; + private frame = 0; + private lastFrame = 0; + private aimAngle = -Math.PI / 2; + private lastPointerAngle: number | null = null; + private pointer: Point | null = null; + private chargeStart: number | null = null; + private sinking: Sinking[] = []; + private clockStart: number | null = null; + private clockEnd: number | null = null; + private blockedUntil = 0; + private lastHud: BilliardsHud | null = null; + private lastHudAt = 0; + + constructor(canvas: HTMLCanvasElement, onHud: (hud: BilliardsHud) => void) { + const context = canvas.getContext("2d"); + if (!context) throw new Error("Canvas 2D is not available"); + this.canvas = canvas; + this.context = context; + this.onHud = onHud; + this.stopObservingResize = observeResize(canvas, () => this.resize()); + canvas.addEventListener("pointerdown", this.handlePointerDown); + canvas.addEventListener("pointermove", this.handlePointerMove); + canvas.addEventListener("pointerup", this.handlePointerUp); + canvas.addEventListener("pointercancel", this.handlePointerCancel); + canvas.addEventListener("contextmenu", this.handleContextMenu); + this.resize(); + this.frame = requestAnimationFrame(this.tick); + } + + dispose(): void { + cancelAnimationFrame(this.frame); + this.stopObservingResize(); + this.canvas.removeEventListener("pointerdown", this.handlePointerDown); + this.canvas.removeEventListener("pointermove", this.handlePointerMove); + this.canvas.removeEventListener("pointerup", this.handlePointerUp); + this.canvas.removeEventListener("pointercancel", this.handlePointerCancel); + this.canvas.removeEventListener("contextmenu", this.handleContextMenu); + this.audio.dispose(); + } + + restart(): void { + this.game = new BilliardsGame(); + this.aimAngle = -Math.PI / 2; + this.chargeStart = null; + this.sinking = []; + this.clockStart = null; + this.clockEnd = null; + this.blockedUntil = 0; + this.emitHud(performance.now(), true); + } + + /** Drops a shot being charged. False when there was none. */ + cancelCharge(): boolean { + if (this.chargeStart === null) return false; + this.chargeStart = null; + return true; + } + + private resize(): void { + const rect = this.canvas.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) return; + const ratio = window.devicePixelRatio || 1; + this.canvas.width = Math.round(rect.width * ratio); + this.canvas.height = Math.round(rect.height * ratio); + this.staticLayer.width = this.canvas.width; + this.staticLayer.height = this.canvas.height; + this.scale = this.canvas.width / FRAME_WIDTH; + drawStaticLayer(this.staticLayer, this.scale); + } + + private toTable(event: PointerEvent): Point { + const rect = this.canvas.getBoundingClientRect(); + return { + x: ((event.clientX - rect.left) / rect.width) * FRAME_WIDTH - TABLE_ORIGIN.x, + y: ((event.clientY - rect.top) / rect.width) * FRAME_WIDTH - TABLE_ORIGIN.y, + }; + } + + private pocketAt(point: Point | null): number | null { + if (!point || !this.game.needsCall()) return null; + for (const pocket of POCKETS) { + if (Math.hypot(pocket.x - point.x, pocket.y - point.y) < POCKET_PICK_RADIUS) return pocket.id; + } + return null; + } + + private power(now: number): number { + return this.chargeStart === null ? 0 : Math.min(1, (now - this.chargeStart) / CHARGE_MS); + } + + private readonly handlePointerMove = (event: PointerEvent) => { + this.pointer = this.toTable(event); + this.canvas.style.cursor = this.pocketAt(this.pointer) === null ? "crosshair" : "pointer"; + const cue = this.game.ball(0); + if (!cue?.onTable) return; + const target = Math.atan2(this.pointer.y - cue.y, this.pointer.x - cue.x); + // The aim holds still while a shot charges, so pressing a trackpad can't nudge it. + if (this.chargeStart === null) { + this.aimAngle = + event.shiftKey && this.lastPointerAngle !== null + ? this.aimAngle + wrapAngle(target - this.lastPointerAngle) * FINE_AIM + : target; + } + this.lastPointerAngle = target; + }; + + private readonly handlePointerDown = (event: PointerEvent) => { + if (event.button !== 0) return; + this.audio.unlock(); + const now = performance.now(); + if (this.game.phase !== "aiming") return; + const pocket = this.pocketAt(this.toTable(event)); + if (pocket !== null) { + this.game.callPocket(pocket); + this.emitHud(now, true); + return; + } + if (this.game.needsCall() && this.game.calledPocket === null) { + this.blockedUntil = now + 2500; + this.emitHud(now, true); + return; + } + this.chargeStart = now; + this.canvas.setPointerCapture(event.pointerId); + }; + + private readonly handlePointerUp = (event: PointerEvent) => { + if (this.chargeStart === null) return; + const now = performance.now(); + const power = this.power(now); + this.chargeStart = null; + if (this.canvas.hasPointerCapture(event.pointerId)) { + this.canvas.releasePointerCapture(event.pointerId); + } + const speed = MIN_SHOT_SPEED + (MAX_SHOT_SPEED - MIN_SHOT_SPEED) * power * power; + if (!this.game.shoot(this.aimAngle, speed)) return; + this.audio.cue(power); + this.emitHud(now, true); + }; + + private readonly handlePointerCancel = () => { + this.chargeStart = null; + }; + + private readonly handleContextMenu = (event: Event) => { + event.preventDefault(); + }; + + private readonly tick = (time: number) => { + this.frame = requestAnimationFrame(this.tick); + const seconds = this.lastFrame === 0 ? 0 : Math.min(0.05, (time - this.lastFrame) / 1000); + this.lastFrame = time; + + const phase = this.game.phase; + const events: PhysicsEvent[] = []; + this.game.advance(seconds, events); + this.playEvents(events, time / 1000); + if (this.game.phase !== phase) { + if (this.game.phase === "cleared") this.clockEnd = time; + // The clock starts once the break settles. + if (!this.game.isBreak && this.clockStart === null) this.clockStart = time; + this.emitHud(time, true); + } + this.sinking = this.sinking.filter((sinking) => time / 1000 - sinking.start < SINK_SECONDS); + + drawScene(this.context, this.staticLayer, this.scale, { + game: this.game, + aimAngle: this.aimAngle, + power: this.chargeStart === null ? null : this.power(time), + hoverPocket: this.pocketAt(this.pointer), + sinking: this.sinking, + now: time / 1000, + }); + if (time - this.lastHudAt > HUD_INTERVAL_MS) this.emitHud(time, false); + }; + + private playEvents(events: ReadonlyArray, now: number): void { + const clicks: number[] = []; + const thuds: number[] = []; + for (const event of events) { + if (event.kind === "ball") clicks.push(event.speed); + else if (event.kind === "cushion") thuds.push(event.speed); + else { + this.audio.pocket(); + const pocket = POCKETS[event.pocket]; + if (pocket) { + this.sinking.push({ ball: event.ball, x: event.x, y: event.y, pocket, start: now }); + } + } + } + // A break makes dozens of contacts in one frame; the loudest few carry it. + for (const speed of clicks.sort((a, b) => b - a).slice(0, 3)) this.audio.click(speed); + for (const speed of thuds.sort((a, b) => b - a).slice(0, 2)) this.audio.cushion(speed); + } + + private emitHud(now: number, force: boolean): void { + const game = this.game; + const hud: BilliardsHud = { + phase: game.phase, + isBreak: game.isBreak, + shots: game.shots, + penaltySeconds: game.penaltySeconds, + totalMs: + (this.clockStart === null ? 0 : (this.clockEnd ?? now) - this.clockStart) + + game.penaltySeconds * 1000, + needsCall: game.needsCall(), + calledPocket: game.calledPocket, + foul: game.phase === "rolling" ? null : (game.lastShot?.foul ?? null), + forgiven: game.lastShot?.forgiven ?? false, + blocked: now < this.blockedUntil, + }; + this.lastHudAt = now; + const last = this.lastHud; + const changed = + !last || + (Object.keys(hud) as Array).some((key) => + key === "totalMs" + ? Math.floor(hud.totalMs / 1000) !== Math.floor(last.totalMs / 1000) + : hud[key] !== last[key], + ); + if (!force && !changed) return; + this.lastHud = hud; + this.onHud(hud); + } +} diff --git a/apps/web/src/components/billiards/billiardsTable.ts b/apps/web/src/components/billiards/billiardsTable.ts new file mode 100644 index 0000000000..6426858f7a --- /dev/null +++ b/apps/web/src/components/billiards/billiardsTable.ts @@ -0,0 +1,82 @@ +// Table geometry in table units: the cloth is 1 wide and 2 long, top-down and portrait. +// The head (where the cue ball starts) is at the bottom, the rack at the top. + +export const TABLE_WIDTH = 1; +export const TABLE_LENGTH = 2; +export const BALL_RADIUS = 0.0225; +/** Cushion plus wood beyond the cloth edge. */ +export const RAIL_WIDTH = 0.075; +const CUSHION_DEPTH = 0.036; + +export interface Point { + readonly x: number; + readonly y: number; +} + +export const HEAD_SPOT: Point = { x: 0.5, y: 1.5 }; +export const FOOT_SPOT: Point = { x: 0.5, y: 0.5 }; + +export interface Pocket { + readonly id: number; + readonly x: number; + readonly y: number; + /** A ball whose centre comes this close drops. */ + readonly radius: number; +} + +export const POCKETS: ReadonlyArray = [ + { id: 0, x: -0.014, y: -0.014, radius: 0.05 }, + { id: 1, x: 1.014, y: -0.014, radius: 0.05 }, + { id: 2, x: -0.034, y: 1, radius: 0.046 }, + { id: 3, x: 1.034, y: 1, radius: 0.046 }, + { id: 4, x: -0.014, y: 2.014, radius: 0.05 }, + { id: 5, x: 1.014, y: 2.014, radius: 0.05 }, +]; + +// Where a cushion nose ends next to a corner, and half the side pocket opening. +const CORNER_MOUTH = 0.075; +const SIDE_MOUTH = 0.05; +const D = CUSHION_DEPTH; + +/** + * Each cushion as [jaw back, nose start, nose end, jaw back]: drawn as one polygon, and its three + * edges facing the cloth are what balls bounce off. + */ +export const CUSHIONS: ReadonlyArray> = (() => { + const top: Point[] = [ + { x: CORNER_MOUTH - 0.027, y: -D }, + { x: CORNER_MOUTH, y: 0 }, + { x: 1 - CORNER_MOUTH, y: 0 }, + { x: 1 - CORNER_MOUTH + 0.027, y: -D }, + ]; + const leftUpper: Point[] = [ + { x: -D, y: CORNER_MOUTH - 0.027 }, + { x: 0, y: CORNER_MOUTH }, + { x: 0, y: 1 - SIDE_MOUTH }, + { x: -0.045, y: 1 - SIDE_MOUTH + 0.012 }, + ]; + const leftLower: Point[] = [ + { x: -0.045, y: 1 + SIDE_MOUTH - 0.012 }, + { x: 0, y: 1 + SIDE_MOUTH }, + { x: 0, y: 2 - CORNER_MOUTH }, + { x: -D, y: 2 - CORNER_MOUTH + 0.027 }, + ]; + const mirrorX = (points: Point[]) => points.map((p) => ({ x: TABLE_WIDTH - p.x, y: p.y })); + const mirrorY = (points: Point[]) => points.map((p) => ({ x: p.x, y: TABLE_LENGTH - p.y })); + return [top, mirrorY(top), leftUpper, leftLower, mirrorX(leftUpper), mirrorX(leftLower)]; +})(); + +export interface Segment { + readonly a: Point; + readonly b: Point; +} + +export const CUSHION_SEGMENTS: ReadonlyArray = CUSHIONS.flatMap((polygon) => { + const segments: Segment[] = []; + for (let i = 0; i < polygon.length - 1; i++) { + const a = polygon[i]; + const b = polygon[i + 1]; + if (a && b) segments.push({ a, b }); + } + return segments; +}); diff --git a/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts b/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts new file mode 100644 index 0000000000..646a17c7c9 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts @@ -0,0 +1,57 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { describe, expect, it } from "vite-plus/test"; + +import { snapshotThreads, threadAlerts } from "./billiardsThreadAlerts.ts"; + +function shell( + id: string, + state: { + running?: boolean; + completedAt?: string | null; + needsInput?: boolean; + subagent?: boolean; + runStatus?: string; + } = {}, +): EnvironmentThreadShell { + return { + environmentId: "env", + id, + title: id, + lineage: { relationshipToParent: state.subagent ? "subagent" : null, sideChat: false }, + runtime: state.running ? { status: "running" } : { status: "completed" }, + latestRun: + state.completedAt === undefined + ? null + : { status: state.runStatus ?? "completed", completedAt: state.completedAt }, + hasPendingApprovals: false, + hasPendingUserInput: state.needsInput ?? false, + pendingSubagentRequest: null, + } as unknown as EnvironmentThreadShell; +} + +describe("threadAlerts", () => { + it("says nothing about threads that were already done when the game opened", () => { + const threads = [shell("a", { completedAt: "2026-11-26T10:00:00Z" })]; + expect(threadAlerts(snapshotThreads(threads), threads)).toEqual([]); + }); + + it("reports a thread that finishes while playing", () => { + const baseline = snapshotThreads([shell("a", { running: true, completedAt: null })]); + const alerts = threadAlerts(baseline, [shell("a", { completedAt: "2026-11-26T10:05:00Z" })]); + expect(alerts.map((alert) => [alert.thread.id, alert.kind])).toEqual([["a", "done"]]); + }); + + it("reports a thread that starts needing you, but not a subagent or a stopped run", () => { + const baseline = snapshotThreads([ + shell("a", { running: true }), + shell("b", { running: true, subagent: true }), + shell("c", { running: true }), + ]); + const alerts = threadAlerts(baseline, [ + shell("a", { running: true, needsInput: true }), + shell("b", { completedAt: "2026-11-26T10:05:00Z", subagent: true }), + shell("c", { completedAt: "2026-11-26T10:05:00Z", runStatus: "interrupted" }), + ]); + expect(alerts.map((alert) => [alert.thread.id, alert.kind])).toEqual([["a", "needsYou"]]); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsThreadAlerts.ts b/apps/web/src/components/billiards/billiardsThreadAlerts.ts new file mode 100644 index 0000000000..296f18c02f --- /dev/null +++ b/apps/web/src/components/billiards/billiardsThreadAlerts.ts @@ -0,0 +1,73 @@ +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/models"; +import { isListedThreadLineage } from "@t3tools/contracts"; + +// While the game is open, it shows a bubble for each thread that finished or started needing +// you since the game opened, so playing never hides an agent that's done. + +export type ThreadAlertKind = "done" | "needsYou"; + +export interface ThreadAlert { + readonly key: string; + readonly thread: EnvironmentThreadShell; + readonly kind: ThreadAlertKind; +} + +interface ThreadMark { + readonly completedAt: string | null; + readonly needsYou: boolean; +} + +export type ThreadBaseline = ReadonlyMap; + +function threadAlertKey(thread: EnvironmentThreadShell): string { + return `${thread.environmentId}:${thread.id}`; +} + +function needsYou(thread: EnvironmentThreadShell): boolean { + return ( + thread.hasPendingApprovals || + thread.hasPendingUserInput || + (thread.pendingSubagentRequest ?? null) !== null + ); +} + +function finishedAt(thread: EnvironmentThreadShell): string | null { + const run = thread.latestRun; + if (!run?.completedAt || run.status === "interrupted" || run.status === "cancelled") return null; + return threadRuntimeIsActive(thread.runtime) ? null : run.completedAt; +} + +/** Where every thread stands when the game opens. */ +export function snapshotThreads(threads: ReadonlyArray): ThreadBaseline { + return new Map( + threads.map((thread) => [ + threadAlertKey(thread), + { completedAt: finishedAt(thread), needsYou: needsYou(thread) }, + ]), + ); +} + +/** Listed threads that finished, or started needing you, since `baseline`. */ +export function threadAlerts( + baseline: ThreadBaseline, + threads: ReadonlyArray, +): ThreadAlert[] { + const alerts: ThreadAlert[] = []; + for (const thread of threads) { + if (!isListedThreadLineage(thread.lineage)) continue; + const key = threadAlertKey(thread); + const before = baseline.get(key); + if (needsYou(thread)) { + if (!before?.needsYou) alerts.push({ key, thread, kind: "needsYou" }); + continue; + } + const completedAt = finishedAt(thread); + if (completedAt !== null && completedAt !== before?.completedAt) { + alerts.push({ key, thread, kind: "done" }); + } + } + return alerts; +} diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 0ddb535296..3478112260 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -1,7 +1,7 @@ import { ArrowLeftIcon, ArrowRightIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; -import type { ReactNode } from "react"; +import type { MouseEvent, ReactNode } from "react"; import { T, useGT } from "gt-react"; -import { memo } from "react"; +import { lazy, memo, Suspense, useState } from "react"; import { Link, useLocation, useNavigate } from "@tanstack/react-router"; import { useAtomValue } from "@effect/atom-react"; @@ -43,6 +43,9 @@ import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUp import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; +// Loaded only when someone triple-clicks the logo. +const BilliardsOverlay = lazy(() => import("../billiards/BilliardsOverlay")); + export const SidebarChromeHeader = memo(function SidebarChromeHeader({ isElectron, }: { @@ -169,17 +172,32 @@ function HistoryNavigationButton({ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) { const gt = useGT(); + const [billiardsOpen, setBilliardsOpen] = useState(false); + // A triple-click opens the billiards easter egg; a single click still goes home. + const openBilliardsOnTripleClick = (event: MouseEvent) => { + if (event.detail < 3) return; + event.preventDefault(); + setBilliardsOpen(true); + }; return ( - - - + <> + + + + {billiardsOpen ? ( + + setBilliardsOpen(false)} /> + + ) : null} + ); } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 9e8e552d4a..0d62ff2c6c 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3111,6 +3111,26 @@ "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", + "082bec31dabcc747": "Sag zuerst ein Loch für die 8 an: Klick darauf.", + "8ef73b820d9c2068": "Weiße versenkt. +{seconds} s", + "6e5ca67f8c64ad7e": "Keine Kugel getroffen. Einmal gratis, danach kostet es {seconds} s.", + "5423b71c71cfb18c": "Keine Kugel getroffen. +{seconds} s", + "61d672c96dc8d887": "Die 8 fiel zu früh und liegt wieder auf ihrem Punkt. +{seconds} s", + "3bd41c9312c93563": "Falsches Loch. Die 8 liegt wieder auf ihrem Punkt. +{seconds} s", + "b3a4c68407de4257": "Weiße mit der 8 versenkt. Die 8 liegt wieder auf ihrem Punkt. +{seconds} s", + "d1244c2b4eb6f283": "Nur noch die 8 ist übrig. Klick auf das Loch, das du ansagst.", + "f3127de5f465fbf6": "8 angesagt. Klick auf ein anderes Loch, um es zu ändern.", + "be86b3498545b015": "Die Uhr läuft ab dem Anstoß. Halten zum Aufladen, loslassen zum Stoßen.", + "1514485143207779": "Zielen mit der Maus, halten zum Aufladen, loslassen zum Stoßen. Shift zielt feiner, Esc schließt.", + "412cfbefb305eb90": "Billard", + "80140e56c78edfbd": "Stöße {shots}", + "41d5b3a5d887b6f8": "Strafzeit +{seconds} s", + "17547068ba80744d": "{title} ist fertig", + "a689501ff2ddb4b6": "{title} braucht dich", + "b2be70822d55f16a": "Öffnen", + "52499724d03777c6": "Tisch abgeräumt", + "9fab80fe09b3dacf": "{clock} gespielt, +{seconds} s Strafzeit, {shots} Stöße", + "03b3f43d7b61d793": "Nochmal spielen", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} Min. {seconds} s", "f2a955905704b91d": "{hours} Std. {minutes} Min.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 7a86e077d8..9f5e8837c6 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", + "082bec31dabcc747": "Call a pocket for the 8 first: click it.", + "8ef73b820d9c2068": "Scratch. +{seconds} s", + "6e5ca67f8c64ad7e": "No ball hit. Free this once, after that it costs {seconds} s.", + "5423b71c71cfb18c": "No ball hit. +{seconds} s", + "61d672c96dc8d887": "The 8 went in too early and is back on its spot. +{seconds} s", + "3bd41c9312c93563": "Wrong pocket. The 8 is back on its spot. +{seconds} s", + "b3a4c68407de4257": "Scratch on the 8. It is back on its spot. +{seconds} s", + "d1244c2b4eb6f283": "Only the 8 is left. Click the pocket you call.", + "f3127de5f465fbf6": "8 called. Click another pocket to change it.", + "be86b3498545b015": "The clock starts after the break. Hold to charge, release to shoot.", + "1514485143207779": "Move to aim, hold to charge, release to shoot. Shift aims finer, Esc closes.", + "412cfbefb305eb90": "Billiards", + "80140e56c78edfbd": "Shots {shots}", + "41d5b3a5d887b6f8": "Penalties +{seconds} s", + "17547068ba80744d": "{title} is done", + "a689501ff2ddb4b6": "{title} needs you", + "b2be70822d55f16a": "Open", + "52499724d03777c6": "Table cleared", + "9fab80fe09b3dacf": "{clock} played, +{seconds} s penalties, {shots} shots", + "03b3f43d7b61d793": "Play again", "49cc06e79f21f85a": "{seconds}s", "8603d41c52392f1d": "{minutes}m {seconds}s", "f2a955905704b91d": "{hours}h {minutes}m", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 0cd18d2f03..9a47b4a1ad 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", + "082bec31dabcc747": "Primero canta una tronera para la 8: haz clic en ella.", + "8ef73b820d9c2068": "Blanca entronerada. +{seconds} s", + "6e5ca67f8c64ad7e": "No tocaste ninguna bola. Gratis una vez, después cuesta {seconds} s.", + "5423b71c71cfb18c": "No tocaste ninguna bola. +{seconds} s", + "61d672c96dc8d887": "La 8 entró demasiado pronto y vuelve a su punto. +{seconds} s", + "3bd41c9312c93563": "Tronera equivocada. La 8 vuelve a su punto. +{seconds} s", + "b3a4c68407de4257": "Blanca entronerada con la 8. La 8 vuelve a su punto. +{seconds} s", + "d1244c2b4eb6f283": "Solo queda la 8. Haz clic en la tronera que cantas.", + "f3127de5f465fbf6": "8 cantada. Haz clic en otra tronera para cambiarla.", + "be86b3498545b015": "El reloj empieza después del saque. Mantén para cargar, suelta para tirar.", + "1514485143207779": "Mueve para apuntar, mantén para cargar, suelta para tirar. Mayús apunta más fino, Esc cierra.", + "412cfbefb305eb90": "Billar", + "80140e56c78edfbd": "Tiros {shots}", + "41d5b3a5d887b6f8": "Penalizaciones +{seconds} s", + "17547068ba80744d": "{title} terminó", + "a689501ff2ddb4b6": "{title} te necesita", + "b2be70822d55f16a": "Abrir", + "52499724d03777c6": "Mesa limpia", + "9fab80fe09b3dacf": "{clock} de juego, +{seconds} s de penalización, {shots} tiros", + "03b3f43d7b61d793": "Jugar otra vez", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f31ae29b98..240692cde6 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", + "082bec31dabcc747": "Annoncez d’abord une poche pour la 8 : cliquez dessus.", + "8ef73b820d9c2068": "Blanche empochée. +{seconds} s", + "6e5ca67f8c64ad7e": "Aucune bille touchée. Gratuit une fois, ensuite cela coûte {seconds} s.", + "5423b71c71cfb18c": "Aucune bille touchée. +{seconds} s", + "61d672c96dc8d887": "La 8 est tombée trop tôt et revient sur son point. +{seconds} s", + "3bd41c9312c93563": "Mauvaise poche. La 8 revient sur son point. +{seconds} s", + "b3a4c68407de4257": "Blanche empochée avec la 8. La 8 revient sur son point. +{seconds} s", + "d1244c2b4eb6f283": "Il ne reste que la 8. Cliquez sur la poche que vous annoncez.", + "f3127de5f465fbf6": "8 annoncée. Cliquez sur une autre poche pour changer.", + "be86b3498545b015": "Le chrono démarre après la casse. Maintenez pour charger, relâchez pour tirer.", + "1514485143207779": "Bougez pour viser, maintenez pour charger, relâchez pour tirer. Maj vise plus finement, Échap ferme.", + "412cfbefb305eb90": "Billard", + "80140e56c78edfbd": "Coups {shots}", + "41d5b3a5d887b6f8": "Pénalités +{seconds} s", + "17547068ba80744d": "{title} est terminé", + "a689501ff2ddb4b6": "{title} a besoin de vous", + "b2be70822d55f16a": "Ouvrir", + "52499724d03777c6": "Table nettoyée", + "9fab80fe09b3dacf": "{clock} de jeu, +{seconds} s de pénalités, {shots} coups", + "03b3f43d7b61d793": "Rejouer", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 633f52eb81..20152c1469 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3108,6 +3108,26 @@ "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", + "082bec31dabcc747": "先に8番のポケットを指定してください:クリックで指定します。", + "8ef73b820d9c2068": "スクラッチ。+{seconds}秒", + "6e5ca67f8c64ad7e": "どのボールにも当たりませんでした。1回目は無料、次からは{seconds}秒加算されます。", + "5423b71c71cfb18c": "どのボールにも当たりませんでした。+{seconds}秒", + "61d672c96dc8d887": "8番が早く落ちたので元の位置に戻ります。+{seconds}秒", + "3bd41c9312c93563": "違うポケットです。8番は元の位置に戻ります。+{seconds}秒", + "b3a4c68407de4257": "8番と一緒にスクラッチ。8番は元の位置に戻ります。+{seconds}秒", + "d1244c2b4eb6f283": "残りは8番だけです。狙うポケットをクリックしてください。", + "f3127de5f465fbf6": "8番を指定しました。別のポケットをクリックすると変更できます。", + "be86b3498545b015": "時計はブレイクの後に動き始めます。長押しでため、離して打ちます。", + "1514485143207779": "動かして狙い、長押しでため、離して打ちます。Shiftで細かく狙い、Escで閉じます。", + "412cfbefb305eb90": "ビリヤード", + "80140e56c78edfbd": "ショット {shots}", + "41d5b3a5d887b6f8": "ペナルティ +{seconds}秒", + "17547068ba80744d": "{title} が完了しました", + "a689501ff2ddb4b6": "{title} が対応を待っています", + "b2be70822d55f16a": "開く", + "52499724d03777c6": "テーブルクリア", + "9fab80fe09b3dacf": "プレイ {clock}、ペナルティ +{seconds}秒、{shots}ショット", + "03b3f43d7b61d793": "もう一度プレイ", "49cc06e79f21f85a": "{seconds}秒", "8603d41c52392f1d": "{minutes}分{seconds}秒", "f2a955905704b91d": "{hours}時間{minutes}分", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 3a56c352d3..34bbebfc4b 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3109,6 +3109,26 @@ "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", + "082bec31dabcc747": "먼저 8번 공의 포켓을 지정하세요: 포켓을 클릭하세요.", + "8ef73b820d9c2068": "스크래치. +{seconds}초", + "6e5ca67f8c64ad7e": "아무 공도 맞히지 못했습니다. 한 번은 무료, 그 다음부터는 {seconds}초가 추가됩니다.", + "5423b71c71cfb18c": "아무 공도 맞히지 못했습니다. +{seconds}초", + "61d672c96dc8d887": "8번 공이 너무 일찍 들어가 제자리로 돌아갑니다. +{seconds}초", + "3bd41c9312c93563": "잘못된 포켓입니다. 8번 공이 제자리로 돌아갑니다. +{seconds}초", + "b3a4c68407de4257": "8번 공과 함께 스크래치. 8번 공이 제자리로 돌아갑니다. +{seconds}초", + "d1244c2b4eb6f283": "8번 공만 남았습니다. 지정할 포켓을 클릭하세요.", + "f3127de5f465fbf6": "8번 공 포켓을 지정했습니다. 다른 포켓을 클릭하면 바뀝니다.", + "be86b3498545b015": "시계는 브레이크 후에 시작합니다. 길게 눌러 힘을 모으고 놓아서 치세요.", + "1514485143207779": "움직여서 조준하고, 길게 눌러 힘을 모으고, 놓아서 치세요. Shift로 세밀하게 조준, Esc로 닫기.", + "412cfbefb305eb90": "당구", + "80140e56c78edfbd": "샷 {shots}", + "41d5b3a5d887b6f8": "페널티 +{seconds}초", + "17547068ba80744d": "{title} 완료", + "a689501ff2ddb4b6": "{title}에서 확인이 필요합니다", + "b2be70822d55f16a": "열기", + "52499724d03777c6": "테이블 클리어", + "9fab80fe09b3dacf": "플레이 {clock}, 페널티 +{seconds}초, {shots}샷", + "03b3f43d7b61d793": "다시 하기", "49cc06e79f21f85a": "{seconds}초", "8603d41c52392f1d": "{minutes}분 {seconds}초", "f2a955905704b91d": "{hours}시간 {minutes}분", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 3c4bf88004..255886a7ce 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", + "082bec31dabcc747": "Primeiro escolha uma caçapa para a 8: clique nela.", + "8ef73b820d9c2068": "Branca encaçapada. +{seconds} s", + "6e5ca67f8c64ad7e": "Nenhuma bola atingida. Grátis uma vez, depois custa {seconds} s.", + "5423b71c71cfb18c": "Nenhuma bola atingida. +{seconds} s", + "61d672c96dc8d887": "A 8 caiu cedo demais e voltou para o seu ponto. +{seconds} s", + "3bd41c9312c93563": "Caçapa errada. A 8 voltou para o seu ponto. +{seconds} s", + "b3a4c68407de4257": "Branca encaçapada com a 8. A 8 voltou para o seu ponto. +{seconds} s", + "d1244c2b4eb6f283": "Só resta a 8. Clique na caçapa que você escolhe.", + "f3127de5f465fbf6": "8 cantada. Clique em outra caçapa para mudar.", + "be86b3498545b015": "O relógio começa depois da abertura. Segure para carregar, solte para tacar.", + "1514485143207779": "Mova para mirar, segure para carregar, solte para tacar. Shift mira mais fino, Esc fecha.", + "412cfbefb305eb90": "Sinuca", + "80140e56c78edfbd": "Tacadas {shots}", + "41d5b3a5d887b6f8": "Penalidades +{seconds} s", + "17547068ba80744d": "{title} terminou", + "a689501ff2ddb4b6": "{title} precisa de você", + "b2be70822d55f16a": "Abrir", + "52499724d03777c6": "Mesa limpa", + "9fab80fe09b3dacf": "{clock} de jogo, +{seconds} s de penalidade, {shots} tacadas", + "03b3f43d7b61d793": "Jogar de novo", "49cc06e79f21f85a": "{seconds}s", "8603d41c52392f1d": "{minutes}min {seconds}s", "f2a955905704b91d": "{hours}h {minutes}min", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index c94a7a61e3..becc709b99 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", + "082bec31dabcc747": "Сначала закажите лузу для восьмёрки: нажмите на неё.", + "8ef73b820d9c2068": "Биток в лузе. +{seconds} с", + "6e5ca67f8c64ad7e": "Ни один шар не задет. Один раз бесплатно, потом это стоит {seconds} с.", + "5423b71c71cfb18c": "Ни один шар не задет. +{seconds} с", + "61d672c96dc8d887": "Восьмёрка упала слишком рано и вернулась на точку. +{seconds} с", + "3bd41c9312c93563": "Не та луза. Восьмёрка вернулась на точку. +{seconds} с", + "b3a4c68407de4257": "Биток упал вместе с восьмёркой. Восьмёрка вернулась на точку. +{seconds} с", + "d1244c2b4eb6f283": "Осталась только восьмёрка. Нажмите на лузу, которую заказываете.", + "f3127de5f465fbf6": "Луза для восьмёрки заказана. Нажмите на другую, чтобы изменить.", + "be86b3498545b015": "Время пойдёт после разбоя. Удерживайте для силы, отпустите для удара.", + "1514485143207779": "Двигайте, чтобы целиться, удерживайте для силы, отпустите для удара. Shift — точнее, Esc — закрыть.", + "412cfbefb305eb90": "Бильярд", + "80140e56c78edfbd": "Удары {shots}", + "41d5b3a5d887b6f8": "Штраф +{seconds} с", + "17547068ba80744d": "{title}: готово", + "a689501ff2ddb4b6": "{title}: нужен ваш ответ", + "b2be70822d55f16a": "Открыть", + "52499724d03777c6": "Стол очищен", + "9fab80fe09b3dacf": "{clock} игры, +{seconds} с штрафа, {shots} ударов", + "03b3f43d7b61d793": "Играть снова", "49cc06e79f21f85a": "{seconds} с", "8603d41c52392f1d": "{minutes} мин {seconds} с", "f2a955905704b91d": "{hours} ч {minutes} мин", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6eff8ad435..e1b270e269 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3110,6 +3110,26 @@ "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", + "082bec31dabcc747": "Ropa först ut ett hål för 8:an: klicka på det.", + "8ef73b820d9c2068": "Vit i hål. +{seconds} s", + "6e5ca67f8c64ad7e": "Ingen boll träffad. Gratis en gång, sedan kostar det {seconds} s.", + "5423b71c71cfb18c": "Ingen boll träffad. +{seconds} s", + "61d672c96dc8d887": "8:an gick i för tidigt och står på sin punkt igen. +{seconds} s", + "3bd41c9312c93563": "Fel hål. 8:an står på sin punkt igen. +{seconds} s", + "b3a4c68407de4257": "Vit i hål med 8:an. 8:an står på sin punkt igen. +{seconds} s", + "d1244c2b4eb6f283": "Bara 8:an är kvar. Klicka på hålet du ropar ut.", + "f3127de5f465fbf6": "8:an utropad. Klicka på ett annat hål för att byta.", + "be86b3498545b015": "Klockan startar efter utslaget. Håll för att ladda, släpp för att stöta.", + "1514485143207779": "Rör för att sikta, håll för att ladda, släpp för att stöta. Shift siktar finare, Esc stänger.", + "412cfbefb305eb90": "Biljard", + "80140e56c78edfbd": "Stötar {shots}", + "41d5b3a5d887b6f8": "Straff +{seconds} s", + "17547068ba80744d": "{title} är klar", + "a689501ff2ddb4b6": "{title} behöver dig", + "b2be70822d55f16a": "Öppna", + "52499724d03777c6": "Bordet rensat", + "9fab80fe09b3dacf": "{clock} spelat, +{seconds} s straff, {shots} stötar", + "03b3f43d7b61d793": "Spela igen", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 10e12bcfd2..723c46a88b 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3114,6 +3114,26 @@ "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", + "082bec31dabcc747": "请先为 8 号球指定袋口:点击袋口。", + "8ef73b820d9c2068": "母球落袋。+{seconds} 秒", + "6e5ca67f8c64ad7e": "没有击中任何球。第一次免罚,之后每次加 {seconds} 秒。", + "5423b71c71cfb18c": "没有击中任何球。+{seconds} 秒", + "61d672c96dc8d887": "8 号球过早落袋,已放回置球点。+{seconds} 秒", + "3bd41c9312c93563": "袋口不对。8 号球已放回置球点。+{seconds} 秒", + "b3a4c68407de4257": "8 号球落袋时母球也落袋。8 号球已放回置球点。+{seconds} 秒", + "d1244c2b4eb6f283": "只剩 8 号球了。点击你指定的袋口。", + "f3127de5f465fbf6": "已指定 8 号球袋口。点击其他袋口可更改。", + "be86b3498545b015": "开球后开始计时。按住蓄力,松开击球。", + "1514485143207779": "移动瞄准,按住蓄力,松开击球。按住 Shift 精细瞄准,Esc 关闭。", + "412cfbefb305eb90": "台球", + "80140e56c78edfbd": "击球 {shots}", + "41d5b3a5d887b6f8": "罚时 +{seconds} 秒", + "17547068ba80744d": "{title} 已完成", + "a689501ff2ddb4b6": "{title} 需要你处理", + "b2be70822d55f16a": "打开", + "52499724d03777c6": "清台", + "9fab80fe09b3dacf": "用时 {clock},罚时 +{seconds} 秒,{shots} 杆", + "03b3f43d7b61d793": "再玩一次", "49cc06e79f21f85a": "{seconds} 秒", "8603d41c52392f1d": "{minutes} 分 {seconds} 秒", "f2a955905704b91d": "{hours} 小时 {minutes} 分钟", From 2167ac777b31ddfc540826900a91970cfef75440 Mon Sep 17 00:00:00 2001 From: Michi Date: Thu, 26 Nov 2026 14:19:10 +0100 Subject: [PATCH 2/6] feat(web): billiards rolling balls, cloth trail, effects and bouncing aim line --- .../components/billiards/billiardsAim.test.ts | 34 ++ .../src/components/billiards/billiardsAim.ts | 87 +++++ .../components/billiards/billiardsBalls.ts | 211 ++++++++++ .../src/components/billiards/billiardsFx.ts | 368 ++++++++++++++++++ .../components/billiards/billiardsRender.ts | 222 +++++------ .../components/billiards/billiardsSession.ts | 97 ++++- 6 files changed, 892 insertions(+), 127 deletions(-) create mode 100644 apps/web/src/components/billiards/billiardsAim.test.ts create mode 100644 apps/web/src/components/billiards/billiardsAim.ts create mode 100644 apps/web/src/components/billiards/billiardsBalls.ts create mode 100644 apps/web/src/components/billiards/billiardsFx.ts diff --git a/apps/web/src/components/billiards/billiardsAim.test.ts b/apps/web/src/components/billiards/billiardsAim.test.ts new file mode 100644 index 0000000000..82e590937b --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAim.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { castTrajectory } from "./billiardsAim.ts"; +import { makeBall } from "./billiardsPhysics.ts"; +import { BALL_RADIUS } from "./billiardsTable.ts"; + +const R = BALL_RADIUS; + +describe("castTrajectory", () => { + it("stops where the cue ball touches the first ball", () => { + const cue = makeBall(0, 0.5, 1.5); + const path = castTrajectory([cue, makeBall(3, 0.5, 1)], cue, -Math.PI / 2); + expect(path.ball?.id).toBe(3); + expect(path.points.at(-1)?.y).toBeCloseTo(1 + 2 * R); + }); + + it("follows the cue ball off a cushion to a ball behind it", () => { + const cue = makeBall(0, 0.5, 1.8); + // 45 degrees up and right: off the right rail, then on to a ball up on the left. + const bounceY = 1.8 - (1 - R - 0.5); + const target = makeBall(5, 1 - R - 0.3, bounceY - 0.3); + const path = castTrajectory([cue, target], cue, -Math.PI / 4); + expect(path.points).toHaveLength(3); + expect(path.points[1]?.x).toBeCloseTo(1 - R); + expect(path.ball?.id).toBe(5); + }); + + it("ends in the pocket when the cue ball heads straight into one", () => { + const cue = makeBall(0, 0.3, 0.3); + const path = castTrajectory([cue], cue, (-3 * Math.PI) / 4); + expect(path.pocket).toBe(0); + expect(path.ball).toBeNull(); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsAim.ts b/apps/web/src/components/billiards/billiardsAim.ts new file mode 100644 index 0000000000..1c462d2f49 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAim.ts @@ -0,0 +1,87 @@ +import type { Ball } from "./billiardsPhysics.ts"; +import { BALL_RADIUS, TABLE_LENGTH, TABLE_WIDTH, type Point } from "./billiardsTable.ts"; + +const R = BALL_RADIUS; +/** How many cushions the guide follows the cue ball off. */ +const AIM_BOUNCES = 2; +const MAX_LENGTH = 3; + +export interface Trajectory { + /** The cue ball's path: its centre at the start, at each cushion, and where it ends. */ + readonly points: ReadonlyArray; + /** The ball it hits first, with the cue ball touching it at the path's last point. */ + readonly ball: Ball | null; + /** The path ends in this pocket: a scratch, unless a ball comes first. */ + readonly pocket: number | null; + /** Direction of the last segment, for the cue ball's deflection off `ball`. */ + readonly dx: number; + readonly dy: number; +} + +// Where the rails open into a pocket, measured along the rail the path reaches. +const CORNER_OPENING = 0.07; +const SIDE_OPENING = 0.045; + +/** The pocket whose mouth the path reaches at a rail, if any. */ +function pocketAt(x: number, y: number, onSideRail: boolean): number | null { + const right = x > TABLE_WIDTH / 2; + const top = y < TABLE_LENGTH / 2; + if (onSideRail && Math.abs(y - TABLE_LENGTH / 2) < SIDE_OPENING) return right ? 3 : 2; + const along = onSideRail ? Math.min(y, TABLE_LENGTH - y) : Math.min(x, TABLE_WIDTH - x); + if (along < CORNER_OPENING) return top ? (right ? 1 : 0) : right ? 5 : 4; + return null; +} + +/** + * Where the cue ball goes along `angle` if nothing slows it: off up to `bounces` cushions, + * until it touches a ball or runs into a pocket. Cushions are treated as straight rails. + */ +export function castTrajectory( + balls: ReadonlyArray, + cue: Ball, + angle: number, + bounces = AIM_BOUNCES, +): Trajectory { + let x = cue.x; + let y = cue.y; + let dx = Math.cos(angle); + let dy = Math.sin(angle); + let travelled = 0; + const points: Point[] = [{ x, y }]; + for (let bounce = 0; ; bounce++) { + let best = Infinity; + let hit: Ball | null = null; + for (const ball of balls) { + if (!ball.onTable || ball === cue) continue; + const fx = x - ball.x; + const fy = y - ball.y; + const b = fx * dx + fy * dy; + const c = fx * fx + fy * fy - 4 * R * R; + const disc = b * b - c; + if (disc < 0) continue; + const t = -b - Math.sqrt(disc); + if (t > 1e-6 && t < best) { + best = t; + hit = ball; + } + } + const wallX = dx > 0 ? (TABLE_WIDTH - R - x) / dx : dx < 0 ? (R - x) / dx : Infinity; + const wallY = dy > 0 ? (TABLE_LENGTH - R - y) / dy : dy < 0 ? (R - y) / dy : Infinity; + const wall = Math.max(0, Math.min(wallX, wallY)); + const remaining = MAX_LENGTH - travelled; + if (hit && best <= wall && best <= remaining) { + points.push({ x: x + dx * best, y: y + dy * best }); + return { points, ball: hit, pocket: null, dx, dy }; + } + const step = Math.min(wall, remaining); + x += dx * step; + y += dy * step; + travelled += step; + points.push({ x, y }); + if (step === remaining) return { points, ball: null, pocket: null, dx, dy }; + const pocket = pocketAt(x, y, wall === wallX); + if (pocket !== null || bounce >= bounces) return { points, ball: null, pocket, dx, dy }; + if (wall === wallX) dx = -dx; + if (wall === wallY) dy = -dy; + } +} diff --git a/apps/web/src/components/billiards/billiardsBalls.ts b/apps/web/src/components/billiards/billiardsBalls.ts new file mode 100644 index 0000000000..24090a6494 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsBalls.ts @@ -0,0 +1,211 @@ +import { EIGHT } from "./billiardsRules.ts"; +import { BALL_RADIUS } from "./billiardsTable.ts"; + +// Balls are shaded per pixel from a 3D orientation, so stripes and numbers visibly roll. +// Each ball keeps a small sprite that is redrawn only when the ball turned. + +const COLORS: ReadonlyArray = [ + [244, 241, 232], + [242, 194, 48], + [33, 96, 212], + [216, 50, 43], + [108, 63, 163], + [240, 122, 31], + [29, 138, 74], + [140, 34, 51], + [21, 21, 21], +]; +const WHITE: readonly [number, number, number] = [246, 243, 234]; +const CUE_DOT: readonly [number, number, number] = [200, 40, 40]; +// Light from the top left, a little above. +const LIGHT = normalize([-0.38, -0.48, 0.79]); +const HALF = normalize([LIGHT[0], LIGHT[1], LIGHT[2] + 1]); +/** Cosine of the number disc's angular radius. */ +const NUMBER_DISC = Math.cos(0.5); +/** Stripe balls are white where the pole axis is steeper than this. */ +const STRIPE_CAP = 0.58; + +type Vec3 = [number, number, number]; + +function cross(a: Vec3, b: Vec3): Vec3 { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +} + +function normalize(v: Vec3): Vec3 { + const length = Math.hypot(v[0], v[1], v[2]); + return [v[0] / length, v[1] / length, v[2] / length]; +} + +/** Body axes in world space: e1, e2 (stripe pole) and e3 (number). z points at the viewer. */ +interface Orientation { + e1: Vec3; + e2: Vec3; + e3: Vec3; +} + +interface Sprite { + readonly canvas: HTMLCanvasElement; + readonly image: ImageData; + dirty: boolean; +} + +function rollVector(v: Vec3, ux: number, uy: number, cos: number, sin: number): void { + // Turns v in the plane of the travel direction u and z, carrying z towards u. + const a = v[0] * ux + v[1] * uy; + const c = v[2]; + const a2 = a * cos + c * sin; + const c2 = c * cos - a * sin; + v[0] += (a2 - a) * ux; + v[1] += (a2 - a) * uy; + v[2] = c2; +} + +export class BallSprites { + private readonly orientations = new Map(); + private readonly sprites = new Map(); + private size = 0; + + /** Sets the sprite size from the pixels per table unit; redraws everything when it changes. */ + resize(scale: number): void { + const size = Math.max(8, Math.min(72, Math.ceil(BALL_RADIUS * 2 * scale))); + if (size === this.size) return; + this.size = size; + this.sprites.clear(); + } + + reset(): void { + this.orientations.clear(); + for (const sprite of this.sprites.values()) sprite.dirty = true; + } + + /** Rolls a ball by the distance it travelled. */ + roll(id: number, dx: number, dy: number): void { + const distance = Math.hypot(dx, dy); + if (distance < 1e-6) return; + const orientation = this.orientation(id); + const angle = distance / BALL_RADIUS; + const ux = dx / distance; + const uy = dy / distance; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + rollVector(orientation.e1, ux, uy, cos, sin); + rollVector(orientation.e2, ux, uy, cos, sin); + orientation.e1 = normalize(orientation.e1); + orientation.e2 = normalize(orientation.e2); + // Rebuild e3 from the other two, so rounding never skews the frame. + const [a, b] = [orientation.e1, orientation.e2]; + orientation.e3 = cross(a, b); + const c = orientation.e3; + orientation.e3 = normalize(c); + orientation.e2 = cross(orientation.e3, a); + const sprite = this.sprites.get(id); + if (sprite) sprite.dirty = true; + } + + /** Draws ball `id` centred on (x, y) in table units; `size` scales it, as when it sinks. */ + draw(ctx: CanvasRenderingContext2D, id: number, x: number, y: number, size = 1): void { + const sprite = this.sprite(id); + const r = BALL_RADIUS * size; + ctx.drawImage(sprite.canvas, x - r, y - r, r * 2, r * 2); + if (id === 0) return; + const { e3 } = this.orientation(id); + this.drawNumber(ctx, id, x, y, r, e3); + if (id > EIGHT) this.drawNumber(ctx, id, x, y, r, [-e3[0], -e3[1], -e3[2]]); + } + + private drawNumber( + ctx: CanvasRenderingContext2D, + id: number, + x: number, + y: number, + r: number, + axis: Vec3, + ): void { + if (axis[2] < 0.35) return; + const angle = Math.atan2(axis[1], axis[0]); + ctx.save(); + ctx.translate(x + axis[0] * r * 0.98, y + axis[1] * r * 0.98); + ctx.rotate(angle); + ctx.scale(axis[2], 1); + ctx.rotate(-angle); + ctx.globalAlpha = Math.min(1, (axis[2] - 0.35) * 4); + ctx.fillStyle = "#151515"; + ctx.font = `700 ${r * 0.62}px ui-sans-serif, system-ui, sans-serif`; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(String(id), 0, r * 0.04); + ctx.restore(); + } + + private orientation(id: number): Orientation { + let orientation = this.orientations.get(id); + if (!orientation) { + orientation = { e1: [1, 0, 0], e2: [0, 1, 0], e3: [0, 0, 1] }; + this.orientations.set(id, orientation); + } + return orientation; + } + + private sprite(id: number): Sprite { + let sprite = this.sprites.get(id); + if (!sprite) { + const canvas = document.createElement("canvas"); + canvas.width = this.size; + canvas.height = this.size; + const context = canvas.getContext("2d"); + const image = context + ? context.createImageData(this.size, this.size) + : new ImageData(this.size, this.size); + sprite = { canvas, image, dirty: true }; + this.sprites.set(id, sprite); + } + if (sprite.dirty) { + this.paint(id, sprite); + sprite.dirty = false; + } + return sprite; + } + + private paint(id: number, sprite: Sprite): void { + const { e2, e3 } = this.orientation(id); + const base = COLORS[id > EIGHT ? id - EIGHT : id] ?? WHITE; + const stripe = id > EIGHT; + const size = this.size; + const half = size / 2; + const data = sprite.image.data; + for (let py = 0; py < size; py++) { + for (let px = 0; px < size; px++) { + const i = (py * size + px) * 4; + const x = (px + 0.5 - half) / half; + const y = (py + 0.5 - half) / half; + const rr = x * x + y * y; + if (rr >= 1) { + data[i + 3] = 0; + continue; + } + const z = Math.sqrt(1 - rr); + const b2 = x * e2[0] + y * e2[1] + z * e2[2]; + const b3 = x * e3[0] + y * e3[1] + z * e3[2]; + let color = base; + if (id === 0) { + color = Math.abs(b3) > 0.965 ? CUE_DOT : WHITE; + } else if (Math.abs(b3) > NUMBER_DISC && (b3 > 0 || stripe)) { + color = WHITE; + } else if (stripe && Math.abs(b2) > STRIPE_CAP) { + color = WHITE; + } + const diffuse = Math.max(0, x * LIGHT[0] + y * LIGHT[1] + z * LIGHT[2]); + const specular = Math.max(0, x * HALF[0] + y * HALF[1] + z * HALF[2]) ** 48; + const light = 0.42 + 0.68 * diffuse; + // A soft rim darkens the edge, like the cloth under it bouncing less light back. + const rim = 0.78 + 0.22 * z; + const edge = Math.min(1, (1 - Math.sqrt(rr)) * half * 1.5); + data[i] = Math.min(255, color[0] * light * rim + specular * 235); + data[i + 1] = Math.min(255, color[1] * light * rim + specular * 235); + data[i + 2] = Math.min(255, color[2] * light * rim + specular * 235); + data[i + 3] = edge * 255; + } + } + sprite.canvas.getContext("2d")?.putImageData(sprite.image, 0, 0); + } +} diff --git a/apps/web/src/components/billiards/billiardsFx.ts b/apps/web/src/components/billiards/billiardsFx.ts new file mode 100644 index 0000000000..e48636d7e5 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsFx.ts @@ -0,0 +1,368 @@ +import type { Ball, PhysicsEvent } from "./billiardsPhysics.ts"; +import { EIGHT } from "./billiardsRules.ts"; +import { BALL_RADIUS, POCKETS, TABLE_LENGTH, TABLE_WIDTH } from "./billiardsTable.ts"; + +// Everything here is looks only: it never feeds back into the simulation. + +const R = BALL_RADIUS; +const MAX_PARTICLES = 240; +const GOLD = "255, 200, 80"; +const WHITE = "255, 255, 255"; +const DUST = "205, 225, 255"; + +/** + * The cloth's memory: a rolling ball brushes the nap into a light trail that stays for the game. + * A ball crossing an older trail brushes it back flat, so crossings return to plain cloth. Each + * shot paints into its own layer, which is XORed onto the settled marks when the shot ends, so + * a ball never erases the trail it is drawing right now. + */ +export class ClothNap { + private readonly settled = document.createElement("canvas"); + private readonly shot = document.createElement("canvas"); + private readonly view = document.createElement("canvas"); + private scale = 1; + private originX = 0; + private originY = 0; + private shotMarked = false; + private viewStale = true; + + resize(width: number, height: number, scale: number, originX: number, originY: number): void { + for (const canvas of [this.settled, this.shot, this.view]) { + canvas.width = width; + canvas.height = height; + } + this.scale = scale; + this.originX = originX; + this.originY = originY; + this.shotMarked = false; + this.viewStale = true; + } + + clear(): void { + for (const canvas of [this.settled, this.shot, this.view]) { + canvas.getContext("2d")?.clearRect(0, 0, canvas.width, canvas.height); + } + this.shotMarked = false; + this.viewStale = true; + } + + /** Brushes the nap along a ball's path this frame. */ + stamp(x0: number, y0: number, x1: number, y1: number): void { + const ctx = this.shot.getContext("2d"); + if (!ctx) return; + ctx.setTransform(this.scale, 0, 0, this.scale, this.originX, this.originY); + ctx.strokeStyle = "#fff"; + ctx.lineWidth = R * 1.6; + ctx.lineCap = "round"; + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.stroke(); + this.shotMarked = true; + this.viewStale = true; + } + + /** The shot ended: its trail joins the cloth, flattening the older trails it crossed. */ + commit(): void { + if (!this.shotMarked) return; + const ctx = this.settled.getContext("2d"); + if (ctx) { + ctx.globalCompositeOperation = "xor"; + ctx.drawImage(this.shot, 0, 0); + ctx.globalCompositeOperation = "source-over"; + } + this.shot.getContext("2d")?.clearRect(0, 0, this.shot.width, this.shot.height); + this.shotMarked = false; + this.viewStale = true; + } + + /** Lays the nap over the cloth, never over the pockets or rails. Expects the table transform. */ + draw(ctx: CanvasRenderingContext2D, shiftX: number, shiftY: number): void { + if (this.viewStale) { + const view = this.view.getContext("2d"); + if (view) { + view.clearRect(0, 0, this.view.width, this.view.height); + view.drawImage(this.settled, 0, 0); + if (this.shotMarked) { + view.globalCompositeOperation = "xor"; + view.drawImage(this.shot, 0, 0); + view.globalCompositeOperation = "source-over"; + } + } + this.viewStale = false; + } + ctx.save(); + ctx.beginPath(); + ctx.rect(0, 0, TABLE_WIDTH, TABLE_LENGTH); + for (const pocket of POCKETS) { + ctx.moveTo(pocket.x + pocket.radius, pocket.y); + ctx.arc(pocket.x, pocket.y, pocket.radius, 0, Math.PI * 2); + } + ctx.clip("evenodd"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 0.13; + ctx.filter = `blur(${Math.max(1, R * 0.2 * this.scale)}px)`; + ctx.drawImage(this.view, shiftX, shiftY); + ctx.restore(); + } +} + +interface Particle { + x: number; + y: number; + vx: number; + vy: number; + age: number; + readonly life: number; + readonly size: number; + readonly color: string; + readonly drag: number; +} + +interface Ring { + readonly x: number; + readonly y: number; + age: number; + readonly life: number; + readonly from: number; + readonly to: number; + readonly width: number; + readonly color: string; + readonly alpha: number; +} + +export class Effects { + private particles: Particle[] = []; + private rings: Ring[] = []; + private shakeTime = 0; + private shakePower = 0; + /** A shot gets one hit-stop at most, on its first hard contact. */ + private impactShown = false; + /** Seconds the whole scene stays frozen, for the weight of a hard hit. */ + hitStop = 0; + + reset(): void { + this.particles = []; + this.rings = []; + this.shakeTime = 0; + this.hitStop = 0; + } + + cueStrike(cue: Ball, angle: number, power: number): void { + this.impactShown = false; + this.ring(cue.x, cue.y, R, R * (2 + power * 2), 0.18, 0.004, WHITE, 0.35 + power * 0.4); + const count = Math.round(3 + power * 6); + for (let i = 0; i < count; i++) { + // Chalk puffs back off the tip. + const spread = angle + Math.PI + (Math.random() - 0.5) * 1.2; + const speed = 0.08 + Math.random() * 0.25 * (0.4 + power); + this.particle( + cue.x - Math.cos(angle) * R, + cue.y - Math.sin(angle) * R, + Math.cos(spread) * speed, + Math.sin(spread) * speed, + 0.35 + Math.random() * 0.25, + 0.003 + Math.random() * 0.003, + "127, 178, 224", + 5, + ); + } + } + + /** Turns this frame's contacts into effects. `breakShot` says whether the rack is breaking. */ + onEvents( + events: ReadonlyArray, + balls: ReadonlyArray, + breakShot: boolean, + ): void { + let hardest = 0; + for (const event of events) { + if (event.kind === "ball") { + hardest = Math.max(hardest, event.speed); + if (event.speed < 0.5) continue; + const a = balls.find((ball) => ball.id === event.a); + const b = balls.find((ball) => ball.id === event.b); + if (!a || !b) continue; + const x = (a.x + b.x) / 2; + const y = (a.y + b.y) / 2; + const v = Math.min(1, event.speed / 5); + this.ring(x, y, R * 0.3, R * (1 + v * 1.6), 0.16, 0.003, WHITE, 0.25 + v * 0.45); + if (event.speed > 2.5) this.burst(x, y, Math.round(2 + v * 6), 0.4 * v, WHITE, 0.25); + } else if (event.kind === "cushion") { + if (event.speed < 0.4) continue; + const v = Math.min(1, event.speed / 4); + this.burst(event.x, event.y, Math.round(3 + v * 7), 0.12 + 0.22 * v, DUST, 0.5); + this.ring( + event.x, + event.y, + R * 0.4, + R * (1.2 + v * 1.5), + 0.25, + 0.0025, + DUST, + 0.15 + v * 0.3, + ); + } else { + const pocket = POCKETS[event.pocket]; + if (!pocket) continue; + const gold = event.ball === EIGHT; + const color = gold ? GOLD : event.ball === 0 ? "255, 110, 90" : WHITE; + this.ring( + pocket.x, + pocket.y, + pocket.radius * 0.8, + pocket.radius * 2.4, + 0.5, + 0.006, + color, + 0.8, + ); + this.ring(pocket.x, pocket.y, pocket.radius, pocket.radius * 1.6, 0.3, 0.003, color, 0.5); + for (let i = 0; i < 14; i++) { + // Sparks drawn into the pocket. + const angle = (i / 14) * Math.PI * 2 + Math.random() * 0.3; + const distance = pocket.radius * (1.6 + Math.random()); + const speed = distance / 0.35; + this.particle( + pocket.x + Math.cos(angle) * distance, + pocket.y + Math.sin(angle) * distance, + -Math.cos(angle) * speed, + -Math.sin(angle) * speed, + 0.32, + 0.0035, + color, + 0, + ); + } + } + } + if (this.impactShown) return; + if (breakShot && hardest > 3) { + this.impactShown = true; + this.hitStop = 0.05; + this.shake(0.006, 0.3); + } else if (hardest > 5.5) { + this.impactShown = true; + this.hitStop = 0.03; + } + } + + /** The table cleared: a wide gold wave from the called pocket. */ + celebrate(pocketId: number | null): void { + const pocket = POCKETS.find((candidate) => candidate.id === pocketId) ?? POCKETS[0]; + if (!pocket) return; + for (const [delay, width] of [ + [0, 0.012], + [0.12, 0.007], + [0.24, 0.004], + ] as const) { + this.rings.push({ + x: pocket.x, + y: pocket.y, + age: -delay, + life: 1.3, + from: pocket.radius, + to: 2.4, + width, + color: GOLD, + alpha: 0.7, + }); + } + this.shake(0.004, 0.25); + } + + private shake(power: number, time: number): void { + this.shakePower = Math.max(this.shakePower * (this.shakeTime > 0 ? 1 : 0), power); + this.shakeTime = Math.max(this.shakeTime, time); + } + + /** How far the frame is thrown this instant, in table units. */ + shakeOffset(): { readonly x: number; readonly y: number } { + if (this.shakeTime <= 0) return { x: 0, y: 0 }; + const power = this.shakePower * Math.min(1, this.shakeTime / 0.3); + return { x: (Math.random() - 0.5) * 2 * power, y: (Math.random() - 0.5) * 2 * power }; + } + + update(seconds: number): void { + this.shakeTime = Math.max(0, this.shakeTime - seconds); + for (const particle of this.particles) { + particle.age += seconds; + const drag = Math.exp(-particle.drag * seconds); + particle.vx *= drag; + particle.vy *= drag; + particle.x += particle.vx * seconds; + particle.y += particle.vy * seconds; + } + this.particles = this.particles.filter((particle) => particle.age < particle.life); + for (const ring of this.rings) ring.age += seconds; + this.rings = this.rings.filter((ring) => ring.age < ring.life); + } + + /** Draws rings and particles. Expects the table transform. */ + draw(ctx: CanvasRenderingContext2D): void { + ctx.save(); + ctx.globalCompositeOperation = "lighter"; + for (const ring of this.rings) { + if (ring.age < 0) continue; + const t = ring.age / ring.life; + const ease = 1 - (1 - t) * (1 - t); + ctx.strokeStyle = `rgba(${ring.color}, ${ring.alpha * (1 - t)})`; + ctx.lineWidth = ring.width * (1 - t * 0.6); + ctx.beginPath(); + ctx.arc(ring.x, ring.y, ring.from + (ring.to - ring.from) * ease, 0, Math.PI * 2); + ctx.stroke(); + } + for (const particle of this.particles) { + const t = particle.age / particle.life; + ctx.fillStyle = `rgba(${particle.color}, ${0.85 * (1 - t)})`; + ctx.beginPath(); + ctx.arc(particle.x, particle.y, particle.size * (1 - t * 0.5), 0, Math.PI * 2); + ctx.fill(); + } + ctx.restore(); + } + + private burst(x: number, y: number, count: number, speed: number, color: string, life: number) { + for (let i = 0; i < count; i++) { + const angle = Math.random() * Math.PI * 2; + const v = speed * (0.4 + Math.random() * 0.6); + this.particle( + x, + y, + Math.cos(angle) * v, + Math.sin(angle) * v, + life * (0.6 + Math.random() * 0.4), + 0.0025 + Math.random() * 0.003, + color, + 4, + ); + } + } + + private particle( + x: number, + y: number, + vx: number, + vy: number, + life: number, + size: number, + color: string, + drag: number, + ): void { + if (this.particles.length >= MAX_PARTICLES) this.particles.shift(); + this.particles.push({ x, y, vx, vy, age: 0, life, size, color, drag }); + } + + private ring( + x: number, + y: number, + from: number, + to: number, + life: number, + width: number, + color: string, + alpha: number, + ): void { + this.rings.push({ x, y, age: 0, life, from, to, width, color, alpha }); + } +} diff --git a/apps/web/src/components/billiards/billiardsRender.ts b/apps/web/src/components/billiards/billiardsRender.ts index e9fba68eb9..8e19827746 100644 --- a/apps/web/src/components/billiards/billiardsRender.ts +++ b/apps/web/src/components/billiards/billiardsRender.ts @@ -1,3 +1,6 @@ +import { castTrajectory } from "./billiardsAim.ts"; +import type { BallSprites } from "./billiardsBalls.ts"; +import type { ClothNap, Effects } from "./billiardsFx.ts"; import type { Ball } from "./billiardsPhysics.ts"; import { EIGHT, type BilliardsGame } from "./billiardsRules.ts"; import { @@ -21,17 +24,6 @@ export const TABLE_ORIGIN = { }; const R = BALL_RADIUS; -const BALL_COLORS = [ - "#f4f1e8", - "#f2c230", - "#2160d4", - "#d8322b", - "#6c3fa3", - "#f07a1f", - "#1d8a4a", - "#8c2233", - "#151515", -]; const CLOTH_CENTER = "#1d6896"; const CLOTH_EDGE = "#0f3b5c"; const CUSHION = "#164f78"; @@ -55,12 +47,31 @@ export interface SceneView { readonly sinking: ReadonlyArray; /** Seconds, for pulses and animations. */ readonly now: number; + readonly sprites: BallSprites; + readonly nap: ClothNap; + readonly fx: Effects; + /** Screen shake, in table units. */ + readonly shake: { readonly x: number; readonly y: number }; + /** 0 to 1: darkens the edges while the final 8 rolls in slow motion. */ + readonly vignette: number; } export { SINK_SECONDS }; -function frameTransform(ctx: CanvasRenderingContext2D, scale: number): void { - ctx.setTransform(scale, 0, 0, scale, TABLE_ORIGIN.x * scale, TABLE_ORIGIN.y * scale); +function frameTransform( + ctx: CanvasRenderingContext2D, + scale: number, + shiftX = 0, + shiftY = 0, +): void { + ctx.setTransform( + scale, + 0, + 0, + scale, + (TABLE_ORIGIN.x + shiftX) * scale, + (TABLE_ORIGIN.y + shiftY) * scale, + ); } /** Everything that never moves, drawn once per resize. */ @@ -205,10 +216,17 @@ export function drawScene( scale: number, view: SceneView, ): void { - const { game } = view; + const { game, sprites } = view; + const shiftX = view.shake.x * scale; + const shiftY = view.shake.y * scale; ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.drawImage(staticLayer, 0, 0); - frameTransform(ctx, scale); + if (shiftX !== 0 || shiftY !== 0) { + ctx.fillStyle = "#06080c"; + ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); + } + ctx.drawImage(staticLayer, shiftX, shiftY); + frameTransform(ctx, scale, view.shake.x, view.shake.y); + view.nap.draw(ctx, shiftX, shiftY); const cue = game.ball(0); const aiming = game.phase === "aiming" && cue?.onTable; @@ -216,15 +234,30 @@ export function drawScene( if (aiming && cue) drawAimGuide(ctx, game, cue, view.aimAngle); for (const ball of game.balls) if (ball.onTable) drawShadow(ctx, ball.x, ball.y, 1); - for (const ball of game.balls) if (ball.onTable) drawBall(ctx, ball.id, ball.x, ball.y, 1); - for (const sinking of view.sinking) drawSinking(ctx, sinking, view.now); + for (const ball of game.balls) if (ball.onTable) sprites.draw(ctx, ball.id, ball.x, ball.y); + for (const sinking of view.sinking) drawSinking(ctx, sprites, sinking, view.now); + view.fx.draw(ctx); if (aiming && cue) drawCue(ctx, cue, view.aimAngle, view.power ?? 0); if (view.power !== null) drawPowerMeter(ctx, view.power); for (const [i, id] of game.pottedOrder.entries()) { - drawBall(ctx, id, 0.035 + i * 0.066, TRAY_Y, 1); + sprites.draw(ctx, id, 0.035 + i * 0.066, TRAY_Y); } + if (view.vignette > 0) drawVignette(ctx, view.vignette); +} + +function drawVignette(ctx: CanvasRenderingContext2D, amount: number): void { + const shade = ctx.createRadialGradient(0.5, 1, 0.45, 0.5, 1, 1.45); + shade.addColorStop(0, "rgba(0, 0, 0, 0)"); + shade.addColorStop(1, `rgba(0, 0, 0, ${0.6 * amount})`); + ctx.fillStyle = shade; + ctx.fillRect( + -TABLE_ORIGIN.x - 0.05, + -TABLE_ORIGIN.y - 0.05, + FRAME_WIDTH + 0.1, + FRAME_HEIGHT + 0.1, + ); } function drawShadow(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void { @@ -245,47 +278,12 @@ function drawShadow(ctx: CanvasRenderingContext2D, x: number, y: number, size: n ctx.fill(); } -function drawBall( +function drawSinking( ctx: CanvasRenderingContext2D, - id: number, - x: number, - y: number, - size: number, + sprites: BallSprites, + sinking: Sinking, + now: number, ): void { - const r = R * size; - const color = BALL_COLORS[id > EIGHT ? id - EIGHT : id] ?? "#fff"; - ctx.save(); - ctx.beginPath(); - ctx.arc(x, y, r, 0, Math.PI * 2); - ctx.clip(); - ctx.fillStyle = id > EIGHT ? "#f4f1e8" : color; - ctx.fillRect(x - r, y - r, r * 2, r * 2); - if (id > EIGHT) { - ctx.fillStyle = color; - ctx.fillRect(x - r, y - r * 0.55, r * 2, r * 1.1); - } - if (id !== 0) { - ctx.fillStyle = "#f7f4ea"; - ctx.beginPath(); - ctx.arc(x, y, r * 0.47, 0, Math.PI * 2); - ctx.fill(); - ctx.fillStyle = "#151515"; - ctx.font = `700 ${r * 0.62}px ui-sans-serif, system-ui, sans-serif`; - ctx.textAlign = "center"; - ctx.textBaseline = "middle"; - ctx.fillText(String(id), x, y + r * 0.04); - } - const shade = ctx.createRadialGradient(x - r * 0.35, y - r * 0.4, r * 0.05, x, y, r); - shade.addColorStop(0, "rgba(255, 255, 255, 0.6)"); - shade.addColorStop(0.22, "rgba(255, 255, 255, 0.12)"); - shade.addColorStop(0.65, "rgba(0, 0, 0, 0)"); - shade.addColorStop(1, "rgba(0, 0, 0, 0.42)"); - ctx.fillStyle = shade; - ctx.fillRect(x - r, y - r, r * 2, r * 2); - ctx.restore(); -} - -function drawSinking(ctx: CanvasRenderingContext2D, sinking: Sinking, now: number): void { const t = Math.min(1, (now - sinking.start) / SINK_SECONDS); const ease = t * t; const x = sinking.x + (sinking.pocket.x - sinking.x) * ease; @@ -293,91 +291,69 @@ function drawSinking(ctx: CanvasRenderingContext2D, sinking: Sinking, now: numbe const size = 1 - 0.45 * ease; ctx.save(); ctx.globalAlpha = 1 - ease * 0.85; - drawBall(ctx, sinking.ball, x, y, size); + sprites.draw(ctx, sinking.ball, x, y, size); ctx.restore(); } -interface AimHit { - readonly x: number; - readonly y: number; - readonly ball: Ball | null; -} - -/** Where the cue ball would first touch a ball, or the cushion line, along `angle`. */ -function castAim(game: BilliardsGame, cue: Ball, angle: number): AimHit { - const dx = Math.cos(angle); - const dy = Math.sin(angle); - let best = Infinity; - let hit: Ball | null = null; - for (const ball of game.balls) { - if (!ball.onTable || ball === cue) continue; - const fx = cue.x - ball.x; - const fy = cue.y - ball.y; - const b = fx * dx + fy * dy; - const c = fx * fx + fy * fy - 4 * R * R; - const disc = b * b - c; - if (disc < 0) continue; - const t = -b - Math.sqrt(disc); - if (t > 0 && t < best) { - best = t; - hit = ball; - } - } - const wallX = dx > 0 ? (1 - R - cue.x) / dx : dx < 0 ? (R - cue.x) / dx : Infinity; - const wallY = dy > 0 ? (2 - R - cue.y) / dy : dy < 0 ? (R - cue.y) / dy : Infinity; - const wall = Math.max(0, Math.min(wallX, wallY)); - if (wall < best) { - best = wall; - hit = null; - } - return { x: cue.x + dx * best, y: cue.y + dy * best, ball: hit }; -} - function drawAimGuide( ctx: CanvasRenderingContext2D, game: BilliardsGame, cue: Ball, angle: number, ): void { - const hit = castAim(game, cue, angle); + const path = castTrajectory(game.balls, cue, angle); ctx.save(); ctx.lineCap = "round"; - ctx.setLineDash([0.01, 0.012]); - ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"; - ctx.lineWidth = 0.0035; - ctx.beginPath(); - ctx.moveTo(cue.x, cue.y); - ctx.lineTo(hit.x, hit.y); - ctx.stroke(); + // Zero-length dashes with round caps draw dots; each cushion leg fades a little more. + ctx.setLineDash([0, 0.017]); + ctx.lineWidth = 0.0065; + for (let i = 1; i < path.points.length; i++) { + const from = path.points[i - 1]; + const to = path.points[i]; + if (!from || !to) continue; + ctx.strokeStyle = `rgba(255, 255, 255, ${0.8 - (i - 1) * 0.25})`; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } ctx.setLineDash([]); - ctx.strokeStyle = "rgba(255, 255, 255, 0.55)"; - ctx.lineWidth = 0.003; - ctx.beginPath(); - ctx.arc(hit.x, hit.y, R, 0, Math.PI * 2); - ctx.stroke(); - if (hit.ball) { - const nx = (hit.ball.x - hit.x) / (2 * R); - const ny = (hit.ball.y - hit.y) / (2 * R); - ctx.strokeStyle = "rgba(255, 255, 255, 0.6)"; + const end = path.points[path.points.length - 1] ?? cue; + if (path.ball) { + const { ball } = path; + ctx.strokeStyle = "rgba(255, 255, 255, 0.75)"; ctx.lineWidth = 0.004; ctx.beginPath(); - ctx.moveTo(hit.ball.x + nx * R, hit.ball.y + ny * R); - ctx.lineTo(hit.ball.x + nx * 0.3, hit.ball.y + ny * 0.3); + ctx.arc(end.x, end.y, R, 0, Math.PI * 2); + ctx.stroke(); + const nx = (ball.x - end.x) / (2 * R); + const ny = (ball.y - end.y) / (2 * R); + ctx.strokeStyle = "rgba(255, 255, 255, 0.7)"; + ctx.lineWidth = 0.0045; + ctx.beginPath(); + ctx.moveTo(ball.x + nx * R, ball.y + ny * R); + ctx.lineTo(ball.x + nx * 0.3, ball.y + ny * 0.3); ctx.stroke(); // The cue ball leaves at right angles to the object ball. - const dx = Math.cos(angle); - const dy = Math.sin(angle); - const along = dx * nx + dy * ny; - const tx = dx - along * nx; - const ty = dy - along * ny; + const along = path.dx * nx + path.dy * ny; + const tx = path.dx - along * nx; + const ty = path.dy - along * ny; const length = Math.hypot(tx, ty); if (length > 0.05) { - ctx.strokeStyle = "rgba(255, 255, 255, 0.22)"; + ctx.strokeStyle = "rgba(255, 255, 255, 0.25)"; + ctx.lineWidth = 0.003; ctx.beginPath(); - ctx.moveTo(hit.x, hit.y); - ctx.lineTo(hit.x + (tx / length) * 0.12, hit.y + (ty / length) * 0.12); + ctx.moveTo(end.x, end.y); + ctx.lineTo(end.x + (tx / length) * 0.12, end.y + (ty / length) * 0.12); ctx.stroke(); } + } else if (path.pocket !== null) { + // Straight into a pocket: a scratch. + ctx.strokeStyle = "rgba(255, 110, 90, 0.85)"; + ctx.lineWidth = 0.004; + ctx.beginPath(); + ctx.arc(end.x, end.y, R, 0, Math.PI * 2); + ctx.stroke(); } ctx.restore(); } @@ -453,6 +429,6 @@ function drawPocketCalls(ctx: CanvasRenderingContext2D, view: SceneView): void { ctx.beginPath(); ctx.arc(pocket.x, pocket.y, pocket.radius * 1.3, 0, Math.PI * 2); ctx.stroke(); - if (called) drawBall(ctx, EIGHT, pocket.x, pocket.y, 0.6); + if (called) view.sprites.draw(ctx, EIGHT, pocket.x, pocket.y, 0.6); } } diff --git a/apps/web/src/components/billiards/billiardsSession.ts b/apps/web/src/components/billiards/billiardsSession.ts index c583b5fa5a..ecb2ca5ea3 100644 --- a/apps/web/src/components/billiards/billiardsSession.ts +++ b/apps/web/src/components/billiards/billiardsSession.ts @@ -1,6 +1,8 @@ import { observeResize } from "~/lib/observeResize"; import { BilliardsAudio } from "./billiardsAudio.ts"; +import { BallSprites } from "./billiardsBalls.ts"; +import { ClothNap, Effects } from "./billiardsFx.ts"; import { MAX_SHOT_SPEED, type PhysicsEvent } from "./billiardsPhysics.ts"; import { drawScene, @@ -10,7 +12,7 @@ import { TABLE_ORIGIN, type Sinking, } from "./billiardsRender.ts"; -import { BilliardsGame, type Foul, type Phase } from "./billiardsRules.ts"; +import { BilliardsGame, EIGHT, type Foul, type Phase } from "./billiardsRules.ts"; import { POCKETS, type Point } from "./billiardsTable.ts"; /** What the overlay shows around the canvas. */ @@ -35,6 +37,8 @@ const MIN_SHOT_SPEED = 0.3; const FINE_AIM = 0.12; const POCKET_PICK_RADIUS = 0.1; const HUD_INTERVAL_MS = 250; +/** How slow the final 8 rolls as it nears the called pocket. */ +const SLOW_MOTION = 0.3; function wrapAngle(angle: number): number { return Math.atan2(Math.sin(angle), Math.cos(angle)); @@ -47,6 +51,9 @@ export class BilliardsSession { private readonly staticLayer = document.createElement("canvas"); private readonly onHud: (hud: BilliardsHud) => void; private readonly audio = new BilliardsAudio(); + private readonly sprites = new BallSprites(); + private readonly nap = new ClothNap(); + private readonly fx = new Effects(); private readonly stopObservingResize: () => void; private game = new BilliardsGame(); private scale = 1; @@ -60,6 +67,10 @@ export class BilliardsSession { private clockStart: number | null = null; private clockEnd: number | null = null; private blockedUntil = 0; + /** Hit-stops and slow motion don't count against the player's clock. */ + private frozenMs = 0; + private timeScale = 1; + private finalShot = false; private lastHud: BilliardsHud | null = null; private lastHudAt = 0; @@ -98,6 +109,12 @@ export class BilliardsSession { this.clockStart = null; this.clockEnd = null; this.blockedUntil = 0; + this.frozenMs = 0; + this.timeScale = 1; + this.finalShot = false; + this.sprites.reset(); + this.nap.clear(); + this.fx.reset(); this.emitHud(performance.now(), true); } @@ -118,6 +135,14 @@ export class BilliardsSession { this.staticLayer.height = this.canvas.height; this.scale = this.canvas.width / FRAME_WIDTH; drawStaticLayer(this.staticLayer, this.scale); + this.sprites.resize(this.scale); + this.nap.resize( + this.canvas.width, + this.canvas.height, + this.scale, + TABLE_ORIGIN.x * this.scale, + TABLE_ORIGIN.y * this.scale, + ); } private toTable(event: PointerEvent): Point { @@ -185,8 +210,12 @@ export class BilliardsSession { this.canvas.releasePointerCapture(event.pointerId); } const speed = MIN_SHOT_SPEED + (MAX_SHOT_SPEED - MIN_SHOT_SPEED) * power * power; + const finalShot = this.game.objectBallsLeft() === 0; if (!this.game.shoot(this.aimAngle, speed)) return; + this.finalShot = finalShot; this.audio.cue(power); + const cue = this.game.ball(0); + if (cue) this.fx.cueStrike(cue, this.aimAngle, power); this.emitHud(now, true); }; @@ -203,16 +232,39 @@ export class BilliardsSession { const seconds = this.lastFrame === 0 ? 0 : Math.min(0.05, (time - this.lastFrame) / 1000); this.lastFrame = time; + // A hit-stop freezes everything for a beat; slow motion stretches the final 8. + let simSeconds = seconds * this.timeScale; + let frozenSeconds = seconds - simSeconds; + if (this.fx.hitStop > 0) { + const stop = Math.min(this.fx.hitStop, seconds); + this.fx.hitStop -= stop; + simSeconds = 0; + frozenSeconds = seconds; + } + if (this.clockStart !== null && this.clockEnd === null) this.frozenMs += frozenSeconds * 1000; + const phase = this.game.phase; + const breakShot = this.game.isBreak; + const before = new Map(); + for (const ball of this.game.balls) + if (ball.onTable) before.set(ball.id, { x: ball.x, y: ball.y }); const events: PhysicsEvent[] = []; - this.game.advance(seconds, events); + this.game.advance(simSeconds, events); + this.trackRolling(before, simSeconds); this.playEvents(events, time / 1000); + this.fx.onEvents(events, this.game.balls, breakShot); if (this.game.phase !== phase) { - if (this.game.phase === "cleared") this.clockEnd = time; + this.nap.commit(); + if (this.game.phase === "cleared") { + this.clockEnd = time; + this.fx.celebrate(this.game.calledPocket); + } // The clock starts once the break settles. if (!this.game.isBreak && this.clockStart === null) this.clockStart = time; this.emitHud(time, true); } + this.updateSlowMotion(seconds); + this.fx.update(simSeconds === 0 ? 0 : Math.max(simSeconds, seconds * 0.5)); this.sinking = this.sinking.filter((sinking) => time / 1000 - sinking.start < SINK_SECONDS); drawScene(this.context, this.staticLayer, this.scale, { @@ -222,10 +274,47 @@ export class BilliardsSession { hoverPocket: this.pocketAt(this.pointer), sinking: this.sinking, now: time / 1000, + sprites: this.sprites, + nap: this.nap, + fx: this.fx, + shake: this.fx.shakeOffset(), + vignette: Math.min(1, (1 - this.timeScale) / (1 - SLOW_MOTION)), }); if (time - this.lastHudAt > HUD_INTERVAL_MS) this.emitHud(time, false); }; + /** Rolls each moving ball's sprite and brushes the cloth along its path. */ + private trackRolling(before: ReadonlyMap, seconds: number): void { + if (seconds === 0) return; + for (const ball of this.game.balls) { + const start = before.get(ball.id); + if (!start || !ball.onTable) continue; + const dx = ball.x - start.x; + const dy = ball.y - start.y; + const distance = Math.hypot(dx, dy); + // A respot jumps the ball; it didn't roll there. + if (distance < 1e-5 || distance > 0.2) continue; + this.sprites.roll(ball.id, dx, dy); + this.nap.stamp(start.x, start.y, ball.x, ball.y); + } + } + + private updateSlowMotion(seconds: number): void { + let target = 1; + const eight = this.game.ball(EIGHT); + const pocket = POCKETS.find((candidate) => candidate.id === this.game.calledPocket); + if (this.finalShot && this.game.phase === "rolling" && eight?.onTable && pocket) { + const dx = pocket.x - eight.x; + const dy = pocket.y - eight.y; + const distance = Math.hypot(dx, dy); + const speed = Math.hypot(eight.vx, eight.vy); + const heading = speed > 0 ? (dx * eight.vx + dy * eight.vy) / (distance * speed) : 0; + if (speed > 0.05 && distance < 0.35 && heading > 0.85) target = SLOW_MOTION; + } + this.timeScale += (target - this.timeScale) * Math.min(1, seconds * 8); + if (Math.abs(this.timeScale - target) < 0.01) this.timeScale = target; + } + private playEvents(events: ReadonlyArray, now: number): void { const clicks: number[] = []; const thuds: number[] = []; @@ -253,7 +342,7 @@ export class BilliardsSession { shots: game.shots, penaltySeconds: game.penaltySeconds, totalMs: - (this.clockStart === null ? 0 : (this.clockEnd ?? now) - this.clockStart) + + (this.clockStart === null ? 0 : (this.clockEnd ?? now) - this.clockStart - this.frozenMs) + game.penaltySeconds * 1000, needsCall: game.needsCall(), calledPocket: game.calledPocket, From 1ff2dd66b746cdf7da952c08cb1f016488dc9265 Mon Sep 17 00:00:00 2001 From: Michi Date: Thu, 26 Nov 2026 14:31:34 +0100 Subject: [PATCH 3/6] feat(web): billiards daily rack, local leaderboard and medals; aim line follows the physics --- .../components/billiards/BilliardsOverlay.tsx | 89 +++++++++++++++++- .../components/billiards/billiardsAim.test.ts | 23 ++++- .../src/components/billiards/billiardsAim.ts | 59 ++++++++++-- .../components/billiards/billiardsPhysics.ts | 16 ++-- .../billiards/billiardsRecords.test.ts | 56 ++++++++++++ .../components/billiards/billiardsRecords.ts | 90 +++++++++++++++++++ .../components/billiards/billiardsRender.ts | 14 ++- .../billiards/billiardsRules.test.ts | 6 +- .../components/billiards/billiardsSession.ts | 76 ++++++++++++++-- apps/web/src/i18n/translations/de.json | 12 ++- apps/web/src/i18n/translations/en.json | 12 ++- apps/web/src/i18n/translations/es.json | 12 ++- apps/web/src/i18n/translations/fr.json | 12 ++- apps/web/src/i18n/translations/ja.json | 12 ++- apps/web/src/i18n/translations/ko.json | 12 ++- apps/web/src/i18n/translations/pt-BR.json | 12 ++- apps/web/src/i18n/translations/ru.json | 12 ++- apps/web/src/i18n/translations/sv.json | 12 ++- apps/web/src/i18n/translations/zh.json | 12 ++- 19 files changed, 506 insertions(+), 43 deletions(-) create mode 100644 apps/web/src/components/billiards/billiardsRecords.test.ts create mode 100644 apps/web/src/components/billiards/billiardsRecords.ts diff --git a/apps/web/src/components/billiards/BilliardsOverlay.tsx b/apps/web/src/components/billiards/BilliardsOverlay.tsx index 38cf072d9a..37c423b22a 100644 --- a/apps/web/src/components/billiards/BilliardsOverlay.tsx +++ b/apps/web/src/components/billiards/BilliardsOverlay.tsx @@ -1,16 +1,22 @@ import { useNavigate } from "@tanstack/react-router"; import { useGT } from "gt-react"; -import { CircleCheckIcon, MessageCircleQuestionIcon, XIcon } from "lucide-react"; +import { CircleCheckIcon, MedalIcon, MessageCircleQuestionIcon, XIcon } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { cn } from "../../lib/utils"; import { useThreadShells } from "../../state/entities"; +import { medalFor, nextMedal, type Medal } from "./billiardsRecords"; import { FOUL_PENALTY_SECONDS } from "./billiardsRules"; import { BilliardsSession, type BilliardsHud } from "./billiardsSession"; import { snapshotThreads, threadAlerts, type ThreadAlert } from "./billiardsThreadAlerts"; const MAX_ALERTS = 3; +const MEDAL_COLORS: Readonly> = { + gold: "#e8b931", + silver: "#c4cbd4", + bronze: "#c8834f", +}; function formatClock(ms: number, tenths = false): string { const seconds = Math.floor(ms / 1000); @@ -70,6 +76,23 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { }); }; + const medalLabel = (medal: Medal) => + medal === "gold" + ? gt("Gold medal") + : medal === "silver" + ? gt("Silver medal") + : gt("Bronze medal"); + const nextMedalText = (totalMs: number) => { + const next = nextMedal(totalMs); + if (!next) return null; + const time = formatClock(next[1]); + return next[0] === "gold" + ? gt("Next: gold under {time}", { time }) + : next[0] === "silver" + ? gt("Next: silver under {time}", { time }) + : gt("Next: bronze under {time}", { time }); + }; + const status = (() => { if (!hud) return { text: "", tone: "quiet" }; if (hud.blocked) return { text: gt("Call a pocket for the 8 first: click it."), tone: "warn" }; @@ -122,7 +145,7 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { } if (hud.isBreak) { return { - text: gt("The clock starts after the break. Hold to charge, release to shoot."), + text: gt("Today's rack is the same for everyone. The clock starts after the break."), tone: "quiet", }; } @@ -151,6 +174,11 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { {gt("Penalties +{seconds} s", { seconds: hud.penaltySeconds })} ) : null} + {hud?.todayRuns[0] ? ( + + {gt("Best {time}", { time: formatClock(hud.todayRuns[0].totalMs, true) })} + + ) : null} {formatClock(hud?.totalMs ?? 0)} + ); + })} + + ) : null} {alerts.length > 0 ? (
{alerts.map((alert) => ( @@ -289,6 +375,15 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { {hud.result?.rankToday === 1 ? (

{gt("New best today!")}

) : null} + {hud.result?.newSkins.map((id) => ( +

+ + {gt("New stick unlocked: {name}", { name: skinName(id) })} +

+ ))} {hud.result && hud.result.medal !== "gold" ? (

{nextMedalText(hud.result.run.totalMs)} diff --git a/apps/web/src/components/billiards/billiardsCues.ts b/apps/web/src/components/billiards/billiardsCues.ts index 3c7c70e1c9..e9e90c9a78 100644 --- a/apps/web/src/components/billiards/billiardsCues.ts +++ b/apps/web/src/components/billiards/billiardsCues.ts @@ -1,11 +1,12 @@ import type { Ball } from "./billiardsPhysics.ts"; import { RING_RADIUS, type PowerKind, type PowerRing } from "./billiardsRules.ts"; +import type { SkinId } from "./billiardsSkins.ts"; import { BALL_RADIUS } from "./billiardsTable.ts"; // The stick's looks and the power-up rings. A power-up changes the stick while it's armed; // the same looks become unlockable skins later. -export type CueStyle = "classic" | PowerKind; +export type CueStyle = SkinId | PowerKind; const R = BALL_RADIUS; const CUE_LENGTH = 1.15; @@ -65,6 +66,10 @@ export function drawCue( const scale = ctx.getTransform().a; ctx.shadowColor = `rgba(${POWER_COLORS[style]}, 0.9)`; ctx.shadowBlur = (0.018 + Math.sin(now * 6) * 0.006) * scale; + } else if (style === "ember") { + const scale = ctx.getTransform().a; + ctx.shadowColor = "rgba(255, 110, 30, 0.6)"; + ctx.shadowBlur = (0.01 + Math.sin(now * 2.2) * 0.004) * scale; } outline(0); ctx.fillStyle = body; @@ -89,6 +94,66 @@ function cueStops(style: CueStyle, now: number): ReadonlyArray = [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f3c6a0"], + [0.03, "#e8a476"], + ]; + for (let i = 0; i < 8; i++) { + const at = 0.08 + i * 0.11; + stops.push([at, i % 2 === 0 ? "#b87333" : "#d48a4f"], [at + 0.004, "#6b3a1c"]); + } + stops.push([1, "#5a2e14"]); + return stops; + } + case "chrome": { + // A slow reflection slides along polished steel. + const band = 0.1 + ((now * 0.25) % 1) * 0.8; + return [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f4f7fa"], + [0.03, "#cfd6de"], + [Math.max(0.035, band - 0.1), "#8d97a3"], + [band, "#ffffff"], + [Math.min(0.97, band + 0.1), "#8d97a3"], + [1, "#3c434c"], + ]; + } + case "ember": { + // Charred wood with embers that breathe along it. + const stops: Array = [ + [0, "#ffd9a0"], + [0.015, "#ffd9a0"], + [0.016, "#2a0f06"], + ]; + for (let i = 1; i < 9; i++) { + const heat = 0.5 + 0.5 * Math.sin(now * 2.6 + i * 1.7); + stops.push([i / 9, `hsl(${18 + heat * 14}, 100%, ${10 + heat * 42}%)`]); + } + stops.push([1, "#120604"]); + return stops; + } case "golden": { // A shine runs down the stick, over and over. const band = 0.08 + ((now * 0.45) % 1) * 0.84; diff --git a/apps/web/src/components/billiards/billiardsSession.ts b/apps/web/src/components/billiards/billiardsSession.ts index d6fe3ced04..867c3a2141 100644 --- a/apps/web/src/components/billiards/billiardsSession.ts +++ b/apps/web/src/components/billiards/billiardsSession.ts @@ -23,6 +23,7 @@ import { type Medal, } from "./billiardsRecords.ts"; import { cueTip, POWER_COLORS, type CueStyle } from "./billiardsCues.ts"; +import { loadSkin, saveSkin, unlockedSkins, type SkinId } from "./billiardsSkins.ts"; import { BilliardsGame, EIGHT, @@ -57,6 +58,8 @@ export interface BilliardsHud { /** A power-up waiting for the next shot. */ readonly armed: "wand" | "glow" | null; readonly goldenShots: number; + readonly skin: SkinId; + readonly unlockedSkins: ReadonlySet; } export interface RunResult { @@ -64,6 +67,8 @@ export interface RunResult { /** 1 is the best run today. */ readonly rankToday: number; readonly medal: Medal | null; + /** Skins this run unlocked. */ + readonly newSkins: ReadonlyArray; } function dailyGame(day: string): BilliardsGame { @@ -101,6 +106,8 @@ export class BilliardsSession { private runs = loadRuns(); private todayRuns = runsOn(this.runs, this.day); private result: RunResult | null = null; + private unlocked = unlockedSkins(this.runs); + private skin: SkinId = this.unlocked.has(loadSkin()) ? loadSkin() : "classic"; private scale = 1; private frame = 0; private lastFrame = 0; @@ -359,11 +366,15 @@ export class BilliardsSession { finishedAt: new Date().toISOString(), }; this.runs = saveRun(this.runs, run); + const before = this.unlocked; + this.unlocked = unlockedSkins(this.runs); + const newSkins = [...this.unlocked].filter((id) => !before.has(id)); this.todayRuns = runsOn(this.runs, this.day); this.result = { run, rankToday: this.todayRuns.indexOf(run) + 1, medal: medalFor(run.totalMs), + newSkins, }; } @@ -446,20 +457,25 @@ export class BilliardsSession { this.fx.trail(cue.x, cue.y, POWER_COLORS.glow); } const style = this.cueStyle(); - if ( - style !== "classic" && - this.game.phase === "aiming" && - cue?.onTable && - Math.random() < 0.35 - ) { + const sparks = + style === "wand" || style === "golden" || style === "glow" ? POWER_COLORS[style] : null; + if (sparks && this.game.phase === "aiming" && cue?.onTable && Math.random() < 0.35) { const tip = cueTip(cue, this.aimAngle, this.power(now)); - this.fx.trail(tip.x, tip.y, POWER_COLORS[style]); + this.fx.trail(tip.x, tip.y, sparks); } } private cueStyle(): CueStyle { if (this.game.armed) return this.game.armed; - return this.game.goldenShots > 0 ? "golden" : "classic"; + return this.game.goldenShots > 0 ? "golden" : this.skin; + } + + /** Picks a stick skin; only unlocked ones take. */ + setSkin(id: SkinId): void { + if (!this.unlocked.has(id)) return; + this.skin = id; + saveSkin(id); + this.emitHud(performance.now(), true); } private emitHud(now: number, force: boolean): void { @@ -480,6 +496,8 @@ export class BilliardsSession { result: this.result, armed: game.armed, goldenShots: game.goldenShots, + skin: this.skin, + unlockedSkins: this.unlocked, }; this.lastHudAt = now; const last = this.lastHud; diff --git a/apps/web/src/components/billiards/billiardsSkins.test.ts b/apps/web/src/components/billiards/billiardsSkins.test.ts new file mode 100644 index 0000000000..b02af74fbe --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSkins.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import type { BilliardsRun } from "./billiardsRecords.ts"; +import { unlockedSkins } from "./billiardsSkins.ts"; + +const run = (totalMs: number): BilliardsRun => ({ + day: "2026-11-26", + totalMs, + penaltySeconds: 0, + shots: 20, + finishedAt: "2026-11-26T12:00:00.000Z", +}); + +describe("unlockedSkins", () => { + it("starts with only the classic stick", () => { + expect([...unlockedSkins([])]).toEqual(["classic"]); + }); + + it("unlocks Ari for any cleared table, and each medal's stick with every lower one", () => { + expect([...unlockedSkins([run(400_000)])]).toEqual(["classic", "ari"]); + expect([...unlockedSkins([run(400_000), run(200_000)])]).toEqual([ + "classic", + "ari", + "copper", + "chrome", + ]); + expect(unlockedSkins([run(100_000)]).has("ember")).toBe(true); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsSkins.ts b/apps/web/src/components/billiards/billiardsSkins.ts new file mode 100644 index 0000000000..7ad9ad9bfc --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSkins.ts @@ -0,0 +1,79 @@ +import { medalFor, type BilliardsRun, type Medal } from "./billiardsRecords.ts"; + +// Stick skins: looks earned with results on this machine. A power-up's look still wins while it's +// armed, so a skin never hides that one is ready. + +const STORAGE_KEY = "ari-billiards-skin"; + +export type SkinId = "classic" | "ari" | "copper" | "chrome" | "ember"; + +export interface Skin { + readonly id: SkinId; + /** What earns it: nothing, any cleared table, or a medal. */ + readonly unlock: null | "clear" | Medal; + /** A CSS gradient for the picker swatch. */ + readonly swatch: string; +} + +export const SKINS: ReadonlyArray = [ + { + id: "classic", + unlock: null, + swatch: "linear-gradient(90deg, #120a06, #2a1810 35%, #d4af37 37%, #b8875a 40%, #e0c69c)", + }, + { + id: "ari", + unlock: "clear", + swatch: "linear-gradient(90deg, #2a0f42, #5b2a86 45%, #ffc83d 47%, #5b2a86 50%, #8a4fc0)", + }, + { + id: "copper", + unlock: "bronze", + swatch: "linear-gradient(90deg, #5a2e14, #b87333 30%, #e8a476 50%, #b87333 70%, #f3c6a0)", + }, + { + id: "chrome", + unlock: "silver", + swatch: "linear-gradient(90deg, #3c434c, #9aa4b0 30%, #f4f7fa 50%, #9aa4b0 70%, #dfe5ec)", + }, + { + id: "ember", + unlock: "gold", + swatch: "linear-gradient(90deg, #120604, #3a1408 30%, #ff7a1a 45%, #3a1408 60%, #ffb347)", + }, +]; + +const MEDAL_RANK: Readonly> = { bronze: 1, silver: 2, gold: 3 }; + +/** The skins these runs have earned. */ +export function unlockedSkins(runs: ReadonlyArray): ReadonlySet { + let best = 0; + for (const run of runs) { + const medal = medalFor(run.totalMs); + if (medal) best = Math.max(best, MEDAL_RANK[medal]); + } + return new Set( + SKINS.filter( + (skin) => + skin.unlock === null || + (skin.unlock === "clear" ? runs.length > 0 : best >= MEDAL_RANK[skin.unlock]), + ).map((skin) => skin.id), + ); +} + +export function loadSkin(): SkinId { + try { + const stored = window.localStorage.getItem(STORAGE_KEY); + return SKINS.find((skin) => skin.id === stored)?.id ?? "classic"; + } catch { + return "classic"; + } +} + +export function saveSkin(id: SkinId): void { + try { + window.localStorage.setItem(STORAGE_KEY, id); + } catch { + // Not saved; the choice still holds for this game. + } +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index fbbd463cd7..3b184ec3da 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3111,6 +3111,17 @@ "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", + "209d36a8ffe3791c": "Klassisch", + "88b909e76e754bef": "Kupfer", + "9ca687520bab7394": "Chrom", + "00f65fd8e47554b2": "Glut", + "637a3c803f6578d7": "Räume einen Tisch ab", + "af4bf1e680b765c6": "Gewinne eine Bronzemedaille", + "52074a21b1859001": "Gewinne eine Silbermedaille", + "ef059864c4430c66": "Gewinne eine Goldmedaille", + "ec925d6946a88b5b": "Queue wählen", + "152ec44c76dca1ec": "Queue", + "4fa58c8eb16781d2": "Neues Queue freigeschaltet: {name}", "0f0b7208bbe0f06f": "Zauberstab bereit: Die erste Kugel, die du triffst, fällt ins nächste Loch.", "9de13db44f3016c5": "Leuchtqueue bereit: Die Weiße bricht durch bis zu {count} Kugeln und versenkt sie.", "c3405ef38e586f1d": "{count, plural, =1 {Goldqueue: volle Sicht für diesen Stoß.} other {Goldqueue: volle Sicht für {count} Stöße.}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 8c59178892..106670c0e8 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", + "209d36a8ffe3791c": "Classic", + "88b909e76e754bef": "Copper", + "9ca687520bab7394": "Chrome", + "00f65fd8e47554b2": "Ember", + "637a3c803f6578d7": "Clear a table", + "af4bf1e680b765c6": "Win a bronze medal", + "52074a21b1859001": "Win a silver medal", + "ef059864c4430c66": "Win a gold medal", + "ec925d6946a88b5b": "Choose a stick", + "152ec44c76dca1ec": "Stick", + "4fa58c8eb16781d2": "New stick unlocked: {name}", "0f0b7208bbe0f06f": "Wand ready: the first ball you hit drops into the nearest pocket.", "9de13db44f3016c5": "Glow cue ready: the cue ball bursts through up to {count} balls and drops them.", "c3405ef38e586f1d": "{count, plural, =1 {Golden cue: full sight for this shot.} other {Golden cue: full sight for {count} shots.}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 1a58ef0dae..4dd0bcf388 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", + "209d36a8ffe3791c": "Clásico", + "88b909e76e754bef": "Cobre", + "9ca687520bab7394": "Cromo", + "00f65fd8e47554b2": "Brasa", + "637a3c803f6578d7": "Limpia una mesa", + "af4bf1e680b765c6": "Gana una medalla de bronce", + "52074a21b1859001": "Gana una medalla de plata", + "ef059864c4430c66": "Gana una medalla de oro", + "ec925d6946a88b5b": "Elegir un taco", + "152ec44c76dca1ec": "Taco", + "4fa58c8eb16781d2": "Nuevo taco desbloqueado: {name}", "0f0b7208bbe0f06f": "Varita lista: la primera bola que toques cae en la tronera más cercana.", "9de13db44f3016c5": "Taco brillante listo: la blanca atraviesa hasta {count} bolas y las entronera.", "c3405ef38e586f1d": "{count, plural, =1 {Taco dorado: visión completa en este tiro.} other {Taco dorado: visión completa durante {count} tiros.}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 92ccbdc4af..725616d151 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", + "209d36a8ffe3791c": "Classique", + "88b909e76e754bef": "Cuivre", + "9ca687520bab7394": "Chrome", + "00f65fd8e47554b2": "Braise", + "637a3c803f6578d7": "Nettoyez une table", + "af4bf1e680b765c6": "Gagnez une médaille de bronze", + "52074a21b1859001": "Gagnez une médaille d’argent", + "ef059864c4430c66": "Gagnez une médaille d’or", + "ec925d6946a88b5b": "Choisir une queue", + "152ec44c76dca1ec": "Queue", + "4fa58c8eb16781d2": "Nouvelle queue débloquée : {name}", "0f0b7208bbe0f06f": "Baguette prête : la première bille touchée tombe dans la poche la plus proche.", "9de13db44f3016c5": "Queue lumineuse prête : la blanche traverse jusqu’à {count} billes et les empoche.", "c3405ef38e586f1d": "{count, plural, =1 {Queue dorée : vision complète pour ce coup.} other {Queue dorée : vision complète pour {count} coups.}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 3946e058c4..f1b02c0b07 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3108,6 +3108,17 @@ "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", + "209d36a8ffe3791c": "クラシック", + "88b909e76e754bef": "カッパー", + "9ca687520bab7394": "クローム", + "00f65fd8e47554b2": "エンバー", + "637a3c803f6578d7": "テーブルを1回クリア", + "af4bf1e680b765c6": "銅メダルを獲得", + "52074a21b1859001": "銀メダルを獲得", + "ef059864c4430c66": "金メダルを獲得", + "ec925d6946a88b5b": "キューを選ぶ", + "152ec44c76dca1ec": "キュー", + "4fa58c8eb16781d2": "新しいキューを解放:{name}", "0f0b7208bbe0f06f": "ワンド準備完了:最初に当てたボールが一番近いポケットに落ちます。", "9de13db44f3016c5": "光るキュー準備完了:手球が最大{count}個のボールを突き抜けて落とします。", "c3405ef38e586f1d": "{count, plural, other {ゴールドキュー:あと{count}ショット、ラインが全部見えます。}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c676da75f3..3826d5e26a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3109,6 +3109,17 @@ "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", + "209d36a8ffe3791c": "클래식", + "88b909e76e754bef": "구리", + "9ca687520bab7394": "크롬", + "00f65fd8e47554b2": "불씨", + "637a3c803f6578d7": "테이블 한 번 클리어", + "af4bf1e680b765c6": "동메달 획득", + "52074a21b1859001": "은메달 획득", + "ef059864c4430c66": "금메달 획득", + "ec925d6946a88b5b": "큐 고르기", + "152ec44c76dca1ec": "큐", + "4fa58c8eb16781d2": "새 큐 잠금 해제: {name}", "0f0b7208bbe0f06f": "지팡이 준비: 처음 맞힌 공이 가장 가까운 포켓으로 들어갑니다.", "9de13db44f3016c5": "빛나는 큐 준비: 수구가 최대 {count}개의 공을 뚫고 지나가며 넣습니다.", "c3405ef38e586f1d": "{count, plural, other {황금 큐: {count}샷 동안 전체 경로가 보입니다.}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f2b066a1cc..87846aa1fe 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", + "209d36a8ffe3791c": "Clássico", + "88b909e76e754bef": "Cobre", + "9ca687520bab7394": "Cromo", + "00f65fd8e47554b2": "Brasa", + "637a3c803f6578d7": "Limpe uma mesa", + "af4bf1e680b765c6": "Ganhe uma medalha de bronze", + "52074a21b1859001": "Ganhe uma medalha de prata", + "ef059864c4430c66": "Ganhe uma medalha de ouro", + "ec925d6946a88b5b": "Escolher um taco", + "152ec44c76dca1ec": "Taco", + "4fa58c8eb16781d2": "Novo taco desbloqueado: {name}", "0f0b7208bbe0f06f": "Varinha pronta: a primeira bola que você acertar cai na caçapa mais próxima.", "9de13db44f3016c5": "Taco brilhante pronto: a branca atravessa até {count} bolas e as encaçapa.", "c3405ef38e586f1d": "{count, plural, =1 {Taco dourado: visão completa nesta tacada.} other {Taco dourado: visão completa por {count} tacadas.}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5452adaa56..23fdd9e662 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", + "209d36a8ffe3791c": "Классика", + "88b909e76e754bef": "Медь", + "9ca687520bab7394": "Хром", + "00f65fd8e47554b2": "Угли", + "637a3c803f6578d7": "Очистите стол", + "af4bf1e680b765c6": "Получите бронзовую медаль", + "52074a21b1859001": "Получите серебряную медаль", + "ef059864c4430c66": "Получите золотую медаль", + "ec925d6946a88b5b": "Выбрать кий", + "152ec44c76dca1ec": "Кий", + "4fa58c8eb16781d2": "Новый кий открыт: {name}", "0f0b7208bbe0f06f": "Палочка готова: первый шар, по которому вы попадёте, упадёт в ближайшую лузу.", "9de13db44f3016c5": "Светящийся кий готов: биток пробьёт до {count} шаров и забьёт их.", "c3405ef38e586f1d": "{count, plural, =1 {Золотой кий: полная траектория на этот удар.} few {Золотой кий: полная траектория на {count} удара.} many {Золотой кий: полная траектория на {count} ударов.} other {Золотой кий: полная траектория на {count} удара.}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 404ecc6285..d4ed4a85a4 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3110,6 +3110,17 @@ "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", + "209d36a8ffe3791c": "Klassisk", + "88b909e76e754bef": "Koppar", + "9ca687520bab7394": "Krom", + "00f65fd8e47554b2": "Glöd", + "637a3c803f6578d7": "Rensa ett bord", + "af4bf1e680b765c6": "Vinn en bronsmedalj", + "52074a21b1859001": "Vinn en silvermedalj", + "ef059864c4430c66": "Vinn en guldmedalj", + "ec925d6946a88b5b": "Välj en kö", + "152ec44c76dca1ec": "Kö", + "4fa58c8eb16781d2": "Ny kö upplåst: {name}", "0f0b7208bbe0f06f": "Trollstav redo: första bollen du träffar går i närmaste hål.", "9de13db44f3016c5": "Glödkö redo: den vita bollen bryter igenom upp till {count} bollar och sänker dem.", "c3405ef38e586f1d": "{count, plural, =1 {Guldkö: full sikt för den här stöten.} other {Guldkö: full sikt i {count} stötar.}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index b4e53a70aa..c68460c4f2 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3114,6 +3114,17 @@ "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", + "209d36a8ffe3791c": "经典", + "88b909e76e754bef": "紫铜", + "9ca687520bab7394": "铬银", + "00f65fd8e47554b2": "余烬", + "637a3c803f6578d7": "清台一次", + "af4bf1e680b765c6": "获得铜牌", + "52074a21b1859001": "获得银牌", + "ef059864c4430c66": "获得金牌", + "ec925d6946a88b5b": "选择球杆", + "152ec44c76dca1ec": "球杆", + "4fa58c8eb16781d2": "解锁新球杆:{name}", "0f0b7208bbe0f06f": "魔杖就绪:你击中的第一个球会落入最近的袋口。", "9de13db44f3016c5": "光之球杆就绪:母球最多穿过 {count} 个球并让它们落袋。", "c3405ef38e586f1d": "{count, plural, other {金色球杆:接下来 {count} 杆可看到完整路线。}}", From fb129364cff86e0759880351fe4d02751771f7c1 Mon Sep 17 00:00:00 2001 From: Michi Date: Thu, 26 Nov 2026 15:28:27 +0100 Subject: [PATCH 6/6] feat(web): billiards pool-hall look: brass scoreboard, chalk, callouts, pinned notes --- .../components/billiards/BilliardsOverlay.tsx | 476 +++++++++--------- .../components/billiards/billiardsAudio.ts | 6 + .../components/billiards/billiardsBalls.ts | 12 +- .../src/components/billiards/billiardsHud.ts | 323 ++++++++++++ .../components/billiards/billiardsRender.ts | 25 +- .../components/billiards/billiardsSession.ts | 96 ++++ apps/web/src/i18n/translations/de.json | 37 +- apps/web/src/i18n/translations/en.json | 37 +- apps/web/src/i18n/translations/es.json | 37 +- apps/web/src/i18n/translations/fr.json | 37 +- apps/web/src/i18n/translations/ja.json | 37 +- apps/web/src/i18n/translations/ko.json | 37 +- apps/web/src/i18n/translations/pt-BR.json | 37 +- apps/web/src/i18n/translations/ru.json | 37 +- apps/web/src/i18n/translations/sv.json | 37 +- apps/web/src/i18n/translations/zh.json | 37 +- 16 files changed, 864 insertions(+), 444 deletions(-) create mode 100644 apps/web/src/components/billiards/billiardsHud.ts diff --git a/apps/web/src/components/billiards/BilliardsOverlay.tsx b/apps/web/src/components/billiards/BilliardsOverlay.tsx index a720a90afb..704b6662d3 100644 --- a/apps/web/src/components/billiards/BilliardsOverlay.tsx +++ b/apps/web/src/components/billiards/BilliardsOverlay.tsx @@ -1,38 +1,67 @@ import { useNavigate } from "@tanstack/react-router"; import { useGT } from "gt-react"; -import { - CircleCheckIcon, - LockIcon, - MedalIcon, - MessageCircleQuestionIcon, - PaletteIcon, - GiftIcon, - XIcon, -} from "lucide-react"; -import { useEffect, useRef, useState } from "react"; +import { GiftIcon, LockIcon, MedalIcon, PaletteIcon, XIcon } from "lucide-react"; +import { useEffect, useRef, useState, type CSSProperties } from "react"; import { createPortal } from "react-dom"; import { cn } from "../../lib/utils"; import { useThreadShells } from "../../state/entities"; +import { formatClock, type BilliardsLabels } from "./billiardsHud"; import { medalFor, nextMedal, type Medal } from "./billiardsRecords"; -import { POWER_COLORS } from "./billiardsCues"; -import { FOUL_PENALTY_SECONDS, GLOW_BALLS } from "./billiardsRules"; +import { GLOW_BALLS, GOLDEN_SHOTS } from "./billiardsRules"; import { BilliardsSession, type BilliardsHud } from "./billiardsSession"; import { SKINS, type Skin, type SkinId } from "./billiardsSkins"; import { snapshotThreads, threadAlerts, type ThreadAlert } from "./billiardsThreadAlerts"; const MAX_ALERTS = 3; const MEDAL_COLORS: Readonly> = { - gold: "#e8b931", - silver: "#c4cbd4", - bronze: "#c8834f", + gold: "#f0c04a", + silver: "#d3d9e0", + bronze: "#d08a52", }; -function formatClock(ms: number, tenths = false): string { - const seconds = Math.floor(ms / 1000); - const clock = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; - return tenths ? `${clock}.${Math.floor((ms % 1000) / 100)}` : clock; +// The pool hall's materials, kept here so the overlay matches what the canvas draws. +const CHALK = "rgba(236, 233, 222, 0.92)"; +const CHALK_DIM = "rgba(236, 233, 222, 0.55)"; +const CHALK_YELLOW = "#ffe08a"; +const CHALKBOARD: CSSProperties = { + background: "radial-gradient(120% 90% at 50% 40%, #2c3a33 0%, #1d2823 60%, #151c18 100%)", + border: "10px solid #4a2f1b", + boxShadow: + "inset 0 0 0 2px #6b4527, inset 0 0 30px rgba(0,0,0,0.55), 0 24px 60px rgba(0,0,0,0.7)", + color: CHALK, + textShadow: "0 0 1px rgba(236,233,222,0.5)", +}; +const BRASS_KNOB: CSSProperties = { + background: "radial-gradient(circle at 35% 30%, #f6dc93, #c9a24a 55%, #6e5016)", + boxShadow: "0 2px 6px rgba(0,0,0,0.6), inset 0 -1px 2px rgba(0,0,0,0.35)", + color: "#3a2808", +}; +const PAPER: CSSProperties = { + background: "linear-gradient(180deg, #fbf3dc, #efe2bf)", + boxShadow: "0 8px 18px rgba(0,0,0,0.55), 0 1px 0 rgba(255,255,255,0.6) inset", + color: "#2b2114", +}; +const WOOD_DRAWER: CSSProperties = { + background: "linear-gradient(180deg, #3d2416, #2a1810)", + boxShadow: "0 16px 40px rgba(0,0,0,0.7), inset 0 1px 0 rgba(255,255,255,0.08)", + border: "1px solid #5a3a22", +}; +const KEYFRAMES = ` +@keyframes ari-billiards-note-in { + 0% { transform: translateY(-24px) rotate(-9deg); opacity: 0; } + 55% { transform: translateY(3px) rotate(2deg); opacity: 1; } + 78% { transform: translateY(-1px) rotate(-3deg); } + 100% { transform: translateY(0) rotate(-1.5deg); } } +@keyframes ari-billiards-pin-glow { + 0%, 100% { box-shadow: 0 0 0 0 rgba(255, 90, 70, 0.7); } + 50% { box-shadow: 0 0 0 5px rgba(255, 90, 70, 0); } +} +@keyframes ari-billiards-board-in { + 0% { transform: translateY(14px) scale(0.96); opacity: 0; } + 100% { transform: translateY(0) scale(1); opacity: 1; } +}`; function alertId(alert: ThreadAlert): string { return `${alert.key}:${alert.kind}:${alert.thread.latestRun?.completedAt ?? ""}`; @@ -45,6 +74,7 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { const dialogRef = useRef(null); const canvasRef = useRef(null); const sessionRef = useRef(null); + const chimedRef = useRef>(new Set()); const [hud, setHud] = useState(null); const threads = useThreadShells(); const [baseline] = useState(() => snapshotThreads(threads)); @@ -53,6 +83,7 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { const alerts = threadAlerts(baseline, threads) .filter((alert) => !dismissed.has(alertId(alert))) .slice(0, MAX_ALERTS); + const alertKey = alerts.map(alertId).join("|"); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- runs the canvas game session while mounted and reports its HUD useEffect(() => { @@ -67,6 +98,37 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { }; }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hands the canvas game its words in the reader's language + useEffect(() => { + const labels: BilliardsLabels = { + scratch: gt("Scratch"), + miss: gt("No ball hit"), + freeMiss: gt("Free this once"), + early8: gt("8 too early"), + wrong8: gt("Wrong pocket"), + scratch8: gt("Scratch on the 8"), + wand: gt("Wand"), + golden: gt("Golden cue"), + glow: gt("Glow cue"), + wandHint: gt("The first ball you hit drops"), + goldenHint: gt("Full sight for {count} shots", { count: GOLDEN_SHOTS }), + glowHint: gt("Bursts through {count} balls", { count: GLOW_BALLS }), + callPocket: gt("Click a pocket to call the 8"), + callFirst: gt("Call a pocket first"), + breakHint: gt("Hold to charge, release to shoot"), + controlsHint: gt("Shift for fine aim, Esc to close"), + penalty: (seconds) => gt("+{seconds} s", { seconds }), + }; + sessionRef.current?.setLabels(labels); + }, [gt]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rings a bell (Web Audio) when a new thread note is pinned + useEffect(() => { + const ids = alertKey === "" ? [] : alertKey.split("|"); + if (ids.some((id) => !chimedRef.current.has(id))) sessionRef.current?.chime(); + chimedRef.current = new Set([...chimedRef.current, ...ids]); + }, [alertKey, sessionRef, chimedRef]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a window Escape listener that closes the game while it is open useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { @@ -116,7 +178,6 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { return gt("Win a gold medal"); } }; - const medalLabel = (medal: Medal) => medal === "gold" ? gt("Gold medal") @@ -134,96 +195,7 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { : gt("Next: bronze under {time}", { time }); }; - const status = ((): { text: string; tone: string; color?: string } => { - if (!hud) return { text: "", tone: "quiet" }; - if (hud.blocked) return { text: gt("Call a pocket for the 8 first: click it."), tone: "warn" }; - switch (hud.foul) { - case "scratch": - return { - text: gt("Scratch. +{seconds} s", { seconds: FOUL_PENALTY_SECONDS.scratch }), - tone: "warn", - }; - case "noContact": - return hud.forgiven - ? { - text: gt("No ball hit. Free this once, after that it costs {seconds} s.", { - seconds: FOUL_PENALTY_SECONDS.noContact, - }), - tone: "call", - } - : { - text: gt("No ball hit. +{seconds} s", { seconds: FOUL_PENALTY_SECONDS.noContact }), - tone: "warn", - }; - case "early8": - return { - text: gt("The 8 went in too early and is back on its spot. +{seconds} s", { - seconds: FOUL_PENALTY_SECONDS.early8, - }), - tone: "warn", - }; - case "wrong8": - return { - text: gt("Wrong pocket. The 8 is back on its spot. +{seconds} s", { - seconds: FOUL_PENALTY_SECONDS.wrong8, - }), - tone: "warn", - }; - case "scratch8": - return { - text: gt("Scratch on the 8. It is back on its spot. +{seconds} s", { - seconds: FOUL_PENALTY_SECONDS.scratch8, - }), - tone: "warn", - }; - case null: - break; - } - if (hud.armed === "wand") { - return { - text: gt("Wand ready: the first ball you hit drops into the nearest pocket."), - tone: "power", - color: `rgb(${POWER_COLORS.wand})`, - }; - } - if (hud.armed === "glow") { - return { - text: gt( - "Glow cue ready: the cue ball bursts through up to {count} balls and drops them.", - { - count: GLOW_BALLS, - }, - ), - tone: "power", - color: `rgb(${POWER_COLORS.glow})`, - }; - } - if (hud.needsCall) { - return hud.calledPocket === null - ? { text: gt("Only the 8 is left. Click the pocket you call."), tone: "call" } - : { text: gt("8 called. Click another pocket to change it."), tone: "call" }; - } - if (hud.goldenShots > 0) { - return { - text: gt( - "{count, plural, =1 {Golden cue: full sight for this shot.} other {Golden cue: full sight for {count} shots.}}", - { count: hud.goldenShots }, - ), - tone: "power", - color: `rgb(${POWER_COLORS.golden})`, - }; - } - if (hud.isBreak) { - return { - text: gt("Today's rack is the same for everyone. The clock starts after the break."), - tone: "quiet", - }; - } - return { - text: gt("Move to aim, hold to charge, release to shoot. Shift aims finer, Esc closes."), - tone: "quiet", - }; - })(); + const result = hud?.phase === "cleared" ? hud.result : null; return createPortal(

void }) { aria-modal="true" aria-label={gt("Billiards")} tabIndex={-1} - className="fixed inset-0 z-[200] flex items-center justify-center bg-black/80 outline-none backdrop-blur-sm [-webkit-app-region:no-drag]" + className="fixed inset-0 z-[200] flex items-center justify-center bg-black/85 outline-none backdrop-blur-sm [-webkit-app-region:no-drag]" > +
-
-
- {gt("Shots {shots}", { shots: hud?.shots ?? 0 })} - {hud && hud.penaltySeconds > 0 ? ( - - {gt("Penalties +{seconds} s", { seconds: hud.penaltySeconds })} - - ) : null} - {hud?.todayRuns[0] ? ( - - {gt("Best {time}", { time: formatClock(hud.todayRuns[0].totalMs, true) })} - - ) : null} - {formatClock(hud?.totalMs ?? 0)} - - -
-

+ +

+ {pickerOpen && hud ? ( -
-

{gt("Stick")}

+
+

+ {gt("Stick")} +

{SKINS.map((skin) => { const unlocked = hud.unlockedSkins.has(skin.id); + const selected = hud.skin === skin.id; return (
) : null} + {alerts.length > 0 ? ( -
+
{alerts.map((alert) => (
- {alert.kind === "done" ? ( - - ) : ( - - )} - + +

{alert.kind === "done" - ? gt("{title} is done", { title: alert.thread.title }) - : gt("{title} needs you", { title: alert.thread.title })} - - - + ? gt("Done", { $context: "a thread finished" }) + : gt("Needs you")} +

+

{alert.thread.title}

+
+ + +
))}
) : null} + {hud?.phase === "cleared" ? ( -
-
-

{gt("Table cleared")}

-

- {formatClock(hud.result?.run.totalMs ?? hud.totalMs, true)} +

+
+

+ {gt("Table cleared")} +

+

+ {formatClock(result?.run.totalMs ?? hud.totalMs, true)}

- {hud.result?.medal ? ( +

+ {gt("{clock} played, +{seconds} s penalties, {shots} shots", { + clock: formatClock( + (result?.run.totalMs ?? hud.totalMs) - hud.penaltySeconds * 1000, + true, + ), + seconds: hud.penaltySeconds, + shots: hud.shots, + })} +

+ {result?.medal ? (

- {medalLabel(hud.result.medal)} + {medalLabel(result.medal)}

) : null} - {hud.result?.rankToday === 1 ? ( -

{gt("New best today!")}

+ {result?.rankToday === 1 ? ( +

+ {gt("New best today!")} +

) : null} - {hud.result?.newSkins.map((id) => ( -

- + {result?.newSkins.map((id) => ( +

+ {gt("New stick unlocked: {name}", { name: skinName(id) })}

))} - {hud.result && hud.result.medal !== "gold" ? ( -

- {nextMedalText(hud.result.run.totalMs)} + {result && result.medal !== "gold" ? ( +

+ {nextMedalText(result.run.totalMs)}

) : null} -

- {gt("{clock} played, +{seconds} s penalties, {shots} shots", { - clock: formatClock(hud.totalMs - hud.penaltySeconds * 1000, true), - seconds: hud.penaltySeconds, - shots: hud.shots, - })} -

{hud.todayRuns.length > 1 ? ( -
-

+

+

{gt("Today on this computer")}

-
    - {hud.todayRuns.slice(0, 5).map((run, index) => ( -
  1. - {index + 1} - {formatClock(run.totalMs, true)} - {run.penaltySeconds > 0 ? ( - - {gt("+{seconds} s", { seconds: run.penaltySeconds })} +
      + {hud.todayRuns.slice(0, 5).map((run, index) => { + const medal = medalFor(run.totalMs); + const current = run === result?.run; + return ( +
    1. + + {index + 1} - ) : null} - {(() => { - const medal = medalFor(run.totalMs); - return medal ? ( + {formatClock(run.totalMs, true)} + {run.penaltySeconds > 0 ? ( + + {gt("+{seconds} s", { seconds: run.penaltySeconds })} + + ) : null} + {medal ? ( void }) { /> ) : ( - ); - })()} -
    2. - ))} + )} + + ); + })}
) : null} @@ -438,14 +420,16 @@ export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { diff --git a/apps/web/src/components/billiards/billiardsAudio.ts b/apps/web/src/components/billiards/billiardsAudio.ts index 1da7740fe2..4c9bf625c0 100644 --- a/apps/web/src/components/billiards/billiardsAudio.ts +++ b/apps/web/src/components/billiards/billiardsAudio.ts @@ -71,6 +71,12 @@ export class BilliardsAudio { } } + /** A soft two-note bell: a thread wants attention. */ + chime(): void { + this.tone("sine", 1318, 1318, 0.2, 0.6); + this.tone("sine", 1760, 1760, 0.16, 0.8, 0.12); + } + /** A ball taken by a power-up: a soft magic swish. */ guide(): void { this.tone("sine", 520, 1400, 0.16, 0.35); diff --git a/apps/web/src/components/billiards/billiardsBalls.ts b/apps/web/src/components/billiards/billiardsBalls.ts index 24090a6494..620171a2a0 100644 --- a/apps/web/src/components/billiards/billiardsBalls.ts +++ b/apps/web/src/components/billiards/billiardsBalls.ts @@ -123,17 +123,21 @@ export class BallSprites { ): void { if (axis[2] < 0.35) return; const angle = Math.atan2(axis[1], axis[0]); + // Drawn at real pixel size: tiny fonts scaled up by the table transform render soft. + const matrix = ctx.getTransform(); + const at = matrix.transformPoint({ x: x + axis[0] * r * 0.98, y: y + axis[1] * r * 0.98 }); + const pixels = r * matrix.a; ctx.save(); - ctx.translate(x + axis[0] * r * 0.98, y + axis[1] * r * 0.98); + ctx.setTransform(1, 0, 0, 1, at.x, at.y); ctx.rotate(angle); ctx.scale(axis[2], 1); ctx.rotate(-angle); - ctx.globalAlpha = Math.min(1, (axis[2] - 0.35) * 4); + ctx.globalAlpha *= Math.min(1, (axis[2] - 0.35) * 4); ctx.fillStyle = "#151515"; - ctx.font = `700 ${r * 0.62}px ui-sans-serif, system-ui, sans-serif`; + ctx.font = `700 ${pixels * 0.62}px ui-sans-serif, system-ui, sans-serif`; ctx.textAlign = "center"; ctx.textBaseline = "middle"; - ctx.fillText(String(id), 0, r * 0.04); + ctx.fillText(String(id), 0, pixels * 0.04); ctx.restore(); } diff --git a/apps/web/src/components/billiards/billiardsHud.ts b/apps/web/src/components/billiards/billiardsHud.ts new file mode 100644 index 0000000000..40103aaebf --- /dev/null +++ b/apps/web/src/components/billiards/billiardsHud.ts @@ -0,0 +1,323 @@ +import { RAIL_WIDTH, TABLE_LENGTH, TABLE_WIDTH } from "./billiardsTable.ts"; + +// The scoreboard lives in the scene: a brass plate on the top rail for the clock, chalk tallies +// for shots, and callouts that pop up where something happened. Words come in translated. + +export interface BilliardsLabels { + readonly scratch: string; + readonly miss: string; + readonly freeMiss: string; + readonly early8: string; + readonly wrong8: string; + readonly scratch8: string; + readonly wand: string; + readonly golden: string; + readonly glow: string; + readonly wandHint: string; + readonly goldenHint: string; + readonly glowHint: string; + readonly callPocket: string; + readonly callFirst: string; + readonly breakHint: string; + readonly controlsHint: string; + readonly penalty: (seconds: number) => string; +} + +export interface ScoreView { + readonly totalMs: number; + readonly penaltySeconds: number; + readonly shots: number; + readonly bestMs: number | null; + readonly goldenShots: number; + readonly isBreak: boolean; + /** Only the 8 is left and no pocket is called yet. */ + readonly callNeeded: boolean; +} + +const BRASS = "#c9a24a"; +const PLATE_WIDTH = 0.44; +const PLATE_HEIGHT = 0.14; +const PLATE_Y = -RAIL_WIDTH - 0.02 - PLATE_HEIGHT; +const CHALK = "236, 233, 222"; +const ROUNDED = `ui-rounded, "SF Pro Rounded", ui-sans-serif, system-ui, sans-serif`; +const MONO = "ui-monospace, SFMono-Regular, Menlo, monospace"; + +export function formatClock(ms: number, tenths = false): string { + const seconds = Math.floor(Math.max(0, ms) / 1000); + const clock = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + return tenths ? `${clock}.${Math.floor((Math.max(0, ms) % 1000) / 100)}` : clock; +} + +interface TextStyle { + readonly weight?: number; + readonly family?: string; + readonly fill: string; + readonly stroke?: string; + /** Outline width, in table units. */ + readonly strokeWidth?: number; + readonly align?: CanvasTextAlign; + /** In table units. */ + readonly maxWidth?: number; +} + +/** + * Text at (x, y) in table units, `size` tall, drawn at real pixel size: canvas fonts smaller than a + * pixel, scaled up by the table transform, come out soft and blocky. + */ +function drawText( + ctx: CanvasRenderingContext2D, + text: string, + x: number, + y: number, + size: number, + style: TextStyle, +): void { + const matrix = ctx.getTransform(); + const at = matrix.transformPoint({ x, y }); + const scale = matrix.a; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.font = `${style.weight ?? 700} ${size * scale}px ${style.family ?? ROUNDED}`; + ctx.textAlign = style.align ?? "center"; + ctx.textBaseline = "middle"; + const maxWidth = style.maxWidth === undefined ? undefined : style.maxWidth * scale; + if (style.stroke) { + ctx.lineJoin = "round"; + ctx.lineWidth = (style.strokeWidth ?? 0.008) * scale; + ctx.strokeStyle = style.stroke; + ctx.strokeText(text, at.x, at.y, maxWidth); + } + ctx.fillStyle = style.fill; + ctx.fillText(text, at.x, at.y, maxWidth); + ctx.restore(); +} + +function brassPlate(ctx: CanvasRenderingContext2D, x: number, width: number): void { + const plate = ctx.createLinearGradient(0, PLATE_Y, 0, PLATE_Y + PLATE_HEIGHT); + plate.addColorStop(0, "#f4dc95"); + plate.addColorStop(0.45, BRASS); + plate.addColorStop(1, "#76561a"); + const scale = ctx.getTransform().a; + ctx.save(); + ctx.shadowColor = "rgba(0, 0, 0, 0.6)"; + ctx.shadowBlur = 0.03 * scale; + ctx.shadowOffsetY = 0.01 * scale; + ctx.fillStyle = plate; + ctx.beginPath(); + ctx.roundRect(x, PLATE_Y, width, PLATE_HEIGHT, 0.018); + ctx.fill(); + ctx.restore(); + // Bevel and two screws. + ctx.strokeStyle = "rgba(255, 244, 205, 0.6)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.roundRect(x + 0.006, PLATE_Y + 0.006, width - 0.012, PLATE_HEIGHT - 0.012, 0.013); + ctx.stroke(); + for (const sx of [x + 0.024, x + width - 0.024]) { + const sy = PLATE_Y + PLATE_HEIGHT / 2; + ctx.fillStyle = "#6b4d17"; + ctx.beginPath(); + ctx.arc(sx, sy, 0.008, 0, Math.PI * 2); + ctx.fill(); + ctx.strokeStyle = "rgba(255, 240, 200, 0.65)"; + ctx.lineWidth = 0.002; + ctx.beginPath(); + ctx.moveTo(sx - 0.0055, sy - 0.002); + ctx.lineTo(sx + 0.0055, sy + 0.002); + ctx.stroke(); + } +} + +/** Text cut into brass: dark letters over a light edge. */ +function engrave( + ctx: CanvasRenderingContext2D, + text: string, + x: number, + y: number, + size: number, + color = "#3a2808", +): void { + drawText(ctx, text, x, y + size * 0.05, size, { family: MONO, fill: "rgba(255, 246, 214, 0.6)" }); + drawText(ctx, text, x, y, size, { family: MONO, fill: color }); +} + +/** A chalk stroke: soft, a little rough. */ +function chalkLine( + ctx: CanvasRenderingContext2D, + x0: number, + y0: number, + x1: number, + y1: number, +): void { + ctx.strokeStyle = `rgba(${CHALK}, 0.3)`; + ctx.lineWidth = 0.011; + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.stroke(); + ctx.strokeStyle = `rgba(${CHALK}, 0.9)`; + ctx.lineWidth = 0.0055; + ctx.stroke(); +} + +const MAX_TALLIES = 20; + +/** Shots as chalk tallies, in fives, in the dark left of the scoreboard. */ +function drawTallies(ctx: CanvasRenderingContext2D, shots: number): void { + ctx.save(); + ctx.lineCap = "round"; + const height = 0.075; + const top = PLATE_Y + (PLATE_HEIGHT - height) / 2; + const left = -0.15; + const groupWidth = 0.1; + for (let i = 0; i < Math.min(shots, MAX_TALLIES); i++) { + const group = Math.floor(i / 5); + const within = i % 5; + const gx = left + group * groupWidth; + // A fixed wobble per mark, so the tally doesn't jitter. + const wobble = Math.sin(i * 12.9898) * 0.005; + if (within < 4) { + const x = gx + within * 0.018; + chalkLine(ctx, x + wobble, top, x - wobble, top + height); + } else { + chalkLine(ctx, gx - 0.008, top + height * 0.82, gx + 0.064, top + height * 0.18); + } + } + ctx.restore(); + if (shots > MAX_TALLIES) { + drawText(ctx, `+${shots - MAX_TALLIES}`, left, top + height + 0.03, 0.032, { + fill: `rgba(${CHALK}, 0.85)`, + align: "left", + }); + } +} + +function drawTrophy(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void { + ctx.beginPath(); + ctx.moveTo(x - size, y - size); + ctx.lineTo(x + size, y - size); + ctx.quadraticCurveTo(x + size, y + size * 0.3, x, y + size * 0.4); + ctx.quadraticCurveTo(x - size, y + size * 0.3, x - size, y - size); + ctx.fill(); + ctx.fillRect(x - size * 0.15, y + size * 0.35, size * 0.3, size * 0.5); + ctx.fillRect(x - size * 0.55, y + size * 0.8, size * 1.1, size * 0.25); +} + +/** The brass scoreboard (clock, penalties, today's best) and the shot tallies. Table transform. */ +export function drawScoreboard(ctx: CanvasRenderingContext2D, view: ScoreView): void { + const x = (TABLE_WIDTH - PLATE_WIDTH) / 2; + brassPlate(ctx, x, PLATE_WIDTH); + const penalty = view.penaltySeconds > 0; + const clockY = PLATE_Y + PLATE_HEIGHT * (view.bestMs === null ? 0.52 : 0.4); + engrave(ctx, formatClock(view.totalMs), penalty ? 0.47 : 0.5, clockY, 0.085); + if (penalty) engrave(ctx, `+${view.penaltySeconds}`, 0.655, clockY + 0.004, 0.036, "#8a1c10"); + if (view.bestMs !== null) { + const bestY = PLATE_Y + PLATE_HEIGHT * 0.79; + ctx.fillStyle = "#4a340c"; + drawTrophy(ctx, 0.425, bestY - 0.003, 0.0105); + engrave(ctx, formatClock(view.bestMs, true), 0.52, bestY, 0.032, "#4a340c"); + } + drawTallies(ctx, view.shots); + + // The golden cue's shots left, as gold pips under the plate. + for (let i = 0; i < view.goldenShots; i++) { + ctx.fillStyle = "#ffd36a"; + ctx.beginPath(); + ctx.arc( + 0.5 + (i - (view.goldenShots - 1) / 2) * 0.035, + PLATE_Y + PLATE_HEIGHT + 0.012, + 0.008, + 0, + Math.PI * 2, + ); + ctx.fill(); + } +} + +/** Instructions written in chalk on the cloth: how to shoot, or that the 8 needs a pocket. */ +export function drawChalkHints( + ctx: CanvasRenderingContext2D, + view: ScoreView, + labels: BilliardsLabels, + now: number, +): void { + const lines = view.isBreak + ? [labels.breakHint, labels.controlsHint] + : view.callNeeded + ? [labels.callPocket] + : []; + const pulse = view.callNeeded ? 0.65 + 0.35 * Math.sin(now * 3) : 0.8; + for (const [i, line] of lines.entries()) { + const size = i === 0 ? 0.046 : 0.032; + const y = (view.isBreak ? 1.7 : TABLE_LENGTH / 2) + i * 0.065; + drawText(ctx, line, 0.5, y, size, { + weight: 600, + fill: `rgba(${CHALK}, ${(i === 0 ? 0.8 : 0.55) * pulse})`, + stroke: "rgba(0, 0, 0, 0.25)", + strokeWidth: 0.006, + maxWidth: 0.92, + }); + } +} + +interface Callout { + readonly text: string; + readonly detail: string | null; + readonly x: number; + readonly y: number; + readonly color: string; + age: number; + readonly life: number; +} + +/** Words that pop up where something happened, rise a little and fade. */ +export class Callouts { + private items: Callout[] = []; + + add(text: string, x: number, y: number, color: string, detail: string | null = null): void { + // Keep it on the table, clear of the rails. + const cx = Math.max(0.22, Math.min(TABLE_WIDTH - 0.22, x)); + const cy = Math.max(0.1, Math.min(TABLE_LENGTH - 0.16, y)); + this.items.push({ text, detail, x: cx, y: cy, color, age: 0, life: detail ? 2.6 : 1.8 }); + } + + reset(): void { + this.items = []; + } + + update(seconds: number): void { + for (const item of this.items) item.age += seconds; + this.items = this.items.filter((item) => item.age < item.life); + } + + draw(ctx: CanvasRenderingContext2D): void { + for (const item of this.items) { + const t = item.age / item.life; + const pop = + item.age < 0.18 + ? 0.6 + (item.age / 0.18) * 0.55 + : Math.max(1, 1.15 - (item.age - 0.18) * 1.5); + const alpha = t > 0.75 ? (1 - t) / 0.25 : 1; + const y = item.y - 0.07 * Math.min(1, item.age / 0.6); + ctx.save(); + ctx.globalAlpha = alpha; + drawText(ctx, item.text, item.x, y, 0.062 * pop, { + weight: 800, + fill: item.color, + stroke: "rgba(8, 10, 14, 0.88)", + strokeWidth: 0.012 * pop, + maxWidth: 0.95, + }); + if (item.detail) { + drawText(ctx, item.detail, item.x, y + 0.06, 0.034, { + weight: 650, + fill: "rgba(255, 255, 255, 0.95)", + stroke: "rgba(8, 10, 14, 0.85)", + strokeWidth: 0.008, + maxWidth: 0.95, + }); + } + ctx.restore(); + } + } +} diff --git a/apps/web/src/components/billiards/billiardsRender.ts b/apps/web/src/components/billiards/billiardsRender.ts index 5e814fa220..bfbbdfeffb 100644 --- a/apps/web/src/components/billiards/billiardsRender.ts +++ b/apps/web/src/components/billiards/billiardsRender.ts @@ -19,9 +19,10 @@ import { // The canvas is a 9:16 frame around the table, in table units. export const FRAME_WIDTH = 1.4; const FRAME_HEIGHT = (FRAME_WIDTH * 16) / 9; +// The table sits a little low in the frame, leaving the top for the brass scoreboard. export const TABLE_ORIGIN = { x: (FRAME_WIDTH - TABLE_WIDTH) / 2, - y: (FRAME_HEIGHT - TABLE_LENGTH) / 2, + y: 0.3, }; const R = BALL_RADIUS; @@ -60,6 +61,11 @@ export interface SceneView { export { SINK_SECONDS }; +/** Sets the table transform: table units, origin at the cloth's top left corner. */ +export function tableTransform(ctx: CanvasRenderingContext2D, scale: number): void { + frameTransform(ctx, scale); +} + function frameTransform( ctx: CanvasRenderingContext2D, scale: number, @@ -84,9 +90,11 @@ export function drawStaticLayer(layer: HTMLCanvasElement, scale: number): void { ctx.clearRect(0, 0, layer.width, layer.height); frameTransform(ctx, scale); + // A dark pool hall: warm near the table, black at the edges. const backdrop = ctx.createRadialGradient(0.5, 1, 0.2, 0.5, 1, 1.6); - backdrop.addColorStop(0, "#141b24"); - backdrop.addColorStop(1, "#06080c"); + backdrop.addColorStop(0, "#21170f"); + backdrop.addColorStop(0.6, "#0d0906"); + backdrop.addColorStop(1, "#030202"); ctx.fillStyle = backdrop; ctx.fillRect(-TABLE_ORIGIN.x, -TABLE_ORIGIN.y, FRAME_WIDTH, FRAME_HEIGHT); @@ -181,6 +189,15 @@ export function drawStaticLayer(layer: HTMLCanvasElement, scale: number): void { ctx.fill(); } + // One lamp over the middle of the table: a warm pool of light, edges falling off into the dark. + const lamp = ctx.createRadialGradient(0.5, 0.95, 0.05, 0.5, 1, 1.35); + lamp.addColorStop(0, "rgba(255, 214, 160, 0.09)"); + lamp.addColorStop(0.45, "rgba(255, 200, 140, 0.02)"); + lamp.addColorStop(0.75, "rgba(0, 0, 0, 0.18)"); + lamp.addColorStop(1, "rgba(0, 0, 0, 0.5)"); + ctx.fillStyle = lamp; + ctx.fillRect(-TABLE_ORIGIN.x, -TABLE_ORIGIN.y, FRAME_WIDTH, FRAME_HEIGHT); + // The tray the potted balls line up in. ctx.fillStyle = "rgba(255, 255, 255, 0.04)"; ctx.beginPath(); @@ -188,7 +205,7 @@ export function drawStaticLayer(layer: HTMLCanvasElement, scale: number): void { ctx.fill(); } -const TRAY_Y = TABLE_LENGTH + RAIL_WIDTH + 0.07; +const TRAY_Y = TABLE_LENGTH + RAIL_WIDTH + 0.045; function noisePattern(ctx: CanvasRenderingContext2D, scale: number): CanvasPattern | string { const size = 128; diff --git a/apps/web/src/components/billiards/billiardsSession.ts b/apps/web/src/components/billiards/billiardsSession.ts index 867c3a2141..2e5c7175c7 100644 --- a/apps/web/src/components/billiards/billiardsSession.ts +++ b/apps/web/src/components/billiards/billiardsSession.ts @@ -3,12 +3,20 @@ import { observeResize } from "~/lib/observeResize"; import { BilliardsAudio } from "./billiardsAudio.ts"; import { BallSprites } from "./billiardsBalls.ts"; import { ClothNap, Effects } from "./billiardsFx.ts"; +import { + Callouts, + drawChalkHints, + drawScoreboard, + type BilliardsLabels, + type ScoreView, +} from "./billiardsHud.ts"; import { shotSpeed, type PhysicsEvent } from "./billiardsPhysics.ts"; import { drawScene, drawStaticLayer, FRAME_WIDTH, SINK_SECONDS, + tableTransform, TABLE_ORIGIN, type Sinking, } from "./billiardsRender.ts"; @@ -27,6 +35,7 @@ import { loadSkin, saveSkin, unlockedSkins, type SkinId } from "./billiardsSkins import { BilliardsGame, EIGHT, + FOUL_PENALTY_SECONDS, placeRings, seededRandom, type Foul, @@ -83,6 +92,8 @@ const CHARGE_MS = 1100; const FINE_AIM = 0.12; const POCKET_PICK_RADIUS = 0.1; const HUD_INTERVAL_MS = 250; +const FOUL_COLOR = "#ff8a70"; +const CALL_COLOR = "#ffd36a"; /** How slow the final 8 rolls as it nears the called pocket. */ const SLOW_MOTION = 0.3; @@ -100,6 +111,10 @@ export class BilliardsSession { private readonly sprites = new BallSprites(); private readonly nap = new ClothNap(); private readonly fx = new Effects(); + private readonly callouts = new Callouts(); + private labels: BilliardsLabels | null = null; + /** Where the cue ball dropped this shot, for the scratch callout. */ + private scratchPocket: number | null = null; private readonly stopObservingResize: () => void; private day = rackDay(); private game = dailyGame(this.day); @@ -170,9 +185,20 @@ export class BilliardsSession { this.sprites.reset(); this.nap.clear(); this.fx.reset(); + this.callouts.reset(); this.emitHud(performance.now(), true); } + /** The words the scene draws, in the reader's language. */ + setLabels(labels: BilliardsLabels): void { + this.labels = labels; + } + + /** A soft bell, for a thread that wants attention while playing. */ + chime(): void { + this.audio.chime(); + } + /** Drops a shot being charged. False when there was none. */ cancelCharge(): boolean { if (this.chargeStart === null) return false; @@ -249,6 +275,9 @@ export class BilliardsSession { } if (this.game.needsCall() && this.game.calledPocket === null) { this.blockedUntil = now + 2500; + const cue = this.game.ball(0); + if (cue && this.labels) + this.callouts.add(this.labels.callFirst, cue.x, cue.y - 0.06, CALL_COLOR); this.emitHud(now, true); return; } @@ -310,6 +339,7 @@ export class BilliardsSession { this.fx.onEvents(events, this.game.balls, breakShot); if (this.game.phase !== phase) { this.nap.commit(); + if (phase === "rolling") this.calloutShot(); if (this.game.phase === "cleared") { this.clockEnd = time; this.fx.celebrate(this.game.calledPocket); @@ -323,6 +353,7 @@ export class BilliardsSession { this.updateSlowMotion(seconds); this.fx.update(simSeconds === 0 ? 0 : Math.max(simSeconds, seconds * 0.5)); this.sinking = this.sinking.filter((sinking) => time / 1000 - sinking.start < SINK_SECONDS); + this.callouts.update(seconds); drawScene(this.context, this.staticLayer, this.scale, { game: this.game, @@ -338,6 +369,13 @@ export class BilliardsSession { vignette: Math.min(1, (1 - this.timeScale) / (1 - SLOW_MOTION)), cueStyle: this.cueStyle(), }); + tableTransform(this.context, this.scale); + const score = this.scoreView(time); + if (this.labels && this.game.phase === "aiming") { + drawChalkHints(this.context, score, this.labels, time / 1000); + } + drawScoreboard(this.context, score); + this.callouts.draw(this.context); if (time - this.lastHudAt > HUD_INTERVAL_MS) this.emitHud(time, false); }; @@ -357,6 +395,53 @@ export class BilliardsSession { } } + /** Says what a shot's foul cost, where it happened. */ + private calloutShot(): void { + const shot = this.game.lastShot; + const labels = this.labels; + const scratchPocket = this.scratchPocket; + this.scratchPocket = null; + if (!shot?.foul || !labels) return; + const seconds = shot.forgiven ? 0 : FOUL_PENALTY_SECONDS[shot.foul]; + const detail = shot.forgiven ? labels.freeMiss : labels.penalty(seconds); + const color = shot.forgiven ? CALL_COLOR : FOUL_COLOR; + const pocket = POCKETS.find((candidate) => candidate.id === scratchPocket); + const cue = this.game.ball(0); + const eight = this.game.ball(EIGHT); + switch (shot.foul) { + case "scratch": + if (pocket) this.callouts.add(labels.scratch, pocket.x, pocket.y, color, detail); + break; + case "noContact": + if (cue) this.callouts.add(labels.miss, cue.x, cue.y - 0.06, color, detail); + break; + case "early8": + case "wrong8": + case "scratch8": { + const text = + shot.foul === "early8" + ? labels.early8 + : shot.foul === "wrong8" + ? labels.wrong8 + : labels.scratch8; + if (eight) this.callouts.add(text, eight.x, eight.y - 0.06, color, detail); + break; + } + } + } + + private scoreView(now: number): ScoreView { + return { + totalMs: this.totalMs(now), + penaltySeconds: this.game.penaltySeconds, + shots: this.game.shots, + bestMs: this.todayRuns[0]?.totalMs ?? null, + goldenShots: this.game.goldenShots, + isBreak: this.game.isBreak, + callNeeded: this.game.needsCall() && this.game.calledPocket === null, + }; + } + private recordRun(now: number): void { const run: BilliardsRun = { day: this.day, @@ -414,6 +499,7 @@ export class BilliardsSession { case "touch": break; case "pocket": { + if (event.ball === 0) this.scratchPocket = event.pocket; this.audio.pocket(); const pocket = POCKETS[event.pocket]; if (pocket) { @@ -426,6 +512,16 @@ export class BilliardsSession { if (!ring) break; this.audio.powerUp(); this.fx.powerBurst(ring.x, ring.y, POWER_COLORS[ring.kind]); + if (this.labels) { + const { labels } = this; + const [name, hint] = + ring.kind === "wand" + ? [labels.wand, labels.wandHint] + : ring.kind === "golden" + ? [labels.golden, labels.goldenHint] + : [labels.glow, labels.glowHint]; + this.callouts.add(name, ring.x, ring.y - 0.05, `rgb(${POWER_COLORS[ring.kind]})`, hint); + } this.emitHud(now * 1000, true); break; } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3b184ec3da..ce62571c69 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3111,6 +3111,24 @@ "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", + "0bc152a492a12716": "Weiße versenkt", + "aa2534f03870a3f9": "Keine Kugel getroffen", + "e13bcb690bb9c28f": "Einmal gratis", + "3d83bccbd9e6b227": "8 zu früh", + "163440207bcb77bb": "Falsches Loch", + "24517a21c5ca36f7": "Weiße mit der 8", + "e353b6587c16a231": "Zauberstab", + "c174eedba0edabdc": "Goldqueue", + "e3114242f399e91b": "Leuchtqueue", + "59a3f31ee049d0f5": "Die erste getroffene Kugel fällt", + "b6ab17c9f0d8fece": "Volle Sicht für {count} Stöße", + "597ea9e53fc7cb87": "Bricht durch {count} Kugeln", + "3b3a060f716e1b53": "Klick auf ein Loch, um die 8 anzusagen", + "c655975d03078dd5": "Erst ein Loch ansagen", + "3dfd844f131e4d0a": "Halten zum Aufladen, loslassen zum Stoßen", + "11b40436e8016644": "Shift zielt feiner, Esc schließt", + "c8bf7e23d2bc15ae": "Fertig", + "d25661576338fcf0": "Braucht dich", "209d36a8ffe3791c": "Klassisch", "88b909e76e754bef": "Kupfer", "9ca687520bab7394": "Chrom", @@ -3122,35 +3140,16 @@ "ec925d6946a88b5b": "Queue wählen", "152ec44c76dca1ec": "Queue", "4fa58c8eb16781d2": "Neues Queue freigeschaltet: {name}", - "0f0b7208bbe0f06f": "Zauberstab bereit: Die erste Kugel, die du triffst, fällt ins nächste Loch.", - "9de13db44f3016c5": "Leuchtqueue bereit: Die Weiße bricht durch bis zu {count} Kugeln und versenkt sie.", - "c3405ef38e586f1d": "{count, plural, =1 {Goldqueue: volle Sicht für diesen Stoß.} other {Goldqueue: volle Sicht für {count} Stöße.}}", "743592404305841f": "Goldmedaille", "aa1a6773ceaf9223": "Silbermedaille", "b2c0da632a0a1b98": "Bronzemedaille", "a8bf31becdf2dc58": "Nächstes Ziel: Gold unter {time}", "853a57697469a28d": "Nächstes Ziel: Silber unter {time}", "344ff8f2b12b3d70": "Nächstes Ziel: Bronze unter {time}", - "6a850e710ae0c905": "Der Tisch von heute ist für alle gleich. Die Uhr läuft ab dem Anstoß.", - "c8b2492b475e4dfa": "Bestzeit {time}", "67f492a1bb0c8673": "Neue Tagesbestzeit!", "60f19313f8c6f1a2": "Heute auf diesem Computer", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Sag zuerst ein Loch für die 8 an: Klick darauf.", - "8ef73b820d9c2068": "Weiße versenkt. +{seconds} s", - "6e5ca67f8c64ad7e": "Keine Kugel getroffen. Einmal gratis, danach kostet es {seconds} s.", - "5423b71c71cfb18c": "Keine Kugel getroffen. +{seconds} s", - "61d672c96dc8d887": "Die 8 fiel zu früh und liegt wieder auf ihrem Punkt. +{seconds} s", - "3bd41c9312c93563": "Falsches Loch. Die 8 liegt wieder auf ihrem Punkt. +{seconds} s", - "b3a4c68407de4257": "Weiße mit der 8 versenkt. Die 8 liegt wieder auf ihrem Punkt. +{seconds} s", - "d1244c2b4eb6f283": "Nur noch die 8 ist übrig. Klick auf das Loch, das du ansagst.", - "f3127de5f465fbf6": "8 angesagt. Klick auf ein anderes Loch, um es zu ändern.", - "1514485143207779": "Zielen mit der Maus, halten zum Aufladen, loslassen zum Stoßen. Shift zielt feiner, Esc schließt.", "412cfbefb305eb90": "Billard", - "80140e56c78edfbd": "Stöße {shots}", - "41d5b3a5d887b6f8": "Strafzeit +{seconds} s", - "17547068ba80744d": "{title} ist fertig", - "a689501ff2ddb4b6": "{title} braucht dich", "b2be70822d55f16a": "Öffnen", "52499724d03777c6": "Tisch abgeräumt", "9fab80fe09b3dacf": "{clock} gespielt, +{seconds} s Strafzeit, {shots} Stöße", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 106670c0e8..80f68e5143 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", + "0bc152a492a12716": "Scratch", + "aa2534f03870a3f9": "No ball hit", + "e13bcb690bb9c28f": "Free this once", + "3d83bccbd9e6b227": "8 too early", + "163440207bcb77bb": "Wrong pocket", + "24517a21c5ca36f7": "Scratch on the 8", + "e353b6587c16a231": "Wand", + "c174eedba0edabdc": "Golden cue", + "e3114242f399e91b": "Glow cue", + "59a3f31ee049d0f5": "The first ball you hit drops", + "b6ab17c9f0d8fece": "Full sight for {count} shots", + "597ea9e53fc7cb87": "Bursts through {count} balls", + "3b3a060f716e1b53": "Click a pocket to call the 8", + "c655975d03078dd5": "Call a pocket first", + "3dfd844f131e4d0a": "Hold to charge, release to shoot", + "11b40436e8016644": "Shift for fine aim, Esc to close", + "c8bf7e23d2bc15ae": "Done", + "d25661576338fcf0": "Needs you", "209d36a8ffe3791c": "Classic", "88b909e76e754bef": "Copper", "9ca687520bab7394": "Chrome", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Choose a stick", "152ec44c76dca1ec": "Stick", "4fa58c8eb16781d2": "New stick unlocked: {name}", - "0f0b7208bbe0f06f": "Wand ready: the first ball you hit drops into the nearest pocket.", - "9de13db44f3016c5": "Glow cue ready: the cue ball bursts through up to {count} balls and drops them.", - "c3405ef38e586f1d": "{count, plural, =1 {Golden cue: full sight for this shot.} other {Golden cue: full sight for {count} shots.}}", "743592404305841f": "Gold medal", "aa1a6773ceaf9223": "Silver medal", "b2c0da632a0a1b98": "Bronze medal", "a8bf31becdf2dc58": "Next: gold under {time}", "853a57697469a28d": "Next: silver under {time}", "344ff8f2b12b3d70": "Next: bronze under {time}", - "6a850e710ae0c905": "Today's rack is the same for everyone. The clock starts after the break.", - "c8b2492b475e4dfa": "Best {time}", "67f492a1bb0c8673": "New best today!", "60f19313f8c6f1a2": "Today on this computer", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Call a pocket for the 8 first: click it.", - "8ef73b820d9c2068": "Scratch. +{seconds} s", - "6e5ca67f8c64ad7e": "No ball hit. Free this once, after that it costs {seconds} s.", - "5423b71c71cfb18c": "No ball hit. +{seconds} s", - "61d672c96dc8d887": "The 8 went in too early and is back on its spot. +{seconds} s", - "3bd41c9312c93563": "Wrong pocket. The 8 is back on its spot. +{seconds} s", - "b3a4c68407de4257": "Scratch on the 8. It is back on its spot. +{seconds} s", - "d1244c2b4eb6f283": "Only the 8 is left. Click the pocket you call.", - "f3127de5f465fbf6": "8 called. Click another pocket to change it.", - "1514485143207779": "Move to aim, hold to charge, release to shoot. Shift aims finer, Esc closes.", "412cfbefb305eb90": "Billiards", - "80140e56c78edfbd": "Shots {shots}", - "41d5b3a5d887b6f8": "Penalties +{seconds} s", - "17547068ba80744d": "{title} is done", - "a689501ff2ddb4b6": "{title} needs you", "b2be70822d55f16a": "Open", "52499724d03777c6": "Table cleared", "9fab80fe09b3dacf": "{clock} played, +{seconds} s penalties, {shots} shots", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4dd0bcf388..3e4797102a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", + "0bc152a492a12716": "Blanca entronerada", + "aa2534f03870a3f9": "Ninguna bola tocada", + "e13bcb690bb9c28f": "Gratis esta vez", + "3d83bccbd9e6b227": "8 demasiado pronto", + "163440207bcb77bb": "Tronera equivocada", + "24517a21c5ca36f7": "Blanca con la 8", + "e353b6587c16a231": "Varita", + "c174eedba0edabdc": "Taco dorado", + "e3114242f399e91b": "Taco brillante", + "59a3f31ee049d0f5": "La primera bola que toques cae", + "b6ab17c9f0d8fece": "Visión completa durante {count} tiros", + "597ea9e53fc7cb87": "Atraviesa {count} bolas", + "3b3a060f716e1b53": "Haz clic en una tronera para cantar la 8", + "c655975d03078dd5": "Primero canta una tronera", + "3dfd844f131e4d0a": "Mantén para cargar, suelta para tirar", + "11b40436e8016644": "Mayús apunta más fino, Esc cierra", + "c8bf7e23d2bc15ae": "Listo", + "d25661576338fcf0": "Te necesita", "209d36a8ffe3791c": "Clásico", "88b909e76e754bef": "Cobre", "9ca687520bab7394": "Cromo", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Elegir un taco", "152ec44c76dca1ec": "Taco", "4fa58c8eb16781d2": "Nuevo taco desbloqueado: {name}", - "0f0b7208bbe0f06f": "Varita lista: la primera bola que toques cae en la tronera más cercana.", - "9de13db44f3016c5": "Taco brillante listo: la blanca atraviesa hasta {count} bolas y las entronera.", - "c3405ef38e586f1d": "{count, plural, =1 {Taco dorado: visión completa en este tiro.} other {Taco dorado: visión completa durante {count} tiros.}}", "743592404305841f": "Medalla de oro", "aa1a6773ceaf9223": "Medalla de plata", "b2c0da632a0a1b98": "Medalla de bronce", "a8bf31becdf2dc58": "Siguiente: oro en menos de {time}", "853a57697469a28d": "Siguiente: plata en menos de {time}", "344ff8f2b12b3d70": "Siguiente: bronce en menos de {time}", - "6a850e710ae0c905": "La mesa de hoy es igual para todos. El reloj empieza después del saque.", - "c8b2492b475e4dfa": "Mejor {time}", "67f492a1bb0c8673": "¡Nuevo récord del día!", "60f19313f8c6f1a2": "Hoy en este ordenador", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Primero canta una tronera para la 8: haz clic en ella.", - "8ef73b820d9c2068": "Blanca entronerada. +{seconds} s", - "6e5ca67f8c64ad7e": "No tocaste ninguna bola. Gratis una vez, después cuesta {seconds} s.", - "5423b71c71cfb18c": "No tocaste ninguna bola. +{seconds} s", - "61d672c96dc8d887": "La 8 entró demasiado pronto y vuelve a su punto. +{seconds} s", - "3bd41c9312c93563": "Tronera equivocada. La 8 vuelve a su punto. +{seconds} s", - "b3a4c68407de4257": "Blanca entronerada con la 8. La 8 vuelve a su punto. +{seconds} s", - "d1244c2b4eb6f283": "Solo queda la 8. Haz clic en la tronera que cantas.", - "f3127de5f465fbf6": "8 cantada. Haz clic en otra tronera para cambiarla.", - "1514485143207779": "Mueve para apuntar, mantén para cargar, suelta para tirar. Mayús apunta más fino, Esc cierra.", "412cfbefb305eb90": "Billar", - "80140e56c78edfbd": "Tiros {shots}", - "41d5b3a5d887b6f8": "Penalizaciones +{seconds} s", - "17547068ba80744d": "{title} terminó", - "a689501ff2ddb4b6": "{title} te necesita", "b2be70822d55f16a": "Abrir", "52499724d03777c6": "Mesa limpia", "9fab80fe09b3dacf": "{clock} de juego, +{seconds} s de penalización, {shots} tiros", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 725616d151..26a7ef60a0 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", + "0bc152a492a12716": "Blanche empochée", + "aa2534f03870a3f9": "Aucune bille touchée", + "e13bcb690bb9c28f": "Gratuit cette fois", + "3d83bccbd9e6b227": "8 trop tôt", + "163440207bcb77bb": "Mauvaise poche", + "24517a21c5ca36f7": "Blanche avec la 8", + "e353b6587c16a231": "Baguette", + "c174eedba0edabdc": "Queue dorée", + "e3114242f399e91b": "Queue lumineuse", + "59a3f31ee049d0f5": "La première bille touchée tombe", + "b6ab17c9f0d8fece": "Vision complète pour {count} coups", + "597ea9e53fc7cb87": "Traverse {count} billes", + "3b3a060f716e1b53": "Cliquez sur une poche pour annoncer la 8", + "c655975d03078dd5": "Annoncez d’abord une poche", + "3dfd844f131e4d0a": "Maintenez pour charger, relâchez pour tirer", + "11b40436e8016644": "Maj vise plus finement, Échap ferme", + "c8bf7e23d2bc15ae": "Terminé", + "d25661576338fcf0": "Vous attend", "209d36a8ffe3791c": "Classique", "88b909e76e754bef": "Cuivre", "9ca687520bab7394": "Chrome", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Choisir une queue", "152ec44c76dca1ec": "Queue", "4fa58c8eb16781d2": "Nouvelle queue débloquée : {name}", - "0f0b7208bbe0f06f": "Baguette prête : la première bille touchée tombe dans la poche la plus proche.", - "9de13db44f3016c5": "Queue lumineuse prête : la blanche traverse jusqu’à {count} billes et les empoche.", - "c3405ef38e586f1d": "{count, plural, =1 {Queue dorée : vision complète pour ce coup.} other {Queue dorée : vision complète pour {count} coups.}}", "743592404305841f": "Médaille d’or", "aa1a6773ceaf9223": "Médaille d’argent", "b2c0da632a0a1b98": "Médaille de bronze", "a8bf31becdf2dc58": "Prochain objectif : or sous {time}", "853a57697469a28d": "Prochain objectif : argent sous {time}", "344ff8f2b12b3d70": "Prochain objectif : bronze sous {time}", - "6a850e710ae0c905": "La table du jour est la même pour tous. Le chrono démarre après la casse.", - "c8b2492b475e4dfa": "Record {time}", "67f492a1bb0c8673": "Nouveau record du jour !", "60f19313f8c6f1a2": "Aujourd’hui sur cet ordinateur", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Annoncez d’abord une poche pour la 8 : cliquez dessus.", - "8ef73b820d9c2068": "Blanche empochée. +{seconds} s", - "6e5ca67f8c64ad7e": "Aucune bille touchée. Gratuit une fois, ensuite cela coûte {seconds} s.", - "5423b71c71cfb18c": "Aucune bille touchée. +{seconds} s", - "61d672c96dc8d887": "La 8 est tombée trop tôt et revient sur son point. +{seconds} s", - "3bd41c9312c93563": "Mauvaise poche. La 8 revient sur son point. +{seconds} s", - "b3a4c68407de4257": "Blanche empochée avec la 8. La 8 revient sur son point. +{seconds} s", - "d1244c2b4eb6f283": "Il ne reste que la 8. Cliquez sur la poche que vous annoncez.", - "f3127de5f465fbf6": "8 annoncée. Cliquez sur une autre poche pour changer.", - "1514485143207779": "Bougez pour viser, maintenez pour charger, relâchez pour tirer. Maj vise plus finement, Échap ferme.", "412cfbefb305eb90": "Billard", - "80140e56c78edfbd": "Coups {shots}", - "41d5b3a5d887b6f8": "Pénalités +{seconds} s", - "17547068ba80744d": "{title} est terminé", - "a689501ff2ddb4b6": "{title} a besoin de vous", "b2be70822d55f16a": "Ouvrir", "52499724d03777c6": "Table nettoyée", "9fab80fe09b3dacf": "{clock} de jeu, +{seconds} s de pénalités, {shots} coups", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f1b02c0b07..b4ba418791 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3108,6 +3108,24 @@ "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", + "0bc152a492a12716": "スクラッチ", + "aa2534f03870a3f9": "どのボールにも当たらず", + "e13bcb690bb9c28f": "今回は無料", + "3d83bccbd9e6b227": "8番が早すぎ", + "163440207bcb77bb": "違うポケット", + "24517a21c5ca36f7": "8番と一緒にスクラッチ", + "e353b6587c16a231": "ワンド", + "c174eedba0edabdc": "ゴールドキュー", + "e3114242f399e91b": "光るキュー", + "59a3f31ee049d0f5": "最初に当てたボールが落ちる", + "b6ab17c9f0d8fece": "{count}ショットの間ラインが全部見える", + "597ea9e53fc7cb87": "{count}個のボールを突き抜ける", + "3b3a060f716e1b53": "ポケットをクリックして8番を指定", + "c655975d03078dd5": "先にポケットを指定", + "3dfd844f131e4d0a": "長押しでため、離して打つ", + "11b40436e8016644": "Shiftで細かく狙う、Escで閉じる", + "c8bf7e23d2bc15ae": "完了", + "d25661576338fcf0": "対応待ち", "209d36a8ffe3791c": "クラシック", "88b909e76e754bef": "カッパー", "9ca687520bab7394": "クローム", @@ -3119,35 +3137,16 @@ "ec925d6946a88b5b": "キューを選ぶ", "152ec44c76dca1ec": "キュー", "4fa58c8eb16781d2": "新しいキューを解放:{name}", - "0f0b7208bbe0f06f": "ワンド準備完了:最初に当てたボールが一番近いポケットに落ちます。", - "9de13db44f3016c5": "光るキュー準備完了:手球が最大{count}個のボールを突き抜けて落とします。", - "c3405ef38e586f1d": "{count, plural, other {ゴールドキュー:あと{count}ショット、ラインが全部見えます。}}", "743592404305841f": "金メダル", "aa1a6773ceaf9223": "銀メダル", "b2c0da632a0a1b98": "銅メダル", "a8bf31becdf2dc58": "次は金:{time}未満", "853a57697469a28d": "次は銀:{time}未満", "344ff8f2b12b3d70": "次は銅:{time}未満", - "6a850e710ae0c905": "今日の配置は全員共通です。時計はブレイクの後に動き始めます。", - "c8b2492b475e4dfa": "ベスト {time}", "67f492a1bb0c8673": "今日の自己ベスト更新!", "60f19313f8c6f1a2": "今日のこのコンピューターの記録", "36d880c1abd2d448": "+{seconds}秒", - "082bec31dabcc747": "先に8番のポケットを指定してください:クリックで指定します。", - "8ef73b820d9c2068": "スクラッチ。+{seconds}秒", - "6e5ca67f8c64ad7e": "どのボールにも当たりませんでした。1回目は無料、次からは{seconds}秒加算されます。", - "5423b71c71cfb18c": "どのボールにも当たりませんでした。+{seconds}秒", - "61d672c96dc8d887": "8番が早く落ちたので元の位置に戻ります。+{seconds}秒", - "3bd41c9312c93563": "違うポケットです。8番は元の位置に戻ります。+{seconds}秒", - "b3a4c68407de4257": "8番と一緒にスクラッチ。8番は元の位置に戻ります。+{seconds}秒", - "d1244c2b4eb6f283": "残りは8番だけです。狙うポケットをクリックしてください。", - "f3127de5f465fbf6": "8番を指定しました。別のポケットをクリックすると変更できます。", - "1514485143207779": "動かして狙い、長押しでため、離して打ちます。Shiftで細かく狙い、Escで閉じます。", "412cfbefb305eb90": "ビリヤード", - "80140e56c78edfbd": "ショット {shots}", - "41d5b3a5d887b6f8": "ペナルティ +{seconds}秒", - "17547068ba80744d": "{title} が完了しました", - "a689501ff2ddb4b6": "{title} が対応を待っています", "b2be70822d55f16a": "開く", "52499724d03777c6": "テーブルクリア", "9fab80fe09b3dacf": "プレイ {clock}、ペナルティ +{seconds}秒、{shots}ショット", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 3826d5e26a..410118f913 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3109,6 +3109,24 @@ "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", + "0bc152a492a12716": "스크래치", + "aa2534f03870a3f9": "맞힌 공 없음", + "e13bcb690bb9c28f": "이번엔 무료", + "3d83bccbd9e6b227": "8번 공이 너무 일찍", + "163440207bcb77bb": "잘못된 포켓", + "24517a21c5ca36f7": "8번 공과 스크래치", + "e353b6587c16a231": "지팡이", + "c174eedba0edabdc": "황금 큐", + "e3114242f399e91b": "빛나는 큐", + "59a3f31ee049d0f5": "처음 맞힌 공이 들어갑니다", + "b6ab17c9f0d8fece": "{count}샷 동안 전체 경로", + "597ea9e53fc7cb87": "공 {count}개를 뚫고 지나감", + "3b3a060f716e1b53": "포켓을 클릭해 8번 공을 지정하세요", + "c655975d03078dd5": "먼저 포켓을 지정하세요", + "3dfd844f131e4d0a": "길게 눌러 모으고, 놓아서 치기", + "11b40436e8016644": "Shift로 세밀하게, Esc로 닫기", + "c8bf7e23d2bc15ae": "완료", + "d25661576338fcf0": "확인 필요", "209d36a8ffe3791c": "클래식", "88b909e76e754bef": "구리", "9ca687520bab7394": "크롬", @@ -3120,35 +3138,16 @@ "ec925d6946a88b5b": "큐 고르기", "152ec44c76dca1ec": "큐", "4fa58c8eb16781d2": "새 큐 잠금 해제: {name}", - "0f0b7208bbe0f06f": "지팡이 준비: 처음 맞힌 공이 가장 가까운 포켓으로 들어갑니다.", - "9de13db44f3016c5": "빛나는 큐 준비: 수구가 최대 {count}개의 공을 뚫고 지나가며 넣습니다.", - "c3405ef38e586f1d": "{count, plural, other {황금 큐: {count}샷 동안 전체 경로가 보입니다.}}", "743592404305841f": "금메달", "aa1a6773ceaf9223": "은메달", "b2c0da632a0a1b98": "동메달", "a8bf31becdf2dc58": "다음 목표: {time} 미만 금메달", "853a57697469a28d": "다음 목표: {time} 미만 은메달", "344ff8f2b12b3d70": "다음 목표: {time} 미만 동메달", - "6a850e710ae0c905": "오늘의 배치는 모두에게 같습니다. 시계는 브레이크 후에 시작합니다.", - "c8b2492b475e4dfa": "최고 {time}", "67f492a1bb0c8673": "오늘의 새 최고 기록!", "60f19313f8c6f1a2": "오늘 이 컴퓨터의 기록", "36d880c1abd2d448": "+{seconds}초", - "082bec31dabcc747": "먼저 8번 공의 포켓을 지정하세요: 포켓을 클릭하세요.", - "8ef73b820d9c2068": "스크래치. +{seconds}초", - "6e5ca67f8c64ad7e": "아무 공도 맞히지 못했습니다. 한 번은 무료, 그 다음부터는 {seconds}초가 추가됩니다.", - "5423b71c71cfb18c": "아무 공도 맞히지 못했습니다. +{seconds}초", - "61d672c96dc8d887": "8번 공이 너무 일찍 들어가 제자리로 돌아갑니다. +{seconds}초", - "3bd41c9312c93563": "잘못된 포켓입니다. 8번 공이 제자리로 돌아갑니다. +{seconds}초", - "b3a4c68407de4257": "8번 공과 함께 스크래치. 8번 공이 제자리로 돌아갑니다. +{seconds}초", - "d1244c2b4eb6f283": "8번 공만 남았습니다. 지정할 포켓을 클릭하세요.", - "f3127de5f465fbf6": "8번 공 포켓을 지정했습니다. 다른 포켓을 클릭하면 바뀝니다.", - "1514485143207779": "움직여서 조준하고, 길게 눌러 힘을 모으고, 놓아서 치세요. Shift로 세밀하게 조준, Esc로 닫기.", "412cfbefb305eb90": "당구", - "80140e56c78edfbd": "샷 {shots}", - "41d5b3a5d887b6f8": "페널티 +{seconds}초", - "17547068ba80744d": "{title} 완료", - "a689501ff2ddb4b6": "{title}에서 확인이 필요합니다", "b2be70822d55f16a": "열기", "52499724d03777c6": "테이블 클리어", "9fab80fe09b3dacf": "플레이 {clock}, 페널티 +{seconds}초, {shots}샷", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 87846aa1fe..95fbce4f0b 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", + "0bc152a492a12716": "Branca encaçapada", + "aa2534f03870a3f9": "Nenhuma bola atingida", + "e13bcb690bb9c28f": "Grátis desta vez", + "3d83bccbd9e6b227": "8 cedo demais", + "163440207bcb77bb": "Caçapa errada", + "24517a21c5ca36f7": "Branca com a 8", + "e353b6587c16a231": "Varinha", + "c174eedba0edabdc": "Taco dourado", + "e3114242f399e91b": "Taco brilhante", + "59a3f31ee049d0f5": "A primeira bola atingida cai", + "b6ab17c9f0d8fece": "Visão completa por {count} tacadas", + "597ea9e53fc7cb87": "Atravessa {count} bolas", + "3b3a060f716e1b53": "Clique em uma caçapa para cantar a 8", + "c655975d03078dd5": "Escolha uma caçapa primeiro", + "3dfd844f131e4d0a": "Segure para carregar, solte para tacar", + "11b40436e8016644": "Shift mira mais fino, Esc fecha", + "c8bf7e23d2bc15ae": "Pronto", + "d25661576338fcf0": "Precisa de você", "209d36a8ffe3791c": "Clássico", "88b909e76e754bef": "Cobre", "9ca687520bab7394": "Cromo", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Escolher um taco", "152ec44c76dca1ec": "Taco", "4fa58c8eb16781d2": "Novo taco desbloqueado: {name}", - "0f0b7208bbe0f06f": "Varinha pronta: a primeira bola que você acertar cai na caçapa mais próxima.", - "9de13db44f3016c5": "Taco brilhante pronto: a branca atravessa até {count} bolas e as encaçapa.", - "c3405ef38e586f1d": "{count, plural, =1 {Taco dourado: visão completa nesta tacada.} other {Taco dourado: visão completa por {count} tacadas.}}", "743592404305841f": "Medalha de ouro", "aa1a6773ceaf9223": "Medalha de prata", "b2c0da632a0a1b98": "Medalha de bronze", "a8bf31becdf2dc58": "Próxima: ouro abaixo de {time}", "853a57697469a28d": "Próxima: prata abaixo de {time}", "344ff8f2b12b3d70": "Próxima: bronze abaixo de {time}", - "6a850e710ae0c905": "A mesa de hoje é a mesma para todos. O relógio começa depois da abertura.", - "c8b2492b475e4dfa": "Melhor {time}", "67f492a1bb0c8673": "Novo recorde do dia!", "60f19313f8c6f1a2": "Hoje neste computador", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Primeiro escolha uma caçapa para a 8: clique nela.", - "8ef73b820d9c2068": "Branca encaçapada. +{seconds} s", - "6e5ca67f8c64ad7e": "Nenhuma bola atingida. Grátis uma vez, depois custa {seconds} s.", - "5423b71c71cfb18c": "Nenhuma bola atingida. +{seconds} s", - "61d672c96dc8d887": "A 8 caiu cedo demais e voltou para o seu ponto. +{seconds} s", - "3bd41c9312c93563": "Caçapa errada. A 8 voltou para o seu ponto. +{seconds} s", - "b3a4c68407de4257": "Branca encaçapada com a 8. A 8 voltou para o seu ponto. +{seconds} s", - "d1244c2b4eb6f283": "Só resta a 8. Clique na caçapa que você escolhe.", - "f3127de5f465fbf6": "8 cantada. Clique em outra caçapa para mudar.", - "1514485143207779": "Mova para mirar, segure para carregar, solte para tacar. Shift mira mais fino, Esc fecha.", "412cfbefb305eb90": "Sinuca", - "80140e56c78edfbd": "Tacadas {shots}", - "41d5b3a5d887b6f8": "Penalidades +{seconds} s", - "17547068ba80744d": "{title} terminou", - "a689501ff2ddb4b6": "{title} precisa de você", "b2be70822d55f16a": "Abrir", "52499724d03777c6": "Mesa limpa", "9fab80fe09b3dacf": "{clock} de jogo, +{seconds} s de penalidade, {shots} tacadas", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 23fdd9e662..1846d723a4 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", + "0bc152a492a12716": "Биток в лузе", + "aa2534f03870a3f9": "Ни один шар не задет", + "e13bcb690bb9c28f": "В этот раз бесплатно", + "3d83bccbd9e6b227": "Восьмёрка слишком рано", + "163440207bcb77bb": "Не та луза", + "24517a21c5ca36f7": "Биток вместе с восьмёркой", + "e353b6587c16a231": "Палочка", + "c174eedba0edabdc": "Золотой кий", + "e3114242f399e91b": "Светящийся кий", + "59a3f31ee049d0f5": "Первый задетый шар падает", + "b6ab17c9f0d8fece": "Полная траектория на {count} удара", + "597ea9e53fc7cb87": "Пробивает {count} шара", + "3b3a060f716e1b53": "Нажмите на лузу, чтобы заказать восьмёрку", + "c655975d03078dd5": "Сначала закажите лузу", + "3dfd844f131e4d0a": "Удерживайте для силы, отпустите для удара", + "11b40436e8016644": "Shift — точнее, Esc — закрыть", + "c8bf7e23d2bc15ae": "Готово", + "d25661576338fcf0": "Нужен ваш ответ", "209d36a8ffe3791c": "Классика", "88b909e76e754bef": "Медь", "9ca687520bab7394": "Хром", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Выбрать кий", "152ec44c76dca1ec": "Кий", "4fa58c8eb16781d2": "Новый кий открыт: {name}", - "0f0b7208bbe0f06f": "Палочка готова: первый шар, по которому вы попадёте, упадёт в ближайшую лузу.", - "9de13db44f3016c5": "Светящийся кий готов: биток пробьёт до {count} шаров и забьёт их.", - "c3405ef38e586f1d": "{count, plural, =1 {Золотой кий: полная траектория на этот удар.} few {Золотой кий: полная траектория на {count} удара.} many {Золотой кий: полная траектория на {count} ударов.} other {Золотой кий: полная траектория на {count} удара.}}", "743592404305841f": "Золотая медаль", "aa1a6773ceaf9223": "Серебряная медаль", "b2c0da632a0a1b98": "Бронзовая медаль", "a8bf31becdf2dc58": "Дальше: золото быстрее {time}", "853a57697469a28d": "Дальше: серебро быстрее {time}", "344ff8f2b12b3d70": "Дальше: бронза быстрее {time}", - "6a850e710ae0c905": "Сегодняшняя расстановка одинакова для всех. Время пойдёт после разбоя.", - "c8b2492b475e4dfa": "Лучшее {time}", "67f492a1bb0c8673": "Новый рекорд дня!", "60f19313f8c6f1a2": "Сегодня на этом компьютере", "36d880c1abd2d448": "+{seconds} с", - "082bec31dabcc747": "Сначала закажите лузу для восьмёрки: нажмите на неё.", - "8ef73b820d9c2068": "Биток в лузе. +{seconds} с", - "6e5ca67f8c64ad7e": "Ни один шар не задет. Один раз бесплатно, потом это стоит {seconds} с.", - "5423b71c71cfb18c": "Ни один шар не задет. +{seconds} с", - "61d672c96dc8d887": "Восьмёрка упала слишком рано и вернулась на точку. +{seconds} с", - "3bd41c9312c93563": "Не та луза. Восьмёрка вернулась на точку. +{seconds} с", - "b3a4c68407de4257": "Биток упал вместе с восьмёркой. Восьмёрка вернулась на точку. +{seconds} с", - "d1244c2b4eb6f283": "Осталась только восьмёрка. Нажмите на лузу, которую заказываете.", - "f3127de5f465fbf6": "Луза для восьмёрки заказана. Нажмите на другую, чтобы изменить.", - "1514485143207779": "Двигайте, чтобы целиться, удерживайте для силы, отпустите для удара. Shift — точнее, Esc — закрыть.", "412cfbefb305eb90": "Бильярд", - "80140e56c78edfbd": "Удары {shots}", - "41d5b3a5d887b6f8": "Штраф +{seconds} с", - "17547068ba80744d": "{title}: готово", - "a689501ff2ddb4b6": "{title}: нужен ваш ответ", "b2be70822d55f16a": "Открыть", "52499724d03777c6": "Стол очищен", "9fab80fe09b3dacf": "{clock} игры, +{seconds} с штрафа, {shots} ударов", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d4ed4a85a4..e110b06444 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3110,6 +3110,24 @@ "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", + "0bc152a492a12716": "Vit i hål", + "aa2534f03870a3f9": "Ingen boll träffad", + "e13bcb690bb9c28f": "Gratis den här gången", + "3d83bccbd9e6b227": "8:an för tidigt", + "163440207bcb77bb": "Fel hål", + "24517a21c5ca36f7": "Vit i hål med 8:an", + "e353b6587c16a231": "Trollstav", + "c174eedba0edabdc": "Guldkö", + "e3114242f399e91b": "Glödkö", + "59a3f31ee049d0f5": "Första bollen du träffar går i", + "b6ab17c9f0d8fece": "Full sikt i {count} stötar", + "597ea9e53fc7cb87": "Bryter igenom {count} bollar", + "3b3a060f716e1b53": "Klicka på ett hål för att ropa ut 8:an", + "c655975d03078dd5": "Ropa ut ett hål först", + "3dfd844f131e4d0a": "Håll för att ladda, släpp för att stöta", + "11b40436e8016644": "Shift siktar finare, Esc stänger", + "c8bf7e23d2bc15ae": "Klar", + "d25661576338fcf0": "Behöver dig", "209d36a8ffe3791c": "Klassisk", "88b909e76e754bef": "Koppar", "9ca687520bab7394": "Krom", @@ -3121,35 +3139,16 @@ "ec925d6946a88b5b": "Välj en kö", "152ec44c76dca1ec": "Kö", "4fa58c8eb16781d2": "Ny kö upplåst: {name}", - "0f0b7208bbe0f06f": "Trollstav redo: första bollen du träffar går i närmaste hål.", - "9de13db44f3016c5": "Glödkö redo: den vita bollen bryter igenom upp till {count} bollar och sänker dem.", - "c3405ef38e586f1d": "{count, plural, =1 {Guldkö: full sikt för den här stöten.} other {Guldkö: full sikt i {count} stötar.}}", "743592404305841f": "Guldmedalj", "aa1a6773ceaf9223": "Silvermedalj", "b2c0da632a0a1b98": "Bronsmedalj", "a8bf31becdf2dc58": "Nästa: guld under {time}", "853a57697469a28d": "Nästa: silver under {time}", "344ff8f2b12b3d70": "Nästa: brons under {time}", - "6a850e710ae0c905": "Dagens bord är samma för alla. Klockan startar efter utslaget.", - "c8b2492b475e4dfa": "Bästa {time}", "67f492a1bb0c8673": "Nytt dagsrekord!", "60f19313f8c6f1a2": "Idag på den här datorn", "36d880c1abd2d448": "+{seconds} s", - "082bec31dabcc747": "Ropa först ut ett hål för 8:an: klicka på det.", - "8ef73b820d9c2068": "Vit i hål. +{seconds} s", - "6e5ca67f8c64ad7e": "Ingen boll träffad. Gratis en gång, sedan kostar det {seconds} s.", - "5423b71c71cfb18c": "Ingen boll träffad. +{seconds} s", - "61d672c96dc8d887": "8:an gick i för tidigt och står på sin punkt igen. +{seconds} s", - "3bd41c9312c93563": "Fel hål. 8:an står på sin punkt igen. +{seconds} s", - "b3a4c68407de4257": "Vit i hål med 8:an. 8:an står på sin punkt igen. +{seconds} s", - "d1244c2b4eb6f283": "Bara 8:an är kvar. Klicka på hålet du ropar ut.", - "f3127de5f465fbf6": "8:an utropad. Klicka på ett annat hål för att byta.", - "1514485143207779": "Rör för att sikta, håll för att ladda, släpp för att stöta. Shift siktar finare, Esc stänger.", "412cfbefb305eb90": "Biljard", - "80140e56c78edfbd": "Stötar {shots}", - "41d5b3a5d887b6f8": "Straff +{seconds} s", - "17547068ba80744d": "{title} är klar", - "a689501ff2ddb4b6": "{title} behöver dig", "b2be70822d55f16a": "Öppna", "52499724d03777c6": "Bordet rensat", "9fab80fe09b3dacf": "{clock} spelat, +{seconds} s straff, {shots} stötar", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index c68460c4f2..a2365d9f22 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3114,6 +3114,24 @@ "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", + "0bc152a492a12716": "母球落袋", + "aa2534f03870a3f9": "没有击中球", + "e13bcb690bb9c28f": "这次免罚", + "3d83bccbd9e6b227": "8 号球太早", + "163440207bcb77bb": "袋口不对", + "24517a21c5ca36f7": "母球和 8 号球一起落袋", + "e353b6587c16a231": "魔杖", + "c174eedba0edabdc": "金色球杆", + "e3114242f399e91b": "光之球杆", + "59a3f31ee049d0f5": "击中的第一个球会落袋", + "b6ab17c9f0d8fece": "{count} 杆内看到完整路线", + "597ea9e53fc7cb87": "穿过 {count} 个球", + "3b3a060f716e1b53": "点击袋口指定 8 号球", + "c655975d03078dd5": "先指定袋口", + "3dfd844f131e4d0a": "按住蓄力,松开击球", + "11b40436e8016644": "Shift 精细瞄准,Esc 关闭", + "c8bf7e23d2bc15ae": "已完成", + "d25661576338fcf0": "需要你", "209d36a8ffe3791c": "经典", "88b909e76e754bef": "紫铜", "9ca687520bab7394": "铬银", @@ -3125,35 +3143,16 @@ "ec925d6946a88b5b": "选择球杆", "152ec44c76dca1ec": "球杆", "4fa58c8eb16781d2": "解锁新球杆:{name}", - "0f0b7208bbe0f06f": "魔杖就绪:你击中的第一个球会落入最近的袋口。", - "9de13db44f3016c5": "光之球杆就绪:母球最多穿过 {count} 个球并让它们落袋。", - "c3405ef38e586f1d": "{count, plural, other {金色球杆:接下来 {count} 杆可看到完整路线。}}", "743592404305841f": "金牌", "aa1a6773ceaf9223": "银牌", "b2c0da632a0a1b98": "铜牌", "a8bf31becdf2dc58": "下一个目标:{time} 内拿金牌", "853a57697469a28d": "下一个目标:{time} 内拿银牌", "344ff8f2b12b3d70": "下一个目标:{time} 内拿铜牌", - "6a850e710ae0c905": "今天的球局对所有人都一样。开球后开始计时。", - "c8b2492b475e4dfa": "最佳 {time}", "67f492a1bb0c8673": "今日新纪录!", "60f19313f8c6f1a2": "今天在这台电脑上", "36d880c1abd2d448": "+{seconds} 秒", - "082bec31dabcc747": "请先为 8 号球指定袋口:点击袋口。", - "8ef73b820d9c2068": "母球落袋。+{seconds} 秒", - "6e5ca67f8c64ad7e": "没有击中任何球。第一次免罚,之后每次加 {seconds} 秒。", - "5423b71c71cfb18c": "没有击中任何球。+{seconds} 秒", - "61d672c96dc8d887": "8 号球过早落袋,已放回置球点。+{seconds} 秒", - "3bd41c9312c93563": "袋口不对。8 号球已放回置球点。+{seconds} 秒", - "b3a4c68407de4257": "8 号球落袋时母球也落袋。8 号球已放回置球点。+{seconds} 秒", - "d1244c2b4eb6f283": "只剩 8 号球了。点击你指定的袋口。", - "f3127de5f465fbf6": "已指定 8 号球袋口。点击其他袋口可更改。", - "1514485143207779": "移动瞄准,按住蓄力,松开击球。按住 Shift 精细瞄准,Esc 关闭。", "412cfbefb305eb90": "台球", - "80140e56c78edfbd": "击球 {shots}", - "41d5b3a5d887b6f8": "罚时 +{seconds} 秒", - "17547068ba80744d": "{title} 已完成", - "a689501ff2ddb4b6": "{title} 需要你处理", "b2be70822d55f16a": "打开", "52499724d03777c6": "清台", "9fab80fe09b3dacf": "用时 {clock},罚时 +{seconds} 秒,{shots} 杆",