captainspock commited on
Commit
f4edbb9
·
verified ·
1 Parent(s): 2a028fc

Create index.html

Browse files
Files changed (1) hide show
  1. index.html +1310 -0
index.html ADDED
@@ -0,0 +1,1310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>FunctionGemma Physics Playground</title>
8
+ <script src="https://cdn.tailwindcss.com"></script>
9
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
10
+ <script src="https://cdn.jsdelivr.net/npm/poly-decomp@0.3.0/build/decomp.min.js"></script>
11
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
12
+ <link
13
+ href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&family=Fira+Code:wght@500;700&display=swap"
14
+ rel="stylesheet" />
15
+ <script>
16
+ tailwind.config = {
17
+ theme: {
18
+ extend: {
19
+ fontFamily: {
20
+ sans: ["Space Grotesk", "sans-serif"],
21
+ mono: ["Fira Code", "monospace"],
22
+ },
23
+ colors: {
24
+ "neo-bg": "#f0f0f0",
25
+ "neo-black": "#1a1a1a",
26
+ "neo-white": "#ffffff",
27
+ "neo-purple": "#a78bfa",
28
+ "neo-yellow": "#facc15",
29
+ "neo-green": "#4ade80",
30
+ "neo-red": "#f87171",
31
+ "neo-blue": "#60a5fa",
32
+ "neo-gray": "#94a3b8",
33
+ },
34
+ boxShadow: {
35
+ neo: "4px 4px 0px 0px #000000",
36
+ "neo-sm": "2px 2px 0px 0px #000000",
37
+ "neo-lg": "8px 8px 0px 0px #000000",
38
+ },
39
+ },
40
+ },
41
+ };
42
+ </script>
43
+
44
+ <style>
45
+ body {
46
+ overflow: hidden;
47
+ background-color: #e0e7ff;
48
+ background-image: radial-gradient(#a5b4fc 1px, transparent 1px);
49
+ background-size: 20px 20px;
50
+ }
51
+ /* Custom Scrollbar */
52
+ ::-webkit-scrollbar {
53
+ width: 12px;
54
+ height: 12px;
55
+ }
56
+ ::-webkit-scrollbar-track {
57
+ background: #fff;
58
+ border-left: 2px solid black;
59
+ }
60
+ ::-webkit-scrollbar-thumb {
61
+ background: #000;
62
+ border: 2px solid #fff;
63
+ }
64
+ ::-webkit-scrollbar-thumb:hover {
65
+ background: #333;
66
+ }
67
+ .neo-border {
68
+ border: 3px solid black;
69
+ }
70
+ .neo-btn {
71
+ transition: all 0.1s ease-in-out;
72
+ }
73
+ .neo-btn:active {
74
+ transform: translate(2px, 2px);
75
+ box-shadow: 2px 2px 0px 0px #000000;
76
+ }
77
+ .level-card {
78
+ transition: all 0.2s;
79
+ }
80
+ .level-card:hover:not(.locked) {
81
+ transform: translate(-2px, -2px);
82
+ box-shadow: 6px 6px 0px 0px #000000;
83
+ }
84
+ .locked {
85
+ background-color: #e2e8f0;
86
+ cursor: not-allowed;
87
+ opacity: 0.7;
88
+ background-image: repeating-linear-gradient(45deg, #cbd5e1 0, #cbd5e1 1px, transparent 0, transparent 50%);
89
+ background-size: 10px 10px;
90
+ }
91
+ .code-editor {
92
+ font-family: "Fira Code", monospace;
93
+ background-color: #ffffff;
94
+ color: #000000;
95
+ line-height: 1.6;
96
+ }
97
+ .toggle-checkbox:checked {
98
+ right: 0;
99
+ border-color: #4ade80;
100
+ }
101
+ .toggle-checkbox:checked+.toggle-label {
102
+ background-color: #4ade80;
103
+ }
104
+ /* Action Item Delete Button Transition */
105
+ .action-item .btn-delete {
106
+ opacity: 0;
107
+ transition: opacity 0.2s;
108
+ }
109
+ .action-item:hover .btn-delete {
110
+ opacity: 1;
111
+ }
112
+ </style>
113
+ </head>
114
+
115
+ <body class="h-screen w-screen flex flex-col md:flex-row p-4 gap-4">
116
+ <!-- Loading Overlay -->
117
+ <div id="loading-overlay" class="fixed inset-0 bg-black/90 z-50 flex flex-col items-center justify-center">
118
+ <div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-neo-green mb-4"></div>
119
+ <div class="text-white font-mono font-bold text-xl">LOADING MODEL...</div>
120
+ <div class="text-gray-400 font-mono text-sm mt-2">This may take a moment</div>
121
+ </div>
122
+
123
+ <!-- Sidebar / Controls -->
124
+ <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">
125
+ <!-- Decorative Header Strip -->
126
+ <div class="h-4 w-full bg-neo-black"></div>
127
+
128
+ <div class="p-6 border-b-2 border-black bg-neo-yellow flex justify-between items-center shrink-0">
129
+ <div>
130
+ <h1 class="text-3xl font-bold text-black uppercase tracking-tighter">Function <span
131
+ class="text-white bg-black px-1">Gemma</span></h1>
132
+ <div class="text-xs font-mono font-bold text-black mt-1">PHYSICS PLAYGROUND</div>
133
+ </div>
134
+ </div>
135
+
136
+ <!-- MENU: Level Select -->
137
+ <div id="view-menu" class="flex-1 overflow-y-auto p-6 bg-white hidden">
138
+ <h2 class="font-bold text-xl mb-4 border-b-2 border-black pb-2">SELECT LEVEL</h2>
139
+ <div id="level-grid" class="grid grid-cols-2 gap-4">
140
+ <!-- Injected via JS -->
141
+ </div>
142
+ </div>
143
+
144
+ <!-- MENU: Game View -->
145
+ <div id="view-game" class="flex-1 flex flex-col overflow-hidden relative">
146
+ <div class="overflow-y-auto flex-1 p-6 flex flex-col gap-6">
147
+ <!-- Level Header -->
148
+ <div>
149
+ <div class="flex items-center gap-2 mb-2">
150
+ <button id="btn-back"
151
+ class="neo-btn p-2 border-2 border-black shadow-neo-sm bg-white hover:bg-gray-100 text-xs font-bold"><i
152
+ class="fas fa-arrow-left"></i> LEVELS</button>
153
+ <div class="font-bold text-sm bg-black text-white px-2 py-1 ml-auto" id="level-indicator">LEVEL 1</div>
154
+ </div>
155
+
156
+ <!-- Level Info Card -->
157
+ <div class="neo-border p-4 bg-neo-blue shadow-neo-sm relative overflow-hidden group">
158
+ <div
159
+ class="absolute -right-4 -top-4 w-16 h-16 bg-white/20 rounded-full group-hover:scale-150 transition-transform">
160
+ </div>
161
+ <div class="flex justify-between items-center mb-3 relative z-10">
162
+ <h2 class="font-bold text-black text-lg border-b-2 border-black inline-block bg-white px-2"
163
+ id="level-title">...</h2>
164
+ <span id="timer-display"
165
+ 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>
166
+ </div>
167
+ <p class="text-sm text-black font-medium opacity-90 mb-2" id="level-desc">...</p>
168
+
169
+ <!-- Collapsible Hint -->
170
+ <div class="mt-2">
171
+ <button id="btn-hint"
172
+ 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
173
+ class="fas fa-lightbulb text-yellow-500"></i> SHOW HINT</button>
174
+ <div id="hint-content" class="mt-2 bg-white/50 p-2 border-2 border-black text-xs font-mono hidden"><i
175
+ class="fas fa-code mr-1"></i> <span id="level-hint-text">...</span></div>
176
+ </div>
177
+ </div>
178
+ </div>
179
+
180
+ <!-- Editor / Command Input -->
181
+ <div class="flex flex-col gap-2 shrink-0">
182
+ <div class="flex justify-between items-end">
183
+ <div class="flex gap-2 items-center">
184
+ <label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm">COMMAND</label>
185
+ <button id="btn-solution"
186
+ 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"
187
+ title="Load Example Solution"><i class="fas fa-magic"></i> VIEW SOLUTION</button>
188
+ </div>
189
+ <div class="text-xs font-bold text-gray-500" id="star-reqs">3★ < 2 items</div>
190
+ </div>
191
+ <div class="relative flex flex-col gap-2">
192
+ <textarea id="code-input"
193
+ 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"
194
+ spellcheck="false" placeholder="e.g., Add a circle in the middle. You can execute multiple commands by separating them with new lines."></textarea>
195
+ <button id="btn-execute"
196
+ 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
197
+ class="fas fa-terminal"></i> EXECUTE</button>
198
+ </div>
199
+ <div id="error-log"
200
+ class="text-white bg-neo-red border-2 border-black text-xs font-bold px-2 py-1 shadow-neo-sm hidden">
201
+ </div>
202
+ </div>
203
+
204
+ <!-- Active Elements List -->
205
+ <div class="flex-1 min-h-0 flex flex-col">
206
+ <label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm w-max mb-1">SCENE
207
+ OBJECTS</label>
208
+ <div id="action-list"
209
+ class="flex-1 overflow-y-auto border-2 border-black bg-gray-50 p-2 space-y-2 shadow-neo-sm min-h-[100px]">
210
+ <div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>
211
+ </div>
212
+ </div>
213
+ </div>
214
+
215
+ <!-- Action Bar -->
216
+ <div class="p-4 bg-gray-100 border-t-2 border-black flex gap-3 shrink-0">
217
+ <button id="btn-play"
218
+ 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
219
+ class="fas fa-play"></i> RUN</button>
220
+ <button id="btn-reset"
221
+ class="neo-btn px-4 py-3 bg-white border-2 border-black shadow-neo text-black font-bold hover:bg-gray-100"
222
+ title="Reset Simulation">
223
+ <i class="fas fa-undo"></i>
224
+ </button>
225
+ <button id="btn-clear-all"
226
+ 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"
227
+ title="Clear All Objects">
228
+ <i class="fas fa-trash-alt"></i>
229
+ </button>
230
+ </div>
231
+ </div>
232
+ </div>
233
+
234
+ <!-- Main Canvas Area -->
235
+ <div class="flex-1 relative flex items-center justify-center p-2">
236
+ <!-- Canvas Container -->
237
+ <div id="canvas-container"
238
+ class="w-full h-full bg-white neo-border shadow-neo flex justify-center items-center relative overflow-hidden">
239
+ <!-- Win Overlay -->
240
+ <div id="win-message"
241
+ class="absolute z-50 hidden w-full h-full flex items-center justify-center bg-black/50 backdrop-blur-sm">
242
+ <div
243
+ 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">
244
+ <h2 class="text-4xl font-black mb-2 text-black">LEVEL CLEAR!</h2>
245
+
246
+ <div class="flex justify-center gap-2 mb-4 text-4xl text-white drop-shadow-md" id="result-stars">
247
+ <!-- Stars injected here -->
248
+ </div>
249
+
250
+ <div class="text-sm font-bold mb-6 font-mono">ITEMS USED: <span id="result-items">0</span></div>
251
+
252
+ <div class="flex flex-col gap-2">
253
+ <button id="btn-next-level"
254
+ 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
255
+ LEVEL <i class="fas fa-arrow-right ml-2"></i></button>
256
+ <button onclick="document.getElementById('btn-reset').click()"
257
+ 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>
258
+ </div>
259
+ </div>
260
+ </div>
261
+
262
+ <!-- Canvas Injected Here -->
263
+ </div>
264
+
265
+ <!-- Status Badge -->
266
+ <div class="absolute top-6 right-8 pointer-events-none z-20">
267
+ <div id="status-badge"
268
+ 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">
269
+ <div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div>
270
+ READY
271
+ </div>
272
+ </div>
273
+ </div>
274
+ <script type="module">
275
+ import { AutoModelForCausalLM, AutoTokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
276
+ // --- Game Constants ---
277
+ const CONFIG = {
278
+ width: 1000,
279
+ height: 750,
280
+ gridWidth: 20,
281
+ gridHeight: 15,
282
+ colors: {
283
+ background: "#ffffff",
284
+ wall: "#1a1a1a",
285
+ ball: "#60a5fa",
286
+ goal: "#4ade80",
287
+ userShape: "#facc15",
288
+ },
289
+ };
290
+ const STORAGE_KEY = "functiongemma_save_v1";
291
+ // --- Helper Functions ---
292
+ const pX = (units) => (units * CONFIG.width) / CONFIG.gridWidth;
293
+ const pY = (units) => (units * CONFIG.height) / CONFIG.gridHeight;
294
+ const strokeStyle = { strokeStyle: "#000000", lineWidth: 3 };
295
+ // --- LEVEL DEFINITIONS ---
296
+ const LEVELS = [
297
+ {
298
+ id: 0,
299
+ title: "Tutorial",
300
+ difficulty: 1,
301
+ desc: "Welcome! Press RUN to start the simulation. The ball will move on its own.",
302
+ hint: "Just press the green RUN button!",
303
+ stars: [0, 1],
304
+ solution: `// No code needed!`,
305
+ setup: (World, Bodies, Composite) => {
306
+ const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
307
+ const ball = Bodies.circle(pX(2), CONFIG.height - 50 - 20, 20, {
308
+ restitution: 0.6,
309
+ friction: 0,
310
+ frictionAir: 0,
311
+ frictionStatic: 0,
312
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
313
+ });
314
+ Matter.Body.setVelocity(ball, { x: 10, y: 0 });
315
+ const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
316
+ isStatic: true,
317
+ isSensor: true,
318
+ label: "GoalZone",
319
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
320
+ });
321
+ World.add(Composite, [floor, ball, goal]);
322
+ return { ball, goal };
323
+ },
324
+ },
325
+ {
326
+ id: 1,
327
+ title: "The Bridge",
328
+ difficulty: 1,
329
+ desc: "There is a gap in the path. Build a bridge so the ball can roll across.",
330
+ hint: "Add a wide line in the center to connect the platforms.",
331
+ stars: [1, 2],
332
+ solution: `add a long line in the middle`,
333
+ setup: (World, Bodies, Composite) => {
334
+ const p1 = Bodies.rectangle(pX(4), pY(4), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
335
+ const p2 = Bodies.rectangle(pX(16), pY(12), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
336
+ const ball = Bodies.circle(pX(3), pY(2), 20, {
337
+ restitution: 0.2,
338
+ friction: 0,
339
+ frictionAir: 0,
340
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
341
+ });
342
+ const goal = Bodies.rectangle(pX(18), pY(11), 80, 80, {
343
+ isStatic: true,
344
+ isSensor: true,
345
+ label: "GoalZone",
346
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
347
+ });
348
+ World.add(Composite, [p1, p2, ball, goal]);
349
+ return { ball, goal };
350
+ },
351
+ },
352
+ {
353
+ id: 2,
354
+ title: "A Little Push",
355
+ difficulty: 2,
356
+ desc: "Oh no, we're stuck! Give the ball a nudge to get it moving towards the goal.",
357
+ hint: "Drop a heavy object in the top left to push it towards the goal.",
358
+ stars: [1, 3],
359
+ solution: `Add a circle at 2,2`,
360
+ setup: (World, Bodies, Composite) => {
361
+ const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
362
+ const ball = Bodies.circle(pX(2.2), CONFIG.height - 50 - 20, 20, {
363
+ restitution: 0.6,
364
+ friction: 0,
365
+ frictionAir: 0,
366
+ frictionStatic: 0,
367
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
368
+ });
369
+ const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
370
+ isStatic: true,
371
+ isSensor: true,
372
+ label: "GoalZone",
373
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
374
+ });
375
+ World.add(Composite, [floor, ball, goal]);
376
+ return { ball, goal };
377
+ },
378
+ },
379
+ {
380
+ id: 3,
381
+ title: "The Bounce",
382
+ difficulty: 2,
383
+ desc: "High velocity incoming! How can you redirect the ball into the goal?",
384
+ hint: "Add a centered platform at the bottom to reflect the ball towards the goal.",
385
+ stars: [1, 2],
386
+ solution: `add a wide line at the bottom`,
387
+ setup: (World, Bodies, Composite) => {
388
+ // Wall in middle top
389
+ const wall = Bodies.rectangle(pX(10), pY(3), 20, pY(6), { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
390
+ const ball = Bodies.circle(pX(2), pY(1.2), 20, {
391
+ restitution: 1.0,
392
+ friction: 0,
393
+ frictionAir: 0.001,
394
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
395
+ });
396
+ // Initial Velocity: Down and Right
397
+ Matter.Body.setVelocity(ball, { x: 12, y: 12 });
398
+ const goal = Bodies.rectangle(pX(18), pY(2), pX(2), pY(2), {
399
+ isStatic: true,
400
+ isSensor: true,
401
+ label: "GoalZone",
402
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
403
+ });
404
+ World.add(Composite, [wall, ball, goal]);
405
+ return { ball, goal };
406
+ },
407
+ },
408
+ {
409
+ id: 4,
410
+ title: "Protect",
411
+ difficulty: 3,
412
+ desc: "Ambush! Ninja stars are incoming. Protect the ball's path so it can land safely.",
413
+ hint: "Add a few heavy blocks at certain locations to shield the ball from the stars.",
414
+ stars: [3, 5],
415
+ solution: `add a heavy block at 5, 3\nadd a heavy block at 15, 5\nadd a heavy block at 5, 7`,
416
+ setup: (World, Bodies, Composite, addEvent) => {
417
+ const ball = Bodies.circle(pX(10), pY(1), 20, {
418
+ restitution: 0.5,
419
+ friction: 0.001,
420
+ frictionAir: 0.001,
421
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
422
+ });
423
+ const goal = Bodies.rectangle(pX(10), pY(14), pX(2), pY(2), {
424
+ isStatic: true,
425
+ isSensor: true,
426
+ label: "GoalZone",
427
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
428
+ });
429
+ const createNinjaStar = (x, y, vx, vy, angVel, delay) => {
430
+ 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');
431
+ const star = Matter.Bodies.fromVertices(x, y, starVerts, {
432
+ render: { fillStyle: "#ef4444", strokeStyle: "#ef4444", lineWidth: 1 },
433
+ restitution: 0.8,
434
+ isStatic: true
435
+ }, true);
436
+ Matter.Body.scale(star, 0.5, 0.5);
437
+ Matter.Body.setVelocity(star, { x: vx, y: vy });
438
+ Matter.Body.setAngularVelocity(star, angVel);
439
+ World.add(Composite, star);
440
+ if (addEvent) {
441
+ addEvent(delay, () => {
442
+ Matter.Body.setStatic(star, false);
443
+ });
444
+ }
445
+ return star;
446
+ };
447
+ // Ninja Stars
448
+ createNinjaStar(pX(2), pY(5), 15, -5, 0.3, 0.1);
449
+ createNinjaStar(pX(18), pY(8), -15, -5, -0.3, 0.3);
450
+ createNinjaStar(pX(2), pY(11), 15, -5, 0.3, 0.50);
451
+ World.add(Composite, [ball, goal]);
452
+ return { ball, goal };
453
+ },
454
+ },
455
+ {
456
+ id: 5,
457
+ title: "Timing is Key",
458
+ difficulty: 3,
459
+ desc: "The goal is moving! Push the ball off the ledge so it lands in the moving target.",
460
+ hint: "Add a heavy ball on the top left after a short delay to drop the ball onto the platform.",
461
+ stars: [1, 2],
462
+ solution: `add a heavy ball in the top left after 1 second`,
463
+ setup: (World, Bodies, Composite) => {
464
+ // Rotating Cross
465
+ const cross = Matter.Body.create({
466
+ parts: [
467
+ Bodies.rectangle(pX(8), pY(4), pX(7), 10, { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } }),
468
+ Bodies.rectangle(pX(8), pY(4), 10, pX(7), { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } })
469
+ ],
470
+ isStatic: true,
471
+ });
472
+ Matter.Events.on(STATE.engine, 'beforeUpdate', () => {
473
+ if (STATE.isPlaying) {
474
+ Matter.Body.rotate(cross, -0.01);
475
+ }
476
+ });
477
+ World.add(Composite, cross);
478
+ // Platform
479
+ const platform = Bodies.rectangle(pX(8), pY(8)-10, pX(14), 20, {
480
+ isStatic: true,
481
+ render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
482
+ });
483
+ // Ball
484
+ const ball = Bodies.circle(pX(2.1), pY(7), 20, {
485
+ restitution: 0.5,
486
+ friction: 0.1,
487
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
488
+ });
489
+ // Moving Goal
490
+ const goal = Bodies.rectangle(pX(10), pY(13), 120, 120, {
491
+ isStatic: true,
492
+ isSensor: true,
493
+ label: "GoalZone",
494
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
495
+ });
496
+ // Goal Movement Logic
497
+ const updateGoal = () => {
498
+ if (!STATE.isPlaying) return;
499
+ const time = STATE.time;
500
+ const speed = 0.002;
501
+ const range = pX(8);
502
+ const center = pX(10);
503
+ const x = center + Math.sin(time * speed) * range;
504
+ Matter.Body.setPosition(goal, { x: x, y: pY(13) });
505
+ };
506
+ Matter.Events.on(STATE.engine, 'beforeUpdate', updateGoal);
507
+ World.add(Composite, [platform, ball, goal]);
508
+ return { ball, goal };
509
+ },
510
+ },
511
+ {
512
+ id: 6,
513
+ title: "Catapult",
514
+ difficulty: 3,
515
+ desc: "Launch the ball into the goal! Can you time it right?",
516
+ hint: "Drop a heavy object in the right place at the right time to send the ball flying.",
517
+ stars: [1, 2],
518
+ solution: `add a heavy square at 14, 1, delayed by 2 seconds`,
519
+ setup: (World, Bodies, Composite) => {
520
+ const group = Matter.Body.nextGroup(true);
521
+ // Ramp for ball
522
+ const ramp = Bodies.rectangle(pX(2), pY(11.5), pX(4), 5, {
523
+ isStatic: true,
524
+ angle: Math.PI / 16,
525
+ render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
526
+ });
527
+ // Catapult
528
+ const pivotX = pX(10);
529
+ const pivotY = pY(13);
530
+ const catapult = Bodies.rectangle(pivotX, pivotY - 10, pX(12), 10, {
531
+ collisionFilter: { group: group },
532
+ density: 0.0001,
533
+ render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
534
+ });
535
+ const pivot = Bodies.rectangle(pivotX, pivotY + 20, 20, 60, {
536
+ isStatic: true,
537
+ collisionFilter: { group: group },
538
+ render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
539
+ });
540
+ const constraint = Matter.Constraint.create({
541
+ bodyA: catapult,
542
+ pointB: { x: pivotX, y: pivotY - 10 },
543
+ stiffness: 1.0,
544
+ length: 0,
545
+ render: { visible: true }
546
+ });
547
+ // Ball
548
+ const ball = Bodies.circle(pX(1), pY(8), 20, {
549
+ restitution: 0.0,
550
+ friction: 0.0,
551
+ density: 0.00001,
552
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
553
+ });
554
+ // Goal
555
+ const goal = Bodies.rectangle(pX(18), pY(2), pX(4), pY(4), {
556
+ isStatic: true,
557
+ isSensor: true,
558
+ label: "GoalZone",
559
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
560
+ });
561
+ World.add(Composite, [ramp, catapult, pivot, constraint, ball, goal]);
562
+ return { ball, goal };
563
+ },
564
+ },
565
+ {
566
+ id: 7,
567
+ title: "Newton's Cradle",
568
+ difficulty: 4,
569
+ desc: "A chain reaction! The ball is part of a Newton's cradle. How can we get things moving?",
570
+ hint: "Add heavy circles on the left and right to start the motion. You may need to time them carefully.",
571
+ stars: [2, 4],
572
+ solution: `Add a heavy circle in the top left.\nAdd a heavy circle in the top right, delayed by 10 seconds.`,
573
+ setup: (World, Bodies, Composite) => {
574
+ const xx = pX(8), yy = pY(2), number = 5, size = 25, length = pY(4);
575
+ const separation = 2.1;
576
+ for (let i = 0; i < number; i++) {
577
+ const x = xx + i * (size * separation);
578
+ const circle = Bodies.circle(x, yy + length, size, {
579
+ inertia: Infinity, restitution: 0.1, friction: 0, frictionAir: 0, slop: size * 0.02,
580
+ render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
581
+ });
582
+ const constraint = Matter.Constraint.create({
583
+ pointA: { x: x, y: yy },
584
+ bodyB: circle,
585
+ stiffness: 1,
586
+ length: length,
587
+ render: { strokeStyle: '#000', lineWidth: 1 }
588
+ });
589
+ World.add(Composite, [circle, constraint]);
590
+ }
591
+ const ramp = Bodies.rectangle(pX(4), pY(5.5), pX(7), 10, {
592
+ friction: 0.01,
593
+ frictionStatic: 0.01,
594
+ restitution: 0.1,
595
+ isStatic: true, angle: Math.PI / 12, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
596
+ });
597
+ // Tunnel walls
598
+ const p1 = Bodies.rectangle(pX(14.5), yy + length + 30, pX(3), 10, {
599
+ isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
600
+ });
601
+ const p2 = Bodies.rectangle(pX(15.25), yy + length + 30 - pY(1) - 10, pX(4.5), 10, {
602
+ isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
603
+ });
604
+ const p3 = Bodies.rectangle(pX(17.85), pY(8), pX(4), 10, {
605
+ isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
606
+ });
607
+ const p4 = Bodies.rectangle(pX(19.75), pY(6.1), pX(4), 10, {
608
+ // make vertical
609
+ angle: Math.PI / 2,
610
+ restitution: 0.1,
611
+ isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
612
+ });
613
+ const ball = Bodies.circle(xx + number * (size * separation), yy + length, 20, {
614
+ restitution: 0.1, friction: 0.0, frictionAir: 0.0,
615
+ render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
616
+ });
617
+ const goal = Bodies.rectangle(pX(6.5), pY(12.5), pX(8), pY(4), {
618
+ isStatic: true,
619
+ isSensor: true,
620
+ label: "GoalZone",
621
+ render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
622
+ });
623
+ World.add(Composite, [ramp, p1, p2, p3, p4, ball, goal]);
624
+ return { ball, goal };
625
+ },
626
+ }
627
+ ];
628
+ // --- State Management ---
629
+ const STATE = {
630
+ engine: null,
631
+ render: null,
632
+ runner: null,
633
+ time: 0,
634
+ startTime: 0,
635
+ isPlaying: false,
636
+ isFinished: false,
637
+ eventQueue: [],
638
+ plannedActions: [],
639
+ currentLevelIndex: 0,
640
+ currentBall: null,
641
+ progress: { unlockedIndex: 0, stars: {} },
642
+ winCondition: null,
643
+ };
644
+ function loadProgress() {
645
+ const saved = localStorage.getItem(STORAGE_KEY);
646
+ if (saved) {
647
+ try {
648
+ STATE.progress = JSON.parse(saved);
649
+ } catch (e) {
650
+ console.error("Save Corrupt");
651
+ }
652
+ }
653
+ }
654
+ function saveProgress() {
655
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(STATE.progress));
656
+ }
657
+ // --- Engine Initialization ---
658
+ function initPhysics() {
659
+ const container = document.getElementById("canvas-container");
660
+ STATE.engine = Matter.Engine.create();
661
+ STATE.engine.world.gravity.y = 1;
662
+ STATE.engine.timing.timeScale = 0.5;
663
+ STATE.render = Matter.Render.create({
664
+ element: container,
665
+ engine: STATE.engine,
666
+ options: {
667
+ width: CONFIG.width,
668
+ height: CONFIG.height,
669
+ wireframes: false,
670
+ background: CONFIG.colors.background,
671
+ pixelRatio: window.devicePixelRatio,
672
+ showAngleIndicator: false,
673
+ },
674
+ });
675
+ Matter.Events.on(STATE.render, "afterRender", function () {
676
+ const context = STATE.render.context;
677
+ const width = STATE.render.options.width;
678
+ const height = STATE.render.options.height;
679
+ // Grid
680
+ context.beginPath();
681
+ context.strokeStyle = "rgba(0, 0, 0, 0.1)";
682
+ context.lineWidth = 1;
683
+ context.font = "bold 10px 'Fira Code'";
684
+ context.fillStyle = "rgba(0, 0, 0, 0.3)";
685
+ context.textAlign = "center";
686
+ for (let i = 0; i <= CONFIG.gridWidth; i++) {
687
+ const x = (width * i) / CONFIG.gridWidth;
688
+ context.moveTo(x, 0);
689
+ context.lineTo(x, height);
690
+ if (i > 0 && i < CONFIG.gridWidth) context.fillText(i, x, 15);
691
+ }
692
+ for (let i = 0; i <= CONFIG.gridHeight; i++) {
693
+ const y = (height * i) / CONFIG.gridHeight;
694
+ context.moveTo(0, y);
695
+ context.lineTo(width, y);
696
+ if (i > 0 && i < CONFIG.gridHeight) context.fillText(i, 15, y + 4);
697
+ }
698
+ context.stroke();
699
+ // Custom Objects
700
+ if (!STATE.isPlaying && !STATE.isFinished) {
701
+ context.font = "bold 14px 'Fira Code', monospace";
702
+ context.textAlign = "center";
703
+ context.textBaseline = "middle";
704
+ STATE.plannedActions.forEach((action) => {
705
+ if (action.previewBody) {
706
+ const body = action.previewBody;
707
+ const x = body.position.x;
708
+ const y = body.position.y;
709
+ if (action.delay > 0) {
710
+ context.fillStyle = "rgba(0, 0, 0, 0.7)";
711
+ context.fillText(`in ${action.delay}s`, x, body.bounds.max.y + 20);
712
+ }
713
+ if (action.params.velocity) {
714
+ const vx = action.params.velocity[0],
715
+ vy = action.params.velocity[1];
716
+ drawVelocityArrow(context, x, y, vx, vy, "#ef4444");
717
+ }
718
+ }
719
+ });
720
+ // Draw velocity arrows for any dynamic body in the world (Level setup items)
721
+ Matter.Composite.allBodies(STATE.engine.world).forEach((body) => {
722
+ // Skip planned action previews
723
+ if (STATE.plannedActions.some((a) => a.previewBody === body)) return;
724
+ const vx = body.velocity.x || 0;
725
+ const vy = body.velocity.y || 0;
726
+ if (Math.hypot(vx, vy) > 0.1) {
727
+ let color = body.render.fillStyle;
728
+ // Use red for dark objects (enemies), otherwise use body color
729
+ if (color === "#333" || color === CONFIG.colors.wall) color = "#ef4444";
730
+ drawVelocityArrow(context, body.position.x, body.position.y, vx, vy, color);
731
+ }
732
+ });
733
+ }
734
+ // Goal Zone
735
+ const bodies = Matter.Composite.allBodies(STATE.engine.world);
736
+ bodies.forEach((body) => {
737
+ if (body.label === "GoalZone") {
738
+ const bounds = body.bounds;
739
+ const w = bounds.max.x - bounds.min.x;
740
+ const h = bounds.max.y - bounds.min.y;
741
+ const cx = (bounds.min.x + bounds.max.x) / 2;
742
+ const cy = (bounds.min.y + bounds.max.y) / 2;
743
+ context.save();
744
+ context.translate(cx, cy);
745
+ context.beginPath();
746
+ context.rect(-w / 2, -h / 2, w, h);
747
+ context.strokeStyle = "#4ade80";
748
+ context.lineWidth = 3;
749
+ context.setLineDash([15, 10]);
750
+ context.stroke();
751
+ context.fillStyle = "#1a1a1a";
752
+ context.fillRect(-2, -20, 4, 40);
753
+ context.beginPath();
754
+ context.moveTo(2, -20);
755
+ context.lineTo(25, -10);
756
+ context.lineTo(2, 0);
757
+ context.fill();
758
+ context.font = "bold 14px 'Space Grotesk'";
759
+ context.textAlign = "center";
760
+ context.fillText("GOAL", 0, 35);
761
+ context.restore();
762
+ }
763
+ });
764
+ });
765
+ const canvas = STATE.render.canvas;
766
+ canvas.style.border = "3px solid black";
767
+ const resizeCanvas = () => {
768
+ const cw = container.clientWidth - 40;
769
+ const ch = container.clientHeight - 40;
770
+ const tr = CONFIG.width / CONFIG.height;
771
+ const cr = cw / ch;
772
+ if (cr > tr) {
773
+ canvas.style.height = `${ch}px`;
774
+ canvas.style.width = `${ch * tr}px`;
775
+ } else {
776
+ canvas.style.width = `${cw}px`;
777
+ canvas.style.height = `${cw / tr}px`;
778
+ }
779
+ };
780
+ const resizeObserver = new ResizeObserver(() => {
781
+ window.requestAnimationFrame(() => resizeCanvas());
782
+ });
783
+ resizeObserver.observe(container);
784
+ window.requestAnimationFrame(() => resizeCanvas());
785
+ STATE.runner = Matter.Runner.create({ isFixed: true, delta: 1000 / 60 });
786
+ Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
787
+ Matter.Render.run(STATE.render);
788
+ }
789
+ function drawVelocityArrow(context, x, y, vx, vy, color) {
790
+ if (vx === 0 && vy === 0) return;
791
+ const speed = Math.hypot(vx, vy);
792
+ const arrowScale = 20;
793
+ const maxLength = 150;
794
+ const rawLen = speed * arrowScale;
795
+ const scaleFactor = Math.min(rawLen, maxLength) / speed;
796
+ const endX = x + vx * scaleFactor;
797
+ const endY = y + vy * scaleFactor;
798
+ context.beginPath();
799
+ context.moveTo(x, y);
800
+ context.lineTo(endX, endY);
801
+ context.strokeStyle = color;
802
+ context.lineWidth = 3;
803
+ context.stroke();
804
+ const angle = Math.atan2(endY - y, endX - x);
805
+ const headLen = 12;
806
+ context.beginPath();
807
+ context.moveTo(endX, endY);
808
+ context.lineTo(endX - headLen * Math.cos(angle - Math.PI / 6), endY - headLen * Math.sin(angle - Math.PI / 6));
809
+ context.lineTo(endX - headLen * Math.cos(angle + Math.PI / 6), endY - headLen * Math.sin(angle + Math.PI / 6));
810
+ context.lineTo(endX, endY);
811
+ context.fillStyle = color;
812
+ context.fill();
813
+ context.fillStyle = color;
814
+ context.font = "bold 12px 'Fira Code', monospace";
815
+ context.textAlign = "center";
816
+ context.fillText(`${speed.toFixed(1)}`, endX + (vx / speed) * 15, endY + (vy / speed) * 15);
817
+ }
818
+ function handleUpdate() {
819
+ if (!STATE.isPlaying || STATE.isFinished) return;
820
+ STATE.time = performance.now() - STATE.startTime;
821
+ document.getElementById("timer-display").innerText = (STATE.time / 1000).toFixed(2) + "s";
822
+ STATE.eventQueue
823
+ .filter((e) => e.delay <= STATE.time && !e.executed)
824
+ .forEach((e) => {
825
+ e.action();
826
+ e.executed = true;
827
+ });
828
+ if (STATE.winCondition && STATE.winCondition()) endGame(true);
829
+ }
830
+ function loadLevel(index) {
831
+ if (STATE.runner) Matter.Runner.stop(STATE.runner);
832
+ document.getElementById("view-menu").classList.add("hidden");
833
+ document.getElementById("view-game").classList.remove("hidden");
834
+ document.getElementById("view-game").classList.add("flex");
835
+ STATE.currentLevelIndex = index;
836
+ const level = LEVELS[index];
837
+ const diffs = ["", "EASY", "MEDIUM", "HARD", "EXTREME"];
838
+ const diffColors = ["", "bg-neo-green", "bg-neo-yellow", "bg-neo-red", "bg-neo-purple"];
839
+ const d = level.difficulty || 1;
840
+ 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>`;
841
+ document.getElementById("level-title").innerText = level.title;
842
+ document.getElementById("level-desc").innerText = level.desc;
843
+ document.getElementById("level-hint-text").innerText = level.hint;
844
+ document.getElementById("star-reqs").innerText = `3★ < ${level.stars[0] + 1} items`;
845
+ document.getElementById("hint-content").classList.add("hidden");
846
+ resetSimulationState();
847
+ document.getElementById("code-input").value = "";
848
+ const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});
849
+ STATE.currentBall = ball;
850
+ STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;
851
+ Matter.Render.world(STATE.render);
852
+ }
853
+ function resetSimulationState() {
854
+ Matter.Composite.clear(STATE.engine.world);
855
+ STATE.engine.events = {};
856
+ Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
857
+ STATE.plannedActions = [];
858
+ STATE.eventQueue = [];
859
+ STATE.time = 0;
860
+ STATE.isFinished = false;
861
+ STATE.isPlaying = false;
862
+ STATE.currentBall = null;
863
+ document.getElementById("timer-display").innerText = "0.00s";
864
+ document.getElementById("win-message").style.display = "none";
865
+ document.getElementById("error-log").classList.add("hidden");
866
+ document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;
867
+ updateActionList();
868
+ }
869
+ function endGame(success) {
870
+ STATE.isFinished = true;
871
+ STATE.isPlaying = false;
872
+ Matter.Runner.stop(STATE.runner);
873
+ if (success) {
874
+ document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black"></div> COMPLETE`;
875
+ const used = STATE.plannedActions.length;
876
+ const level = LEVELS[STATE.currentLevelIndex];
877
+ let stars = 1;
878
+ if (used <= level.stars[0]) stars = 3;
879
+ else if (used <= level.stars[1]) stars = 2;
880
+ if (stars > (STATE.progress.stars[level.id] || 0)) STATE.progress.stars[level.id] = stars;
881
+ if (STATE.currentLevelIndex >= STATE.progress.unlockedIndex && STATE.currentLevelIndex < LEVELS.length - 1) {
882
+ STATE.progress.unlockedIndex = STATE.currentLevelIndex + 1;
883
+ }
884
+ saveProgress();
885
+ const starContainer = document.getElementById("result-stars");
886
+ starContainer.innerHTML = "";
887
+ for (let i = 0; i < 3; i++) {
888
+ const filled = i < stars;
889
+ starContainer.innerHTML += `<i class="fas fa-star ${filled ? "text-yellow-400" : "text-gray-600"}"></i>`;
890
+ }
891
+ document.getElementById("result-items").innerText = used;
892
+ const btnNext = document.getElementById("btn-next-level");
893
+ if (STATE.currentLevelIndex >= LEVELS.length - 1) {
894
+ // Update Max
895
+ btnNext.style.display = "none";
896
+ } else {
897
+ btnNext.style.display = "inline-block";
898
+ btnNext.onclick = () => loadLevel(STATE.currentLevelIndex + 1);
899
+ }
900
+ document.getElementById("win-message").style.display = "flex";
901
+ }
902
+ }
903
+ function updateActionList() {
904
+ const list = document.getElementById("action-list");
905
+ list.innerHTML = "";
906
+ if (STATE.plannedActions.length === 0) {
907
+ list.innerHTML = `<div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>`;
908
+ return;
909
+ }
910
+ STATE.plannedActions.forEach((action, index) => {
911
+ const div = document.createElement("div");
912
+ 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";
913
+
914
+ const p = action.params;
915
+ const details = [];
916
+ if (p.size !== 1) details.push(`size:${p.size}`);
917
+ if (p.weight !== 1) details.push(`mass:${p.weight}`);
918
+ if (p.restitution !== 0) details.push(`bounce:${p.restitution}`);
919
+ if (p.angle !== 0) details.push(`angle:${p.angle}°`);
920
+ if (p.velocity && (p.velocity[0] !== 0 || p.velocity[1] !== 0)) details.push(`v:[${p.velocity}]`);
921
+ if (p.isStatic !== (p.shape === 'line')) details.push(p.isStatic ? 'static' : 'dynamic');
922
+ if (p.delay > 0) details.push(`delay:${p.delay}s`);
923
+ const typeName = p.shape;
924
+ const color = p.color || "#000";
925
+ div.innerHTML = `
926
+ <div class="flex items-center gap-2">
927
+ <div class="w-3 h-3 border border-black" style="background-color: ${color}"></div>
928
+ <div class="flex flex-col">
929
+ <div class="flex items-center gap-2">
930
+ <span class="text-xs font-bold uppercase">${typeName}</span>
931
+ <span class="text-[10px] text-gray-500 font-mono">@ [${p.location[0]}, ${p.location[1]}]</span>
932
+ </div>
933
+ ${details.length > 0 ? `<div class="text-[9px] text-gray-400 font-mono leading-tight uppercase">${details.join(' | ')}</div>` : ''}
934
+ </div>
935
+ </div>
936
+ `;
937
+ const btnDelete = document.createElement("button");
938
+ 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";
939
+ btnDelete.innerHTML = `<i class="fas fa-times text-xs"></i>`;
940
+ btnDelete.onclick = () => removeAction(index);
941
+ div.appendChild(btnDelete);
942
+ list.appendChild(div);
943
+ });
944
+ }
945
+ function removeAction(index) {
946
+ const action = STATE.plannedActions[index];
947
+ if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
948
+ STATE.plannedActions.splice(index, 1);
949
+ updateActionList();
950
+ }
951
+ function createBody(shape, x, y, pixelSize, options) {
952
+ switch (shape) {
953
+ case "circle":
954
+ case "ball":
955
+ return Matter.Bodies.circle(x, y, pixelSize / 2, options);
956
+ case "triangle":
957
+ return Matter.Bodies.polygon(x, y, 3, pixelSize / 1.5, options);
958
+ case "line":
959
+ const thickness = 5;
960
+ return Matter.Bodies.rectangle(x, y, pixelSize, thickness, options);
961
+ default: // square, rectangle, etc.
962
+ return Matter.Bodies.rectangle(x, y, pixelSize, pixelSize, options);
963
+ }
964
+ }
965
+ // --- UNIFIED TOOL IMPLEMENTATION ---
966
+ const Tools = {
967
+ add: (params) => {
968
+ let {
969
+ shape = "square",
970
+ location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2],
971
+ size = 1,
972
+ color = CONFIG.colors.userShape,
973
+ mass = 1,
974
+ weight = params.weight || mass,
975
+ delay = 0,
976
+ restitution = 0,
977
+ friction = 0.1,
978
+ rotation = 0,
979
+ angle = params.angle || rotation,
980
+ velocity = [0, 0],
981
+ static: isStaticParam,
982
+ isStatic = params.isStatic !== undefined ? params.isStatic : (isStaticParam !== undefined ? isStaticParam : ["platform", "line"].includes(shape)),
983
+ } = params;
984
+ // Handle location as string (comma-separated or descriptive)
985
+ if (typeof location === 'string') {
986
+ const parts = location.match(/\d+/g);
987
+ if (parts && parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
988
+ location = [parseFloat(parts[0]), parseFloat(parts[1])];
989
+ } else {
990
+ const loc = location.toLowerCase();
991
+ const midX = CONFIG.gridWidth / 2;
992
+ const midY = CONFIG.gridHeight / 2;
993
+ const margin = 2;
994
+ const locations = {
995
+ "center": [midX, midY],
996
+ "top-left": [margin, margin],
997
+ "top-center": [midX, margin],
998
+ "top-right": [CONFIG.gridWidth - margin, margin],
999
+ "center-left": [margin, midY],
1000
+ "center": [midX, midY],
1001
+ "center-right": [CONFIG.gridWidth - margin, midY],
1002
+ "bottom-left": [margin, CONFIG.gridHeight - margin],
1003
+ "bottom-center": [midX, CONFIG.gridHeight - margin],
1004
+ "bottom-right": [CONFIG.gridWidth - margin, CONFIG.gridHeight - margin],
1005
+ };
1006
+ location = locations[loc] || [midX, midY];
1007
+ }
1008
+ }
1009
+ // Ensure location is an array
1010
+ if (!Array.isArray(location) || location.length !== 2) {
1011
+ console.warn("Invalid location format. Defaulting to center.");
1012
+ location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2];
1013
+ }
1014
+ const finalParams = {
1015
+ shape,
1016
+ location,
1017
+ size,
1018
+ color,
1019
+ weight,
1020
+ delay,
1021
+ restitution,
1022
+ friction,
1023
+ angle,
1024
+ velocity,
1025
+ isStatic,
1026
+ };
1027
+ const x = pX(location[0]);
1028
+ const y = pY(location[1]);
1029
+ const pixelSize = pX(size); // Use grid-relative sizing
1030
+ const commonProps = {
1031
+ angle: (angle * Math.PI) / 180,
1032
+ restitution: restitution,
1033
+ friction: friction,
1034
+ render: { fillStyle: color, ...strokeStyle },
1035
+ density: weight * 0.005,
1036
+ };
1037
+ // For preview (ghosts)
1038
+ const previewProps = {
1039
+ ...commonProps,
1040
+ isStatic: true,
1041
+ isSensor: true,
1042
+ render: {
1043
+ fillStyle: color,
1044
+ opacity: 0.4,
1045
+ strokeStyle: "#000000",
1046
+ lineWidth: 2,
1047
+ },
1048
+ };
1049
+ const body = createBody(shape, x, y, pixelSize, previewProps);
1050
+ Matter.World.add(STATE.engine.world, body);
1051
+ STATE.plannedActions.push({
1052
+ type: "add",
1053
+ params: finalParams, // Use the complete object
1054
+ delay: delay || 0,
1055
+ previewBody: body,
1056
+ });
1057
+ },
1058
+ };
1059
+ // --- AI Model Setup ---
1060
+ const MODEL_ID = "Xenova/functiongemma-270m-game";
1061
+ let tokenizer, model;
1062
+ 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."}}}];
1063
+ async function initModel() {
1064
+ try {
1065
+ const loadStart = performance.now();
1066
+ console.log("⏱️ Starting model load...");
1067
+
1068
+ tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID);
1069
+ model = await AutoModelForCausalLM.from_pretrained(MODEL_ID, {
1070
+ device: "webgpu",
1071
+ dtype: "q4",
1072
+ });
1073
+
1074
+ const loadEnd = performance.now();
1075
+ STATE.modelCompilationTime = loadEnd - loadStart;
1076
+ console.log(`✅ Model loaded in ${STATE.modelCompilationTime.toFixed(2)}ms (${(STATE.modelCompilationTime / 1000).toFixed(2)}s)`);
1077
+
1078
+ // Update UI
1079
+ document.getElementById("metric-compilation").innerText = `${(STATE.modelCompilationTime / 1000).toFixed(2)}s`;
1080
+ document.getElementById("loading-overlay").classList.add("hidden");
1081
+ } catch (e) {
1082
+ console.error(e);
1083
+ document.getElementById("loading-overlay").innerHTML = `<div class="text-red-500 font-bold p-4 bg-white border-2 border-black">Error: ${e.message}</div>`;
1084
+ }
1085
+ }
1086
+ // --- Command Execution ---
1087
+ async function executeCommand() {
1088
+ const input = document.getElementById("code-input").value.trim();
1089
+ if (!input) return;
1090
+ const btn = document.getElementById("btn-execute");
1091
+ const errorLog = document.getElementById("error-log");
1092
+ // UI Loading State
1093
+ btn.disabled = true;
1094
+ btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> THINKING...`;
1095
+ errorLog.classList.add("hidden");
1096
+ const systemPrompt = `You are a model that can do function calling with the following functions`;
1097
+ try {
1098
+ const lines = input.split('\n').map(l => l.trim()).filter(l => l.length > 0 && !l.startsWith("//"));
1099
+ for (const line of lines) {
1100
+ // 2. Prepare Messages
1101
+ const messages = [
1102
+ { role: "developer", content: systemPrompt },
1103
+ { role: "user", content: line },
1104
+ ];
1105
+ // 3. Apply Template
1106
+ const inputs = tokenizer.apply_chat_template(messages, {
1107
+ tools: TOOL_SCHEMA,
1108
+ tokenize: true,
1109
+ add_generation_prompt: true,
1110
+ return_dict: true,
1111
+ });
1112
+
1113
+ // 4. Generate with performance tracking
1114
+ const generationStart = performance.now();
1115
+ let ttftRecorded = false;
1116
+ let ttft = 0;
1117
+
1118
+ const output = await model.generate({
1119
+ ...inputs,
1120
+ max_new_tokens: 128,
1121
+ do_sample: false,
1122
+ callback_function: (tokens) => {
1123
+ // Record TTFT on first token
1124
+ if (!ttftRecorded && tokens.length > 0) {
1125
+ ttft = performance.now() - generationStart;
1126
+ ttftRecorded = true;
1127
+ console.log(`⚡ Time to First Token (TTFT): ${ttft.toFixed(2)}ms`);
1128
+ }
1129
+ }
1130
+ });
1131
+
1132
+ const generationEnd = performance.now();
1133
+ const totalTime = generationEnd - generationStart;
1134
+ const inputTokenCount = inputs.input_ids.dims[1];
1135
+ const totalTokenCount = output.dims ? output.dims[1] : output.size;
1136
+ const outputTokenCount = Math.max(0, totalTokenCount - inputTokenCount);
1137
+ const tps = outputTokenCount / (totalTime / 1000);
1138
+
1139
+ // Store and display metrics
1140
+ STATE.lastTTFT = ttft;
1141
+ STATE.lastTPS = tps;
1142
+ console.log(`📊 Performance: TTFT=${ttft.toFixed(0)}ms, TPS=${tps.toFixed(1)} tok/s`);
1143
+ document.getElementById("metric-ttft").innerText = `${ttft.toFixed(0)}ms`;
1144
+ document.getElementById("metric-tps").innerText = `${tps.toFixed(1)} t/s`;
1145
+
1146
+ const decoded = tokenizer.decode(output.slice(0, [inputs.input_ids.dims[1], null]), { skip_special_tokens: false });
1147
+ // 5. Parse Output
1148
+ // Format: <start_function_call>call:add{...}<end_function_call>
1149
+ const startTag = "<start_function_call>";
1150
+ const endTag = "<end_function_call>";
1151
+ const startIndex = decoded.indexOf(startTag);
1152
+ const endIndex = decoded.indexOf(endTag);
1153
+ if (startIndex !== -1 && endIndex !== -1) {
1154
+ let callStr = decoded.substring(startIndex + startTag.length, endIndex);
1155
+ if (callStr.startsWith("call:add")) {
1156
+ // Extract JSON-like string: {location:[...],shape:<escape>...<escape>}
1157
+ let argsStr = callStr.substring(callStr.indexOf("{"));
1158
+ // Sanitize to valid JSON
1159
+ argsStr = argsStr
1160
+ .replace(/<escape>(.*?)<escape>/g, '"$1"') // Handle string escapes
1161
+ .replace(/(\w+):/g, '"$1":'); // Quote keys
1162
+ const args = JSON.parse(argsStr);
1163
+ Tools.add(args);
1164
+ } else {
1165
+ throw new Error("Model did not generate a valid add command.");
1166
+ }
1167
+ } else {
1168
+ throw new Error(`Could not understand command: "${line}"`);
1169
+ }
1170
+ }
1171
+ document.getElementById("code-input").value = "";
1172
+ } catch (err) {
1173
+ errorLog.innerText = err.message;
1174
+ errorLog.classList.remove("hidden");
1175
+ console.error(err);
1176
+ } finally {
1177
+ btn.disabled = false;
1178
+ btn.innerHTML = `<i class="fas fa-terminal"></i> EXECUTE`;
1179
+ updateActionList();
1180
+ }
1181
+ }
1182
+ // --- Real Simulation Run ---
1183
+ function runSimulation() {
1184
+ if (STATE.runner) Matter.Runner.stop(STATE.runner);
1185
+ const storedActions = [...STATE.plannedActions];
1186
+ const level = LEVELS[STATE.currentLevelIndex];
1187
+ Matter.Composite.clear(STATE.engine.world);
1188
+ STATE.engine.events = {};
1189
+ Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
1190
+ STATE.eventQueue = [];
1191
+ STATE.isFinished = false;
1192
+ const addEvent = (delay, action) => {
1193
+ STATE.eventQueue.push({
1194
+ delay: delay * 1000,
1195
+ action: action,
1196
+ executed: false,
1197
+ });
1198
+ };
1199
+ const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, addEvent);
1200
+ STATE.currentBall = ball;
1201
+ STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;
1202
+ // Real Action Executioner
1203
+ const executeReal = (params) => {
1204
+ const { shape, location, size, weight, restitution, friction, angle, velocity, isStatic } = params;
1205
+ const x = pX(location[0]),
1206
+ y = pY(location[1]);
1207
+ const pixelSize = pX(size);
1208
+ const props = {
1209
+ angle: (angle * Math.PI) / 180,
1210
+ restitution,
1211
+ friction,
1212
+ isStatic,
1213
+ render: strokeStyle,
1214
+ density: weight * 0.005,
1215
+ };
1216
+ const body = createBody(shape, x, y, pixelSize, props);
1217
+ if (!isStatic && (velocity[0] !== 0 || velocity[1] !== 0)) {
1218
+ Matter.Body.setVelocity(body, { x: velocity[0], y: velocity[1] });
1219
+ }
1220
+ Matter.World.add(STATE.engine.world, body);
1221
+ };
1222
+ storedActions.forEach((action) => {
1223
+ STATE.eventQueue.push({
1224
+ delay: action.delay * 1000,
1225
+ action: () => executeReal(action.params),
1226
+ executed: false,
1227
+ });
1228
+ });
1229
+ STATE.plannedActions = storedActions;
1230
+ STATE.isPlaying = true;
1231
+ STATE.startTime = performance.now();
1232
+ document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black animate-ping"></div> RUNNING`;
1233
+ Matter.Runner.run(STATE.runner, STATE.engine);
1234
+ }
1235
+ function renderMenu() {
1236
+ if (STATE.runner) Matter.Runner.stop(STATE.runner);
1237
+ document.getElementById("view-game").classList.add("hidden");
1238
+ document.getElementById("view-game").classList.remove("flex");
1239
+ document.getElementById("view-menu").classList.remove("hidden");
1240
+ const grid = document.getElementById("level-grid");
1241
+ grid.innerHTML = "";
1242
+ LEVELS.forEach((level, index) => {
1243
+ const unlocked = index <= STATE.progress.unlockedIndex;
1244
+ const stars = STATE.progress.stars[index] || 0;
1245
+ const card = document.createElement("div");
1246
+ 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"}`;
1247
+ if (unlocked) {
1248
+ card.onclick = () => loadLevel(index);
1249
+ card.innerHTML = `
1250
+ <div class="text-3xl font-black">${index + 1}</div>
1251
+ <div class="flex gap-1 text-xs">
1252
+ ${Array(3)
1253
+ .fill(0)
1254
+ .map((_, i) => `<i class="fas fa-star ${i < stars ? "text-neo-yellow" : "text-gray-300"}"></i>`)
1255
+ .join("")}
1256
+ </div>
1257
+ `;
1258
+ } else {
1259
+ card.innerHTML = `<i class="fas fa-lock text-gray-400 text-2xl"></i>`;
1260
+ }
1261
+ grid.appendChild(card);
1262
+ });
1263
+ }
1264
+ // --- Bindings ---
1265
+ document.getElementById("btn-execute").onclick = executeCommand;
1266
+ document.getElementById("btn-play").onclick = runSimulation;
1267
+ document.getElementById("btn-reset").onclick = () => {
1268
+ Matter.Runner.stop(STATE.runner);
1269
+ const level = LEVELS[STATE.currentLevelIndex];
1270
+ Matter.Composite.clear(STATE.engine.world);
1271
+ const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});
1272
+ STATE.currentBall = ball;
1273
+ STATE.plannedActions.forEach((action) => {
1274
+ Matter.World.add(STATE.engine.world, action.previewBody);
1275
+ });
1276
+ STATE.isPlaying = false;
1277
+ document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;
1278
+ document.getElementById("timer-display").innerText = "0.00s";
1279
+ document.getElementById("win-message").style.display = "none";
1280
+ };
1281
+ document.getElementById("btn-clear-all").onclick = () => {
1282
+ document.getElementById("code-input").value = "";
1283
+ STATE.plannedActions.forEach((action) => {
1284
+ if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
1285
+ });
1286
+ STATE.plannedActions = [];
1287
+ updateActionList();
1288
+ document.getElementById("btn-reset").click();
1289
+ };
1290
+ document.getElementById("btn-back").onclick = renderMenu;
1291
+ document.getElementById("btn-hint").onclick = () => {
1292
+ const content = document.getElementById("hint-content");
1293
+ content.classList.toggle("hidden");
1294
+ };
1295
+ document.getElementById("btn-solution").addEventListener("click", () => {
1296
+ const level = LEVELS[STATE.currentLevelIndex];
1297
+ if (level.solution) {
1298
+ document.getElementById("code-input").value = level.solution;
1299
+ }
1300
+ });
1301
+ window.onload = () => {
1302
+ loadProgress();
1303
+ initPhysics();
1304
+ renderMenu();
1305
+ initModel();
1306
+ };
1307
+ </script>
1308
+ </body>
1309
+
1310
+ </html>