"""Browser-side collision game synchronized with the Creative Mechanics Lab.""" from __future__ import annotations import json from typing import Any def collision_game_payload(question: dict[str, Any]) -> str: """Return the compact physics state consumed by the browser game.""" data = question.get("diagram_data", {}) payload = dict(data) payload.setdefault( "scene", { "custom_collision": "rollers", "custom_train": "train", "custom_rocket": "rocket", "custom_trolley": "trolley", }.get(question.get("diagram_kind"), "rollers"), ) payload.update( { "question_id": question.get("id", "M1-LAB"), "title": question.get("title", "Custom collision"), } ) return json.dumps(payload, separators=(",", ":"), ensure_ascii=True) COLLISION_GAME_HTML = r"""
READY Adjust the question parameters, then start the model.
Click the model or press start.
""" COLLISION_GAME_CSS = r""" .collision-game { --game-ink: #172554; --game-muted: #64748b; --game-p: #22d3ee; --game-q: #f43f8d; --game-accent: #7c3aed; --game-impact: #f59e0b; --game-track: #334155; color: var(--game-ink); width: 100%; } .game-readout, .game-actions { align-items: center; display: flex; flex-wrap: wrap; gap: 10px; justify-content: space-between; } .game-readout { margin-bottom: 10px; } .game-status { background: linear-gradient(100deg, #6d28d9, #ec4899); border-radius: 999px; color: white; font-size: 12px; font-weight: 800; letter-spacing: .08em; padding: 6px 11px; } .game-arena { background: linear-gradient(180deg, #e0f2fe 0%, #f5f3ff 58%, #e2e8f0 59%, #cbd5e1 100%); border: 1px solid rgba(99, 102, 241, .2); border-radius: 20px; box-shadow: inset 0 1px 0 rgba(255,255,255,.7), 0 16px 40px rgba(30,41,59,.12); overflow: hidden; position: relative; width: 100%; } .game-arena canvas { aspect-ratio: 12 / 4.5; cursor: crosshair; display: block; min-height: 270px; width: 100%; } .impact-word { color: #b91c1c; font-size: clamp(34px, 8vw, 82px); font-weight: 900; left: 50%; opacity: 0; pointer-events: none; position: absolute; text-shadow: 0 4px 0 #fef3c7, 0 9px 22px rgba(127,29,29,.32); top: 26%; transform: translate(-50%, -50%) scale(.35) rotate(-7deg); } .impact-word.is-impacting { animation: collision-word .62s cubic-bezier(.2,.85,.25,1); } @keyframes collision-word { 0% { opacity: 0; transform: translate(-50%, -50%) scale(.25) rotate(-10deg); } 28% { opacity: 1; transform: translate(-50%, -50%) scale(1.12) rotate(4deg); } 100% { opacity: 0; transform: translate(-50%, -62%) scale(1.45) rotate(-3deg); } } .game-actions { justify-content: flex-start; margin-top: 12px; } .game-actions button { border-radius: 12px; cursor: pointer; font-weight: 800; padding: 10px 16px; } .game-launch { background: linear-gradient(100deg, #0891b2, #2563eb); border: 0; color: white; } .game-reset { background: white; border: 1px solid #cbd5e1; color: var(--game-ink); } .game-sound { align-items: center; display: inline-flex; font-size: 13px; gap: 7px; margin-left: auto; } .game-event { background: rgba(255,255,255,.8); border-left: 4px solid var(--game-accent); border-radius: 10px; color: var(--game-ink); margin-top: 10px; padding: 9px 12px; } @media (max-width: 680px) { .game-arena canvas { min-height: 225px; } .game-sound { margin-left: 0; } .game-readout { align-items: flex-start; flex-direction: column; } } @media (prefers-reduced-motion: reduce) { .impact-word.is-impacting { animation-duration: .01ms; } } """ COLLISION_GAME_JS = r""" let gameRoot = null; let canvas = null; let context = null; let launchButton = null; let resetButton = null; let soundToggle = null; let statusNode = null; let parameterNode = null; let eventNode = null; let impactWord = null; let params = {}; let phase = "ready"; let frameId = 0; let startStamp = 0; let impactStamp = 0; let soundPlayed = false; let audioContext = null; let pX = 0; let qX = 0; let pRadius = 36; let qRadius = 42; let pAngle = 0; let qAngle = 0; let resizeObserver = null; const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; function readParams() { try { params = JSON.parse(props.value || "{}"); } catch (error) { params = {}; } } function css(name, fallback) { const value = gameRoot ? getComputedStyle(gameRoot).getPropertyValue(name).trim() : ""; return value || fallback; } function radiusFor(mass, width) { return Math.max(27, Math.min(58, 20 + Math.cbrt(Number(mass || 1)) * width * 0.018)); } function resizeCanvas() { if (!canvas || !context) return; const rect = canvas.getBoundingClientRect(); const dpr = Math.min(window.devicePixelRatio || 1, 2); canvas.width = Math.max(1, Math.round(rect.width * dpr)); canvas.height = Math.max(1, Math.round(rect.height * dpr)); context.setTransform(dpr, 0, 0, dpr, 0, 0); if (phase === "ready") setReadyPositions(); draw(0); } function setReadyPositions() { if (!canvas) return; const width = canvas.getBoundingClientRect().width; pRadius = radiusFor(params.m1, width); qRadius = radiusFor(params.m2, width); pX = width * 0.16; qX = width * 0.84; pAngle = 0; qAngle = 0; } function updateText() { if (!parameterNode) return; const signText = (value) => Number(value || 0).toFixed(1); parameterNode.textContent = `mP ${Number(params.m1 || 0).toFixed(1)} kg · mQ ${Number(params.m2 || 0).toFixed(1)} kg · d ${Number(params.distance || 0).toFixed(1)} m · uP ${signText(params.u1)} m/s · uQ ${signText(params.u2)} m/s`; if (params.collision) { eventNode.textContent = `Predicted impact at t = ${Number(params.time || 0).toFixed(3)} s. Click the cyan roller or press launch.`; } else { eventNode.textContent = `This setup does not collide. Launch it to observe the closest approach of ${Number(params.closest_gap || 0).toFixed(3)} m.`; } } function resetGame(message = true) { cancelAnimationFrame(frameId); phase = "ready"; soundPlayed = false; if (impactWord) impactWord.classList.remove("is-impacting"); if (statusNode) statusNode.textContent = "READY"; setReadyPositions(); updateText(); if (message && eventNode) { eventNode.textContent = params.collision ? `Predicted impact at t = ${Number(params.time || 0).toFixed(3)} s. Click the cyan roller or press launch.` : `No collision is predicted. Launch to inspect closest approach.`; } draw(0); } function unlockAudio() { if (!audioContext) { const AudioCtor = window.AudioContext || window.webkitAudioContext; if (AudioCtor) audioContext = new AudioCtor(); } if (audioContext && audioContext.state === "suspended") audioContext.resume(); } function playImpactSound() { if (!soundToggle || !soundToggle.checked || !audioContext) return; const now = audioContext.currentTime; const relativeSpeed = Math.abs(Number(params.v1_impact || 0) - Number(params.v2_impact || 0)); const intensity = Math.min(1, 0.35 + relativeSpeed / 24); const duration = 0.34; const buffer = audioContext.createBuffer(1, Math.floor(audioContext.sampleRate * duration), audioContext.sampleRate); const channel = buffer.getChannelData(0); for (let index = 0; index < channel.length; index += 1) { const decay = Math.pow(1 - index / channel.length, 3.2); channel[index] = (Math.random() * 2 - 1) * decay * intensity; } const noise = audioContext.createBufferSource(); const filter = audioContext.createBiquadFilter(); const noiseGain = audioContext.createGain(); noise.buffer = buffer; filter.type = "lowpass"; filter.frequency.setValueAtTime(1450, now); filter.frequency.exponentialRampToValueAtTime(160, now + duration); noiseGain.gain.setValueAtTime(0.0001, now); noiseGain.gain.exponentialRampToValueAtTime(0.52 * intensity, now + 0.006); noiseGain.gain.exponentialRampToValueAtTime(0.0001, now + duration); noise.connect(filter).connect(noiseGain).connect(audioContext.destination); noise.start(now); noise.stop(now + duration); const thump = audioContext.createOscillator(); const thumpGain = audioContext.createGain(); thump.type = "sine"; thump.frequency.setValueAtTime(105, now); thump.frequency.exponentialRampToValueAtTime(38, now + 0.26); thumpGain.gain.setValueAtTime(0.55 * intensity, now); thumpGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.29); thump.connect(thumpGain).connect(audioContext.destination); thump.start(now); thump.stop(now + 0.3); } function triggerImpact(now) { if (soundPlayed) return; soundPlayed = true; impactStamp = now; playImpactSound(); if (impactWord) { impactWord.classList.remove("is-impacting"); void impactWord.offsetWidth; impactWord.classList.add("is-impacting"); } if (statusNode) statusNode.textContent = params.impact_model && params.impact_model.startsWith("Join") ? "IMPACT · JOIN" : "IMPACT · REBOUND"; if (eventNode) { eventNode.textContent = `Impact! Before: vP ${Number(params.v1_impact || 0).toFixed(2)} m/s, vQ ${Number(params.v2_impact || 0).toFixed(2)} m/s. After: vP ${Number(params.post_p || 0).toFixed(2)} m/s, vQ ${Number(params.post_q || 0).toFixed(2)} m/s.`; } } function drawRoller(x, y, radius, angle, fill, label, mass) { const gradient = context.createRadialGradient(x - radius * .35, y - radius * .45, radius * .12, x, y, radius); gradient.addColorStop(0, "rgba(255,255,255,.95)"); gradient.addColorStop(.22, fill); gradient.addColorStop(1, css("--game-ink", "#172554")); context.save(); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2); context.fillStyle = gradient; context.fill(); context.lineWidth = 3; context.strokeStyle = css("--game-ink", "#172554"); context.stroke(); context.clip(); context.translate(x, y); context.rotate(angle); context.strokeStyle = "rgba(255,255,255,.72)"; context.lineWidth = Math.max(5, radius * .13); context.beginPath(); context.moveTo(-radius, 0); context.lineTo(radius, 0); context.stroke(); context.restore(); context.fillStyle = css("--game-ink", "#172554"); context.font = "800 14px Inter, Arial, sans-serif"; context.textAlign = "center"; context.fillText(`${label} · ${Number(mass || 0).toFixed(1)} kg`, x, y + 5); } function drawShockwave(midX, y, shock) { if (shock <= 0 || shock >= 1) return; context.save(); context.globalAlpha = 1 - shock; context.strokeStyle = css("--game-impact", "#f59e0b"); context.lineWidth = 8 * (1 - shock) + 2; for (let ring = 0; ring < 3; ring += 1) { context.beginPath(); context.arc(midX, y, 24 + shock * 115 + ring * 18, 0, Math.PI * 2); context.stroke(); } context.fillStyle = css("--game-impact", "#f59e0b"); for (let spark = 0; spark < 14; spark += 1) { const theta = spark * Math.PI * 2 / 14; const length = 30 + shock * 105; context.beginPath(); context.arc(midX + Math.cos(theta) * length, y + Math.sin(theta) * length, 4 * (1 - shock) + 1, 0, Math.PI * 2); context.fill(); } context.restore(); } function draw(shock = 0) { if (!canvas || !context || !gameRoot) return; const rect = canvas.getBoundingClientRect(); const width = rect.width; const height = rect.height; context.clearRect(0, 0, width, height); const trackY = height * .71; context.strokeStyle = "rgba(51,65,85,.18)"; context.lineWidth = 1; for (let x = 0; x < width; x += 44) { context.beginPath(); context.moveTo(x, 0); context.lineTo(x, height); context.stroke(); } context.strokeStyle = css("--game-track", "#334155"); context.lineWidth = 9; context.lineCap = "round"; context.beginPath(); context.moveTo(22, trackY + 2); context.lineTo(width - 22, trackY + 2); context.stroke(); const shake = shock > 0 && shock < .5 ? (1 - shock * 2) * 8 : 0; context.save(); context.translate(shake ? (Math.random() - .5) * shake : 0, shake ? (Math.random() - .5) * shake : 0); drawRoller(pX, trackY - pRadius, pRadius, pAngle, css("--game-p", "#22d3ee"), "P", params.m1); drawRoller(qX, trackY - qRadius, qRadius, qAngle, css("--game-q", "#f43f8d"), "Q", params.m2); drawShockwave((pX + qX) / 2, trackY - (pRadius + qRadius) / 2, shock); context.restore(); context.fillStyle = css("--game-muted", "#64748b"); context.font = "600 12px Inter, Arial, sans-serif"; context.textAlign = "left"; context.fillText(`uP ${Number(params.u1 || 0).toFixed(1)} m/s`, 18, 25); context.textAlign = "right"; context.fillText(`uQ ${Number(params.u2 || 0).toFixed(1)} m/s`, width - 18, 25); } function animate(now) { const rect = canvas.getBoundingClientRect(); const width = rect.width; const impactP = width * .5 - (pRadius + qRadius) / 2; const impactQ = width * .5 + (pRadius + qRadius) / 2; const preDuration = reducedMotion ? 1 : 2600; const postDuration = reducedMotion ? 1 : 1750; const elapsed = now - startStamp; if (params.collision) { if (elapsed <= preDuration) { const progress = Math.min(1, elapsed / preDuration); const smooth = progress * progress * (3 - 2 * progress); pX = width * .16 + (impactP - width * .16) * smooth; qX = width * .84 + (impactQ - width * .84) * smooth; pAngle += Number(params.u1 || 0) * .009; qAngle += Number(params.u2 || 0) * .009; if (statusNode) statusNode.textContent = progress < .15 ? "LAUNCHED" : "ROLLING"; draw(0); } else { triggerImpact(now); const postElapsed = Math.min(postDuration, elapsed - preDuration); const simulationSeconds = postElapsed / postDuration * 1.25; const pixelScale = width * .018; pX = impactP + Number(params.post_p || 0) * simulationSeconds * pixelScale; qX = impactQ + Number(params.post_q || 0) * simulationSeconds * pixelScale; pAngle += Number(params.post_p || 0) * .011; qAngle += Number(params.post_q || 0) * .011; draw(Math.min(1, (now - impactStamp) / 650)); if (elapsed >= preDuration + postDuration) { phase = "done"; if (statusNode) statusNode.textContent = params.impact_model && params.impact_model.startsWith("Join") ? "COMPLETE · TOGETHER" : "COMPLETE · REBOUNDED"; return; } } } else { const duration = reducedMotion ? 1 : 2900; const progress = Math.min(1, elapsed / duration); const closestRatio = Math.max(.12, Math.min(.72, Number(params.closest_gap || params.distance || 1) / Math.max(1, Number(params.distance || 1)))); const nearestP = width * .5 - (pRadius + qRadius + width * closestRatio * .2) / 2; const nearestQ = width * .5 + (pRadius + qRadius + width * closestRatio * .2) / 2; const approach = Math.sin(progress * Math.PI / 2); pX = width * .16 + (nearestP - width * .16) * approach; qX = width * .84 + (nearestQ - width * .84) * approach; pAngle += Number(params.u1 || 0) * .008; qAngle += Number(params.u2 || 0) * .008; if (statusNode) statusNode.textContent = "CLOSEST APPROACH"; draw(0); if (elapsed >= duration) { phase = "done"; if (statusNode) statusNode.textContent = "COMPLETE · NO COLLISION"; if (eventNode) eventNode.textContent = `No impact sound: the least separation is ${Number(params.closest_gap || 0).toFixed(3)} m at t = ${Number(params.closest_time || 0).toFixed(3)} s.`; return; } } frameId = requestAnimationFrame(animate); } function launchGame() { if (phase === "running") return; unlockAudio(); resetGame(false); phase = "running"; startStamp = performance.now(); if (statusNode) statusNode.textContent = "LAUNCHED"; frameId = requestAnimationFrame(animate); } function canvasLaunch(event) { if (!canvas || phase === "running") return; const rect = canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; const rollerY = rect.height * .71 - pRadius; if (Math.hypot(x - pX, y - rollerY) <= pRadius + 18) launchGame(); else if (eventNode) eventNode.textContent = "Click directly on the cyan roller P to trigger it."; } function bindGame() { gameRoot = element.querySelector(".collision-game"); if (!gameRoot) return; canvas = gameRoot.querySelector("[data-game-canvas]"); context = canvas ? canvas.getContext("2d") : null; launchButton = gameRoot.querySelector("[data-game-launch]"); resetButton = gameRoot.querySelector("[data-game-reset]"); soundToggle = gameRoot.querySelector("[data-game-sound]"); statusNode = gameRoot.querySelector("[data-game-status]"); parameterNode = gameRoot.querySelector("[data-game-parameters]"); eventNode = gameRoot.querySelector("[data-game-event]"); impactWord = gameRoot.querySelector("[data-impact-word]"); if (!gameRoot.dataset.bound) { launchButton.addEventListener("click", launchGame); resetButton.addEventListener("click", () => resetGame(true)); canvas.addEventListener("click", canvasLaunch); gameRoot.dataset.bound = "true"; } if (resizeObserver) resizeObserver.disconnect(); resizeObserver = new ResizeObserver(resizeCanvas); resizeObserver.observe(gameRoot); readParams(); resetGame(true); requestAnimationFrame(resizeCanvas); } watch("value", bindGame); bindGame(); """ CREATIVE_EXPERIMENT_JS = r""" let gameRoot = null; let canvas = null; let context = null; let launchButton = null; let resetButton = null; let soundToggle = null; let musicToggle = null; let statusNode = null; let parameterNode = null; let eventNode = null; let impactWord = null; let params = {}; let phase = "ready"; let frameId = 0; let startStamp = 0; let effectStamp = 0; let effectPlayed = false; let audioContext = null; let musicNodes = []; let resizeObserver = null; let sceneState = {}; const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; function sceneName() { return params.scene || "rollers"; } function readParams() { try { params = JSON.parse(props.value || "{}"); } catch (error) { params = { scene: "rollers" }; } if (!params.scene) params.scene = "rollers"; } function css(name, fallback) { const value = gameRoot ? getComputedStyle(gameRoot).getPropertyValue(name).trim() : ""; return value || fallback; } function unlockAudio() { if (!audioContext) { const AudioCtor = window.AudioContext || window.webkitAudioContext; if (AudioCtor) audioContext = new AudioCtor(); } if (audioContext && audioContext.state === "suspended") audioContext.resume(); } function stopMusic() { musicNodes.forEach((node) => { try { node.stop(); } catch (error) { /* already stopped */ } try { node.disconnect(); } catch (error) { /* already disconnected */ } }); musicNodes = []; } function startMusic() { stopMusic(); if (!musicToggle || !musicToggle.checked || !audioContext) return; const now = audioContext.currentTime; const master = audioContext.createGain(); const filter = audioContext.createBiquadFilter(); const lfo = audioContext.createOscillator(); const lfoGain = audioContext.createGain(); master.gain.setValueAtTime(0.0001, now); master.gain.exponentialRampToValueAtTime(0.018, now + 0.8); filter.type = "lowpass"; filter.frequency.value = 900; lfo.frequency.value = 0.18; lfoGain.gain.value = 0.007; lfo.connect(lfoGain).connect(master.gain); lfo.start(now); musicNodes.push(lfo, lfoGain, master, filter); const frequencies = sceneName() === "rocket" ? [174.61, 261.63] : [196.0, 293.66]; frequencies.forEach((frequency, index) => { const oscillator = audioContext.createOscillator(); const gain = audioContext.createGain(); oscillator.type = index ? "sine" : "triangle"; oscillator.frequency.value = frequency; gain.gain.value = index ? 0.32 : 0.5; oscillator.connect(gain).connect(filter); oscillator.start(now); musicNodes.push(oscillator, gain); }); filter.connect(master).connect(audioContext.destination); } function noiseBurst(duration, volume, startFrequency, endFrequency) { if (!soundToggle || !soundToggle.checked || !audioContext) return; const now = audioContext.currentTime; const buffer = audioContext.createBuffer(1, Math.floor(audioContext.sampleRate * duration), audioContext.sampleRate); const samples = buffer.getChannelData(0); for (let index = 0; index < samples.length; index += 1) { samples[index] = (Math.random() * 2 - 1) * Math.pow(1 - index / samples.length, 2.7); } const source = audioContext.createBufferSource(); const filter = audioContext.createBiquadFilter(); const gain = audioContext.createGain(); source.buffer = buffer; filter.type = "lowpass"; filter.frequency.setValueAtTime(startFrequency, now); filter.frequency.exponentialRampToValueAtTime(endFrequency, now + duration); gain.gain.setValueAtTime(volume, now); gain.gain.exponentialRampToValueAtTime(0.0001, now + duration); source.connect(filter).connect(gain).connect(audioContext.destination); source.start(now); source.stop(now + duration); } function tone(frequency, duration, volume, type = "sine", secondFrequency = null) { if (!soundToggle || !soundToggle.checked || !audioContext) return; const now = audioContext.currentTime; const oscillator = audioContext.createOscillator(); const gain = audioContext.createGain(); oscillator.type = type; oscillator.frequency.setValueAtTime(frequency, now); if (secondFrequency) oscillator.frequency.exponentialRampToValueAtTime(secondFrequency, now + duration); gain.gain.setValueAtTime(volume, now); gain.gain.exponentialRampToValueAtTime(0.0001, now + duration); oscillator.connect(gain).connect(audioContext.destination); oscillator.start(now); oscillator.stop(now + duration); } function trainHorn() { tone(220, 0.72, 0.12, "sawtooth", 205); tone(277, 0.72, 0.08, "sawtooth", 260); flashWord("TOOT!"); } function rocketWhoosh() { noiseBurst(1.15, 0.12, 2800, 180); tone(72, 0.95, 0.09, "sawtooth", 42); flashWord("WHOOSH!"); } function trolleyScrape() { noiseBurst(0.65, 0.07, 900, 120); flashWord("SCRAPE"); } function collisionImpact() { const relative = Math.abs(Number(params.v1_impact || 0) - Number(params.v2_impact || 0)); noiseBurst(0.36, Math.min(0.5, 0.24 + relative / 70), 1700, 130); tone(105, 0.31, 0.32, "sine", 38); flashWord("KRAK!"); } function landingImpact() { noiseBurst(0.3, 0.18, 1100, 100); tone(82, 0.28, 0.23, "sine", 34); flashWord("LAND!"); } function flashWord(text) { if (!impactWord) return; impactWord.textContent = text; impactWord.classList.remove("is-impacting"); void impactWord.offsetWidth; impactWord.classList.add("is-impacting"); } function radiusFor(mass, width) { return Math.max(27, Math.min(58, 20 + Math.cbrt(Number(mass || 1)) * width * 0.018)); } function resizeCanvas() { if (!canvas || !context) return; const rect = canvas.getBoundingClientRect(); const dpr = Math.min(window.devicePixelRatio || 1, 2); canvas.width = Math.max(1, Math.round(rect.width * dpr)); canvas.height = Math.max(1, Math.round(rect.height * dpr)); context.setTransform(dpr, 0, 0, dpr, 0, 0); if (phase === "ready") initializeScene(); drawScene(0); } function initializeScene() { if (!canvas) return; const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; const scene = sceneName(); if (scene === "train") { sceneState = { x: width * 0.08, speed: Number(params.u || 0), light: 0 }; } else if (scene === "rocket") { const initialRatio = Number(params.height || 0) / Math.max(1, Number(params.top_height || 1)); sceneState = { x: width * 0.5, y: height * 0.82 - initialRatio * height * 0.67, flame: 0, heightRatio: initialRatio }; } else if (scene === "trolley") { sceneState = { x: width * 0.1, progress: 0, sparks: 0 }; } else { sceneState = { pX: width * 0.16, qX: width * 0.84, pRadius: radiusFor(params.m1, width), qRadius: radiusFor(params.m2, width), pAngle: 0, qAngle: 0, }; } } function updateText() { const scene = sceneName(); canvas.setAttribute("aria-label", { rollers: "Two rollers move, collide and rebound using the question parameters", train: "An electric train accelerates, cruises and brakes to rest", rocket: "A rocket capsule rises to its highest point and falls to the ground", trolley: "A pulled cargo trolley moves on a rough horizontal floor", }[scene] || "Animated mechanics experiment"); if (scene === "train") { parameterNode.textContent = `Train ${Number(params.mass_tonnes || 0).toFixed(0)} t · u ${Number(params.u || 0).toFixed(1)} m/s · a ${Number(params.a || 0).toFixed(1)} m/s² · brake ${Number(params.braking || 0).toFixed(1)} m/s²`; eventNode.textContent = `Accelerate ${Number(params.t_acc || 0).toFixed(1)} s, cruise ${Number(params.t_cruise || 0).toFixed(1)} s, then brake. Total distance ${Number(params.total_distance || 0).toFixed(2)} m.`; } else if (scene === "rocket") { parameterNode.textContent = `Capsule ${Number(params.mass_kg || 0).toFixed(0)} kg · launch ${Number(params.u || 0).toFixed(1)} m/s · g ${Number(params.g || 0).toFixed(1)} m/s²`; eventNode.textContent = `Highest point ${Number(params.top_height || 0).toFixed(2)} m · landing at ${Number(params.landing_time || 0).toFixed(2)} s.`; } else if (scene === "trolley") { parameterNode.textContent = `Trolley ${Number(params.mass_kg || 0).toFixed(0)} kg · pull ${Number(params.force || 0).toFixed(0)} N at ${Number(params.angle || 0).toFixed(0)}° · μ ${Number(params.mu || 0).toFixed(2)}`; eventNode.textContent = `Acceleration ${Number(params.a || 0).toFixed(3)} m/s² · displacement ${Number(params.displacement || 0).toFixed(2)} m.`; } else if (params.collision) { parameterNode.textContent = `mP ${Number(params.m1 || 0).toFixed(1)} kg · mQ ${Number(params.m2 || 0).toFixed(1)} kg · d ${Number(params.distance || 0).toFixed(1)} m · uP ${Number(params.u1 || 0).toFixed(1)} m/s · uQ ${Number(params.u2 || 0).toFixed(1)} m/s`; eventNode.textContent = `Impact at ${Number(params.time || 0).toFixed(3)} s. Click either roller or press start.`; } else { parameterNode.textContent = `Rollers do not collide · least separation ${Number(params.closest_gap || 0).toFixed(2)} m`; eventNode.textContent = "Start the experiment to observe their closest approach."; } } function resetGame(message = true) { cancelAnimationFrame(frameId); stopMusic(); phase = "ready"; effectPlayed = false; if (impactWord) impactWord.classList.remove("is-impacting"); statusNode.textContent = "READY"; initializeScene(); updateText(); if (!message) eventNode.textContent = "Experiment reset with the current question values."; drawScene(0); } function drawTrack(width, y) { context.strokeStyle = css("--game-track", "#334155"); context.lineWidth = 8; context.lineCap = "round"; context.beginPath(); context.moveTo(18, y); context.lineTo(width - 18, y); context.stroke(); } function drawRoller(x, y, radius, angle, fill, label, mass) { const gradient = context.createRadialGradient(x - radius * 0.35, y - radius * 0.45, radius * 0.12, x, y, radius); gradient.addColorStop(0, "rgba(255,255,255,.95)"); gradient.addColorStop(0.24, fill); gradient.addColorStop(1, css("--game-ink", "#172554")); context.save(); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2); context.fillStyle = gradient; context.fill(); context.lineWidth = 3; context.strokeStyle = css("--game-ink", "#172554"); context.stroke(); context.clip(); context.translate(x, y); context.rotate(angle); context.strokeStyle = "rgba(255,255,255,.75)"; context.lineWidth = Math.max(5, radius * 0.13); context.beginPath(); context.moveTo(-radius, 0); context.lineTo(radius, 0); context.stroke(); context.restore(); context.fillStyle = css("--game-ink", "#172554"); context.font = "800 14px Inter, Arial, sans-serif"; context.textAlign = "center"; context.fillText(`${label} · ${Number(mass || 0).toFixed(1)} kg`, x, y + 5); } function drawRollers(effect) { const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; const trackY = height * 0.72; drawTrack(width, trackY + 2); drawRoller(sceneState.pX, trackY - sceneState.pRadius, sceneState.pRadius, sceneState.pAngle, css("--game-p", "#22d3ee"), "P", params.m1); drawRoller(sceneState.qX, trackY - sceneState.qRadius, sceneState.qRadius, sceneState.qAngle, css("--game-q", "#f43f8d"), "Q", params.m2); if (effect > 0 && effect < 1) drawShockwave((sceneState.pX + sceneState.qX) / 2, trackY - (sceneState.pRadius + sceneState.qRadius) / 2, effect); } function drawTrain(effect) { const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; const trackY = height * 0.77; drawTrack(width, trackY); context.strokeStyle = css("--game-muted", "#64748b"); context.lineWidth = 3; for (let x = 10; x < width; x += 34) { context.beginPath(); context.moveTo(x, trackY - 6); context.lineTo(x + 12, trackY + 11); context.stroke(); } const cars = Math.max(1, Math.min(4, Math.round(Number(params.mass_tonnes || 20) / 50))); const carWidth = Math.max(48, Math.min(74, width * 0.075)); const carHeight = 42; const totalLength = carWidth * (cars + 1) + 8 * cars; let left = sceneState.x; for (let index = cars; index >= 1; index -= 1) { const x = left - index * (carWidth + 8); context.fillStyle = css("--game-accent", "#7c3aed"); context.fillRect(x, trackY - carHeight - 15, carWidth, carHeight); context.fillStyle = "rgba(255,255,255,.72)"; for (let windowIndex = 0; windowIndex < 3; windowIndex += 1) context.fillRect(x + 8 + windowIndex * 15, trackY - carHeight - 5, 10, 13); } const engineX = left; context.fillStyle = css("--game-p", "#22d3ee"); context.fillRect(engineX, trackY - 66, carWidth + 12, 51); context.beginPath(); context.moveTo(engineX + carWidth + 12, trackY - 66); context.lineTo(engineX + carWidth + 35, trackY - 15); context.lineTo(engineX + carWidth + 12, trackY - 15); context.closePath(); context.fill(); context.fillStyle = css("--game-ink", "#172554"); for (let index = 0; index < cars + 2; index += 1) { const wheelX = engineX + carWidth - index * (carWidth + 8); context.beginPath(); context.arc(wheelX, trackY - 10, 9, 0, Math.PI * 2); context.fill(); } context.fillStyle = css("--game-impact", "#f59e0b"); context.beginPath(); context.arc(engineX + carWidth + 24, trackY - 41, 6 + effect * 9, 0, Math.PI * 2); context.fill(); if (sceneState.speed > 0) { context.strokeStyle = "rgba(255,255,255,.75)"; context.lineWidth = 3; for (let line = 0; line < 3; line += 1) { context.beginPath(); context.moveTo(engineX - totalLength - 20 - line * 18, trackY - 36 + line * 12); context.lineTo(engineX - totalLength - 2, trackY - 36 + line * 12); context.stroke(); } } } function drawRocket(effect) { const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; const groundY = height * 0.82; drawTrack(width, groundY); const massScale = Math.max(0.8, Math.min(1.35, Number(params.mass_kg || 180) / 180)); const bodyWidth = 32 * Math.sqrt(massScale); const bodyHeight = 82 * Math.sqrt(massScale); const x = sceneState.x; const y = sceneState.y; context.fillStyle = css("--game-p", "#22d3ee"); context.fillRect(x - bodyWidth / 2, y - bodyHeight, bodyWidth, bodyHeight); context.beginPath(); context.moveTo(x - bodyWidth / 2, y - bodyHeight); context.lineTo(x, y - bodyHeight - 34); context.lineTo(x + bodyWidth / 2, y - bodyHeight); context.closePath(); context.fill(); context.fillStyle = css("--game-accent", "#7c3aed"); context.beginPath(); context.moveTo(x - bodyWidth / 2, y - 28); context.lineTo(x - bodyWidth, y); context.lineTo(x - bodyWidth / 2, y); context.fill(); context.beginPath(); context.moveTo(x + bodyWidth / 2, y - 28); context.lineTo(x + bodyWidth, y); context.lineTo(x + bodyWidth / 2, y); context.fill(); context.fillStyle = "rgba(255,255,255,.82)"; context.beginPath(); context.arc(x, y - bodyHeight * 0.62, 8, 0, Math.PI * 2); context.fill(); if (sceneState.flame > 0) { context.fillStyle = css("--game-impact", "#f59e0b"); context.beginPath(); context.moveTo(x - bodyWidth * 0.28, y); context.lineTo(x, y + 28 + 36 * sceneState.flame); context.lineTo(x + bodyWidth * 0.28, y); context.closePath(); context.fill(); } if (effect > 0 && effect < 1) drawShockwave(x, groundY - 10, effect); } function drawTrolley(effect) { const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; const floorY = height * 0.77; drawTrack(width, floorY); const massScale = Math.max(0.85, Math.min(1.4, Number(params.mass_kg || 24) / 24)); const bodyWidth = 92 * Math.sqrt(massScale); const bodyHeight = 42; const x = sceneState.x; context.fillStyle = css("--game-p", "#22d3ee"); context.fillRect(x, floorY - bodyHeight - 20, bodyWidth, bodyHeight); context.fillStyle = css("--game-accent", "#7c3aed"); const boxes = Math.max(1, Math.min(4, Math.round(Number(params.mass_kg || 10) / 12))); for (let index = 0; index < boxes; index += 1) context.fillRect(x + 8 + index * 22, floorY - bodyHeight - 48, 18, 24); context.fillStyle = css("--game-ink", "#172554"); context.beginPath(); context.arc(x + 20, floorY - 12, 11, 0, Math.PI * 2); context.fill(); context.beginPath(); context.arc(x + bodyWidth - 20, floorY - 12, 11, 0, Math.PI * 2); context.fill(); const theta = Number(params.angle || 0) * Math.PI / 180; const ropeLength = Math.max(65, Math.min(125, Number(params.force || 20))); context.strokeStyle = css("--game-q", "#f43f8d"); context.lineWidth = 5; context.beginPath(); context.moveTo(x + bodyWidth, floorY - bodyHeight - 5); context.lineTo(x + bodyWidth + ropeLength * Math.cos(theta), floorY - bodyHeight - 5 - ropeLength * Math.sin(theta)); context.stroke(); if (sceneState.sparks > 0) { context.fillStyle = css("--game-impact", "#f59e0b"); for (let index = 0; index < 8; index += 1) { const spread = (index - 4) * 7; context.beginPath(); context.arc(x + spread, floorY - 5 - (index % 3) * 6, 2 + effect * 2, 0, Math.PI * 2); context.fill(); } } } function drawShockwave(x, y, effect) { context.save(); context.globalAlpha = 1 - effect; context.strokeStyle = css("--game-impact", "#f59e0b"); context.lineWidth = 8 * (1 - effect) + 2; for (let ring = 0; ring < 3; ring += 1) { context.beginPath(); context.arc(x, y, 24 + effect * 115 + ring * 18, 0, Math.PI * 2); context.stroke(); } context.restore(); } function drawScene(effect) { if (!canvas || !context) return; const width = canvas.getBoundingClientRect().width; const height = canvas.getBoundingClientRect().height; context.clearRect(0, 0, width, height); context.strokeStyle = "rgba(51,65,85,.14)"; context.lineWidth = 1; for (let x = 0; x < width; x += 44) { context.beginPath(); context.moveTo(x, 0); context.lineTo(x, height); context.stroke(); } if (sceneName() === "train") drawTrain(effect); else if (sceneName() === "rocket") drawRocket(effect); else if (sceneName() === "trolley") drawTrolley(effect); else drawRollers(effect); } function animateRollers(elapsed, duration, now) { const width = canvas.getBoundingClientRect().width; const trackY = canvas.getBoundingClientRect().height * 0.72; if (!params.collision) { const progress = Math.min(1, elapsed / duration); sceneState.pX = width * (0.16 + 0.16 * progress); sceneState.qX = width * (0.84 + 0.04 * progress); sceneState.pAngle += Number(params.u1 || 0) * 0.008; sceneState.qAngle += Number(params.u2 || 0) * 0.008; statusNode.textContent = progress < 1 ? "CLOSEST APPROACH" : "COMPLETE · NO COLLISION"; if (progress >= 1) return true; return false; } const pre = duration * 0.6; const post = duration - pre; const impactP = width * 0.5 - (sceneState.pRadius + sceneState.qRadius) / 2; const impactQ = width * 0.5 + (sceneState.pRadius + sceneState.qRadius) / 2; if (elapsed <= pre) { const progress = Math.min(1, elapsed / pre); const smooth = progress * progress * (3 - 2 * progress); sceneState.pX = width * 0.16 + (impactP - width * 0.16) * smooth; sceneState.qX = width * 0.84 + (impactQ - width * 0.84) * smooth; sceneState.pAngle += Number(params.u1 || 0) * 0.009; sceneState.qAngle += Number(params.u2 || 0) * 0.009; statusNode.textContent = "ROLLING"; return false; } if (!effectPlayed) { effectPlayed = true; effectStamp = now; collisionImpact(); } const after = Math.min(post, elapsed - pre); const seconds = after / post * 1.25; const pixelScale = width * 0.018; sceneState.pX = impactP + Number(params.post_p || 0) * seconds * pixelScale; sceneState.qX = impactQ + Number(params.post_q || 0) * seconds * pixelScale; sceneState.pAngle += Number(params.post_p || 0) * 0.011; sceneState.qAngle += Number(params.post_q || 0) * 0.011; statusNode.textContent = params.impact_model && params.impact_model.startsWith("Join") ? "IMPACT · JOIN" : "IMPACT · REBOUND"; return elapsed >= duration; } function animateTrain(elapsed, duration) { const width = canvas.getBoundingClientRect().width; const progress = Math.min(1, elapsed / duration); const simulatedTime = progress * Number(params.total_time || 1); let distance = 0; let speed = 0; if (simulatedTime <= Number(params.t_acc || 0)) { distance = Number(params.u || 0) * simulatedTime + 0.5 * Number(params.a || 0) * simulatedTime * simulatedTime; speed = Number(params.u || 0) + Number(params.a || 0) * simulatedTime; statusNode.textContent = "TRAIN · ACCELERATING"; } else if (simulatedTime <= Number(params.t_acc || 0) + Number(params.t_cruise || 0)) { const accelerationDistance = Number(params.u || 0) * Number(params.t_acc || 0) + 0.5 * Number(params.a || 0) * Number(params.t_acc || 0) ** 2; const cruiseElapsed = simulatedTime - Number(params.t_acc || 0); distance = accelerationDistance + Number(params.top_speed || 0) * cruiseElapsed; speed = Number(params.top_speed || 0); statusNode.textContent = "TRAIN · CRUISING"; } else { const accelerationDistance = Number(params.u || 0) * Number(params.t_acc || 0) + 0.5 * Number(params.a || 0) * Number(params.t_acc || 0) ** 2; const cruiseDistance = Number(params.top_speed || 0) * Number(params.t_cruise || 0); const brakeElapsed = simulatedTime - Number(params.t_acc || 0) - Number(params.t_cruise || 0); distance = accelerationDistance + cruiseDistance + Number(params.top_speed || 0) * brakeElapsed - 0.5 * Number(params.braking || 0) * brakeElapsed * brakeElapsed; speed = Math.max(0, Number(params.top_speed || 0) - Number(params.braking || 0) * brakeElapsed); statusNode.textContent = "TRAIN · BRAKING"; } sceneState.x = width * 0.1 + width * 0.64 * distance / Math.max(1, Number(params.total_distance || 1)); sceneState.speed = speed; sceneState.light = Math.min(1, speed / Math.max(1, Number(params.top_speed || 1))); if (progress >= 1) statusNode.textContent = "TRAIN · ARRIVED"; return progress >= 1; } function animateRocket(elapsed, duration, now) { const height = canvas.getBoundingClientRect().height; const progress = Math.min(1, elapsed / duration); const simulatedTime = progress * Number(params.landing_time || 1); const physicalHeight = Math.max(0, Number(params.height || 0) + Number(params.u || 0) * simulatedTime - 0.5 * Number(params.g || 0) * simulatedTime * simulatedTime); const ratio = physicalHeight / Math.max(1, Number(params.top_height || 1)); sceneState.y = height * 0.82 - ratio * height * 0.67; sceneState.flame = Math.max(0, 1 - progress * 8); statusNode.textContent = simulatedTime <= Number(params.top_time || 0) ? "ROCKET · ASCENDING" : "ROCKET · DESCENDING"; if (progress >= 0.995 && !effectPlayed) { effectPlayed = true; effectStamp = now; landingImpact(); } if (progress >= 1) statusNode.textContent = "ROCKET · LANDED"; return progress >= 1; } function animateTrolley(elapsed, duration) { const width = canvas.getBoundingClientRect().width; const progress = Math.min(1, elapsed / duration); const simulatedTime = progress * Number(params.motion_time || 1); const distance = Math.max(0, Number(params.u || 0) * simulatedTime + 0.5 * Number(params.a || 0) * simulatedTime * simulatedTime); sceneState.x = width * 0.08 + width * 0.7 * distance / Math.max(0.1, Number(params.displacement || 0.1)); sceneState.progress = progress; sceneState.sparks = Number(params.mu || 0) > 0.28 ? Math.sin(progress * 34) ** 2 : 0; statusNode.textContent = Number(params.a || 0) >= 0 ? "TROLLEY · ACCELERATING" : "TROLLEY · SLOWING"; if (progress >= 1) statusNode.textContent = params.stopped ? "TROLLEY · STOPPED" : "TROLLEY · OBSERVED"; return progress >= 1; } function animate(now) { const duration = reducedMotion ? 1 : (sceneName() === "train" ? 5200 : 4300); const elapsed = now - startStamp; let complete = false; if (sceneName() === "train") complete = animateTrain(elapsed, duration); else if (sceneName() === "rocket") complete = animateRocket(elapsed, duration, now); else if (sceneName() === "trolley") complete = animateTrolley(elapsed, duration); else complete = animateRollers(elapsed, duration, now); const effect = effectPlayed ? Math.min(1, (now - effectStamp) / 650) : (sceneName() === "train" ? sceneState.light * 0.2 : sceneState.sparks || 0); drawScene(effect); if (complete) { phase = "done"; stopMusic(); return; } frameId = requestAnimationFrame(animate); } function launchGame() { if (phase === "running") return; unlockAudio(); resetGame(true); phase = "running"; effectPlayed = false; startMusic(); if (sceneName() === "train") trainHorn(); else if (sceneName() === "rocket") rocketWhoosh(); else if (sceneName() === "trolley") trolleyScrape(); statusNode.textContent = "STARTED"; startStamp = performance.now(); frameId = requestAnimationFrame(animate); } function bindGame() { gameRoot = element.querySelector(".collision-game"); if (!gameRoot) return; canvas = gameRoot.querySelector("[data-game-canvas]"); context = canvas ? canvas.getContext("2d") : null; launchButton = gameRoot.querySelector("[data-game-launch]"); resetButton = gameRoot.querySelector("[data-game-reset]"); soundToggle = gameRoot.querySelector("[data-game-sound]"); musicToggle = gameRoot.querySelector("[data-game-music]"); statusNode = gameRoot.querySelector("[data-game-status]"); parameterNode = gameRoot.querySelector("[data-game-parameters]"); eventNode = gameRoot.querySelector("[data-game-event]"); impactWord = gameRoot.querySelector("[data-impact-word]"); if (!gameRoot.dataset.bound) { launchButton.addEventListener("click", launchGame); resetButton.addEventListener("click", () => resetGame(false)); canvas.addEventListener("click", launchGame); gameRoot.dataset.bound = "true"; } if (resizeObserver) resizeObserver.disconnect(); resizeObserver = new ResizeObserver(resizeCanvas); resizeObserver.observe(gameRoot); readParams(); resetGame(true); requestAnimationFrame(resizeCanvas); } watch("value", bindGame); bindGame(); """