Xenova's picture
Xenova HF Staff
Update index.html
846e338 verified
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>FunctionGemma Physics Playground</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/decomp.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<link
href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&family=Fira+Code:wght@500;700&display=swap"
rel="stylesheet" />
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ["Space Grotesk", "sans-serif"],
mono: ["Fira Code", "monospace"],
},
colors: {
"neo-bg": "#f0f0f0",
"neo-black": "#1a1a1a",
"neo-white": "#ffffff",
"neo-purple": "#a78bfa",
"neo-yellow": "#facc15",
"neo-green": "#4ade80",
"neo-red": "#f87171",
"neo-blue": "#60a5fa",
"neo-gray": "#94a3b8",
},
boxShadow: {
neo: "4px 4px 0px 0px #000000",
"neo-sm": "2px 2px 0px 0px #000000",
"neo-lg": "8px 8px 0px 0px #000000",
},
},
},
};
</script>
<style>
body {
overflow: hidden;
background-color: #e0e7ff;
background-image: radial-gradient(#a5b4fc 1px, transparent 1px);
background-size: 20px 20px;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 12px;
height: 12px;
}
::-webkit-scrollbar-track {
background: #fff;
border-left: 2px solid black;
}
::-webkit-scrollbar-thumb {
background: #000;
border: 2px solid #fff;
}
::-webkit-scrollbar-thumb:hover {
background: #333;
}
.neo-border {
border: 3px solid black;
}
.neo-btn {
transition: all 0.1s ease-in-out;
}
.neo-btn:active {
transform: translate(2px, 2px);
box-shadow: 2px 2px 0px 0px #000000;
}
.level-card {
transition: all 0.2s;
}
.level-card:hover:not(.locked) {
transform: translate(-2px, -2px);
box-shadow: 6px 6px 0px 0px #000000;
}
.locked {
background-color: #e2e8f0;
cursor: not-allowed;
opacity: 0.7;
background-image: repeating-linear-gradient(45deg, #cbd5e1 0, #cbd5e1 1px, transparent 0, transparent 50%);
background-size: 10px 10px;
}
.code-editor {
font-family: "Fira Code", monospace;
background-color: #ffffff;
color: #000000;
line-height: 1.6;
}
.toggle-checkbox:checked {
right: 0;
border-color: #4ade80;
}
.toggle-checkbox:checked+.toggle-label {
background-color: #4ade80;
}
/* Action Item Delete Button Transition */
.action-item .btn-delete {
opacity: 0;
transition: opacity 0.2s;
}
.action-item:hover .btn-delete {
opacity: 1;
}
</style>
</head>
<body class="h-screen w-screen flex flex-col md:flex-row p-4 gap-4">
<!-- Loading Overlay -->
<div id="loading-overlay" class="fixed inset-0 bg-black/90 z-50 flex flex-col items-center justify-center">
<div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-neo-green mb-4"></div>
<div class="text-white font-mono font-bold text-xl">LOADING MODEL...</div>
<div class="text-gray-400 font-mono text-sm mt-2">This may take a moment</div>
</div>
<!-- Sidebar / Controls -->
<div class="w-full md:w-1/3 lg:w-1/4 flex flex-col neo-border shadow-neo bg-white h-full z-10 relative">
<!-- Decorative Header Strip -->
<div class="h-4 w-full bg-neo-black"></div>
<div class="p-6 border-b-2 border-black bg-neo-yellow flex justify-between items-center shrink-0">
<div>
<h1 class="text-3xl font-bold text-black uppercase tracking-tighter">Function <span
class="text-white bg-black px-1">Gemma</span></h1>
<div class="text-xs font-mono font-bold text-black mt-1">PHYSICS PLAYGROUND</div>
</div>
</div>
<!-- MENU: Level Select -->
<div id="view-menu" class="flex-1 overflow-y-auto p-6 bg-white hidden">
<h2 class="font-bold text-xl mb-4 border-b-2 border-black pb-2">SELECT LEVEL</h2>
<div id="level-grid" class="grid grid-cols-2 gap-4">
<!-- Injected via JS -->
</div>
</div>
<!-- MENU: Game View -->
<div id="view-game" class="flex-1 flex flex-col overflow-hidden relative">
<div class="overflow-y-auto flex-1 p-6 flex flex-col gap-6">
<!-- Level Header -->
<div>
<div class="flex items-center gap-2 mb-2">
<button id="btn-back"
class="neo-btn p-2 border-2 border-black shadow-neo-sm bg-white hover:bg-gray-100 text-xs font-bold"><i
class="fas fa-arrow-left"></i> LEVELS</button>
<div class="font-bold text-sm bg-black text-white px-2 py-1 ml-auto" id="level-indicator">LEVEL 1</div>
</div>
<!-- Level Info Card -->
<div class="neo-border p-4 bg-neo-blue shadow-neo-sm relative overflow-hidden group">
<div
class="absolute -right-4 -top-4 w-16 h-16 bg-white/20 rounded-full group-hover:scale-150 transition-transform">
</div>
<div class="flex justify-between items-center mb-3 relative z-10">
<h2 class="font-bold text-black text-lg border-b-2 border-black inline-block bg-white px-2"
id="level-title">...</h2>
<span id="timer-display"
class="font-mono text-xl font-bold bg-black text-neo-green px-2 py-0.5 border-2 border-black shadow-[2px_2px_0px_0px_#fff]">0.00s</span>
</div>
<p class="text-sm text-black font-medium opacity-90 mb-2" id="level-desc">...</p>
<!-- Collapsible Hint -->
<div class="mt-2">
<button id="btn-hint"
class="text-xs font-bold border-2 border-black px-2 py-1 bg-white hover:bg-yellow-100 shadow-neo-sm flex items-center gap-2"><i
class="fas fa-lightbulb text-yellow-500"></i> SHOW HINT</button>
<div id="hint-content" class="mt-2 bg-white/50 p-2 border-2 border-black text-xs font-mono hidden"><i
class="fas fa-code mr-1"></i> <span id="level-hint-text">...</span></div>
</div>
</div>
</div>
<!-- Editor / Command Input -->
<div class="flex flex-col gap-2 shrink-0">
<div class="flex justify-between items-end">
<div class="flex gap-2 items-center">
<label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm">COMMAND</label>
<button id="btn-solution"
class="text-xs font-bold border-2 border-black px-2 py-0.5 hover:bg-black hover:text-white transition-colors bg-white shadow-neo-sm"
title="Load Example Solution"><i class="fas fa-magic"></i> VIEW SOLUTION</button>
</div>
<div class="text-xs font-bold text-gray-500" id="star-reqs">3★ < 2 items</div>
</div>
<div class="relative flex flex-col gap-2">
<textarea id="code-input"
class="code-editor w-full h-24 p-4 border-2 border-black focus:outline-none focus:ring-4 focus:ring-neo-purple/50 resize-none text-sm shadow-neo-sm"
spellcheck="false" placeholder="e.g., Add a circle in the middle. You can execute multiple commands by separating them with new lines."></textarea>
<button id="btn-execute"
class="neo-btn bg-neo-purple border-2 border-black shadow-neo-sm text-black font-bold py-2 hover:bg-purple-400 disabled:opacity-50 disabled:cursor-not-allowed"><i
class="fas fa-terminal"></i> EXECUTE</button>
</div>
<div id="error-log"
class="text-white bg-neo-red border-2 border-black text-xs font-bold px-2 py-1 shadow-neo-sm hidden">
</div>
</div>
<!-- Active Elements List -->
<div class="flex-1 min-h-0 flex flex-col">
<label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm w-max mb-1">SCENE
OBJECTS</label>
<div id="action-list"
class="flex-1 overflow-y-auto border-2 border-black bg-gray-50 p-2 space-y-2 shadow-neo-sm min-h-[100px]">
<div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>
</div>
</div>
</div>
<!-- Action Bar -->
<div class="p-4 bg-gray-100 border-t-2 border-black flex gap-3 shrink-0">
<button id="btn-play"
class="neo-btn flex-1 bg-neo-green border-2 border-black shadow-neo text-black font-bold py-3 px-4 flex items-center justify-center gap-2 hover:bg-green-400"><i
class="fas fa-play"></i> RUN</button>
<button id="btn-reset"
class="neo-btn px-4 py-3 bg-white border-2 border-black shadow-neo text-black font-bold hover:bg-gray-100"
title="Reset Simulation">
<i class="fas fa-undo"></i>
</button>
<button id="btn-clear-all"
class="neo-btn px-4 py-3 bg-white border-2 border-black shadow-neo text-black font-bold hover:bg-neo-red hover:text-white transition-colors"
title="Clear All Objects">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</div>
</div>
<!-- Main Canvas Area -->
<div class="flex-1 relative flex items-center justify-center p-2">
<!-- Canvas Container -->
<div id="canvas-container"
class="w-full h-full bg-white neo-border shadow-neo flex justify-center items-center relative overflow-hidden">
<!-- Win Overlay -->
<div id="win-message"
class="absolute z-50 hidden w-full h-full flex items-center justify-center bg-black/50 backdrop-blur-sm">
<div
class="bg-neo-yellow border-4 border-black p-8 shadow-neo-lg text-center transform rotate-2 max-w-md w-full m-4">
<h2 class="text-4xl font-black mb-2 text-black">LEVEL CLEAR!</h2>
<div class="flex justify-center gap-2 mb-4 text-4xl text-white drop-shadow-md" id="result-stars">
<!-- Stars injected here -->
</div>
<div class="text-sm font-bold mb-6 font-mono">ITEMS USED: <span id="result-items">0</span></div>
<div class="flex flex-col gap-2">
<button id="btn-next-level"
class="bg-black text-white font-bold py-3 px-6 border-2 border-transparent hover:bg-neo-green hover:text-black hover:border-black transition-colors shadow-neo-sm">NEXT
LEVEL <i class="fas fa-arrow-right ml-2"></i></button>
<button onclick="document.getElementById('btn-reset').click()"
class="bg-white text-black font-bold py-2 px-6 border-2 border-black hover:bg-gray-100 transition-colors shadow-neo-sm">REPLAY</button>
</div>
</div>
</div>
<!-- Canvas Injected Here -->
</div>
<!-- Status Badge -->
<div class="absolute top-6 right-8 pointer-events-none z-20">
<div id="status-badge"
class="bg-white border-2 border-black shadow-neo-sm px-4 py-2 font-black text-sm uppercase tracking-widest flex items-center gap-2">
<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div>
READY
</div>
</div>
</div>
<script type="module">
import { AutoModelForCausalLM, AutoTokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]";
// --- Game Constants ---
const CONFIG = {
width: 1000,
height: 750,
gridWidth: 20,
gridHeight: 15,
colors: {
background: "#ffffff",
wall: "#1a1a1a",
ball: "#60a5fa",
goal: "#4ade80",
userShape: "#facc15",
},
};
const STORAGE_KEY = "functiongemma_save_v1";
// --- Helper Functions ---
const pX = (units) => (units * CONFIG.width) / CONFIG.gridWidth;
const pY = (units) => (units * CONFIG.height) / CONFIG.gridHeight;
const strokeStyle = { strokeStyle: "#000000", lineWidth: 3 };
// --- LEVEL DEFINITIONS ---
const LEVELS = [
{
id: 0,
title: "Tutorial",
difficulty: 1,
desc: "Welcome! Press RUN to start the simulation. The ball will move on its own.",
hint: "Just press the green RUN button!",
stars: [0, 1],
solution: `// No code needed!`,
setup: (World, Bodies, Composite) => {
const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
const ball = Bodies.circle(pX(2), CONFIG.height - 50 - 20, 20, {
restitution: 0.6,
friction: 0,
frictionAir: 0,
frictionStatic: 0,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
Matter.Body.setVelocity(ball, { x: 10, y: 0 });
const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
});
World.add(Composite, [floor, ball, goal]);
return { ball, goal };
},
},
{
id: 1,
title: "The Bridge",
difficulty: 1,
desc: "There is a gap in the path. Build a bridge so the ball can roll across.",
hint: "Add a wide line in the center to connect the platforms.",
stars: [1, 2],
solution: `add a long line in the middle`,
setup: (World, Bodies, Composite) => {
const p1 = Bodies.rectangle(pX(4), pY(4), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
const p2 = Bodies.rectangle(pX(16), pY(12), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
const ball = Bodies.circle(pX(3), pY(2), 20, {
restitution: 0.2,
friction: 0,
frictionAir: 0,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
const goal = Bodies.rectangle(pX(18), pY(11), 80, 80, {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
World.add(Composite, [p1, p2, ball, goal]);
return { ball, goal };
},
},
{
id: 2,
title: "A Little Push",
difficulty: 2,
desc: "Oh no, we're stuck! Give the ball a nudge to get it moving towards the goal.",
hint: "Drop a heavy object in the top left to push it towards the goal.",
stars: [1, 3],
solution: `Add a circle at 2,2`,
setup: (World, Bodies, Composite) => {
const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
const ball = Bodies.circle(pX(2.2), CONFIG.height - 50 - 20, 20, {
restitution: 0.6,
friction: 0,
frictionAir: 0,
frictionStatic: 0,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
});
World.add(Composite, [floor, ball, goal]);
return { ball, goal };
},
},
{
id: 3,
title: "The Bounce",
difficulty: 2,
desc: "High velocity incoming! How can you redirect the ball into the goal?",
hint: "Add a centered platform at the bottom to reflect the ball towards the goal.",
stars: [1, 2],
solution: `add a wide line at the bottom`,
setup: (World, Bodies, Composite) => {
// Wall in middle top
const wall = Bodies.rectangle(pX(10), pY(3), 20, pY(6), { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
const ball = Bodies.circle(pX(2), pY(1.2), 20, {
restitution: 1.0,
friction: 0,
frictionAir: 0.001,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
// Initial Velocity: Down and Right
Matter.Body.setVelocity(ball, { x: 12, y: 12 });
const goal = Bodies.rectangle(pX(18), pY(2), pX(2), pY(2), {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
World.add(Composite, [wall, ball, goal]);
return { ball, goal };
},
},
{
id: 4,
title: "Protect",
difficulty: 3,
desc: "Ambush! Ninja stars are incoming. Protect the ball's path so it can land safely.",
hint: "Add a few heavy blocks at certain locations to shield the ball from the stars.",
stars: [3, 5],
solution: `add a heavy block at 5, 3\nadd a heavy block at 15, 5\nadd a heavy block at 5, 7`,
setup: (World, Bodies, Composite, addEvent) => {
const ball = Bodies.circle(pX(10), pY(1), 20, {
restitution: 0.5,
friction: 0.001,
frictionAir: 0.001,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
const goal = Bodies.rectangle(pX(10), pY(14), pX(2), pY(2), {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
const createNinjaStar = (x, y, vx, vy, angVel, delay) => {
const starVerts = Matter.Vertices.fromPath('50 0 63 38 100 38 69 59 82 100 50 75 18 100 31 59 0 38 37 38');
const star = Matter.Bodies.fromVertices(x, y, starVerts, {
render: { fillStyle: "#ef4444", strokeStyle: "#ef4444", lineWidth: 1 },
restitution: 0.8,
isStatic: true
}, true);
Matter.Body.scale(star, 0.5, 0.5);
Matter.Body.setVelocity(star, { x: vx, y: vy });
Matter.Body.setAngularVelocity(star, angVel);
World.add(Composite, star);
if (addEvent) {
addEvent(delay, () => {
Matter.Body.setStatic(star, false);
});
}
return star;
};
// Ninja Stars
createNinjaStar(pX(2), pY(5), 15, -5, 0.3, 0.1);
createNinjaStar(pX(18), pY(8), -15, -5, -0.3, 0.3);
createNinjaStar(pX(2), pY(11), 15, -5, 0.3, 0.50);
World.add(Composite, [ball, goal]);
return { ball, goal };
},
},
{
id: 5,
title: "Timing is Key",
difficulty: 3,
desc: "The goal is moving! Push the ball off the ledge so it lands in the moving target.",
hint: "Add a heavy ball on the top left after a short delay to drop the ball onto the platform.",
stars: [1, 2],
solution: `add a heavy ball in the top left after 1 second`,
setup: (World, Bodies, Composite) => {
// Rotating Cross
const cross = Matter.Body.create({
parts: [
Bodies.rectangle(pX(8), pY(4), pX(7), 10, { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } }),
Bodies.rectangle(pX(8), pY(4), 10, pX(7), { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } })
],
isStatic: true,
});
Matter.Events.on(STATE.engine, 'beforeUpdate', () => {
if (STATE.isPlaying) {
Matter.Body.rotate(cross, -0.01);
}
});
World.add(Composite, cross);
// Platform
const platform = Bodies.rectangle(pX(8), pY(8)-10, pX(14), 20, {
isStatic: true,
render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
// Ball
const ball = Bodies.circle(pX(2.1), pY(7), 20, {
restitution: 0.5,
friction: 0.1,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
// Moving Goal
const goal = Bodies.rectangle(pX(10), pY(13), 120, 120, {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
// Goal Movement Logic
const updateGoal = () => {
if (!STATE.isPlaying) return;
const time = STATE.time;
const speed = 0.002;
const range = pX(8);
const center = pX(10);
const x = center + Math.sin(time * speed) * range;
Matter.Body.setPosition(goal, { x: x, y: pY(13) });
};
Matter.Events.on(STATE.engine, 'beforeUpdate', updateGoal);
World.add(Composite, [platform, ball, goal]);
return { ball, goal };
},
},
{
id: 6,
title: "Catapult",
difficulty: 3,
desc: "Launch the ball into the goal! Can you time it right?",
hint: "Drop a heavy object in the right place at the right time to send the ball flying.",
stars: [1, 2],
solution: `add a heavy square at 14, 1, delayed by 2 seconds`,
setup: (World, Bodies, Composite) => {
const group = Matter.Body.nextGroup(true);
// Ramp for ball
const ramp = Bodies.rectangle(pX(2), pY(11.5), pX(4), 5, {
isStatic: true,
angle: Math.PI / 16,
render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
// Catapult
const pivotX = pX(10);
const pivotY = pY(13);
const catapult = Bodies.rectangle(pivotX, pivotY - 10, pX(12), 10, {
collisionFilter: { group: group },
density: 0.0001,
render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const pivot = Bodies.rectangle(pivotX, pivotY + 20, 20, 60, {
isStatic: true,
collisionFilter: { group: group },
render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const constraint = Matter.Constraint.create({
bodyA: catapult,
pointB: { x: pivotX, y: pivotY - 10 },
stiffness: 1.0,
length: 0,
render: { visible: true }
});
// Ball
const ball = Bodies.circle(pX(1), pY(8), 20, {
restitution: 0.0,
friction: 0.0,
density: 0.00001,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
// Goal
const goal = Bodies.rectangle(pX(18), pY(2), pX(4), pY(4), {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
World.add(Composite, [ramp, catapult, pivot, constraint, ball, goal]);
return { ball, goal };
},
},
{
id: 7,
title: "Newton's Cradle",
difficulty: 4,
desc: "A chain reaction! The ball is part of a Newton's cradle. How can we get things moving?",
hint: "Add heavy circles on the left and right to start the motion. You may need to time them carefully.",
stars: [2, 4],
solution: `Add a heavy circle in the top left.\nAdd a heavy circle in the top right, delayed by 10 seconds.`,
setup: (World, Bodies, Composite) => {
const xx = pX(8), yy = pY(2), number = 5, size = 25, length = pY(4);
const separation = 2.1;
for (let i = 0; i < number; i++) {
const x = xx + i * (size * separation);
const circle = Bodies.circle(x, yy + length, size, {
inertia: Infinity, restitution: 0.1, friction: 0, frictionAir: 0, slop: size * 0.02,
render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const constraint = Matter.Constraint.create({
pointA: { x: x, y: yy },
bodyB: circle,
stiffness: 1,
length: length,
render: { strokeStyle: '#000', lineWidth: 1 }
});
World.add(Composite, [circle, constraint]);
}
const ramp = Bodies.rectangle(pX(4), pY(5.5), pX(7), 10, {
friction: 0.01,
frictionStatic: 0.01,
restitution: 0.1,
isStatic: true, angle: Math.PI / 12, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
// Tunnel walls
const p1 = Bodies.rectangle(pX(14.5), yy + length + 30, pX(3), 10, {
isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const p2 = Bodies.rectangle(pX(15.25), yy + length + 30 - pY(1) - 10, pX(4.5), 10, {
isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const p3 = Bodies.rectangle(pX(17.85), pY(8), pX(4), 10, {
isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const p4 = Bodies.rectangle(pX(19.75), pY(6.1), pX(4), 10, {
// make vertical
angle: Math.PI / 2,
restitution: 0.1,
isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
});
const ball = Bodies.circle(xx + number * (size * separation), yy + length, 20, {
restitution: 0.1, friction: 0.0, frictionAir: 0.0,
render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
});
const goal = Bodies.rectangle(pX(6.5), pY(12.5), pX(8), pY(4), {
isStatic: true,
isSensor: true,
label: "GoalZone",
render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
});
World.add(Composite, [ramp, p1, p2, p3, p4, ball, goal]);
return { ball, goal };
},
}
];
// --- State Management ---
const STATE = {
engine: null,
render: null,
runner: null,
time: 0,
startTime: 0,
isPlaying: false,
isFinished: false,
eventQueue: [],
plannedActions: [],
currentLevelIndex: 0,
currentBall: null,
progress: { unlockedIndex: 0, stars: {} },
winCondition: null,
};
function loadProgress() {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
try {
STATE.progress = JSON.parse(saved);
} catch (e) {
console.error("Save Corrupt");
}
}
}
function saveProgress() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(STATE.progress));
}
// --- Engine Initialization ---
function initPhysics() {
const container = document.getElementById("canvas-container");
STATE.engine = Matter.Engine.create();
STATE.engine.world.gravity.y = 1;
STATE.engine.timing.timeScale = 0.5;
STATE.render = Matter.Render.create({
element: container,
engine: STATE.engine,
options: {
width: CONFIG.width,
height: CONFIG.height,
wireframes: false,
background: CONFIG.colors.background,
pixelRatio: window.devicePixelRatio,
showAngleIndicator: false,
},
});
Matter.Events.on(STATE.render, "afterRender", function () {
const context = STATE.render.context;
const width = STATE.render.options.width;
const height = STATE.render.options.height;
// Grid
context.beginPath();
context.strokeStyle = "rgba(0, 0, 0, 0.1)";
context.lineWidth = 1;
context.font = "bold 10px 'Fira Code'";
context.fillStyle = "rgba(0, 0, 0, 0.3)";
context.textAlign = "center";
for (let i = 0; i <= CONFIG.gridWidth; i++) {
const x = (width * i) / CONFIG.gridWidth;
context.moveTo(x, 0);
context.lineTo(x, height);
if (i > 0 && i < CONFIG.gridWidth) context.fillText(i, x, 15);
}
for (let i = 0; i <= CONFIG.gridHeight; i++) {
const y = (height * i) / CONFIG.gridHeight;
context.moveTo(0, y);
context.lineTo(width, y);
if (i > 0 && i < CONFIG.gridHeight) context.fillText(i, 15, y + 4);
}
context.stroke();
// Custom Objects
if (!STATE.isPlaying && !STATE.isFinished) {
context.font = "bold 14px 'Fira Code', monospace";
context.textAlign = "center";
context.textBaseline = "middle";
STATE.plannedActions.forEach((action) => {
if (action.previewBody) {
const body = action.previewBody;
const x = body.position.x;
const y = body.position.y;
if (action.delay > 0) {
context.fillStyle = "rgba(0, 0, 0, 0.7)";
context.fillText(`in ${action.delay}s`, x, body.bounds.max.y + 20);
}
if (action.params.velocity) {
const vx = action.params.velocity[0],
vy = action.params.velocity[1];
drawVelocityArrow(context, x, y, vx, vy, "#ef4444");
}
}
});
// Draw velocity arrows for any dynamic body in the world (Level setup items)
Matter.Composite.allBodies(STATE.engine.world).forEach((body) => {
// Skip planned action previews
if (STATE.plannedActions.some((a) => a.previewBody === body)) return;
const vx = body.velocity.x || 0;
const vy = body.velocity.y || 0;
if (Math.hypot(vx, vy) > 0.1) {
let color = body.render.fillStyle;
// Use red for dark objects (enemies), otherwise use body color
if (color === "#333" || color === CONFIG.colors.wall) color = "#ef4444";
drawVelocityArrow(context, body.position.x, body.position.y, vx, vy, color);
}
});
}
// Goal Zone
const bodies = Matter.Composite.allBodies(STATE.engine.world);
bodies.forEach((body) => {
if (body.label === "GoalZone") {
const bounds = body.bounds;
const w = bounds.max.x - bounds.min.x;
const h = bounds.max.y - bounds.min.y;
const cx = (bounds.min.x + bounds.max.x) / 2;
const cy = (bounds.min.y + bounds.max.y) / 2;
context.save();
context.translate(cx, cy);
context.beginPath();
context.rect(-w / 2, -h / 2, w, h);
context.strokeStyle = "#4ade80";
context.lineWidth = 3;
context.setLineDash([15, 10]);
context.stroke();
context.fillStyle = "#1a1a1a";
context.fillRect(-2, -20, 4, 40);
context.beginPath();
context.moveTo(2, -20);
context.lineTo(25, -10);
context.lineTo(2, 0);
context.fill();
context.font = "bold 14px 'Space Grotesk'";
context.textAlign = "center";
context.fillText("GOAL", 0, 35);
context.restore();
}
});
});
const canvas = STATE.render.canvas;
canvas.style.border = "3px solid black";
const resizeCanvas = () => {
const cw = container.clientWidth - 40;
const ch = container.clientHeight - 40;
const tr = CONFIG.width / CONFIG.height;
const cr = cw / ch;
if (cr > tr) {
canvas.style.height = `${ch}px`;
canvas.style.width = `${ch * tr}px`;
} else {
canvas.style.width = `${cw}px`;
canvas.style.height = `${cw / tr}px`;
}
};
const resizeObserver = new ResizeObserver(() => {
window.requestAnimationFrame(() => resizeCanvas());
});
resizeObserver.observe(container);
window.requestAnimationFrame(() => resizeCanvas());
STATE.runner = Matter.Runner.create({ isFixed: true, delta: 1000 / 60 });
Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
Matter.Render.run(STATE.render);
}
function drawVelocityArrow(context, x, y, vx, vy, color) {
if (vx === 0 && vy === 0) return;
const speed = Math.hypot(vx, vy);
const arrowScale = 20;
const maxLength = 150;
const rawLen = speed * arrowScale;
const scaleFactor = Math.min(rawLen, maxLength) / speed;
const endX = x + vx * scaleFactor;
const endY = y + vy * scaleFactor;
context.beginPath();
context.moveTo(x, y);
context.lineTo(endX, endY);
context.strokeStyle = color;
context.lineWidth = 3;
context.stroke();
const angle = Math.atan2(endY - y, endX - x);
const headLen = 12;
context.beginPath();
context.moveTo(endX, endY);
context.lineTo(endX - headLen * Math.cos(angle - Math.PI / 6), endY - headLen * Math.sin(angle - Math.PI / 6));
context.lineTo(endX - headLen * Math.cos(angle + Math.PI / 6), endY - headLen * Math.sin(angle + Math.PI / 6));
context.lineTo(endX, endY);
context.fillStyle = color;
context.fill();
context.fillStyle = color;
context.font = "bold 12px 'Fira Code', monospace";
context.textAlign = "center";
context.fillText(`${speed.toFixed(1)}`, endX + (vx / speed) * 15, endY + (vy / speed) * 15);
}
function handleUpdate() {
if (!STATE.isPlaying || STATE.isFinished) return;
STATE.time = performance.now() - STATE.startTime;
document.getElementById("timer-display").innerText = (STATE.time / 1000).toFixed(2) + "s";
STATE.eventQueue
.filter((e) => e.delay <= STATE.time && !e.executed)
.forEach((e) => {
e.action();
e.executed = true;
});
if (STATE.winCondition && STATE.winCondition()) endGame(true);
}
function loadLevel(index) {
if (STATE.runner) Matter.Runner.stop(STATE.runner);
document.getElementById("view-menu").classList.add("hidden");
document.getElementById("view-game").classList.remove("hidden");
document.getElementById("view-game").classList.add("flex");
STATE.currentLevelIndex = index;
const level = LEVELS[index];
const diffs = ["", "EASY", "MEDIUM", "HARD", "EXTREME"];
const diffColors = ["", "bg-neo-green", "bg-neo-yellow", "bg-neo-red", "bg-neo-purple"];
const d = level.difficulty || 1;
document.getElementById("level-indicator").innerHTML = `LEVEL ${index + 1} <span class="ml-2 px-1 ${diffColors[d]} text-black text-[10px] border border-black">${diffs[d]}</span>`;
document.getElementById("level-title").innerText = level.title;
document.getElementById("level-desc").innerText = level.desc;
document.getElementById("level-hint-text").innerText = level.hint;
document.getElementById("star-reqs").innerText = `3★ < ${level.stars[0] + 1} items`;
document.getElementById("hint-content").classList.add("hidden");
resetSimulationState();
document.getElementById("code-input").value = "";
const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});
STATE.currentBall = ball;
STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;
Matter.Render.world(STATE.render);
}
function resetSimulationState() {
Matter.Composite.clear(STATE.engine.world);
STATE.engine.events = {};
Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
STATE.plannedActions = [];
STATE.eventQueue = [];
STATE.time = 0;
STATE.isFinished = false;
STATE.isPlaying = false;
STATE.currentBall = null;
document.getElementById("timer-display").innerText = "0.00s";
document.getElementById("win-message").style.display = "none";
document.getElementById("error-log").classList.add("hidden");
document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;
updateActionList();
}
function endGame(success) {
STATE.isFinished = true;
STATE.isPlaying = false;
Matter.Runner.stop(STATE.runner);
if (success) {
document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black"></div> COMPLETE`;
const used = STATE.plannedActions.length;
const level = LEVELS[STATE.currentLevelIndex];
let stars = 1;
if (used <= level.stars[0]) stars = 3;
else if (used <= level.stars[1]) stars = 2;
if (stars > (STATE.progress.stars[level.id] || 0)) STATE.progress.stars[level.id] = stars;
if (STATE.currentLevelIndex >= STATE.progress.unlockedIndex && STATE.currentLevelIndex < LEVELS.length - 1) {
STATE.progress.unlockedIndex = STATE.currentLevelIndex + 1;
}
saveProgress();
const starContainer = document.getElementById("result-stars");
starContainer.innerHTML = "";
for (let i = 0; i < 3; i++) {
const filled = i < stars;
starContainer.innerHTML += `<i class="fas fa-star ${filled ? "text-yellow-400" : "text-gray-600"}"></i>`;
}
document.getElementById("result-items").innerText = used;
const btnNext = document.getElementById("btn-next-level");
if (STATE.currentLevelIndex >= LEVELS.length - 1) {
// Update Max
btnNext.style.display = "none";
} else {
btnNext.style.display = "inline-block";
btnNext.onclick = () => loadLevel(STATE.currentLevelIndex + 1);
}
document.getElementById("win-message").style.display = "flex";
}
}
function updateActionList() {
const list = document.getElementById("action-list");
list.innerHTML = "";
if (STATE.plannedActions.length === 0) {
list.innerHTML = `<div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>`;
return;
}
STATE.plannedActions.forEach((action, index) => {
const div = document.createElement("div");
div.className = "action-item flex justify-between items-center bg-white border border-black p-2 shadow-[2px_2px_0px_0px_rgba(0,0,0,0.1)] hover:shadow-[2px_2px_0px_0px_#000] transition-shadow group";
const p = action.params;
const details = [];
if (p.size !== 1) details.push(`size:${p.size}`);
if (p.weight !== 1) details.push(`mass:${p.weight}`);
if (p.restitution !== 0) details.push(`bounce:${p.restitution}`);
if (p.angle !== 0) details.push(`angle:${p.angle}°`);
if (p.velocity && (p.velocity[0] !== 0 || p.velocity[1] !== 0)) details.push(`v:[${p.velocity}]`);
if (p.isStatic !== (p.shape === 'line')) details.push(p.isStatic ? 'static' : 'dynamic');
if (p.delay > 0) details.push(`delay:${p.delay}s`);
const typeName = p.shape;
const color = p.color || "#000";
div.innerHTML = `
<div class="flex items-center gap-2">
<div class="w-3 h-3 border border-black" style="background-color: ${color}"></div>
<div class="flex flex-col">
<div class="flex items-center gap-2">
<span class="text-xs font-bold uppercase">${typeName}</span>
<span class="text-[10px] text-gray-500 font-mono">@ [${p.location[0]}, ${p.location[1]}]</span>
</div>
${details.length > 0 ? `<div class="text-[9px] text-gray-400 font-mono leading-tight uppercase">${details.join(' | ')}</div>` : ''}
</div>
</div>
`;
const btnDelete = document.createElement("button");
btnDelete.className = "btn-delete w-6 h-6 flex items-center justify-center bg-red-100 hover:bg-red-500 hover:text-white text-red-500 border border-black rounded transition-colors";
btnDelete.innerHTML = `<i class="fas fa-times text-xs"></i>`;
btnDelete.onclick = () => removeAction(index);
div.appendChild(btnDelete);
list.appendChild(div);
});
}
function removeAction(index) {
const action = STATE.plannedActions[index];
if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
STATE.plannedActions.splice(index, 1);
updateActionList();
}
function createBody(shape, x, y, pixelSize, options) {
switch (shape) {
case "circle":
case "ball":
return Matter.Bodies.circle(x, y, pixelSize / 2, options);
case "triangle":
return Matter.Bodies.polygon(x, y, 3, pixelSize / 1.5, options);
case "line":
const thickness = 5;
return Matter.Bodies.rectangle(x, y, pixelSize, thickness, options);
default: // square, rectangle, etc.
return Matter.Bodies.rectangle(x, y, pixelSize, pixelSize, options);
}
}
// --- UNIFIED TOOL IMPLEMENTATION ---
const Tools = {
add: (params) => {
let {
shape = "square",
location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2],
size = 1,
color = CONFIG.colors.userShape,
mass = 1,
weight = params.weight || mass,
delay = 0,
restitution = 0,
friction = 0.1,
rotation = 0,
angle = params.angle || rotation,
velocity = [0, 0],
static: isStaticParam,
isStatic = params.isStatic !== undefined ? params.isStatic : (isStaticParam !== undefined ? isStaticParam : ["platform", "line"].includes(shape)),
} = params;
// Handle location as string (comma-separated or descriptive)
if (typeof location === 'string') {
const parts = location.match(/\d+/g);
if (parts && parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
location = [parseFloat(parts[0]), parseFloat(parts[1])];
} else {
const loc = location.toLowerCase();
const midX = CONFIG.gridWidth / 2;
const midY = CONFIG.gridHeight / 2;
const margin = 2;
const locations = {
"center": [midX, midY],
"top-left": [margin, margin],
"top-center": [midX, margin],
"top-right": [CONFIG.gridWidth - margin, margin],
"center-left": [margin, midY],
"center": [midX, midY],
"center-right": [CONFIG.gridWidth - margin, midY],
"bottom-left": [margin, CONFIG.gridHeight - margin],
"bottom-center": [midX, CONFIG.gridHeight - margin],
"bottom-right": [CONFIG.gridWidth - margin, CONFIG.gridHeight - margin],
};
location = locations[loc] || [midX, midY];
}
}
// Ensure location is an array
if (!Array.isArray(location) || location.length !== 2) {
console.warn("Invalid location format. Defaulting to center.");
location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2];
}
const finalParams = {
shape,
location,
size,
color,
weight,
delay,
restitution,
friction,
angle,
velocity,
isStatic,
};
const x = pX(location[0]);
const y = pY(location[1]);
const pixelSize = pX(size); // Use grid-relative sizing
const commonProps = {
angle: (angle * Math.PI) / 180,
restitution: restitution,
friction: friction,
render: { fillStyle: color, ...strokeStyle },
density: weight * 0.005,
};
// For preview (ghosts)
const previewProps = {
...commonProps,
isStatic: true,
isSensor: true,
render: {
fillStyle: color,
opacity: 0.4,
strokeStyle: "#000000",
lineWidth: 2,
},
};
const body = createBody(shape, x, y, pixelSize, previewProps);
Matter.World.add(STATE.engine.world, body);
STATE.plannedActions.push({
type: "add",
params: finalParams, // Use the complete object
delay: delay || 0,
previewBody: body,
});
},
};
// --- AI Model Setup ---
const MODEL_ID = "Xenova/functiongemma-270m-game";
let tokenizer, model;
const TOOL_SCHEMA = [{"type": "function", "function": {"name": "add", "description": "Add a shape into the game scene.", "parameters": {"type": "object", "properties": {"shape": {"type": "string", "enum": ["circle", "square", "triangle", "star", "rectangle", "line", "ellipse"], "description": "The kind shape to add. Required."}, "location": {"type": "string", "description": "The [x, y] coordinates where the shape will be placed or a descriptive string. Required."}, "size": {"type": "number", "description": "The size of the object (between 0.1 and 10.0). Default is 1.0."}, "rotation": {"type": "integer", "description": "The initial clockwise rotation of the object in degrees (0-360). Default is 0."}, "friction": {"type": "number", "description": "The friction of the object (between 0.0 and 1.0). Default is 0.0."}, "restitution": {"type": "number", "description": "The bounciness of the object (between 0.0 and 1.0). Default is 0.0."}, "mass": {"type": "number", "description": "The mass of the object (between 1.0 and 10.0). Default is 1.0."}, "delay": {"type": "number", "description": "The time in seconds to wait before the object appears in the scene. Default is 0.0."}, "static": {"type": "boolean", "description": "Whether the object is static (immovable) or dynamic. Default is False."}, "velocity": {"type": "array", "items": {"type": "number"}, "description": "The initial [vx, vy] velocity vector of the object (values between -10.0 and 10.0). Default is [0.0, 0.0]."}, "color": {"type": "string", "description": "The color of the object as a string or hex code (e.g., \"red\", \"blue\", \"#FF00FF\"). Default is \"red\"."}}, "required": ["shape", "location"]}, "return": {"type": "string", "description": "A unique identifier for the added shape."}}}];
async function initModel() {
try {
tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID);
model = await AutoModelForCausalLM.from_pretrained(MODEL_ID, {
device: "webgpu",
dtype: "q4",
});
document.getElementById("loading-overlay").classList.add("hidden");
} catch (e) {
console.error(e);
document.getElementById("loading-overlay").innerHTML = `<div class="text-red-500 font-bold p-4 bg-white border-2 border-black">Error: ${e.message}</div>`;
}
}
// --- Command Execution ---
async function executeCommand() {
const input = document.getElementById("code-input").value.trim();
if (!input) return;
const btn = document.getElementById("btn-execute");
const errorLog = document.getElementById("error-log");
// UI Loading State
btn.disabled = true;
btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> THINKING...`;
errorLog.classList.add("hidden");
const systemPrompt = `You are a model that can do function calling with the following functions`;
try {
const lines = input.split('\n').map(l => l.trim()).filter(l => l.length > 0 && !l.startsWith("//"));
for (const line of lines) {
// 2. Prepare Messages
const messages = [
{ role: "developer", content: systemPrompt },
{ role: "user", content: line },
];
// 3. Apply Template
const inputs = tokenizer.apply_chat_template(messages, {
tools: TOOL_SCHEMA,
tokenize: true,
add_generation_prompt: true,
return_dict: true,
});
// 4. Generate
const output = await model.generate({ ...inputs, max_new_tokens: 128, do_sample: false });
const decoded = tokenizer.decode(output.slice(0, [inputs.input_ids.dims[1], null]), { skip_special_tokens: false });
// 5. Parse Output
// Format: <start_function_call>call:add{...}<end_function_call>
const startTag = "<start_function_call>";
const endTag = "<end_function_call>";
const startIndex = decoded.indexOf(startTag);
const endIndex = decoded.indexOf(endTag);
if (startIndex !== -1 && endIndex !== -1) {
let callStr = decoded.substring(startIndex + startTag.length, endIndex);
if (callStr.startsWith("call:add")) {
// Extract JSON-like string: {location:[...],shape:<escape>...<escape>}
let argsStr = callStr.substring(callStr.indexOf("{"));
// Sanitize to valid JSON
argsStr = argsStr
.replace(/<escape>(.*?)<escape>/g, '"$1"') // Handle string escapes
.replace(/(\w+):/g, '"$1":'); // Quote keys
const args = JSON.parse(argsStr);
Tools.add(args);
} else {
throw new Error("Model did not generate a valid add command.");
}
} else {
throw new Error(`Could not understand command: "${line}"`);
}
}
document.getElementById("code-input").value = "";
} catch (err) {
errorLog.innerText = err.message;
errorLog.classList.remove("hidden");
console.error(err);
} finally {
btn.disabled = false;
btn.innerHTML = `<i class="fas fa-terminal"></i> EXECUTE`;
updateActionList();
}
}
// --- Real Simulation Run ---
function runSimulation() {
if (STATE.runner) Matter.Runner.stop(STATE.runner);
const storedActions = [...STATE.plannedActions];
const level = LEVELS[STATE.currentLevelIndex];
Matter.Composite.clear(STATE.engine.world);
STATE.engine.events = {};
Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
STATE.eventQueue = [];
STATE.isFinished = false;
const addEvent = (delay, action) => {
STATE.eventQueue.push({
delay: delay * 1000,
action: action,
executed: false,
});
};
const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, addEvent);
STATE.currentBall = ball;
STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;
// Real Action Executioner
const executeReal = (params) => {
const { shape, location, size, weight, restitution, friction, angle, velocity, isStatic } = params;
const x = pX(location[0]),
y = pY(location[1]);
const pixelSize = pX(size);
const props = {
angle: (angle * Math.PI) / 180,
restitution,
friction,
isStatic,
render: strokeStyle,
density: weight * 0.005,
};
const body = createBody(shape, x, y, pixelSize, props);
if (!isStatic && (velocity[0] !== 0 || velocity[1] !== 0)) {
Matter.Body.setVelocity(body, { x: velocity[0], y: velocity[1] });
}
Matter.World.add(STATE.engine.world, body);
};
storedActions.forEach((action) => {
STATE.eventQueue.push({
delay: action.delay * 1000,
action: () => executeReal(action.params),
executed: false,
});
});
STATE.plannedActions = storedActions;
STATE.isPlaying = true;
STATE.startTime = performance.now();
document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black animate-ping"></div> RUNNING`;
Matter.Runner.run(STATE.runner, STATE.engine);
}
function renderMenu() {
if (STATE.runner) Matter.Runner.stop(STATE.runner);
document.getElementById("view-game").classList.add("hidden");
document.getElementById("view-game").classList.remove("flex");
document.getElementById("view-menu").classList.remove("hidden");
const grid = document.getElementById("level-grid");
grid.innerHTML = "";
LEVELS.forEach((level, index) => {
const unlocked = index <= STATE.progress.unlockedIndex;
const stars = STATE.progress.stars[index] || 0;
const card = document.createElement("div");
card.className = `level-card neo-border p-4 flex flex-col items-center justify-center gap-2 aspect-square ${unlocked ? "bg-white cursor-pointer" : "locked"}`;
if (unlocked) {
card.onclick = () => loadLevel(index);
card.innerHTML = `
<div class="text-3xl font-black">${index + 1}</div>
<div class="flex gap-1 text-xs">
${Array(3)
.fill(0)
.map((_, i) => `<i class="fas fa-star ${i < stars ? "text-neo-yellow" : "text-gray-300"}"></i>`)
.join("")}
</div>
`;
} else {
card.innerHTML = `<i class="fas fa-lock text-gray-400 text-2xl"></i>`;
}
grid.appendChild(card);
});
}
// --- Bindings ---
document.getElementById("btn-execute").onclick = executeCommand;
document.getElementById("btn-play").onclick = runSimulation;
document.getElementById("btn-reset").onclick = () => {
Matter.Runner.stop(STATE.runner);
const level = LEVELS[STATE.currentLevelIndex];
Matter.Composite.clear(STATE.engine.world);
const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});
STATE.currentBall = ball;
STATE.plannedActions.forEach((action) => {
Matter.World.add(STATE.engine.world, action.previewBody);
});
STATE.isPlaying = false;
document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;
document.getElementById("timer-display").innerText = "0.00s";
document.getElementById("win-message").style.display = "none";
};
document.getElementById("btn-clear-all").onclick = () => {
document.getElementById("code-input").value = "";
STATE.plannedActions.forEach((action) => {
if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
});
STATE.plannedActions = [];
updateActionList();
document.getElementById("btn-reset").click();
};
document.getElementById("btn-back").onclick = renderMenu;
document.getElementById("btn-hint").onclick = () => {
const content = document.getElementById("hint-content");
content.classList.toggle("hidden");
};
document.getElementById("btn-solution").addEventListener("click", () => {
const level = LEVELS[STATE.currentLevelIndex];
if (level.solution) {
document.getElementById("code-input").value = level.solution;
}
});
window.onload = () => {
loadProgress();
initPhysics();
renderMenu();
initModel();
};
</script>
</body>
</html>