BlueGit

projects-timfalken-com meteors

Merge branch 'feature/ui'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
72918a2fb3bccbfd7f0e4b1a678dec8322dddb15
4 files changed +2520 −0
build/game.js added +1874 −0
@@ -0,0 +1,1874 @@
1 /*
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 * Built by src/build.sh from the sources in src/.
4 */
5
6 /*
7 * Start File:
8 * /workspace/meteors/src/rng.js
9 */
10 'use strict';
11
12 /**
13 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
14 * and (later) for multiplayer replays.
15 */
16 function createRng (seed)
17 {
18 var a = (seed >>> 0) || 1;
19 return function rng ()
20 {
21 a |= 0;
22 a = a + 0x6D2B79F5 | 0;
23 var t = Math.imul(a ^ a >>> 15, 1 | a);
24 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
25 return ((t ^ t >>> 14) >>> 0) / 4294967296;
26 };
27 }
28
29 function pickIndex (rng, count)
30 {
31 var n = count | 0;
32 if (n <= 0)
33 { return 0; }
34 return Math.floor(rng() * n) % n;
35 }
36
37 function pickFrom (rng, list)
38 {
39 if (!list || !list.length)
40 { return undefined; }
41 return list[pickIndex(rng, list.length)];
42 }
43
44 var Rng = {
45 create: createRng,
46 pickIndex: pickIndex,
47 pickFrom: pickFrom
48 };
49
50 if (typeof module !== 'undefined' && module.exports)
51 { module.exports = Rng; }
52 else if (typeof globalThis !== 'undefined')
53 { globalThis.Rng = Rng; }
54
55 /*
56 * End File:
57 * /workspace/meteors/src/rng.js
58 */
59
60 /*
61 * Start File:
62 * /workspace/meteors/src/planet.js
63 */
64 'use strict';
65
66 /**
67 * Planet physics and visuals for Meteors.
68 *
69 * Stage 1 uses a single default planet. Stage 3 lets the player pick a
70 * planet; the numbers and jump-height rules are already applied here so
71 * that later planets only need new data, not new physics code.
72 *
73 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
74 * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
75 * at 1, one jump from the floor clears the field; at 4, you need four.
76 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
77 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
78 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
79 * Time to reach the apex, independent of jump height.
80 *
81 * Jump-height multipliers (never explained in the game):
82 * A vertical match of 3 is 120 % of a horizontal row of 3.
83 * Each extra block beyond 3 adds 5 %.
84 *
85 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
86 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
87 * power 0 to 5 % at power 1.
88 */
89
90 var FIELD_WIDTH = 10;
91 var FIELD_HEIGHT = 13;
92
93 function clamp (value, lo, hi)
94 {
95 return Math.max(lo, Math.min(hi, value));
96 }
97
98 function defaultColors ()
99 {
100 return [
101 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
102 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
103 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
104 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
105 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
106 ];
107 }
108
109 function createPlanet (opts)
110 {
111 opts = opts || {};
112 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
113 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
114 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
115 var colors = opts.colors || defaultColors();
116 var planet = {
117 name: opts.name || 'Terra',
118 people: opts.people || 'Terrans',
119 jumpsToClear: jumpsToClear,
120 fallTime: fallTime,
121 riseTime: riseTime,
122 colors: colors,
123 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
124 fallSpeed: FIELD_HEIGHT / fallTime
125 };
126 return planet;
127 }
128
129 function defaultPlanet ()
130 {
131 return createPlanet({
132 name: 'Terra',
133 people: 'Terrans',
134 jumpsToClear: 2,
135 fallTime: 3,
136 riseTime: 1.5
137 });
138 }
139
140 /**
141 * Jump height in tiles for a match line.
142 * @param {object} planet
143 * @param {number} matchLength number of blocks in the line (>= 3)
144 * @param {boolean} vertical true for a vertical line
145 */
146 function jumpHeight (planet, matchLength, vertical)
147 {
148 var extra = Math.max(0, (matchLength | 0) - 3);
149 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
150 return planet.baseJumpHeight * multiplier;
151 }
152
153 /** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
154 function launchVelocity (planet, height)
155 {
156 if (height <= 0)
157 { return 0; }
158 return (2 * height) / planet.riseTime;
159 }
160
161 /** Constant deceleration (tiles/s^2) paired with launchVelocity. */
162 function launchDeceleration (planet, height)
163 {
164 if (height <= 0)
165 { return 0; }
166 return (2 * height) / (planet.riseTime * planet.riseTime);
167 }
168
169 /**
170 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
171 * chance that a shot-off block misses the opponent).
172 */
173 function power (planet)
174 {
175 var gravity = (planet.jumpsToClear - 1) / 3;
176 var air = (5 - planet.fallTime) / 4;
177 var mass = (3 - planet.riseTime) / 2.5;
178 return (gravity + air + mass) / 3;
179 }
180
181 /** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
182 function missChance (planet)
183 {
184 return 0.60 - 0.55 * power(planet);
185 }
186
187 /**
188 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
189 * launch force (N), and power as a percentage. The numbers do not have to
190 * explain themselves.
191 */
192 function displayValues (planet)
193 {
194 var gravity = 9.81 * planet.jumpsToClear / 2;
195 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
196 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
197 return {
198 gravity: gravity,
199 density: density,
200 newtons: newtons,
201 power: Math.round(power(planet) * 100),
202 missChance: missChance(planet)
203 };
204 }
205
206 var Planet = {
207 FIELD_WIDTH: FIELD_WIDTH,
208 FIELD_HEIGHT: FIELD_HEIGHT,
209 COLOR_COUNT: 5,
210 SETTLE_TIME: 3,
211 SPAWN_INTERVAL: 1,
212 JUMP_VERTICAL_BONUS: 1.2,
213 JUMP_EXTRA_BLOCK: 0.05,
214 createPlanet: createPlanet,
215 defaultPlanet: defaultPlanet,
216 defaultColors: defaultColors,
217 jumpHeight: jumpHeight,
218 launchVelocity: launchVelocity,
219 launchDeceleration: launchDeceleration,
220 power: power,
221 missChance: missChance,
222 displayValues: displayValues
223 };
224
225 if (typeof module !== 'undefined' && module.exports)
226 { module.exports = Planet; }
227 else if (typeof globalThis !== 'undefined')
228 { globalThis.Planet = Planet; }
229
230 /*
231 * End File:
232 * /workspace/meteors/src/planet.js
233 */
234
235 /*
236 * Start File:
237 * /workspace/meteors/src/gameCore.js
238 */
239 'use strict';
240
241 /**
242 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
243 * The view layer reads this state and translates pointer events into
244 * beginDrag / moveDrag / endDrag.
245 */
246
247 var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
248 ? require('./planet.js')
249 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
250
251 var COLOR_GRAY = -1;
252
253 var STATE_STILL = 'still';
254 var STATE_FALLING = 'falling';
255 var STATE_FLYING = 'flying';
256 var STATE_SETTLING = 'settling';
257 var STATE_LOCKED = 'locked';
258 var STATE_MANUAL = 'manual';
259
260 var ALIGN_EPS = 0.15;
261 var SUBSTEP = 1 / 120;
262 var DRAG_LAUNCH_SLACK = 0.65;
263
264 function UnionFind ()
265 {
266 this.parent = Object.create(null);
267 }
268
269 UnionFind.prototype.add = function (id)
270 {
271 if (this.parent[id] == null)
272 { this.parent[id] = id; }
273 };
274
275 UnionFind.prototype.find = function (id)
276 {
277 if (this.parent[id] !== id)
278 { this.parent[id] = this.find(this.parent[id]); }
279 return this.parent[id];
280 };
281
282 UnionFind.prototype.union = function (a, b)
283 {
284 this.add(a);
285 this.add(b);
286 var ra = this.find(a);
287 var rb = this.find(b);
288 if (ra !== rb)
289 { this.parent[rb] = ra; }
290 };
291
292 function GameCore (planet, rng)
293 {
294 this.planet = planet || PlanetMod.defaultPlanet();
295 this.rng = rng || Math.random;
296 this.width = PlanetMod.FIELD_WIDTH;
297 this.height = PlanetMod.FIELD_HEIGHT;
298 this.blocks = [];
299 this.clusters = Object.create(null);
300 this.nextBlockId = 1;
301 this.nextClusterId = 1;
302 this.spawnTimer = 0;
303 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
304 this.settleTime = PlanetMod.SETTLE_TIME;
305 this.score = 0;
306 this.state = 'playing';
307 this.drag = null;
308 this.gameOverTime = 0;
309 }
310
311 GameCore.COLOR_GRAY = COLOR_GRAY;
312 GameCore.STATE_STILL = STATE_STILL;
313 GameCore.STATE_FALLING = STATE_FALLING;
314 GameCore.STATE_FLYING = STATE_FLYING;
315 GameCore.STATE_SETTLING = STATE_SETTLING;
316 GameCore.STATE_LOCKED = STATE_LOCKED;
317 GameCore.STATE_MANUAL = STATE_MANUAL;
318
319 GameCore.prototype.randomColor = function ()
320 {
321 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
322 };
323
324 GameCore.prototype.createBlock = function (col, y, color, state)
325 {
326 var block = {
327 id: this.nextBlockId++,
328 col: col,
329 y: y,
330 color: color,
331 state: state || STATE_STILL,
332 vy: 0,
333 clusterId: null,
334 settleTime: 0,
335 flame: false,
336 pushedClusters: null,
337 manualTarget: 0,
338 manualDecel: 0,
339 manualPhase: null
340 };
341 this.blocks.push(block);
342 return block;
343 };
344
345 GameCore.prototype.removeBlock = function (block)
346 {
347 if (block.clusterId != null)
348 { this.leaveCluster(block); }
349 var index = this.blocks.indexOf(block);
350 if (index >= 0)
351 { this.blocks.splice(index, 1); }
352 };
353
354 GameCore.prototype.leaveCluster = function (block)
355 {
356 var id = block.clusterId;
357 block.clusterId = null;
358 block.flame = false;
359 if (id == null || !this.clusters[id])
360 { return; }
361 var still = 0;
362 for (var i = 0; i < this.blocks.length; i++)
363 {
364 if (this.blocks[i].clusterId === id)
365 { still++; }
366 }
367 if (still === 0)
368 { delete this.clusters[id]; }
369 };
370
371 GameCore.prototype.blocksInColumn = function (col)
372 {
373 var out = [];
374 for (var i = 0; i < this.blocks.length; i++)
375 {
376 if (this.blocks[i].col === col)
377 { out.push(this.blocks[i]); }
378 }
379 out.sort(function (a, b) { return a.y - b.y; });
380 return out;
381 };
382
383 GameCore.prototype.isGrounded = function (block)
384 {
385 return block.state === STATE_STILL
386 || block.state === STATE_SETTLING
387 || block.state === STATE_LOCKED;
388 };
389
390 GameCore.prototype.stackTop = function (col, ignore)
391 {
392 var top = 0;
393 for (var i = 0; i < this.blocks.length; i++)
394 {
395 var block = this.blocks[i];
396 if (block.col !== col)
397 { continue; }
398 if (ignore && ignore(block))
399 { continue; }
400 if (this.isGrounded(block))
401 {
402 var surface = block.y + 1;
403 if (surface > top)
404 { top = surface; }
405 }
406 }
407 return top;
408 };
409
410 GameCore.prototype.isColumnLocked = function (col)
411 {
412 for (var i = 0; i < this.blocks.length; i++)
413 {
414 var block = this.blocks[i];
415 if (block.col === col && block.state === STATE_LOCKED)
416 { return true; }
417 }
418 return false;
419 };
420
421 GameCore.prototype.isColumnStill = function (col)
422 {
423 if (this.isColumnLocked(col))
424 { return false; }
425 for (var i = 0; i < this.blocks.length; i++)
426 {
427 var block = this.blocks[i];
428 if (block.col !== col)
429 { continue; }
430 if (block.state === STATE_FLYING
431 || block.state === STATE_FALLING
432 || block.state === STATE_MANUAL
433 || block.state === STATE_SETTLING)
434 { return false; }
435 }
436 return true;
437 };
438
439 GameCore.prototype.groundedCount = function (col)
440 {
441 var n = 0;
442 for (var i = 0; i < this.blocks.length; i++)
443 {
444 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
445 { n++; }
446 }
447 return n;
448 };
449
450 GameCore.prototype.blockAt = function (col, row)
451 {
452 for (var i = 0; i < this.blocks.length; i++)
453 {
454 var block = this.blocks[i];
455 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
456 { return block; }
457 }
458 return null;
459 };
460
461 GameCore.prototype.place = function (col, row, color, state)
462 {
463 return this.createBlock(col, row, color, state || STATE_STILL);
464 };
465
466 GameCore.prototype.lockedColumnCount = function ()
467 {
468 var n = 0;
469 for (var c = 0; c < this.width; c++)
470 {
471 if (this.isColumnLocked(c))
472 { n++; }
473 }
474 return n;
475 };
476
477 GameCore.prototype.tick = function (dt)
478 {
479 if (this.state === 'gameover')
480 {
481 this.gameOverTime += Math.max(0, dt);
482 return;
483 }
484 if (dt <= 0)
485 { return; }
486 dt = Math.min(dt, 0.1);
487
488 this.spawnTimer += dt;
489 while (this.spawnTimer >= this.spawnInterval)
490 {
491 this.spawnTimer -= this.spawnInterval;
492 this.trySpawn();
493 }
494
495 var left = dt;
496 while (left > 1e-12)
497 {
498 var step = Math.min(SUBSTEP, left);
499 this.integrateFalling(step);
500 this.integrateClusters(step);
501 this.integrateManual(step);
502 this.cullOffTop();
503 left -= step;
504 }
505
506 this.advanceSettle(dt);
507 if (!this.drag)
508 { this.resolveMatches(); }
509 this.checkLocks();
510 this.checkGameOver();
511 };
512
513 /** Step a stretch of time in fixed substeps. Useful for tests. */
514 GameCore.prototype.step = function (seconds, dt)
515 {
516 dt = dt || SUBSTEP;
517 var t = 0;
518 while (t < seconds - 1e-15)
519 {
520 var s = Math.min(dt, seconds - t);
521 this.tick(s);
522 t += s;
523 }
524 };
525
526 GameCore.prototype.trySpawn = function ()
527 {
528 if (this.state !== 'playing')
529 { return null; }
530 var eligible = [];
531 for (var col = 0; col < this.width; col++)
532 {
533 if (this.isColumnLocked(col))
534 { continue; }
535 if (this.groundedCount(col) >= this.height)
536 { continue; }
537 var alreadyFalling = false;
538 var list = this.blocksInColumn(col);
539 for (var i = 0; i < list.length; i++)
540 {
541 if (list[i].state === STATE_FALLING)
542 {
543 alreadyFalling = true;
544 break;
545 }
546 }
547 if (!alreadyFalling)
548 { eligible.push(col); }
549 }
550 if (!eligible.length)
551 { return null; }
552 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
553 var color = this.randomColor();
554 return this.createBlock(col, this.height, color, STATE_FALLING);
555 };
556
557 GameCore.prototype.integrateFalling = function (dt)
558 {
559 var speed = this.planet.fallSpeed;
560 for (var i = 0; i < this.blocks.length; i++)
561 {
562 var block = this.blocks[i];
563 if (block.state !== STATE_FALLING)
564 { continue; }
565 var top = this.stackTop(block.col);
566 var nextY = block.y - speed * dt;
567 if (nextY <= top)
568 {
569 block.y = top;
570 block.state = STATE_STILL;
571 block.vy = 0;
572 }
573 else
574 { block.y = nextY; }
575 }
576 };
577
578 GameCore.prototype.clusterMembers = function (clusterId)
579 {
580 var out = [];
581 for (var i = 0; i < this.blocks.length; i++)
582 {
583 if (this.blocks[i].clusterId === clusterId)
584 { out.push(this.blocks[i]); }
585 }
586 return out;
587 };
588
589
590 /**
591 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
592 * jump of height H peaks at exactly H after riseTime. Returns dy.
593 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
594 * upward deceleration; falling uses planet.fallSpeed.
595 */
596 GameCore.prototype.advanceJump = function (body, dt)
597 {
598 var dy = 0;
599 var left = dt;
600 if (body.phase === 'up')
601 {
602 var decel = body.decel;
603 var vy = body.vy;
604 var tApex = decel > 1e-12 ? vy / decel : Infinity;
605 if (tApex <= left + 1e-15)
606 {
607 dy += vy * tApex - 0.5 * decel * tApex * tApex;
608 body.vy = 0;
609 body.phase = 'down';
610 left -= tApex;
611 }
612 else
613 {
614 var vyNew = vy - decel * left;
615 dy += (vy + vyNew) * 0.5 * left;
616 body.vy = vyNew;
617 left = 0;
618 }
619 }
620 if (body.phase === 'up' && body.vy <= 1e-10)
621 {
622 body.vy = 0;
623 body.phase = 'down';
624 }
625 if (body.phase === 'down' && left > 0)
626 {
627 body.vy = -this.planet.fallSpeed;
628 dy += body.vy * left;
629 }
630 return dy;
631 };
632
633 GameCore.prototype.integrateClusters = function (dt)
634 {
635 var ids = Object.keys(this.clusters);
636 for (var n = 0; n < ids.length; n++)
637 {
638 var cluster = this.clusters[ids[n]];
639 if (!cluster)
640 { continue; }
641 var members = this.clusterMembers(cluster.id);
642 if (!members.length)
643 {
644 delete this.clusters[cluster.id];
645 continue;
646 }
647 if (cluster.phase === 'landed' || cluster.phase === 'hold')
648 { continue; }
649
650 var dy = this.advanceJump(cluster, dt);
651 for (var i = 0; i < members.length; i++)
652 {
653 members[i].y += dy;
654 members[i].vy = cluster.vy;
655 }
656
657 if (cluster.phase === 'down')
658 { this.tryLandCluster(cluster, members); }
659 }
660 };
661
662 GameCore.prototype.tryLandCluster = function (cluster, members)
663 {
664 var self = this;
665 var hit = false;
666 for (var i = 0; i < members.length; i++)
667 {
668 var block = members[i];
669 var top = this.stackTop(block.col, function (other)
670 {
671 return other.clusterId === cluster.id;
672 });
673 if (block.y <= top + 1e-9)
674 { hit = true; }
675 }
676 if (!hit)
677 { return; }
678 this.landCluster(cluster, members);
679 };
680
681 GameCore.prototype.landCluster = function (cluster, members)
682 {
683 var byCol = Object.create(null);
684 for (var i = 0; i < members.length; i++)
685 {
686 var block = members[i];
687 if (!byCol[block.col])
688 { byCol[block.col] = []; }
689 byCol[block.col].push(block);
690 }
691 var cols = Object.keys(byCol);
692 for (var c = 0; c < cols.length; c++)
693 {
694 var col = +cols[c];
695 var list = byCol[col];
696 list.sort(function (a, b) { return a.y - b.y; });
697 var self = this;
698 var top = this.stackTop(col, function (other)
699 {
700 return other.clusterId === cluster.id;
701 });
702 for (var i = 0; i < list.length; i++)
703 {
704 var block = list[i];
705 block.y = top;
706 block.vy = 0;
707 block.flame = false;
708 top = block.y + 1;
709 if (block.color === COLOR_GRAY)
710 {
711 block.state = STATE_SETTLING;
712 block.settleTime = 0;
713 }
714 else
715 {
716 block.state = STATE_STILL;
717 block.clusterId = null;
718 }
719 }
720 }
721 cluster.phase = 'landed';
722 cluster.vy = 0;
723 var remaining = 0;
724 for (var i = 0; i < this.blocks.length; i++)
725 {
726 if (this.blocks[i].clusterId === cluster.id)
727 { remaining++; }
728 }
729 if (remaining === 0)
730 { delete this.clusters[cluster.id]; }
731 };
732
733 GameCore.prototype.integrateManual = function (dt)
734 {
735 for (var i = 0; i < this.blocks.length; i++)
736 {
737 var block = this.blocks[i];
738 if (block.state !== STATE_MANUAL)
739 { continue; }
740
741 if (block.manualPhase === 'up')
742 {
743 var oldY = block.y;
744 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
745 var dy = this.advanceJump(proxy, dt);
746 var nextY = oldY + dy;
747 this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
748 block.vy = proxy.vy;
749 block.manualPhase = proxy.phase;
750 block.y = Math.min(nextY, block.manualTarget);
751 if (block.y >= block.manualTarget - 1e-12)
752 {
753 block.y = block.manualTarget;
754 block.vy = 0;
755 block.manualPhase = 'down';
756 }
757 if (block.y > this.height - 1)
758 {
759 block.y = this.height - 1;
760 block.vy = 0;
761 block.manualPhase = 'down';
762 }
763 }
764
765 if (block.manualPhase === 'down')
766 {
767 var top = this.stackTop(block.col);
768 var nextY = block.y - this.planet.fallSpeed * dt;
769 if (nextY <= top)
770 {
771 block.y = top;
772 block.state = STATE_STILL;
773 block.vy = 0;
774 block.manualPhase = null;
775 block.flame = false;
776 }
777 else
778 {
779 block.y = Math.min(nextY, this.height - 1);
780 block.vy = -this.planet.fallSpeed;
781 }
782 }
783 }
784 };
785
786 GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
787 {
788 if (!manual.pushedClusters)
789 { manual.pushedClusters = Object.create(null); }
790
791 var manualTopOld = oldY + 1;
792 var manualTopNew = nextY + 1;
793 var low = Math.min(oldY, nextY);
794 var high = Math.max(oldY, nextY) + 1;
795
796 for (var i = 0; i < this.blocks.length; i++)
797 {
798 var other = this.blocks[i];
799 if (other === manual)
800 { continue; }
801 if (other.col !== manual.col)
802 { continue; }
803 if (other.state !== STATE_FLYING || other.clusterId == null)
804 { continue; }
805 if (manual.pushedClusters[other.clusterId])
806 { continue; }
807 var otherBot = other.y;
808 var otherTop = other.y + 1;
809 var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
810 var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
811 if (overlapping || crossing)
812 {
813 if (this.pushClusterColumn(other.clusterId, manual.col))
814 {
815 manual.pushedClusters[other.clusterId] = true;
816 return;
817 }
818 }
819 }
820 };
821
822
823 /**
824 * Push every flying block of the cluster that sits in `col` one tile up.
825 * Other columns stay put (they remain linked). Then look for a new
826 * same-color line of 3+ in the flying cluster; if there is one, those
827 * blocks turn gray, join the link, and the whole cluster re-launches
828 * with the same jump height from its current position.
829 */
830 GameCore.prototype.pushClusterColumn = function (clusterId, col)
831 {
832 var cluster = this.clusters[clusterId];
833 if (!cluster)
834 { return false; }
835 var members = this.clusterMembers(clusterId);
836 for (var i = 0; i < members.length; i++)
837 {
838 if (members[i].col === col)
839 { members[i].y += 1; }
840 }
841 this.cullOffTop();
842 if (!this.clusters[clusterId])
843 { return true; }
844 this.checkChainRelaunch(cluster);
845 return true;
846 };
847
848 GameCore.prototype.checkChainRelaunch = function (cluster)
849 {
850 if (!this.clusters[cluster.id])
851 { return; }
852 var lines = this.findFlyingMatchLines(cluster.id);
853 if (!lines.length)
854 { return; }
855 var newly = [];
856 var seen = Object.create(null);
857 for (var i = 0; i < lines.length; i++)
858 {
859 for (var j = 0; j < lines[i].blocks.length; j++)
860 {
861 var block = lines[i].blocks[j];
862 if (seen[block.id])
863 { continue; }
864 seen[block.id] = true;
865 newly.push(block);
866 }
867 }
868 for (var i = 0; i < newly.length; i++)
869 {
870 var block = newly[i];
871 block.color = COLOR_GRAY;
872 block.flame = true;
873 block.clusterId = cluster.id;
874 block.state = STATE_FLYING;
875 }
876 this.relaunchCluster(cluster, cluster.jumpHeight);
877 };
878
879 GameCore.prototype.relaunchCluster = function (cluster, height)
880 {
881 cluster.jumpHeight = height;
882 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
883 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
884 cluster.phase = 'up';
885 var members = this.clusterMembers(cluster.id);
886 for (var i = 0; i < members.length; i++)
887 {
888 members[i].vy = cluster.vy;
889 members[i].state = STATE_FLYING;
890 if (members[i].color === COLOR_GRAY)
891 { members[i].flame = true; }
892 }
893 };
894
895 GameCore.prototype.startManualLaunch = function (block)
896 {
897 var target = this.height - 1;
898 var height = Math.max(0.05, target - block.y);
899 block.state = STATE_MANUAL;
900 block.pushedClusters = Object.create(null);
901 block.manualTarget = target;
902 block.manualPhase = 'up';
903 block.vy = PlanetMod.launchVelocity(this.planet, height);
904 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
905 block.flame = false;
906 if (this.drag && this.drag.blockId === block.id)
907 { this.drag = null; }
908 };
909
910 GameCore.prototype.cullOffTop = function ()
911 {
912 var gone = [];
913 for (var i = 0; i < this.blocks.length; i++)
914 {
915 var block = this.blocks[i];
916 if (block.state === STATE_MANUAL)
917 {
918 if (block.y > this.height - 1)
919 { block.y = this.height - 1; }
920 continue;
921 }
922 if (block.y >= this.height - 1e-9)
923 { gone.push(block); }
924 }
925 for (var i = 0; i < gone.length; i++)
926 {
927 this.score += 1;
928 this.removeBlock(gone[i]);
929 }
930 };
931
932 GameCore.prototype.advanceSettle = function (dt)
933 {
934 for (var i = 0; i < this.blocks.length; i++)
935 {
936 var block = this.blocks[i];
937 if (block.state !== STATE_SETTLING)
938 { continue; }
939 block.settleTime += dt;
940 if (block.settleTime >= this.settleTime)
941 {
942 block.color = this.randomColor();
943 block.state = STATE_STILL;
944 block.settleTime = 0;
945 block.flame = false;
946 this.leaveCluster(block);
947 }
948 }
949 };
950
951 GameCore.prototype.findMatchLines = function ()
952 {
953 var candidates = [];
954 for (var i = 0; i < this.blocks.length; i++)
955 {
956 var block = this.blocks[i];
957 if (block.state === STATE_STILL && block.color >= 0)
958 { candidates.push(block); }
959 }
960 return this.collectLines(candidates, true);
961 };
962
963 GameCore.prototype.findFlyingMatchLines = function (clusterId)
964 {
965 var candidates = [];
966 for (var i = 0; i < this.blocks.length; i++)
967 {
968 var block = this.blocks[i];
969 if (block.clusterId === clusterId && block.color >= 0
970 && (block.state === STATE_FLYING))
971 { candidates.push(block); }
972 }
973 return this.collectLines(candidates, false);
974 };
975
976 GameCore.prototype.collectLines = function (candidates, snapInteger)
977 {
978 var lines = [];
979 if (!candidates.length)
980 { return lines; }
981
982 var byRow = Object.create(null);
983 for (var i = 0; i < candidates.length; i++)
984 {
985 var block = candidates[i];
986 var row = Math.round(block.y);
987 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
988 { continue; }
989 if (!byRow[row])
990 { byRow[row] = []; }
991 byRow[row].push(block);
992 }
993 var rows = Object.keys(byRow);
994 for (var r = 0; r < rows.length; r++)
995 {
996 var list = byRow[rows[r]];
997 list.sort(function (a, b) { return a.col - b.col; });
998 this.pushRuns(lines, list, false, function (a, b)
999 {
1000 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
1001 });
1002 }
1003
1004 var byCol = Object.create(null);
1005 for (var i = 0; i < candidates.length; i++)
1006 {
1007 var block = candidates[i];
1008 if (!byCol[block.col])
1009 { byCol[block.col] = []; }
1010 byCol[block.col].push(block);
1011 }
1012 var cols = Object.keys(byCol);
1013 for (var c = 0; c < cols.length; c++)
1014 {
1015 var list = byCol[cols[c]];
1016 list.sort(function (a, b) { return a.y - b.y; });
1017 this.pushRuns(lines, list, true, function (a, b)
1018 {
1019 return a.color === b.color && a.color >= 0
1020 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
1021 });
1022 }
1023 return lines;
1024 };
1025
1026 GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
1027 {
1028 var start = 0;
1029 for (var i = 1; i <= list.length; i++)
1030 {
1031 var same = i < list.length && adjacent(list[i - 1], list[i]);
1032 if (!same)
1033 {
1034 var length = i - start;
1035 if (length >= 3)
1036 {
1037 lines.push({
1038 blocks: list.slice(start, i),
1039 length: length,
1040 vertical: vertical
1041 });
1042 }
1043 start = i;
1044 }
1045 }
1046 };
1047
1048 GameCore.prototype.resolveMatches = function ()
1049 {
1050 if (this.state !== 'playing' || this.drag)
1051 { return []; }
1052 var lines = this.findMatchLines();
1053 if (!lines.length)
1054 { return []; }
1055
1056 var uf = new UnionFind();
1057 var blockById = Object.create(null);
1058 for (var i = 0; i < lines.length; i++)
1059 {
1060 var line = lines[i];
1061 for (var j = 0; j < line.blocks.length; j++)
1062 {
1063 uf.add(line.blocks[j].id);
1064 blockById[line.blocks[j].id] = line.blocks[j];
1065 if (j > 0)
1066 { uf.union(line.blocks[0].id, line.blocks[j].id); }
1067 }
1068 }
1069 var matched = [];
1070 var seen = Object.create(null);
1071 for (var id in blockById)
1072 {
1073 if (!seen[id])
1074 {
1075 seen[id] = true;
1076 matched.push(blockById[id]);
1077 }
1078 }
1079 for (var i = 0; i < matched.length; i++)
1080 {
1081 for (var j = i + 1; j < matched.length; j++)
1082 {
1083 if (matched[i].col === matched[j].col)
1084 { uf.union(matched[i].id, matched[j].id); }
1085 }
1086 }
1087
1088 var groups = Object.create(null);
1089 for (var i = 0; i < matched.length; i++)
1090 {
1091 var root = uf.find(matched[i].id);
1092 if (!groups[root])
1093 { groups[root] = []; }
1094 groups[root].push(matched[i]);
1095 }
1096
1097 var launched = [];
1098 for (var root in groups)
1099 {
1100 var group = groups[root];
1101 var height = 0;
1102 for (var i = 0; i < lines.length; i++)
1103 {
1104 var line = lines[i];
1105 var overlaps = false;
1106 for (var j = 0; j < line.blocks.length; j++)
1107 {
1108 for (var k = 0; k < group.length; k++)
1109 {
1110 if (line.blocks[j].id === group[k].id)
1111 { overlaps = true; }
1112 }
1113 }
1114 if (overlaps)
1115 {
1116 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
1117 if (h > height)
1118 { height = h; }
1119 }
1120 }
1121 this.launchCluster(group, height);
1122 launched.push({ blocks: group, jumpHeight: height });
1123 }
1124 return launched;
1125 };
1126
1127 /**
1128 * Gray the matched blocks, take everything sitting on top of them in
1129 * those columns, link them, and launch with jump height `height`.
1130 */
1131 GameCore.prototype.launchCluster = function (matchedBlocks, height)
1132 {
1133 var lowestInCol = Object.create(null);
1134 var matchedIds = Object.create(null);
1135 for (var i = 0; i < matchedBlocks.length; i++)
1136 {
1137 var block = matchedBlocks[i];
1138 matchedIds[block.id] = true;
1139 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
1140 { lowestInCol[block.col] = block.y; }
1141 }
1142
1143 var clusterId = this.nextClusterId++;
1144 var cluster = {
1145 id: clusterId,
1146 jumpHeight: height,
1147 vy: PlanetMod.launchVelocity(this.planet, height),
1148 decel: PlanetMod.launchDeceleration(this.planet, height),
1149 phase: 'up'
1150 };
1151 this.clusters[clusterId] = cluster;
1152
1153 var riders = [];
1154 var cols = Object.keys(lowestInCol);
1155 for (var c = 0; c < cols.length; c++)
1156 {
1157 var col = +cols[c];
1158 var lowest = lowestInCol[col];
1159 var list = this.blocksInColumn(col);
1160 for (var i = 0; i < list.length; i++)
1161 {
1162 var block = list[i];
1163 if (!this.isGrounded(block) && block.state !== STATE_STILL)
1164 {
1165 if (block.state !== STATE_SETTLING)
1166 { continue; }
1167 }
1168 if (block.y + ALIGN_EPS >= lowest)
1169 { riders.push(block); }
1170 }
1171 }
1172
1173 for (var i = 0; i < riders.length; i++)
1174 {
1175 var block = riders[i];
1176 var isMatch = !!matchedIds[block.id];
1177 if (isMatch || block.color === COLOR_GRAY)
1178 {
1179 block.color = COLOR_GRAY;
1180 block.flame = true;
1181 }
1182 else
1183 { block.flame = false; }
1184 block.state = STATE_FLYING;
1185 block.clusterId = clusterId;
1186 block.vy = cluster.vy;
1187 block.settleTime = 0;
1188 }
1189 return cluster;
1190 };
1191
1192 GameCore.prototype.checkLocks = function ()
1193 {
1194 for (var col = 0; col < this.width; col++)
1195 {
1196 if (this.isColumnLocked(col))
1197 { continue; }
1198 if (this.groundedCount(col) < this.height)
1199 { continue; }
1200 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
1201 var filled = true;
1202 for (var row = 0; row < this.height; row++)
1203 {
1204 var block = this.blockAt(col, row);
1205 if (!block || !this.isGrounded(block))
1206 {
1207 filled = false;
1208 break;
1209 }
1210 }
1211 if (!filled)
1212 { continue; }
1213 var list = this.blocksInColumn(col);
1214 for (var i = 0; i < list.length; i++)
1215 {
1216 var block = list[i];
1217 if (!this.isGrounded(block))
1218 { continue; }
1219 block.state = STATE_LOCKED;
1220 block.color = COLOR_GRAY;
1221 block.flame = false;
1222 block.vy = 0;
1223 block.settleTime = 0;
1224 if (block.clusterId != null)
1225 { this.leaveCluster(block); }
1226 }
1227 }
1228 };
1229
1230 GameCore.prototype.checkGameOver = function ()
1231 {
1232 if (this.state !== 'playing')
1233 { return; }
1234 for (var col = 0; col < this.width; col++)
1235 {
1236 if (!this.isColumnLocked(col))
1237 { return; }
1238 }
1239 this.state = 'gameover';
1240 this.gameOverTime = 0;
1241 this.drag = null;
1242 };
1243
1244 /* ---------- dragging -------------------------------------------------- */
1245
1246 GameCore.prototype.beginDrag = function (col, y)
1247 {
1248 if (this.state !== 'playing')
1249 { return false; }
1250 col = col | 0;
1251 if (col < 0 || col >= this.width)
1252 { return false; }
1253 if (!this.isColumnStill(col))
1254 { return false; }
1255 var row = Math.floor(y + 1e-6);
1256 if (row < 0)
1257 { return false; }
1258 var block = this.blockAt(col, row);
1259 if (!block || block.state !== STATE_STILL || block.color < 0)
1260 { return false; }
1261 this.drag = { blockId: block.id, pointerY: y, launchIntent: false };
1262 return true;
1263 };
1264
1265 GameCore.prototype.moveDrag = function (y)
1266 {
1267 if (!this.drag)
1268 { return; }
1269 var block = this.blockById(this.drag.blockId);
1270 if (!block || block.state !== STATE_STILL)
1271 {
1272 this.drag = null;
1273 return;
1274 }
1275 if (!this.isColumnStill(block.col))
1276 {
1277 this.drag = null;
1278 return;
1279 }
1280 this.drag.pointerY = y;
1281 this.swapToward(block, y);
1282 var top = this.columnStackTopRow(block.col);
1283 // The top block occupies [top, top+1). Launch only when the pointer
1284 // is pulled into the empty space above the stack.
1285 this.drag.launchIntent = (Math.abs(block.y - top) < ALIGN_EPS && y > top + 1 + 0.25);
1286 };
1287
1288 GameCore.prototype.endDrag = function ()
1289 {
1290 if (!this.drag)
1291 { return; }
1292 var block = this.blockById(this.drag.blockId);
1293 var launch = this.drag.launchIntent;
1294 this.drag = null;
1295 if (launch && block && block.state === STATE_STILL)
1296 { this.startManualLaunch(block); }
1297 else
1298 { this.resolveMatches(); }
1299 };
1300
1301 GameCore.prototype.blockById = function (id)
1302 {
1303 for (var i = 0; i < this.blocks.length; i++)
1304 {
1305 if (this.blocks[i].id === id)
1306 { return this.blocks[i]; }
1307 }
1308 return null;
1309 };
1310
1311 GameCore.prototype.columnStackTopRow = function (col)
1312 {
1313 var top = -1;
1314 var list = this.blocksInColumn(col);
1315 for (var i = 0; i < list.length; i++)
1316 {
1317 if (this.isGrounded(list[i]) && list[i].y > top)
1318 { top = list[i].y; }
1319 }
1320 return top;
1321 };
1322
1323 GameCore.prototype.swapToward = function (block, targetY)
1324 {
1325 var guard = 0;
1326 while (guard++ < this.height + 2)
1327 {
1328 var current = block.y;
1329 if (targetY > current + 0.5)
1330 {
1331 var above = this.blockAt(block.col, current + 1);
1332 if (above && this.isGrounded(above) && above !== block)
1333 { this.swapBlocks(block, above); }
1334 else
1335 { break; }
1336 }
1337 else if (targetY < current - 0.5)
1338 {
1339 var below = this.blockAt(block.col, current - 1);
1340 if (below && this.isGrounded(below) && below !== block)
1341 { this.swapBlocks(block, below); }
1342 else
1343 { break; }
1344 }
1345 else
1346 { break; }
1347 }
1348 };
1349
1350 GameCore.prototype.swapBlocks = function (a, b)
1351 {
1352 var y = a.y;
1353 a.y = b.y;
1354 b.y = y;
1355 };
1356
1357 /**
1358 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
1359 * Returns the moved block, or null if the column is not still.
1360 */
1361 GameCore.prototype.swapTo = function (col, fromRow, toRow)
1362 {
1363 if (!this.isColumnStill(col))
1364 { return null; }
1365 var block = this.blockAt(col, fromRow);
1366 if (!block)
1367 { return null; }
1368 this.swapToward(block, toRow);
1369 return block;
1370 };
1371
1372 /**
1373 * Test helper: a compact picture of grounded/falling/flying blocks.
1374 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
1375 * L locked, f falling, m manual, . empty. Flying colored blocks use
1376 * their color with a marker in `flying`.
1377 */
1378 GameCore.prototype.snapshot = function ()
1379 {
1380 var grid = [];
1381 for (var r = 0; r < this.height; r++)
1382 {
1383 var row = [];
1384 for (var c = 0; c < this.width; c++)
1385 { row.push('.'); }
1386 grid.push(row);
1387 }
1388 var airborne = [];
1389 for (var i = 0; i < this.blocks.length; i++)
1390 {
1391 var block = this.blocks[i];
1392 var ch;
1393 if (block.state === STATE_LOCKED)
1394 { ch = 'L'; }
1395 else if (block.color === COLOR_GRAY)
1396 { ch = 'g'; }
1397 else
1398 { ch = String(block.color); }
1399 if (this.isGrounded(block) || block.state === STATE_FALLING)
1400 {
1401 var row = Math.round(block.y);
1402 if (row >= 0 && row < this.height)
1403 { grid[row][block.col] = ch; }
1404 }
1405 else
1406 {
1407 airborne.push({
1408 id: block.id,
1409 col: block.col,
1410 y: block.y,
1411 color: block.color,
1412 state: block.state,
1413 clusterId: block.clusterId,
1414 flame: block.flame,
1415 vy: block.vy
1416 });
1417 }
1418 }
1419 var lines = [];
1420 for (var r = this.height - 1; r >= 0; r--)
1421 { lines.push(grid[r].join('')); }
1422 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
1423 };
1424
1425 var GameCoreAPI = {
1426 GameCore: GameCore,
1427 COLOR_GRAY: COLOR_GRAY,
1428 STATE_STILL: STATE_STILL,
1429 STATE_FALLING: STATE_FALLING,
1430 STATE_FLYING: STATE_FLYING,
1431 STATE_SETTLING: STATE_SETTLING,
1432 STATE_LOCKED: STATE_LOCKED,
1433 STATE_MANUAL: STATE_MANUAL
1434 };
1435
1436 if (typeof module !== 'undefined' && module.exports)
1437 { module.exports = GameCoreAPI; }
1438 else if (typeof globalThis !== 'undefined')
1439 {
1440 globalThis.GameCore = GameCore;
1441 globalThis.GameCoreAPI = GameCoreAPI;
1442 }
1443
1444 /*
1445 * End File:
1446 * /workspace/meteors/src/gameCore.js
1447 */
1448
1449 /*
1450 * Start File:
1451 * /workspace/meteors/src/main.js
1452 */
1453 'use strict';
1454
1455 /**
1456 * View and input for Meteors. The simulation lives in GameCore; this file
1457 * only draws it, scales it to the viewport, and translates pointer events
1458 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
1459 * that reuses the same core.
1460 */
1461
1462 var IMAGES = [
1463 { name: 'ember', url: 'images/block-ember.png' },
1464 { name: 'aqua', url: 'images/block-aqua.png' },
1465 { name: 'leaf', url: 'images/block-leaf.png' },
1466 { name: 'sun', url: 'images/block-sun.png' },
1467 { name: 'orchid', url: 'images/block-orchid.png' },
1468 { name: 'gray', url: 'images/block-gray.png' },
1469 { name: 'locked', url: 'images/block-locked.png' },
1470 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
1471 { name: 'cell', url: 'images/cell.png' },
1472 { name: 'pixel', url: 'images/pixel.png' }
1473 ];
1474
1475 var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
1476 var GAME_OVER_DELAY = 2;
1477
1478 var game = new Game();
1479 var app = {
1480 mode: 'menu',
1481 core: null,
1482 scene: null,
1483 manager: null,
1484 planet: null,
1485 lastScore: 0,
1486 tile: 48,
1487 fieldX: 0,
1488 fieldY: 0,
1489 fieldW: 0,
1490 fieldH: 0,
1491 hudH: 56,
1492 sprites: Object.create(null),
1493 flames: Object.create(null),
1494 cells: [],
1495 pointerId: null,
1496 gameOverShown: false
1497 };
1498
1499 window.onload = function ()
1500 {
1501 var play = document.getElementById('btn-play');
1502 play.addEventListener('click', onPlay);
1503 play.addEventListener('pointerup', function (e)
1504 {
1505 // A touch-friendly path: some mobile browsers swallow the click
1506 // after a slightly sloppy tap. Ignore the following click.
1507 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1508 {
1509 e.preventDefault();
1510 onPlay();
1511 }
1512 });
1513
1514 game.preloadImagesThenStart(IMAGES, function ()
1515 {
1516 if (game.images.flame && game.images.flame.addAnimationCycle)
1517 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
1518 });
1519 };
1520
1521 function onPlay ()
1522 {
1523 if (app.mode === 'playing')
1524 { return; }
1525 startPlay();
1526 }
1527
1528 function startPlay ()
1529 {
1530 hideEl('menu');
1531 hideEl('game-over');
1532 showEl('hud');
1533
1534 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
1535 app.core = new GameCore(app.planet, Math.random);
1536 app.mode = 'playing';
1537 app.gameOverShown = false;
1538 app.sprites = Object.create(null);
1539 app.flames = Object.create(null);
1540 app.cells = [];
1541 app.pointerId = null;
1542
1543 layout();
1544 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
1545 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
1546 app.scene.renderBackground = true;
1547 game.loadScene(app.scene);
1548
1549 buildCells();
1550 app.manager = app.scene.addObject(makeManager());
1551 bindPointer(app.scene.canvas);
1552 refreshHud();
1553 }
1554
1555 function returnToMenu ()
1556 {
1557 unbindPointer();
1558 if (app.scene)
1559 {
1560 app.scene.destroy();
1561 app.scene = null;
1562 }
1563 app.manager = null;
1564 app.core = null;
1565 app.mode = 'menu';
1566 app.sprites = Object.create(null);
1567 app.flames = Object.create(null);
1568 app.cells = [];
1569
1570 hideEl('hud');
1571 hideEl('game-over');
1572 showEl('menu');
1573 var last = document.getElementById('last-score');
1574 if (app.lastScore > 0)
1575 {
1576 last.hidden = false;
1577 last.querySelector('strong').textContent = String(app.lastScore);
1578 }
1579 }
1580
1581 function buildCells ()
1582 {
1583 if (!app.scene)
1584 { return; }
1585 var img = game.images.cell;
1586 for (var row = 0; row < 13; row++)
1587 {
1588 for (var col = 0; col < 10; col++)
1589 {
1590 var obj = new GameObject(0, 0, img, 0);
1591 placeTile(obj, col, row);
1592 obj.renderer.alpha = 0.9;
1593 app.scene.addObject(obj);
1594 app.cells.push(obj);
1595 }
1596 }
1597 }
1598
1599 function placeTile (obj, col, y)
1600 {
1601 var t = app.tile;
1602 obj.transform.position.x = col * t + t / 2;
1603 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
1604 obj.transform.size = { x: t, y: t };
1605 }
1606
1607 function layout ()
1608 {
1609 var vw = window.innerWidth || 320;
1610 var vh = window.innerHeight || 480;
1611 var safeTop = 0;
1612 try
1613 {
1614 // env(safe-area) is a CSS thing; keep a conservative HUD height.
1615 safeTop = 0;
1616 }
1617 catch (e) { /* ignore */ }
1618 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
1619 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
1620 var availW = Math.max(80, vw - margin * 2);
1621 var availH = Math.max(80, vh - app.hudH - margin);
1622 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
1623 app.fieldW = app.tile * 10;
1624 app.fieldH = app.tile * 13;
1625 app.fieldX = Math.floor((vw - app.fieldW) / 2);
1626 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
1627 if (app.fieldY < app.hudH)
1628 { app.fieldY = app.hudH; }
1629
1630 if (app.scene)
1631 {
1632 app.scene.position.x = app.fieldX;
1633 app.scene.position.y = app.fieldY;
1634 app.scene.size.x = app.fieldW;
1635 app.scene.size.y = app.fieldH;
1636 }
1637 }
1638
1639 function spriteFor (block)
1640 {
1641 if (block.state === 'locked')
1642 { return game.images.locked; }
1643 if (block.color < 0)
1644 { return game.images.gray; }
1645 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
1646 }
1647
1648 function syncSprites ()
1649 {
1650 if (!app.core || !app.scene)
1651 { return; }
1652 var seen = Object.create(null);
1653 var blocks = app.core.blocks;
1654 for (var i = 0; i < blocks.length; i++)
1655 {
1656 var block = blocks[i];
1657 seen[block.id] = true;
1658 var obj = app.sprites[block.id];
1659 if (!obj)
1660 {
1661 obj = new GameObject(0, 0, spriteFor(block), 2);
1662 app.scene.addObject(obj);
1663 app.sprites[block.id] = obj;
1664 }
1665 obj.renderer.sprite = spriteFor(block);
1666 placeTile(obj, block.col, block.y);
1667 obj.renderer.visible = true;
1668 obj.renderer.alpha = 1;
1669
1670 if (block.flame)
1671 {
1672 var flame = app.flames[block.id];
1673 if (!flame)
1674 {
1675 flame = new GameObject(0, 0, game.images.flame, 1);
1676 flame.renderer.setAnimation('burn', 0, 0.08);
1677 app.scene.addObject(flame);
1678 app.flames[block.id] = flame;
1679 }
1680 flame.renderer.visible = true;
1681 var t = app.tile;
1682 flame.transform.position.x = block.col * t + t / 2;
1683 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
1684 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
1685 }
1686 else if (app.flames[block.id])
1687 { app.flames[block.id].renderer.visible = false; }
1688 }
1689
1690 var ids = Object.keys(app.sprites);
1691 for (var i = 0; i < ids.length; i++)
1692 {
1693 if (!seen[ids[i]])
1694 {
1695 app.sprites[ids[i]].destroy();
1696 delete app.sprites[ids[i]];
1697 if (app.flames[ids[i]])
1698 {
1699 app.flames[ids[i]].destroy();
1700 delete app.flames[ids[i]];
1701 }
1702 }
1703 }
1704 }
1705
1706 function refreshHud ()
1707 {
1708 if (!app.core)
1709 { return; }
1710 document.getElementById('score').textContent = String(app.core.score);
1711 var planet = app.planet;
1712 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
1713 var d = Planet.displayValues(planet);
1714 document.getElementById('planet-stats').textContent =
1715 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
1716 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
1717 }
1718
1719 function makeManager ()
1720 {
1721 var obj = new GameObject(0, 0, game.images.pixel, 0);
1722 obj.renderer.visible = false;
1723 var base = obj.update.bind(obj);
1724 obj.update = function (dt)
1725 {
1726 base(dt);
1727 tickView(dt);
1728 };
1729 return obj;
1730 }
1731
1732 function tickView (dt)
1733 {
1734 if (app.mode !== 'playing' || !app.core)
1735 { return; }
1736
1737 layout();
1738 for (var i = 0; i < app.cells.length; i++)
1739 {
1740 var col = i % 10;
1741 var row = Math.floor(i / 10);
1742 placeTile(app.cells[i], col, row);
1743 }
1744
1745 app.core.tick(dt);
1746 syncSprites();
1747 refreshHud();
1748
1749 if (app.core.state === 'gameover' && !app.gameOverShown)
1750 {
1751 app.gameOverShown = true;
1752 app.lastScore = app.core.score;
1753 document.getElementById('go-score').textContent = String(app.lastScore);
1754 showEl('game-over');
1755 }
1756 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
1757 { returnToMenu(); }
1758 }
1759
1760 /* ---------- pointer input (mouse + touch) --------------------------- */
1761
1762 var boundCanvas = null;
1763
1764 function bindPointer (canvas)
1765 {
1766 unbindPointer();
1767 boundCanvas = canvas;
1768 canvas.addEventListener('pointerdown', onPointerDown);
1769 canvas.addEventListener('pointermove', onPointerMove);
1770 canvas.addEventListener('pointerup', onPointerUp);
1771 canvas.addEventListener('pointercancel', onPointerUp);
1772 canvas.addEventListener('lostpointercapture', onPointerUp);
1773 canvas.style.touchAction = 'none';
1774 canvas.style.cursor = 'pointer';
1775 }
1776
1777 function unbindPointer ()
1778 {
1779 if (!boundCanvas)
1780 { return; }
1781 boundCanvas.removeEventListener('pointerdown', onPointerDown);
1782 boundCanvas.removeEventListener('pointermove', onPointerMove);
1783 boundCanvas.removeEventListener('pointerup', onPointerUp);
1784 boundCanvas.removeEventListener('pointercancel', onPointerUp);
1785 boundCanvas.removeEventListener('lostpointercapture', onPointerUp);
1786 boundCanvas = null;
1787 app.pointerId = null;
1788 }
1789
1790 function fieldFromEvent (e)
1791 {
1792 var canvas = app.scene && app.scene.canvas;
1793 if (!canvas)
1794 { return null; }
1795 var rect = canvas.getBoundingClientRect();
1796 if (rect.width <= 0 || rect.height <= 0)
1797 { return null; }
1798 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
1799 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
1800 var col = Math.floor(x / app.tile);
1801 var fieldY = (canvas.height - y) / app.tile;
1802 return { col: col, y: fieldY };
1803 }
1804
1805 function onPointerDown (e)
1806 {
1807 if (!app.core || app.core.state !== 'playing')
1808 { return; }
1809 if (app.pointerId != null)
1810 { return; }
1811 e.preventDefault();
1812 app.pointerId = e.pointerId;
1813 try
1814 { boundCanvas.setPointerCapture(e.pointerId); }
1815 catch (err) { /* ignore */ }
1816 var pos = fieldFromEvent(e);
1817 if (pos)
1818 { app.core.beginDrag(pos.col, pos.y); }
1819 }
1820
1821 function onPointerMove (e)
1822 {
1823 if (app.pointerId == null || e.pointerId !== app.pointerId)
1824 { return; }
1825 if (!app.core || !app.core.drag)
1826 { return; }
1827 e.preventDefault();
1828 var pos = fieldFromEvent(e);
1829 if (pos)
1830 { app.core.moveDrag(pos.y); }
1831 }
1832
1833 function onPointerUp (e)
1834 {
1835 if (app.pointerId == null)
1836 { return; }
1837 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1838 { return; }
1839 if (e)
1840 { e.preventDefault(); }
1841 app.pointerId = null;
1842 if (app.core)
1843 { app.core.endDrag(); }
1844 }
1845
1846 function hideEl (id)
1847 {
1848 document.getElementById(id).hidden = true;
1849 }
1850
1851 function showEl (id)
1852 {
1853 document.getElementById(id).hidden = false;
1854 }
1855
1856 window.addEventListener('resize', function ()
1857 {
1858 if (app.mode === 'playing')
1859 { layout(); }
1860 });
1861
1862 window.addEventListener('orientationchange', function ()
1863 {
1864 setTimeout(function ()
1865 {
1866 if (app.mode === 'playing')
1867 { layout(); }
1868 }, 120);
1869 });
1870
1871 /*
1872 * End File:
1873 * /workspace/meteors/src/main.js
1874 */
@@ -0,0 +1,1874 @@
1/*
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 * Built by src/build.sh from the sources in src/.
4 */
5
6/*
7 * Start File:
8 * /workspace/meteors/src/rng.js
9 */
10'use strict';
11
12/**
13 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
14 * and (later) for multiplayer replays.
15 */
16function createRng (seed)
17{
18 var a = (seed >>> 0) || 1;
19 return function rng ()
20 {
21 a |= 0;
22 a = a + 0x6D2B79F5 | 0;
23 var t = Math.imul(a ^ a >>> 15, 1 | a);
24 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
25 return ((t ^ t >>> 14) >>> 0) / 4294967296;
26 };
27}
28
29function pickIndex (rng, count)
30{
31 var n = count | 0;
32 if (n <= 0)
33 { return 0; }
34 return Math.floor(rng() * n) % n;
35}
36
37function pickFrom (rng, list)
38{
39 if (!list || !list.length)
40 { return undefined; }
41 return list[pickIndex(rng, list.length)];
42}
43
44var Rng = {
45 create: createRng,
46 pickIndex: pickIndex,
47 pickFrom: pickFrom
48};
49
50if (typeof module !== 'undefined' && module.exports)
51{ module.exports = Rng; }
52else if (typeof globalThis !== 'undefined')
53{ globalThis.Rng = Rng; }
54
55/*
56 * End File:
57 * /workspace/meteors/src/rng.js
58 */
59
60/*
61 * Start File:
62 * /workspace/meteors/src/planet.js
63 */
64'use strict';
65
66/**
67 * Planet physics and visuals for Meteors.
68 *
69 * Stage 1 uses a single default planet. Stage 3 lets the player pick a
70 * planet; the numbers and jump-height rules are already applied here so
71 * that later planets only need new data, not new physics code.
72 *
73 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
74 * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
75 * at 1, one jump from the floor clears the field; at 4, you need four.
76 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
77 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
78 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
79 * Time to reach the apex, independent of jump height.
80 *
81 * Jump-height multipliers (never explained in the game):
82 * A vertical match of 3 is 120 % of a horizontal row of 3.
83 * Each extra block beyond 3 adds 5 %.
84 *
85 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
86 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
87 * power 0 to 5 % at power 1.
88 */
89
90var FIELD_WIDTH = 10;
91var FIELD_HEIGHT = 13;
92
93function clamp (value, lo, hi)
94{
95 return Math.max(lo, Math.min(hi, value));
96}
97
98function defaultColors ()
99{
100 return [
101 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
102 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
103 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
104 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
105 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
106 ];
107}
108
109function createPlanet (opts)
110{
111 opts = opts || {};
112 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
113 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
114 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
115 var colors = opts.colors || defaultColors();
116 var planet = {
117 name: opts.name || 'Terra',
118 people: opts.people || 'Terrans',
119 jumpsToClear: jumpsToClear,
120 fallTime: fallTime,
121 riseTime: riseTime,
122 colors: colors,
123 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
124 fallSpeed: FIELD_HEIGHT / fallTime
125 };
126 return planet;
127}
128
129function defaultPlanet ()
130{
131 return createPlanet({
132 name: 'Terra',
133 people: 'Terrans',
134 jumpsToClear: 2,
135 fallTime: 3,
136 riseTime: 1.5
137 });
138}
139
140/**
141 * Jump height in tiles for a match line.
142 * @param {object} planet
143 * @param {number} matchLength number of blocks in the line (>= 3)
144 * @param {boolean} vertical true for a vertical line
145 */
146function jumpHeight (planet, matchLength, vertical)
147{
148 var extra = Math.max(0, (matchLength | 0) - 3);
149 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
150 return planet.baseJumpHeight * multiplier;
151}
152
153/** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
154function launchVelocity (planet, height)
155{
156 if (height <= 0)
157 { return 0; }
158 return (2 * height) / planet.riseTime;
159}
160
161/** Constant deceleration (tiles/s^2) paired with launchVelocity. */
162function launchDeceleration (planet, height)
163{
164 if (height <= 0)
165 { return 0; }
166 return (2 * height) / (planet.riseTime * planet.riseTime);
167}
168
169/**
170 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
171 * chance that a shot-off block misses the opponent).
172 */
173function power (planet)
174{
175 var gravity = (planet.jumpsToClear - 1) / 3;
176 var air = (5 - planet.fallTime) / 4;
177 var mass = (3 - planet.riseTime) / 2.5;
178 return (gravity + air + mass) / 3;
179}
180
181/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
182function missChance (planet)
183{
184 return 0.60 - 0.55 * power(planet);
185}
186
187/**
188 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
189 * launch force (N), and power as a percentage. The numbers do not have to
190 * explain themselves.
191 */
192function displayValues (planet)
193{
194 var gravity = 9.81 * planet.jumpsToClear / 2;
195 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
196 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
197 return {
198 gravity: gravity,
199 density: density,
200 newtons: newtons,
201 power: Math.round(power(planet) * 100),
202 missChance: missChance(planet)
203 };
204}
205
206var Planet = {
207 FIELD_WIDTH: FIELD_WIDTH,
208 FIELD_HEIGHT: FIELD_HEIGHT,
209 COLOR_COUNT: 5,
210 SETTLE_TIME: 3,
211 SPAWN_INTERVAL: 1,
212 JUMP_VERTICAL_BONUS: 1.2,
213 JUMP_EXTRA_BLOCK: 0.05,
214 createPlanet: createPlanet,
215 defaultPlanet: defaultPlanet,
216 defaultColors: defaultColors,
217 jumpHeight: jumpHeight,
218 launchVelocity: launchVelocity,
219 launchDeceleration: launchDeceleration,
220 power: power,
221 missChance: missChance,
222 displayValues: displayValues
223};
224
225if (typeof module !== 'undefined' && module.exports)
226{ module.exports = Planet; }
227else if (typeof globalThis !== 'undefined')
228{ globalThis.Planet = Planet; }
229
230/*
231 * End File:
232 * /workspace/meteors/src/planet.js
233 */
234
235/*
236 * Start File:
237 * /workspace/meteors/src/gameCore.js
238 */
239'use strict';
240
241/**
242 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
243 * The view layer reads this state and translates pointer events into
244 * beginDrag / moveDrag / endDrag.
245 */
246
247var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
248 ? require('./planet.js')
249 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
250
251var COLOR_GRAY = -1;
252
253var STATE_STILL = 'still';
254var STATE_FALLING = 'falling';
255var STATE_FLYING = 'flying';
256var STATE_SETTLING = 'settling';
257var STATE_LOCKED = 'locked';
258var STATE_MANUAL = 'manual';
259
260var ALIGN_EPS = 0.15;
261var SUBSTEP = 1 / 120;
262var DRAG_LAUNCH_SLACK = 0.65;
263
264function UnionFind ()
265{
266 this.parent = Object.create(null);
267}
268
269UnionFind.prototype.add = function (id)
270{
271 if (this.parent[id] == null)
272 { this.parent[id] = id; }
273};
274
275UnionFind.prototype.find = function (id)
276{
277 if (this.parent[id] !== id)
278 { this.parent[id] = this.find(this.parent[id]); }
279 return this.parent[id];
280};
281
282UnionFind.prototype.union = function (a, b)
283{
284 this.add(a);
285 this.add(b);
286 var ra = this.find(a);
287 var rb = this.find(b);
288 if (ra !== rb)
289 { this.parent[rb] = ra; }
290};
291
292function GameCore (planet, rng)
293{
294 this.planet = planet || PlanetMod.defaultPlanet();
295 this.rng = rng || Math.random;
296 this.width = PlanetMod.FIELD_WIDTH;
297 this.height = PlanetMod.FIELD_HEIGHT;
298 this.blocks = [];
299 this.clusters = Object.create(null);
300 this.nextBlockId = 1;
301 this.nextClusterId = 1;
302 this.spawnTimer = 0;
303 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
304 this.settleTime = PlanetMod.SETTLE_TIME;
305 this.score = 0;
306 this.state = 'playing';
307 this.drag = null;
308 this.gameOverTime = 0;
309}
310
311GameCore.COLOR_GRAY = COLOR_GRAY;
312GameCore.STATE_STILL = STATE_STILL;
313GameCore.STATE_FALLING = STATE_FALLING;
314GameCore.STATE_FLYING = STATE_FLYING;
315GameCore.STATE_SETTLING = STATE_SETTLING;
316GameCore.STATE_LOCKED = STATE_LOCKED;
317GameCore.STATE_MANUAL = STATE_MANUAL;
318
319GameCore.prototype.randomColor = function ()
320{
321 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
322};
323
324GameCore.prototype.createBlock = function (col, y, color, state)
325{
326 var block = {
327 id: this.nextBlockId++,
328 col: col,
329 y: y,
330 color: color,
331 state: state || STATE_STILL,
332 vy: 0,
333 clusterId: null,
334 settleTime: 0,
335 flame: false,
336 pushedClusters: null,
337 manualTarget: 0,
338 manualDecel: 0,
339 manualPhase: null
340 };
341 this.blocks.push(block);
342 return block;
343};
344
345GameCore.prototype.removeBlock = function (block)
346{
347 if (block.clusterId != null)
348 { this.leaveCluster(block); }
349 var index = this.blocks.indexOf(block);
350 if (index >= 0)
351 { this.blocks.splice(index, 1); }
352};
353
354GameCore.prototype.leaveCluster = function (block)
355{
356 var id = block.clusterId;
357 block.clusterId = null;
358 block.flame = false;
359 if (id == null || !this.clusters[id])
360 { return; }
361 var still = 0;
362 for (var i = 0; i < this.blocks.length; i++)
363 {
364 if (this.blocks[i].clusterId === id)
365 { still++; }
366 }
367 if (still === 0)
368 { delete this.clusters[id]; }
369};
370
371GameCore.prototype.blocksInColumn = function (col)
372{
373 var out = [];
374 for (var i = 0; i < this.blocks.length; i++)
375 {
376 if (this.blocks[i].col === col)
377 { out.push(this.blocks[i]); }
378 }
379 out.sort(function (a, b) { return a.y - b.y; });
380 return out;
381};
382
383GameCore.prototype.isGrounded = function (block)
384{
385 return block.state === STATE_STILL
386 || block.state === STATE_SETTLING
387 || block.state === STATE_LOCKED;
388};
389
390GameCore.prototype.stackTop = function (col, ignore)
391{
392 var top = 0;
393 for (var i = 0; i < this.blocks.length; i++)
394 {
395 var block = this.blocks[i];
396 if (block.col !== col)
397 { continue; }
398 if (ignore && ignore(block))
399 { continue; }
400 if (this.isGrounded(block))
401 {
402 var surface = block.y + 1;
403 if (surface > top)
404 { top = surface; }
405 }
406 }
407 return top;
408};
409
410GameCore.prototype.isColumnLocked = function (col)
411{
412 for (var i = 0; i < this.blocks.length; i++)
413 {
414 var block = this.blocks[i];
415 if (block.col === col && block.state === STATE_LOCKED)
416 { return true; }
417 }
418 return false;
419};
420
421GameCore.prototype.isColumnStill = function (col)
422{
423 if (this.isColumnLocked(col))
424 { return false; }
425 for (var i = 0; i < this.blocks.length; i++)
426 {
427 var block = this.blocks[i];
428 if (block.col !== col)
429 { continue; }
430 if (block.state === STATE_FLYING
431 || block.state === STATE_FALLING
432 || block.state === STATE_MANUAL
433 || block.state === STATE_SETTLING)
434 { return false; }
435 }
436 return true;
437};
438
439GameCore.prototype.groundedCount = function (col)
440{
441 var n = 0;
442 for (var i = 0; i < this.blocks.length; i++)
443 {
444 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
445 { n++; }
446 }
447 return n;
448};
449
450GameCore.prototype.blockAt = function (col, row)
451{
452 for (var i = 0; i < this.blocks.length; i++)
453 {
454 var block = this.blocks[i];
455 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
456 { return block; }
457 }
458 return null;
459};
460
461GameCore.prototype.place = function (col, row, color, state)
462{
463 return this.createBlock(col, row, color, state || STATE_STILL);
464};
465
466GameCore.prototype.lockedColumnCount = function ()
467{
468 var n = 0;
469 for (var c = 0; c < this.width; c++)
470 {
471 if (this.isColumnLocked(c))
472 { n++; }
473 }
474 return n;
475};
476
477GameCore.prototype.tick = function (dt)
478{
479 if (this.state === 'gameover')
480 {
481 this.gameOverTime += Math.max(0, dt);
482 return;
483 }
484 if (dt <= 0)
485 { return; }
486 dt = Math.min(dt, 0.1);
487
488 this.spawnTimer += dt;
489 while (this.spawnTimer >= this.spawnInterval)
490 {
491 this.spawnTimer -= this.spawnInterval;
492 this.trySpawn();
493 }
494
495 var left = dt;
496 while (left > 1e-12)
497 {
498 var step = Math.min(SUBSTEP, left);
499 this.integrateFalling(step);
500 this.integrateClusters(step);
501 this.integrateManual(step);
502 this.cullOffTop();
503 left -= step;
504 }
505
506 this.advanceSettle(dt);
507 if (!this.drag)
508 { this.resolveMatches(); }
509 this.checkLocks();
510 this.checkGameOver();
511};
512
513/** Step a stretch of time in fixed substeps. Useful for tests. */
514GameCore.prototype.step = function (seconds, dt)
515{
516 dt = dt || SUBSTEP;
517 var t = 0;
518 while (t < seconds - 1e-15)
519 {
520 var s = Math.min(dt, seconds - t);
521 this.tick(s);
522 t += s;
523 }
524};
525
526GameCore.prototype.trySpawn = function ()
527{
528 if (this.state !== 'playing')
529 { return null; }
530 var eligible = [];
531 for (var col = 0; col < this.width; col++)
532 {
533 if (this.isColumnLocked(col))
534 { continue; }
535 if (this.groundedCount(col) >= this.height)
536 { continue; }
537 var alreadyFalling = false;
538 var list = this.blocksInColumn(col);
539 for (var i = 0; i < list.length; i++)
540 {
541 if (list[i].state === STATE_FALLING)
542 {
543 alreadyFalling = true;
544 break;
545 }
546 }
547 if (!alreadyFalling)
548 { eligible.push(col); }
549 }
550 if (!eligible.length)
551 { return null; }
552 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
553 var color = this.randomColor();
554 return this.createBlock(col, this.height, color, STATE_FALLING);
555};
556
557GameCore.prototype.integrateFalling = function (dt)
558{
559 var speed = this.planet.fallSpeed;
560 for (var i = 0; i < this.blocks.length; i++)
561 {
562 var block = this.blocks[i];
563 if (block.state !== STATE_FALLING)
564 { continue; }
565 var top = this.stackTop(block.col);
566 var nextY = block.y - speed * dt;
567 if (nextY <= top)
568 {
569 block.y = top;
570 block.state = STATE_STILL;
571 block.vy = 0;
572 }
573 else
574 { block.y = nextY; }
575 }
576};
577
578GameCore.prototype.clusterMembers = function (clusterId)
579{
580 var out = [];
581 for (var i = 0; i < this.blocks.length; i++)
582 {
583 if (this.blocks[i].clusterId === clusterId)
584 { out.push(this.blocks[i]); }
585 }
586 return out;
587};
588
589
590/**
591 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
592 * jump of height H peaks at exactly H after riseTime. Returns dy.
593 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
594 * upward deceleration; falling uses planet.fallSpeed.
595 */
596GameCore.prototype.advanceJump = function (body, dt)
597{
598 var dy = 0;
599 var left = dt;
600 if (body.phase === 'up')
601 {
602 var decel = body.decel;
603 var vy = body.vy;
604 var tApex = decel > 1e-12 ? vy / decel : Infinity;
605 if (tApex <= left + 1e-15)
606 {
607 dy += vy * tApex - 0.5 * decel * tApex * tApex;
608 body.vy = 0;
609 body.phase = 'down';
610 left -= tApex;
611 }
612 else
613 {
614 var vyNew = vy - decel * left;
615 dy += (vy + vyNew) * 0.5 * left;
616 body.vy = vyNew;
617 left = 0;
618 }
619 }
620 if (body.phase === 'up' && body.vy <= 1e-10)
621 {
622 body.vy = 0;
623 body.phase = 'down';
624 }
625 if (body.phase === 'down' && left > 0)
626 {
627 body.vy = -this.planet.fallSpeed;
628 dy += body.vy * left;
629 }
630 return dy;
631};
632
633GameCore.prototype.integrateClusters = function (dt)
634{
635 var ids = Object.keys(this.clusters);
636 for (var n = 0; n < ids.length; n++)
637 {
638 var cluster = this.clusters[ids[n]];
639 if (!cluster)
640 { continue; }
641 var members = this.clusterMembers(cluster.id);
642 if (!members.length)
643 {
644 delete this.clusters[cluster.id];
645 continue;
646 }
647 if (cluster.phase === 'landed' || cluster.phase === 'hold')
648 { continue; }
649
650 var dy = this.advanceJump(cluster, dt);
651 for (var i = 0; i < members.length; i++)
652 {
653 members[i].y += dy;
654 members[i].vy = cluster.vy;
655 }
656
657 if (cluster.phase === 'down')
658 { this.tryLandCluster(cluster, members); }
659 }
660};
661
662GameCore.prototype.tryLandCluster = function (cluster, members)
663{
664 var self = this;
665 var hit = false;
666 for (var i = 0; i < members.length; i++)
667 {
668 var block = members[i];
669 var top = this.stackTop(block.col, function (other)
670 {
671 return other.clusterId === cluster.id;
672 });
673 if (block.y <= top + 1e-9)
674 { hit = true; }
675 }
676 if (!hit)
677 { return; }
678 this.landCluster(cluster, members);
679};
680
681GameCore.prototype.landCluster = function (cluster, members)
682{
683 var byCol = Object.create(null);
684 for (var i = 0; i < members.length; i++)
685 {
686 var block = members[i];
687 if (!byCol[block.col])
688 { byCol[block.col] = []; }
689 byCol[block.col].push(block);
690 }
691 var cols = Object.keys(byCol);
692 for (var c = 0; c < cols.length; c++)
693 {
694 var col = +cols[c];
695 var list = byCol[col];
696 list.sort(function (a, b) { return a.y - b.y; });
697 var self = this;
698 var top = this.stackTop(col, function (other)
699 {
700 return other.clusterId === cluster.id;
701 });
702 for (var i = 0; i < list.length; i++)
703 {
704 var block = list[i];
705 block.y = top;
706 block.vy = 0;
707 block.flame = false;
708 top = block.y + 1;
709 if (block.color === COLOR_GRAY)
710 {
711 block.state = STATE_SETTLING;
712 block.settleTime = 0;
713 }
714 else
715 {
716 block.state = STATE_STILL;
717 block.clusterId = null;
718 }
719 }
720 }
721 cluster.phase = 'landed';
722 cluster.vy = 0;
723 var remaining = 0;
724 for (var i = 0; i < this.blocks.length; i++)
725 {
726 if (this.blocks[i].clusterId === cluster.id)
727 { remaining++; }
728 }
729 if (remaining === 0)
730 { delete this.clusters[cluster.id]; }
731};
732
733GameCore.prototype.integrateManual = function (dt)
734{
735 for (var i = 0; i < this.blocks.length; i++)
736 {
737 var block = this.blocks[i];
738 if (block.state !== STATE_MANUAL)
739 { continue; }
740
741 if (block.manualPhase === 'up')
742 {
743 var oldY = block.y;
744 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
745 var dy = this.advanceJump(proxy, dt);
746 var nextY = oldY + dy;
747 this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
748 block.vy = proxy.vy;
749 block.manualPhase = proxy.phase;
750 block.y = Math.min(nextY, block.manualTarget);
751 if (block.y >= block.manualTarget - 1e-12)
752 {
753 block.y = block.manualTarget;
754 block.vy = 0;
755 block.manualPhase = 'down';
756 }
757 if (block.y > this.height - 1)
758 {
759 block.y = this.height - 1;
760 block.vy = 0;
761 block.manualPhase = 'down';
762 }
763 }
764
765 if (block.manualPhase === 'down')
766 {
767 var top = this.stackTop(block.col);
768 var nextY = block.y - this.planet.fallSpeed * dt;
769 if (nextY <= top)
770 {
771 block.y = top;
772 block.state = STATE_STILL;
773 block.vy = 0;
774 block.manualPhase = null;
775 block.flame = false;
776 }
777 else
778 {
779 block.y = Math.min(nextY, this.height - 1);
780 block.vy = -this.planet.fallSpeed;
781 }
782 }
783 }
784};
785
786GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
787{
788 if (!manual.pushedClusters)
789 { manual.pushedClusters = Object.create(null); }
790
791 var manualTopOld = oldY + 1;
792 var manualTopNew = nextY + 1;
793 var low = Math.min(oldY, nextY);
794 var high = Math.max(oldY, nextY) + 1;
795
796 for (var i = 0; i < this.blocks.length; i++)
797 {
798 var other = this.blocks[i];
799 if (other === manual)
800 { continue; }
801 if (other.col !== manual.col)
802 { continue; }
803 if (other.state !== STATE_FLYING || other.clusterId == null)
804 { continue; }
805 if (manual.pushedClusters[other.clusterId])
806 { continue; }
807 var otherBot = other.y;
808 var otherTop = other.y + 1;
809 var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
810 var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
811 if (overlapping || crossing)
812 {
813 if (this.pushClusterColumn(other.clusterId, manual.col))
814 {
815 manual.pushedClusters[other.clusterId] = true;
816 return;
817 }
818 }
819 }
820};
821
822
823/**
824 * Push every flying block of the cluster that sits in `col` one tile up.
825 * Other columns stay put (they remain linked). Then look for a new
826 * same-color line of 3+ in the flying cluster; if there is one, those
827 * blocks turn gray, join the link, and the whole cluster re-launches
828 * with the same jump height from its current position.
829 */
830GameCore.prototype.pushClusterColumn = function (clusterId, col)
831{
832 var cluster = this.clusters[clusterId];
833 if (!cluster)
834 { return false; }
835 var members = this.clusterMembers(clusterId);
836 for (var i = 0; i < members.length; i++)
837 {
838 if (members[i].col === col)
839 { members[i].y += 1; }
840 }
841 this.cullOffTop();
842 if (!this.clusters[clusterId])
843 { return true; }
844 this.checkChainRelaunch(cluster);
845 return true;
846};
847
848GameCore.prototype.checkChainRelaunch = function (cluster)
849{
850 if (!this.clusters[cluster.id])
851 { return; }
852 var lines = this.findFlyingMatchLines(cluster.id);
853 if (!lines.length)
854 { return; }
855 var newly = [];
856 var seen = Object.create(null);
857 for (var i = 0; i < lines.length; i++)
858 {
859 for (var j = 0; j < lines[i].blocks.length; j++)
860 {
861 var block = lines[i].blocks[j];
862 if (seen[block.id])
863 { continue; }
864 seen[block.id] = true;
865 newly.push(block);
866 }
867 }
868 for (var i = 0; i < newly.length; i++)
869 {
870 var block = newly[i];
871 block.color = COLOR_GRAY;
872 block.flame = true;
873 block.clusterId = cluster.id;
874 block.state = STATE_FLYING;
875 }
876 this.relaunchCluster(cluster, cluster.jumpHeight);
877};
878
879GameCore.prototype.relaunchCluster = function (cluster, height)
880{
881 cluster.jumpHeight = height;
882 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
883 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
884 cluster.phase = 'up';
885 var members = this.clusterMembers(cluster.id);
886 for (var i = 0; i < members.length; i++)
887 {
888 members[i].vy = cluster.vy;
889 members[i].state = STATE_FLYING;
890 if (members[i].color === COLOR_GRAY)
891 { members[i].flame = true; }
892 }
893};
894
895GameCore.prototype.startManualLaunch = function (block)
896{
897 var target = this.height - 1;
898 var height = Math.max(0.05, target - block.y);
899 block.state = STATE_MANUAL;
900 block.pushedClusters = Object.create(null);
901 block.manualTarget = target;
902 block.manualPhase = 'up';
903 block.vy = PlanetMod.launchVelocity(this.planet, height);
904 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
905 block.flame = false;
906 if (this.drag && this.drag.blockId === block.id)
907 { this.drag = null; }
908};
909
910GameCore.prototype.cullOffTop = function ()
911{
912 var gone = [];
913 for (var i = 0; i < this.blocks.length; i++)
914 {
915 var block = this.blocks[i];
916 if (block.state === STATE_MANUAL)
917 {
918 if (block.y > this.height - 1)
919 { block.y = this.height - 1; }
920 continue;
921 }
922 if (block.y >= this.height - 1e-9)
923 { gone.push(block); }
924 }
925 for (var i = 0; i < gone.length; i++)
926 {
927 this.score += 1;
928 this.removeBlock(gone[i]);
929 }
930};
931
932GameCore.prototype.advanceSettle = function (dt)
933{
934 for (var i = 0; i < this.blocks.length; i++)
935 {
936 var block = this.blocks[i];
937 if (block.state !== STATE_SETTLING)
938 { continue; }
939 block.settleTime += dt;
940 if (block.settleTime >= this.settleTime)
941 {
942 block.color = this.randomColor();
943 block.state = STATE_STILL;
944 block.settleTime = 0;
945 block.flame = false;
946 this.leaveCluster(block);
947 }
948 }
949};
950
951GameCore.prototype.findMatchLines = function ()
952{
953 var candidates = [];
954 for (var i = 0; i < this.blocks.length; i++)
955 {
956 var block = this.blocks[i];
957 if (block.state === STATE_STILL && block.color >= 0)
958 { candidates.push(block); }
959 }
960 return this.collectLines(candidates, true);
961};
962
963GameCore.prototype.findFlyingMatchLines = function (clusterId)
964{
965 var candidates = [];
966 for (var i = 0; i < this.blocks.length; i++)
967 {
968 var block = this.blocks[i];
969 if (block.clusterId === clusterId && block.color >= 0
970 && (block.state === STATE_FLYING))
971 { candidates.push(block); }
972 }
973 return this.collectLines(candidates, false);
974};
975
976GameCore.prototype.collectLines = function (candidates, snapInteger)
977{
978 var lines = [];
979 if (!candidates.length)
980 { return lines; }
981
982 var byRow = Object.create(null);
983 for (var i = 0; i < candidates.length; i++)
984 {
985 var block = candidates[i];
986 var row = Math.round(block.y);
987 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
988 { continue; }
989 if (!byRow[row])
990 { byRow[row] = []; }
991 byRow[row].push(block);
992 }
993 var rows = Object.keys(byRow);
994 for (var r = 0; r < rows.length; r++)
995 {
996 var list = byRow[rows[r]];
997 list.sort(function (a, b) { return a.col - b.col; });
998 this.pushRuns(lines, list, false, function (a, b)
999 {
1000 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
1001 });
1002 }
1003
1004 var byCol = Object.create(null);
1005 for (var i = 0; i < candidates.length; i++)
1006 {
1007 var block = candidates[i];
1008 if (!byCol[block.col])
1009 { byCol[block.col] = []; }
1010 byCol[block.col].push(block);
1011 }
1012 var cols = Object.keys(byCol);
1013 for (var c = 0; c < cols.length; c++)
1014 {
1015 var list = byCol[cols[c]];
1016 list.sort(function (a, b) { return a.y - b.y; });
1017 this.pushRuns(lines, list, true, function (a, b)
1018 {
1019 return a.color === b.color && a.color >= 0
1020 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
1021 });
1022 }
1023 return lines;
1024};
1025
1026GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
1027{
1028 var start = 0;
1029 for (var i = 1; i <= list.length; i++)
1030 {
1031 var same = i < list.length && adjacent(list[i - 1], list[i]);
1032 if (!same)
1033 {
1034 var length = i - start;
1035 if (length >= 3)
1036 {
1037 lines.push({
1038 blocks: list.slice(start, i),
1039 length: length,
1040 vertical: vertical
1041 });
1042 }
1043 start = i;
1044 }
1045 }
1046};
1047
1048GameCore.prototype.resolveMatches = function ()
1049{
1050 if (this.state !== 'playing' || this.drag)
1051 { return []; }
1052 var lines = this.findMatchLines();
1053 if (!lines.length)
1054 { return []; }
1055
1056 var uf = new UnionFind();
1057 var blockById = Object.create(null);
1058 for (var i = 0; i < lines.length; i++)
1059 {
1060 var line = lines[i];
1061 for (var j = 0; j < line.blocks.length; j++)
1062 {
1063 uf.add(line.blocks[j].id);
1064 blockById[line.blocks[j].id] = line.blocks[j];
1065 if (j > 0)
1066 { uf.union(line.blocks[0].id, line.blocks[j].id); }
1067 }
1068 }
1069 var matched = [];
1070 var seen = Object.create(null);
1071 for (var id in blockById)
1072 {
1073 if (!seen[id])
1074 {
1075 seen[id] = true;
1076 matched.push(blockById[id]);
1077 }
1078 }
1079 for (var i = 0; i < matched.length; i++)
1080 {
1081 for (var j = i + 1; j < matched.length; j++)
1082 {
1083 if (matched[i].col === matched[j].col)
1084 { uf.union(matched[i].id, matched[j].id); }
1085 }
1086 }
1087
1088 var groups = Object.create(null);
1089 for (var i = 0; i < matched.length; i++)
1090 {
1091 var root = uf.find(matched[i].id);
1092 if (!groups[root])
1093 { groups[root] = []; }
1094 groups[root].push(matched[i]);
1095 }
1096
1097 var launched = [];
1098 for (var root in groups)
1099 {
1100 var group = groups[root];
1101 var height = 0;
1102 for (var i = 0; i < lines.length; i++)
1103 {
1104 var line = lines[i];
1105 var overlaps = false;
1106 for (var j = 0; j < line.blocks.length; j++)
1107 {
1108 for (var k = 0; k < group.length; k++)
1109 {
1110 if (line.blocks[j].id === group[k].id)
1111 { overlaps = true; }
1112 }
1113 }
1114 if (overlaps)
1115 {
1116 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
1117 if (h > height)
1118 { height = h; }
1119 }
1120 }
1121 this.launchCluster(group, height);
1122 launched.push({ blocks: group, jumpHeight: height });
1123 }
1124 return launched;
1125};
1126
1127/**
1128 * Gray the matched blocks, take everything sitting on top of them in
1129 * those columns, link them, and launch with jump height `height`.
1130 */
1131GameCore.prototype.launchCluster = function (matchedBlocks, height)
1132{
1133 var lowestInCol = Object.create(null);
1134 var matchedIds = Object.create(null);
1135 for (var i = 0; i < matchedBlocks.length; i++)
1136 {
1137 var block = matchedBlocks[i];
1138 matchedIds[block.id] = true;
1139 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
1140 { lowestInCol[block.col] = block.y; }
1141 }
1142
1143 var clusterId = this.nextClusterId++;
1144 var cluster = {
1145 id: clusterId,
1146 jumpHeight: height,
1147 vy: PlanetMod.launchVelocity(this.planet, height),
1148 decel: PlanetMod.launchDeceleration(this.planet, height),
1149 phase: 'up'
1150 };
1151 this.clusters[clusterId] = cluster;
1152
1153 var riders = [];
1154 var cols = Object.keys(lowestInCol);
1155 for (var c = 0; c < cols.length; c++)
1156 {
1157 var col = +cols[c];
1158 var lowest = lowestInCol[col];
1159 var list = this.blocksInColumn(col);
1160 for (var i = 0; i < list.length; i++)
1161 {
1162 var block = list[i];
1163 if (!this.isGrounded(block) && block.state !== STATE_STILL)
1164 {
1165 if (block.state !== STATE_SETTLING)
1166 { continue; }
1167 }
1168 if (block.y + ALIGN_EPS >= lowest)
1169 { riders.push(block); }
1170 }
1171 }
1172
1173 for (var i = 0; i < riders.length; i++)
1174 {
1175 var block = riders[i];
1176 var isMatch = !!matchedIds[block.id];
1177 if (isMatch || block.color === COLOR_GRAY)
1178 {
1179 block.color = COLOR_GRAY;
1180 block.flame = true;
1181 }
1182 else
1183 { block.flame = false; }
1184 block.state = STATE_FLYING;
1185 block.clusterId = clusterId;
1186 block.vy = cluster.vy;
1187 block.settleTime = 0;
1188 }
1189 return cluster;
1190};
1191
1192GameCore.prototype.checkLocks = function ()
1193{
1194 for (var col = 0; col < this.width; col++)
1195 {
1196 if (this.isColumnLocked(col))
1197 { continue; }
1198 if (this.groundedCount(col) < this.height)
1199 { continue; }
1200 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
1201 var filled = true;
1202 for (var row = 0; row < this.height; row++)
1203 {
1204 var block = this.blockAt(col, row);
1205 if (!block || !this.isGrounded(block))
1206 {
1207 filled = false;
1208 break;
1209 }
1210 }
1211 if (!filled)
1212 { continue; }
1213 var list = this.blocksInColumn(col);
1214 for (var i = 0; i < list.length; i++)
1215 {
1216 var block = list[i];
1217 if (!this.isGrounded(block))
1218 { continue; }
1219 block.state = STATE_LOCKED;
1220 block.color = COLOR_GRAY;
1221 block.flame = false;
1222 block.vy = 0;
1223 block.settleTime = 0;
1224 if (block.clusterId != null)
1225 { this.leaveCluster(block); }
1226 }
1227 }
1228};
1229
1230GameCore.prototype.checkGameOver = function ()
1231{
1232 if (this.state !== 'playing')
1233 { return; }
1234 for (var col = 0; col < this.width; col++)
1235 {
1236 if (!this.isColumnLocked(col))
1237 { return; }
1238 }
1239 this.state = 'gameover';
1240 this.gameOverTime = 0;
1241 this.drag = null;
1242};
1243
1244/* ---------- dragging -------------------------------------------------- */
1245
1246GameCore.prototype.beginDrag = function (col, y)
1247{
1248 if (this.state !== 'playing')
1249 { return false; }
1250 col = col | 0;
1251 if (col < 0 || col >= this.width)
1252 { return false; }
1253 if (!this.isColumnStill(col))
1254 { return false; }
1255 var row = Math.floor(y + 1e-6);
1256 if (row < 0)
1257 { return false; }
1258 var block = this.blockAt(col, row);
1259 if (!block || block.state !== STATE_STILL || block.color < 0)
1260 { return false; }
1261 this.drag = { blockId: block.id, pointerY: y, launchIntent: false };
1262 return true;
1263};
1264
1265GameCore.prototype.moveDrag = function (y)
1266{
1267 if (!this.drag)
1268 { return; }
1269 var block = this.blockById(this.drag.blockId);
1270 if (!block || block.state !== STATE_STILL)
1271 {
1272 this.drag = null;
1273 return;
1274 }
1275 if (!this.isColumnStill(block.col))
1276 {
1277 this.drag = null;
1278 return;
1279 }
1280 this.drag.pointerY = y;
1281 this.swapToward(block, y);
1282 var top = this.columnStackTopRow(block.col);
1283 // The top block occupies [top, top+1). Launch only when the pointer
1284 // is pulled into the empty space above the stack.
1285 this.drag.launchIntent = (Math.abs(block.y - top) < ALIGN_EPS && y > top + 1 + 0.25);
1286};
1287
1288GameCore.prototype.endDrag = function ()
1289{
1290 if (!this.drag)
1291 { return; }
1292 var block = this.blockById(this.drag.blockId);
1293 var launch = this.drag.launchIntent;
1294 this.drag = null;
1295 if (launch && block && block.state === STATE_STILL)
1296 { this.startManualLaunch(block); }
1297 else
1298 { this.resolveMatches(); }
1299};
1300
1301GameCore.prototype.blockById = function (id)
1302{
1303 for (var i = 0; i < this.blocks.length; i++)
1304 {
1305 if (this.blocks[i].id === id)
1306 { return this.blocks[i]; }
1307 }
1308 return null;
1309};
1310
1311GameCore.prototype.columnStackTopRow = function (col)
1312{
1313 var top = -1;
1314 var list = this.blocksInColumn(col);
1315 for (var i = 0; i < list.length; i++)
1316 {
1317 if (this.isGrounded(list[i]) && list[i].y > top)
1318 { top = list[i].y; }
1319 }
1320 return top;
1321};
1322
1323GameCore.prototype.swapToward = function (block, targetY)
1324{
1325 var guard = 0;
1326 while (guard++ < this.height + 2)
1327 {
1328 var current = block.y;
1329 if (targetY > current + 0.5)
1330 {
1331 var above = this.blockAt(block.col, current + 1);
1332 if (above && this.isGrounded(above) && above !== block)
1333 { this.swapBlocks(block, above); }
1334 else
1335 { break; }
1336 }
1337 else if (targetY < current - 0.5)
1338 {
1339 var below = this.blockAt(block.col, current - 1);
1340 if (below && this.isGrounded(below) && below !== block)
1341 { this.swapBlocks(block, below); }
1342 else
1343 { break; }
1344 }
1345 else
1346 { break; }
1347 }
1348};
1349
1350GameCore.prototype.swapBlocks = function (a, b)
1351{
1352 var y = a.y;
1353 a.y = b.y;
1354 b.y = y;
1355};
1356
1357/**
1358 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
1359 * Returns the moved block, or null if the column is not still.
1360 */
1361GameCore.prototype.swapTo = function (col, fromRow, toRow)
1362{
1363 if (!this.isColumnStill(col))
1364 { return null; }
1365 var block = this.blockAt(col, fromRow);
1366 if (!block)
1367 { return null; }
1368 this.swapToward(block, toRow);
1369 return block;
1370};
1371
1372/**
1373 * Test helper: a compact picture of grounded/falling/flying blocks.
1374 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
1375 * L locked, f falling, m manual, . empty. Flying colored blocks use
1376 * their color with a marker in `flying`.
1377 */
1378GameCore.prototype.snapshot = function ()
1379{
1380 var grid = [];
1381 for (var r = 0; r < this.height; r++)
1382 {
1383 var row = [];
1384 for (var c = 0; c < this.width; c++)
1385 { row.push('.'); }
1386 grid.push(row);
1387 }
1388 var airborne = [];
1389 for (var i = 0; i < this.blocks.length; i++)
1390 {
1391 var block = this.blocks[i];
1392 var ch;
1393 if (block.state === STATE_LOCKED)
1394 { ch = 'L'; }
1395 else if (block.color === COLOR_GRAY)
1396 { ch = 'g'; }
1397 else
1398 { ch = String(block.color); }
1399 if (this.isGrounded(block) || block.state === STATE_FALLING)
1400 {
1401 var row = Math.round(block.y);
1402 if (row >= 0 && row < this.height)
1403 { grid[row][block.col] = ch; }
1404 }
1405 else
1406 {
1407 airborne.push({
1408 id: block.id,
1409 col: block.col,
1410 y: block.y,
1411 color: block.color,
1412 state: block.state,
1413 clusterId: block.clusterId,
1414 flame: block.flame,
1415 vy: block.vy
1416 });
1417 }
1418 }
1419 var lines = [];
1420 for (var r = this.height - 1; r >= 0; r--)
1421 { lines.push(grid[r].join('')); }
1422 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
1423};
1424
1425var GameCoreAPI = {
1426 GameCore: GameCore,
1427 COLOR_GRAY: COLOR_GRAY,
1428 STATE_STILL: STATE_STILL,
1429 STATE_FALLING: STATE_FALLING,
1430 STATE_FLYING: STATE_FLYING,
1431 STATE_SETTLING: STATE_SETTLING,
1432 STATE_LOCKED: STATE_LOCKED,
1433 STATE_MANUAL: STATE_MANUAL
1434};
1435
1436if (typeof module !== 'undefined' && module.exports)
1437{ module.exports = GameCoreAPI; }
1438else if (typeof globalThis !== 'undefined')
1439{
1440 globalThis.GameCore = GameCore;
1441 globalThis.GameCoreAPI = GameCoreAPI;
1442}
1443
1444/*
1445 * End File:
1446 * /workspace/meteors/src/gameCore.js
1447 */
1448
1449/*
1450 * Start File:
1451 * /workspace/meteors/src/main.js
1452 */
1453'use strict';
1454
1455/**
1456 * View and input for Meteors. The simulation lives in GameCore; this file
1457 * only draws it, scales it to the viewport, and translates pointer events
1458 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
1459 * that reuses the same core.
1460 */
1461
1462var IMAGES = [
1463 { name: 'ember', url: 'images/block-ember.png' },
1464 { name: 'aqua', url: 'images/block-aqua.png' },
1465 { name: 'leaf', url: 'images/block-leaf.png' },
1466 { name: 'sun', url: 'images/block-sun.png' },
1467 { name: 'orchid', url: 'images/block-orchid.png' },
1468 { name: 'gray', url: 'images/block-gray.png' },
1469 { name: 'locked', url: 'images/block-locked.png' },
1470 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
1471 { name: 'cell', url: 'images/cell.png' },
1472 { name: 'pixel', url: 'images/pixel.png' }
1473];
1474
1475var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
1476var GAME_OVER_DELAY = 2;
1477
1478var game = new Game();
1479var app = {
1480 mode: 'menu',
1481 core: null,
1482 scene: null,
1483 manager: null,
1484 planet: null,
1485 lastScore: 0,
1486 tile: 48,
1487 fieldX: 0,
1488 fieldY: 0,
1489 fieldW: 0,
1490 fieldH: 0,
1491 hudH: 56,
1492 sprites: Object.create(null),
1493 flames: Object.create(null),
1494 cells: [],
1495 pointerId: null,
1496 gameOverShown: false
1497};
1498
1499window.onload = function ()
1500{
1501 var play = document.getElementById('btn-play');
1502 play.addEventListener('click', onPlay);
1503 play.addEventListener('pointerup', function (e)
1504 {
1505 // A touch-friendly path: some mobile browsers swallow the click
1506 // after a slightly sloppy tap. Ignore the following click.
1507 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1508 {
1509 e.preventDefault();
1510 onPlay();
1511 }
1512 });
1513
1514 game.preloadImagesThenStart(IMAGES, function ()
1515 {
1516 if (game.images.flame && game.images.flame.addAnimationCycle)
1517 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
1518 });
1519};
1520
1521function onPlay ()
1522{
1523 if (app.mode === 'playing')
1524 { return; }
1525 startPlay();
1526}
1527
1528function startPlay ()
1529{
1530 hideEl('menu');
1531 hideEl('game-over');
1532 showEl('hud');
1533
1534 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
1535 app.core = new GameCore(app.planet, Math.random);
1536 app.mode = 'playing';
1537 app.gameOverShown = false;
1538 app.sprites = Object.create(null);
1539 app.flames = Object.create(null);
1540 app.cells = [];
1541 app.pointerId = null;
1542
1543 layout();
1544 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
1545 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
1546 app.scene.renderBackground = true;
1547 game.loadScene(app.scene);
1548
1549 buildCells();
1550 app.manager = app.scene.addObject(makeManager());
1551 bindPointer(app.scene.canvas);
1552 refreshHud();
1553}
1554
1555function returnToMenu ()
1556{
1557 unbindPointer();
1558 if (app.scene)
1559 {
1560 app.scene.destroy();
1561 app.scene = null;
1562 }
1563 app.manager = null;
1564 app.core = null;
1565 app.mode = 'menu';
1566 app.sprites = Object.create(null);
1567 app.flames = Object.create(null);
1568 app.cells = [];
1569
1570 hideEl('hud');
1571 hideEl('game-over');
1572 showEl('menu');
1573 var last = document.getElementById('last-score');
1574 if (app.lastScore > 0)
1575 {
1576 last.hidden = false;
1577 last.querySelector('strong').textContent = String(app.lastScore);
1578 }
1579}
1580
1581function buildCells ()
1582{
1583 if (!app.scene)
1584 { return; }
1585 var img = game.images.cell;
1586 for (var row = 0; row < 13; row++)
1587 {
1588 for (var col = 0; col < 10; col++)
1589 {
1590 var obj = new GameObject(0, 0, img, 0);
1591 placeTile(obj, col, row);
1592 obj.renderer.alpha = 0.9;
1593 app.scene.addObject(obj);
1594 app.cells.push(obj);
1595 }
1596 }
1597}
1598
1599function placeTile (obj, col, y)
1600{
1601 var t = app.tile;
1602 obj.transform.position.x = col * t + t / 2;
1603 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
1604 obj.transform.size = { x: t, y: t };
1605}
1606
1607function layout ()
1608{
1609 var vw = window.innerWidth || 320;
1610 var vh = window.innerHeight || 480;
1611 var safeTop = 0;
1612 try
1613 {
1614 // env(safe-area) is a CSS thing; keep a conservative HUD height.
1615 safeTop = 0;
1616 }
1617 catch (e) { /* ignore */ }
1618 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
1619 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
1620 var availW = Math.max(80, vw - margin * 2);
1621 var availH = Math.max(80, vh - app.hudH - margin);
1622 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
1623 app.fieldW = app.tile * 10;
1624 app.fieldH = app.tile * 13;
1625 app.fieldX = Math.floor((vw - app.fieldW) / 2);
1626 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
1627 if (app.fieldY < app.hudH)
1628 { app.fieldY = app.hudH; }
1629
1630 if (app.scene)
1631 {
1632 app.scene.position.x = app.fieldX;
1633 app.scene.position.y = app.fieldY;
1634 app.scene.size.x = app.fieldW;
1635 app.scene.size.y = app.fieldH;
1636 }
1637}
1638
1639function spriteFor (block)
1640{
1641 if (block.state === 'locked')
1642 { return game.images.locked; }
1643 if (block.color < 0)
1644 { return game.images.gray; }
1645 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
1646}
1647
1648function syncSprites ()
1649{
1650 if (!app.core || !app.scene)
1651 { return; }
1652 var seen = Object.create(null);
1653 var blocks = app.core.blocks;
1654 for (var i = 0; i < blocks.length; i++)
1655 {
1656 var block = blocks[i];
1657 seen[block.id] = true;
1658 var obj = app.sprites[block.id];
1659 if (!obj)
1660 {
1661 obj = new GameObject(0, 0, spriteFor(block), 2);
1662 app.scene.addObject(obj);
1663 app.sprites[block.id] = obj;
1664 }
1665 obj.renderer.sprite = spriteFor(block);
1666 placeTile(obj, block.col, block.y);
1667 obj.renderer.visible = true;
1668 obj.renderer.alpha = 1;
1669
1670 if (block.flame)
1671 {
1672 var flame = app.flames[block.id];
1673 if (!flame)
1674 {
1675 flame = new GameObject(0, 0, game.images.flame, 1);
1676 flame.renderer.setAnimation('burn', 0, 0.08);
1677 app.scene.addObject(flame);
1678 app.flames[block.id] = flame;
1679 }
1680 flame.renderer.visible = true;
1681 var t = app.tile;
1682 flame.transform.position.x = block.col * t + t / 2;
1683 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
1684 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
1685 }
1686 else if (app.flames[block.id])
1687 { app.flames[block.id].renderer.visible = false; }
1688 }
1689
1690 var ids = Object.keys(app.sprites);
1691 for (var i = 0; i < ids.length; i++)
1692 {
1693 if (!seen[ids[i]])
1694 {
1695 app.sprites[ids[i]].destroy();
1696 delete app.sprites[ids[i]];
1697 if (app.flames[ids[i]])
1698 {
1699 app.flames[ids[i]].destroy();
1700 delete app.flames[ids[i]];
1701 }
1702 }
1703 }
1704}
1705
1706function refreshHud ()
1707{
1708 if (!app.core)
1709 { return; }
1710 document.getElementById('score').textContent = String(app.core.score);
1711 var planet = app.planet;
1712 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
1713 var d = Planet.displayValues(planet);
1714 document.getElementById('planet-stats').textContent =
1715 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
1716 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
1717}
1718
1719function makeManager ()
1720{
1721 var obj = new GameObject(0, 0, game.images.pixel, 0);
1722 obj.renderer.visible = false;
1723 var base = obj.update.bind(obj);
1724 obj.update = function (dt)
1725 {
1726 base(dt);
1727 tickView(dt);
1728 };
1729 return obj;
1730}
1731
1732function tickView (dt)
1733{
1734 if (app.mode !== 'playing' || !app.core)
1735 { return; }
1736
1737 layout();
1738 for (var i = 0; i < app.cells.length; i++)
1739 {
1740 var col = i % 10;
1741 var row = Math.floor(i / 10);
1742 placeTile(app.cells[i], col, row);
1743 }
1744
1745 app.core.tick(dt);
1746 syncSprites();
1747 refreshHud();
1748
1749 if (app.core.state === 'gameover' && !app.gameOverShown)
1750 {
1751 app.gameOverShown = true;
1752 app.lastScore = app.core.score;
1753 document.getElementById('go-score').textContent = String(app.lastScore);
1754 showEl('game-over');
1755 }
1756 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
1757 { returnToMenu(); }
1758}
1759
1760/* ---------- pointer input (mouse + touch) --------------------------- */
1761
1762var boundCanvas = null;
1763
1764function bindPointer (canvas)
1765{
1766 unbindPointer();
1767 boundCanvas = canvas;
1768 canvas.addEventListener('pointerdown', onPointerDown);
1769 canvas.addEventListener('pointermove', onPointerMove);
1770 canvas.addEventListener('pointerup', onPointerUp);
1771 canvas.addEventListener('pointercancel', onPointerUp);
1772 canvas.addEventListener('lostpointercapture', onPointerUp);
1773 canvas.style.touchAction = 'none';
1774 canvas.style.cursor = 'pointer';
1775}
1776
1777function unbindPointer ()
1778{
1779 if (!boundCanvas)
1780 { return; }
1781 boundCanvas.removeEventListener('pointerdown', onPointerDown);
1782 boundCanvas.removeEventListener('pointermove', onPointerMove);
1783 boundCanvas.removeEventListener('pointerup', onPointerUp);
1784 boundCanvas.removeEventListener('pointercancel', onPointerUp);
1785 boundCanvas.removeEventListener('lostpointercapture', onPointerUp);
1786 boundCanvas = null;
1787 app.pointerId = null;
1788}
1789
1790function fieldFromEvent (e)
1791{
1792 var canvas = app.scene && app.scene.canvas;
1793 if (!canvas)
1794 { return null; }
1795 var rect = canvas.getBoundingClientRect();
1796 if (rect.width <= 0 || rect.height <= 0)
1797 { return null; }
1798 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
1799 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
1800 var col = Math.floor(x / app.tile);
1801 var fieldY = (canvas.height - y) / app.tile;
1802 return { col: col, y: fieldY };
1803}
1804
1805function onPointerDown (e)
1806{
1807 if (!app.core || app.core.state !== 'playing')
1808 { return; }
1809 if (app.pointerId != null)
1810 { return; }
1811 e.preventDefault();
1812 app.pointerId = e.pointerId;
1813 try
1814 { boundCanvas.setPointerCapture(e.pointerId); }
1815 catch (err) { /* ignore */ }
1816 var pos = fieldFromEvent(e);
1817 if (pos)
1818 { app.core.beginDrag(pos.col, pos.y); }
1819}
1820
1821function onPointerMove (e)
1822{
1823 if (app.pointerId == null || e.pointerId !== app.pointerId)
1824 { return; }
1825 if (!app.core || !app.core.drag)
1826 { return; }
1827 e.preventDefault();
1828 var pos = fieldFromEvent(e);
1829 if (pos)
1830 { app.core.moveDrag(pos.y); }
1831}
1832
1833function onPointerUp (e)
1834{
1835 if (app.pointerId == null)
1836 { return; }
1837 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1838 { return; }
1839 if (e)
1840 { e.preventDefault(); }
1841 app.pointerId = null;
1842 if (app.core)
1843 { app.core.endDrag(); }
1844}
1845
1846function hideEl (id)
1847{
1848 document.getElementById(id).hidden = true;
1849}
1850
1851function showEl (id)
1852{
1853 document.getElementById(id).hidden = false;
1854}
1855
1856window.addEventListener('resize', function ()
1857{
1858 if (app.mode === 'playing')
1859 { layout(); }
1860});
1861
1862window.addEventListener('orientationchange', function ()
1863{
1864 setTimeout(function ()
1865 {
1866 if (app.mode === 'playing')
1867 { layout(); }
1868 }, 120);
1869});
1870
1871/*
1872 * End File:
1873 * /workspace/meteors/src/main.js
1874 */
build/index.html added +44 −0
@@ -0,0 +1,44 @@
1 <!DOCTYPE html>
2 <html lang="nl">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
6 <meta name="apple-mobile-web-app-capable" content="yes">
7 <meta name="mobile-web-app-capable" content="yes">
8 <meta name="theme-color" content="#0b1020">
9 <link rel="icon" href="favicon.ico" sizes="any">
10 <title>Meteors</title>
11 <link rel="stylesheet" href="style.css">
12 </head>
13 <body>
14 <div id="stars" aria-hidden="true"></div>
15
16 <div id="menu" class="screen">
17 <h1>Meteors</h1>
18 <p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
19 <button type="button" id="btn-play">Spelen</button>
20 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
21 <p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
22 </div>
23
24 <div id="hud" hidden>
25 <div class="hud-left">
26 <div class="hud-label">Punten</div>
27 <div id="score">0</div>
28 </div>
29 <div class="hud-right">
30 <div id="planet-name">Terra</div>
31 <div id="planet-stats"></div>
32 </div>
33 </div>
34
35 <div id="game-over" class="screen overlay" hidden>
36 <h2>Je hebt verloren</h2>
37 <p>Alle kolommen zitten vast.</p>
38 <p class="go-score">Score: <strong id="go-score">0</strong></p>
39 </div>
40
41 <script src="framework.js"></script>
42 <script src="game.js"></script>
43 </body>
44 </html>
@@ -0,0 +1,44 @@
1<!DOCTYPE html>
2<html lang="nl">
3<head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
6 <meta name="apple-mobile-web-app-capable" content="yes">
7 <meta name="mobile-web-app-capable" content="yes">
8 <meta name="theme-color" content="#0b1020">
9 <link rel="icon" href="favicon.ico" sizes="any">
10 <title>Meteors</title>
11 <link rel="stylesheet" href="style.css">
12</head>
13<body>
14 <div id="stars" aria-hidden="true"></div>
15
16 <div id="menu" class="screen">
17 <h1>Meteors</h1>
18 <p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
19 <button type="button" id="btn-play">Spelen</button>
20 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
21 <p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
22 </div>
23
24 <div id="hud" hidden>
25 <div class="hud-left">
26 <div class="hud-label">Punten</div>
27 <div id="score">0</div>
28 </div>
29 <div class="hud-right">
30 <div id="planet-name">Terra</div>
31 <div id="planet-stats"></div>
32 </div>
33 </div>
34
35 <div id="game-over" class="screen overlay" hidden>
36 <h2>Je hebt verloren</h2>
37 <p>Alle kolommen zitten vast.</p>
38 <p class="go-score">Score: <strong id="go-score">0</strong></p>
39 </div>
40
41 <script src="framework.js"></script>
42 <script src="game.js"></script>
43</body>
44</html>
build/style.css added +185 −0
@@ -0,0 +1,185 @@
1 /* Meteors — responsive, portrait-friendly, no page scroll during play. */
2 *, *::before, *::after { box-sizing: border-box; }
3
4 html, body {
5 margin: 0;
6 padding: 0;
7 width: 100%;
8 height: 100%;
9 overflow: hidden;
10 background: #0b1020;
11 color: #e8eaf2;
12 font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
13 touch-action: none;
14 -webkit-user-select: none;
15 user-select: none;
16 -webkit-tap-highlight-color: transparent;
17 }
18
19 #stars {
20 position: fixed;
21 inset: 0;
22 pointer-events: none;
23 background:
24 radial-gradient(1px 1px at 12% 18%, #fff 0 50%, transparent 51%),
25 radial-gradient(1px 1px at 28% 72%, #cde 0 50%, transparent 51%),
26 radial-gradient(1.5px 1.5px at 47% 32%, #fff 0 50%, transparent 51%),
27 radial-gradient(1px 1px at 63% 81%, #bbd 0 50%, transparent 51%),
28 radial-gradient(1px 1px at 81% 22%, #fff 0 50%, transparent 51%),
29 radial-gradient(1.5px 1.5px at 91% 64%, #def 0 50%, transparent 51%),
30 radial-gradient(1px 1px at 8% 88%, #fff 0 50%, transparent 51%),
31 radial-gradient(2px 2px at 72% 48%, #89a 0 50%, transparent 51%),
32 linear-gradient(180deg, #0b1020 0%, #141a33 55%, #1a1440 100%);
33 z-index: 0;
34 }
35
36 .screen {
37 position: fixed;
38 inset: 0;
39 z-index: 5;
40 display: flex;
41 flex-direction: column;
42 align-items: center;
43 justify-content: center;
44 padding: 24px 20px;
45 text-align: center;
46 }
47
48 .screen[hidden], #hud[hidden], #game-over[hidden] { display: none !important; }
49
50 h1 {
51 font-size: clamp(48px, 14vw, 96px);
52 letter-spacing: 0.06em;
53 margin: 0 0 8px;
54 font-weight: 800;
55 background: linear-gradient(180deg, #fff6c8 0%, #ff9a3a 45%, #e85d3a 100%);
56 -webkit-background-clip: text;
57 background-clip: text;
58 color: transparent;
59 filter: drop-shadow(0 2px 12px rgba(232, 93, 58, 0.55));
60 }
61
62 .tagline {
63 margin: 0 0 28px;
64 font-size: clamp(15px, 3.6vw, 20px);
65 color: #c5cae0;
66 max-width: 28em;
67 }
68
69 #btn-play {
70 appearance: none;
71 border: 0;
72 cursor: pointer;
73 font: inherit;
74 font-size: clamp(20px, 5vw, 28px);
75 font-weight: 700;
76 letter-spacing: 0.08em;
77 text-transform: uppercase;
78 color: #1a1020;
79 background: linear-gradient(180deg, #ffe27a, #f0c53a 40%, #e89a20);
80 padding: 14px 48px;
81 border-radius: 999px;
82 box-shadow:
83 0 0 0 3px rgba(255, 220, 120, 0.25),
84 0 8px 24px rgba(240, 197, 58, 0.45);
85 touch-action: manipulation;
86 min-height: 52px;
87 min-width: 200px;
88 }
89
90 #btn-play:is(:hover, :focus-visible) {
91 transform: translateY(-1px);
92 box-shadow:
93 0 0 0 3px rgba(255, 220, 120, 0.4),
94 0 10px 28px rgba(240, 197, 58, 0.6);
95 }
96
97 #btn-play:active { transform: translateY(1px); }
98
99 .last-score {
100 margin: 22px 0 0;
101 font-size: clamp(16px, 4vw, 22px);
102 color: #ffe27a;
103 }
104
105 .hint {
106 margin: 36px auto 0;
107 max-width: 32em;
108 font-size: clamp(13px, 3.2vw, 16px);
109 line-height: 1.45;
110 color: #8e95b3;
111 }
112
113 #hud {
114 position: fixed;
115 top: 0;
116 left: 0;
117 right: 0;
118 z-index: 4;
119 display: flex;
120 justify-content: space-between;
121 align-items: flex-start;
122 padding: calc(8px + env(safe-area-inset-top, 0px)) 14px 4px;
123 pointer-events: none;
124 text-shadow: 0 1px 4px #000;
125 gap: 12px;
126 }
127
128 .hud-label {
129 font-size: 11px;
130 letter-spacing: 0.14em;
131 text-transform: uppercase;
132 color: #9aa3c2;
133 }
134
135 #score {
136 font-size: clamp(28px, 8vw, 42px);
137 font-weight: 800;
138 line-height: 1;
139 color: #fff6c8;
140 }
141
142 #planet-name {
143 font-weight: 700;
144 font-size: clamp(14px, 3.5vw, 18px);
145 text-align: right;
146 }
147
148 #planet-stats {
149 font-variant-numeric: tabular-nums;
150 font-size: clamp(11px, 2.8vw, 14px);
151 color: #b7bdd4;
152 text-align: right;
153 white-space: nowrap;
154 }
155
156 .overlay {
157 background: rgba(8, 10, 22, 0.78);
158 backdrop-filter: blur(6px);
159 }
160
161 .overlay h2 {
162 font-size: clamp(32px, 9vw, 56px);
163 margin: 0 0 8px;
164 color: #ffb0a0;
165 }
166
167 .go-score {
168 font-size: clamp(20px, 5vw, 28px);
169 color: #ffe27a;
170 margin-top: 18px;
171 }
172
173 /* Framework canvases sit on the body. Keep them above the starfield, below HUD. */
174 canvas {
175 z-index: 2;
176 touch-action: none;
177 display: block;
178 }
179
180 /* Very narrow / short phones: shrink hints so the Play button stays on screen. */
181 @media (max-height: 520px) {
182 .hint { display: none; }
183 h1 { font-size: 42px; }
184 #btn-play { padding: 10px 36px; }
185 }
@@ -0,0 +1,185 @@
1/* Meteors — responsive, portrait-friendly, no page scroll during play. */
2*, *::before, *::after { box-sizing: border-box; }
3
4html, body {
5 margin: 0;
6 padding: 0;
7 width: 100%;
8 height: 100%;
9 overflow: hidden;
10 background: #0b1020;
11 color: #e8eaf2;
12 font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
13 touch-action: none;
14 -webkit-user-select: none;
15 user-select: none;
16 -webkit-tap-highlight-color: transparent;
17}
18
19#stars {
20 position: fixed;
21 inset: 0;
22 pointer-events: none;
23 background:
24 radial-gradient(1px 1px at 12% 18%, #fff 0 50%, transparent 51%),
25 radial-gradient(1px 1px at 28% 72%, #cde 0 50%, transparent 51%),
26 radial-gradient(1.5px 1.5px at 47% 32%, #fff 0 50%, transparent 51%),
27 radial-gradient(1px 1px at 63% 81%, #bbd 0 50%, transparent 51%),
28 radial-gradient(1px 1px at 81% 22%, #fff 0 50%, transparent 51%),
29 radial-gradient(1.5px 1.5px at 91% 64%, #def 0 50%, transparent 51%),
30 radial-gradient(1px 1px at 8% 88%, #fff 0 50%, transparent 51%),
31 radial-gradient(2px 2px at 72% 48%, #89a 0 50%, transparent 51%),
32 linear-gradient(180deg, #0b1020 0%, #141a33 55%, #1a1440 100%);
33 z-index: 0;
34}
35
36.screen {
37 position: fixed;
38 inset: 0;
39 z-index: 5;
40 display: flex;
41 flex-direction: column;
42 align-items: center;
43 justify-content: center;
44 padding: 24px 20px;
45 text-align: center;
46}
47
48.screen[hidden], #hud[hidden], #game-over[hidden] { display: none !important; }
49
50h1 {
51 font-size: clamp(48px, 14vw, 96px);
52 letter-spacing: 0.06em;
53 margin: 0 0 8px;
54 font-weight: 800;
55 background: linear-gradient(180deg, #fff6c8 0%, #ff9a3a 45%, #e85d3a 100%);
56 -webkit-background-clip: text;
57 background-clip: text;
58 color: transparent;
59 filter: drop-shadow(0 2px 12px rgba(232, 93, 58, 0.55));
60}
61
62.tagline {
63 margin: 0 0 28px;
64 font-size: clamp(15px, 3.6vw, 20px);
65 color: #c5cae0;
66 max-width: 28em;
67}
68
69#btn-play {
70 appearance: none;
71 border: 0;
72 cursor: pointer;
73 font: inherit;
74 font-size: clamp(20px, 5vw, 28px);
75 font-weight: 700;
76 letter-spacing: 0.08em;
77 text-transform: uppercase;
78 color: #1a1020;
79 background: linear-gradient(180deg, #ffe27a, #f0c53a 40%, #e89a20);
80 padding: 14px 48px;
81 border-radius: 999px;
82 box-shadow:
83 0 0 0 3px rgba(255, 220, 120, 0.25),
84 0 8px 24px rgba(240, 197, 58, 0.45);
85 touch-action: manipulation;
86 min-height: 52px;
87 min-width: 200px;
88}
89
90#btn-play:is(:hover, :focus-visible) {
91 transform: translateY(-1px);
92 box-shadow:
93 0 0 0 3px rgba(255, 220, 120, 0.4),
94 0 10px 28px rgba(240, 197, 58, 0.6);
95}
96
97#btn-play:active { transform: translateY(1px); }
98
99.last-score {
100 margin: 22px 0 0;
101 font-size: clamp(16px, 4vw, 22px);
102 color: #ffe27a;
103}
104
105.hint {
106 margin: 36px auto 0;
107 max-width: 32em;
108 font-size: clamp(13px, 3.2vw, 16px);
109 line-height: 1.45;
110 color: #8e95b3;
111}
112
113#hud {
114 position: fixed;
115 top: 0;
116 left: 0;
117 right: 0;
118 z-index: 4;
119 display: flex;
120 justify-content: space-between;
121 align-items: flex-start;
122 padding: calc(8px + env(safe-area-inset-top, 0px)) 14px 4px;
123 pointer-events: none;
124 text-shadow: 0 1px 4px #000;
125 gap: 12px;
126}
127
128.hud-label {
129 font-size: 11px;
130 letter-spacing: 0.14em;
131 text-transform: uppercase;
132 color: #9aa3c2;
133}
134
135#score {
136 font-size: clamp(28px, 8vw, 42px);
137 font-weight: 800;
138 line-height: 1;
139 color: #fff6c8;
140}
141
142#planet-name {
143 font-weight: 700;
144 font-size: clamp(14px, 3.5vw, 18px);
145 text-align: right;
146}
147
148#planet-stats {
149 font-variant-numeric: tabular-nums;
150 font-size: clamp(11px, 2.8vw, 14px);
151 color: #b7bdd4;
152 text-align: right;
153 white-space: nowrap;
154}
155
156.overlay {
157 background: rgba(8, 10, 22, 0.78);
158 backdrop-filter: blur(6px);
159}
160
161.overlay h2 {
162 font-size: clamp(32px, 9vw, 56px);
163 margin: 0 0 8px;
164 color: #ffb0a0;
165}
166
167.go-score {
168 font-size: clamp(20px, 5vw, 28px);
169 color: #ffe27a;
170 margin-top: 18px;
171}
172
173/* Framework canvases sit on the body. Keep them above the starfield, below HUD. */
174canvas {
175 z-index: 2;
176 touch-action: none;
177 display: block;
178}
179
180/* Very narrow / short phones: shrink hints so the Play button stays on screen. */
181@media (max-height: 520px) {
182 .hint { display: none; }
183 h1 { font-size: 42px; }
184 #btn-play { padding: 10px 36px; }
185}
src/main.js added +417 −0
@@ -0,0 +1,417 @@
1 'use strict';
2
3 /**
4 * View and input for Meteors. The simulation lives in GameCore; this file
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
7 * that reuses the same core.
8 */
9
10 var IMAGES = [
11 { name: 'ember', url: 'images/block-ember.png' },
12 { name: 'aqua', url: 'images/block-aqua.png' },
13 { name: 'leaf', url: 'images/block-leaf.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
16 { name: 'gray', url: 'images/block-gray.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
19 { name: 'cell', url: 'images/cell.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
21 ];
22
23 var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
24 var GAME_OVER_DELAY = 2;
25
26 var game = new Game();
27 var app = {
28 mode: 'menu',
29 core: null,
30 scene: null,
31 manager: null,
32 planet: null,
33 lastScore: 0,
34 tile: 48,
35 fieldX: 0,
36 fieldY: 0,
37 fieldW: 0,
38 fieldH: 0,
39 hudH: 56,
40 sprites: Object.create(null),
41 flames: Object.create(null),
42 cells: [],
43 pointerId: null,
44 gameOverShown: false
45 };
46
47 window.onload = function ()
48 {
49 var play = document.getElementById('btn-play');
50 play.addEventListener('click', onPlay);
51 play.addEventListener('pointerup', function (e)
52 {
53 // A touch-friendly path: some mobile browsers swallow the click
54 // after a slightly sloppy tap. Ignore the following click.
55 if (e.pointerType === 'touch' || e.pointerType === 'pen')
56 {
57 e.preventDefault();
58 onPlay();
59 }
60 });
61
62 game.preloadImagesThenStart(IMAGES, function ()
63 {
64 if (game.images.flame && game.images.flame.addAnimationCycle)
65 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
66 });
67 };
68
69 function onPlay ()
70 {
71 if (app.mode === 'playing')
72 { return; }
73 startPlay();
74 }
75
76 function startPlay ()
77 {
78 hideEl('menu');
79 hideEl('game-over');
80 showEl('hud');
81
82 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
83 app.core = new GameCore(app.planet, Math.random);
84 app.mode = 'playing';
85 app.gameOverShown = false;
86 app.sprites = Object.create(null);
87 app.flames = Object.create(null);
88 app.cells = [];
89 app.pointerId = null;
90
91 layout();
92 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
93 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
94 app.scene.renderBackground = true;
95 game.loadScene(app.scene);
96
97 buildCells();
98 app.manager = app.scene.addObject(makeManager());
99 bindPointer(app.scene.canvas);
100 refreshHud();
101 }
102
103 function returnToMenu ()
104 {
105 unbindPointer();
106 if (app.scene)
107 {
108 app.scene.destroy();
109 app.scene = null;
110 }
111 app.manager = null;
112 app.core = null;
113 app.mode = 'menu';
114 app.sprites = Object.create(null);
115 app.flames = Object.create(null);
116 app.cells = [];
117
118 hideEl('hud');
119 hideEl('game-over');
120 showEl('menu');
121 var last = document.getElementById('last-score');
122 if (app.lastScore > 0)
123 {
124 last.hidden = false;
125 last.querySelector('strong').textContent = String(app.lastScore);
126 }
127 }
128
129 function buildCells ()
130 {
131 if (!app.scene)
132 { return; }
133 var img = game.images.cell;
134 for (var row = 0; row < 13; row++)
135 {
136 for (var col = 0; col < 10; col++)
137 {
138 var obj = new GameObject(0, 0, img, 0);
139 placeTile(obj, col, row);
140 obj.renderer.alpha = 0.9;
141 app.scene.addObject(obj);
142 app.cells.push(obj);
143 }
144 }
145 }
146
147 function placeTile (obj, col, y)
148 {
149 var t = app.tile;
150 obj.transform.position.x = col * t + t / 2;
151 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
152 obj.transform.size = { x: t, y: t };
153 }
154
155 function layout ()
156 {
157 var vw = window.innerWidth || 320;
158 var vh = window.innerHeight || 480;
159 var safeTop = 0;
160 try
161 {
162 // env(safe-area) is a CSS thing; keep a conservative HUD height.
163 safeTop = 0;
164 }
165 catch (e) { /* ignore */ }
166 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
167 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
168 var availW = Math.max(80, vw - margin * 2);
169 var availH = Math.max(80, vh - app.hudH - margin);
170 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
171 app.fieldW = app.tile * 10;
172 app.fieldH = app.tile * 13;
173 app.fieldX = Math.floor((vw - app.fieldW) / 2);
174 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
175 if (app.fieldY < app.hudH)
176 { app.fieldY = app.hudH; }
177
178 if (app.scene)
179 {
180 app.scene.position.x = app.fieldX;
181 app.scene.position.y = app.fieldY;
182 app.scene.size.x = app.fieldW;
183 app.scene.size.y = app.fieldH;
184 }
185 }
186
187 function spriteFor (block)
188 {
189 if (block.state === 'locked')
190 { return game.images.locked; }
191 if (block.color < 0)
192 { return game.images.gray; }
193 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
194 }
195
196 function syncSprites ()
197 {
198 if (!app.core || !app.scene)
199 { return; }
200 var seen = Object.create(null);
201 var blocks = app.core.blocks;
202 for (var i = 0; i < blocks.length; i++)
203 {
204 var block = blocks[i];
205 seen[block.id] = true;
206 var obj = app.sprites[block.id];
207 if (!obj)
208 {
209 obj = new GameObject(0, 0, spriteFor(block), 2);
210 app.scene.addObject(obj);
211 app.sprites[block.id] = obj;
212 }
213 obj.renderer.sprite = spriteFor(block);
214 placeTile(obj, block.col, block.y);
215 obj.renderer.visible = true;
216 obj.renderer.alpha = 1;
217
218 if (block.flame)
219 {
220 var flame = app.flames[block.id];
221 if (!flame)
222 {
223 flame = new GameObject(0, 0, game.images.flame, 1);
224 flame.renderer.setAnimation('burn', 0, 0.08);
225 app.scene.addObject(flame);
226 app.flames[block.id] = flame;
227 }
228 flame.renderer.visible = true;
229 var t = app.tile;
230 flame.transform.position.x = block.col * t + t / 2;
231 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
232 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
233 }
234 else if (app.flames[block.id])
235 { app.flames[block.id].renderer.visible = false; }
236 }
237
238 var ids = Object.keys(app.sprites);
239 for (var i = 0; i < ids.length; i++)
240 {
241 if (!seen[ids[i]])
242 {
243 app.sprites[ids[i]].destroy();
244 delete app.sprites[ids[i]];
245 if (app.flames[ids[i]])
246 {
247 app.flames[ids[i]].destroy();
248 delete app.flames[ids[i]];
249 }
250 }
251 }
252 }
253
254 function refreshHud ()
255 {
256 if (!app.core)
257 { return; }
258 document.getElementById('score').textContent = String(app.core.score);
259 var planet = app.planet;
260 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
261 var d = Planet.displayValues(planet);
262 document.getElementById('planet-stats').textContent =
263 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
264 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
265 }
266
267 function makeManager ()
268 {
269 var obj = new GameObject(0, 0, game.images.pixel, 0);
270 obj.renderer.visible = false;
271 var base = obj.update.bind(obj);
272 obj.update = function (dt)
273 {
274 base(dt);
275 tickView(dt);
276 };
277 return obj;
278 }
279
280 function tickView (dt)
281 {
282 if (app.mode !== 'playing' || !app.core)
283 { return; }
284
285 layout();
286 for (var i = 0; i < app.cells.length; i++)
287 {
288 var col = i % 10;
289 var row = Math.floor(i / 10);
290 placeTile(app.cells[i], col, row);
291 }
292
293 app.core.tick(dt);
294 syncSprites();
295 refreshHud();
296
297 if (app.core.state === 'gameover' && !app.gameOverShown)
298 {
299 app.gameOverShown = true;
300 app.lastScore = app.core.score;
301 document.getElementById('go-score').textContent = String(app.lastScore);
302 showEl('game-over');
303 }
304 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
305 { returnToMenu(); }
306 }
307
308 /* ---------- pointer input (mouse + touch) --------------------------- */
309
310 var boundCanvas = null;
311
312 function bindPointer (canvas)
313 {
314 unbindPointer();
315 boundCanvas = canvas;
316 canvas.addEventListener('pointerdown', onPointerDown);
317 canvas.addEventListener('pointermove', onPointerMove);
318 canvas.addEventListener('pointerup', onPointerUp);
319 canvas.addEventListener('pointercancel', onPointerUp);
320 canvas.addEventListener('lostpointercapture', onPointerUp);
321 canvas.style.touchAction = 'none';
322 canvas.style.cursor = 'pointer';
323 }
324
325 function unbindPointer ()
326 {
327 if (!boundCanvas)
328 { return; }
329 boundCanvas.removeEventListener('pointerdown', onPointerDown);
330 boundCanvas.removeEventListener('pointermove', onPointerMove);
331 boundCanvas.removeEventListener('pointerup', onPointerUp);
332 boundCanvas.removeEventListener('pointercancel', onPointerUp);
333 boundCanvas.removeEventListener('lostpointercapture', onPointerUp);
334 boundCanvas = null;
335 app.pointerId = null;
336 }
337
338 function fieldFromEvent (e)
339 {
340 var canvas = app.scene && app.scene.canvas;
341 if (!canvas)
342 { return null; }
343 var rect = canvas.getBoundingClientRect();
344 if (rect.width <= 0 || rect.height <= 0)
345 { return null; }
346 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
347 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
348 var col = Math.floor(x / app.tile);
349 var fieldY = (canvas.height - y) / app.tile;
350 return { col: col, y: fieldY };
351 }
352
353 function onPointerDown (e)
354 {
355 if (!app.core || app.core.state !== 'playing')
356 { return; }
357 if (app.pointerId != null)
358 { return; }
359 e.preventDefault();
360 app.pointerId = e.pointerId;
361 try
362 { boundCanvas.setPointerCapture(e.pointerId); }
363 catch (err) { /* ignore */ }
364 var pos = fieldFromEvent(e);
365 if (pos)
366 { app.core.beginDrag(pos.col, pos.y); }
367 }
368
369 function onPointerMove (e)
370 {
371 if (app.pointerId == null || e.pointerId !== app.pointerId)
372 { return; }
373 if (!app.core || !app.core.drag)
374 { return; }
375 e.preventDefault();
376 var pos = fieldFromEvent(e);
377 if (pos)
378 { app.core.moveDrag(pos.y); }
379 }
380
381 function onPointerUp (e)
382 {
383 if (app.pointerId == null)
384 { return; }
385 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
386 { return; }
387 if (e)
388 { e.preventDefault(); }
389 app.pointerId = null;
390 if (app.core)
391 { app.core.endDrag(); }
392 }
393
394 function hideEl (id)
395 {
396 document.getElementById(id).hidden = true;
397 }
398
399 function showEl (id)
400 {
401 document.getElementById(id).hidden = false;
402 }
403
404 window.addEventListener('resize', function ()
405 {
406 if (app.mode === 'playing')
407 { layout(); }
408 });
409
410 window.addEventListener('orientationchange', function ()
411 {
412 setTimeout(function ()
413 {
414 if (app.mode === 'playing')
415 { layout(); }
416 }, 120);
417 });
@@ -0,0 +1,417 @@
1'use strict';
2
3/**
4 * View and input for Meteors. The simulation lives in GameCore; this file
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
7 * that reuses the same core.
8 */
9
10var IMAGES = [
11 { name: 'ember', url: 'images/block-ember.png' },
12 { name: 'aqua', url: 'images/block-aqua.png' },
13 { name: 'leaf', url: 'images/block-leaf.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
16 { name: 'gray', url: 'images/block-gray.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
19 { name: 'cell', url: 'images/cell.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
21];
22
23var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
24var GAME_OVER_DELAY = 2;
25
26var game = new Game();
27var app = {
28 mode: 'menu',
29 core: null,
30 scene: null,
31 manager: null,
32 planet: null,
33 lastScore: 0,
34 tile: 48,
35 fieldX: 0,
36 fieldY: 0,
37 fieldW: 0,
38 fieldH: 0,
39 hudH: 56,
40 sprites: Object.create(null),
41 flames: Object.create(null),
42 cells: [],
43 pointerId: null,
44 gameOverShown: false
45};
46
47window.onload = function ()
48{
49 var play = document.getElementById('btn-play');
50 play.addEventListener('click', onPlay);
51 play.addEventListener('pointerup', function (e)
52 {
53 // A touch-friendly path: some mobile browsers swallow the click
54 // after a slightly sloppy tap. Ignore the following click.
55 if (e.pointerType === 'touch' || e.pointerType === 'pen')
56 {
57 e.preventDefault();
58 onPlay();
59 }
60 });
61
62 game.preloadImagesThenStart(IMAGES, function ()
63 {
64 if (game.images.flame && game.images.flame.addAnimationCycle)
65 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
66 });
67};
68
69function onPlay ()
70{
71 if (app.mode === 'playing')
72 { return; }
73 startPlay();
74}
75
76function startPlay ()
77{
78 hideEl('menu');
79 hideEl('game-over');
80 showEl('hud');
81
82 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
83 app.core = new GameCore(app.planet, Math.random);
84 app.mode = 'playing';
85 app.gameOverShown = false;
86 app.sprites = Object.create(null);
87 app.flames = Object.create(null);
88 app.cells = [];
89 app.pointerId = null;
90
91 layout();
92 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
93 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
94 app.scene.renderBackground = true;
95 game.loadScene(app.scene);
96
97 buildCells();
98 app.manager = app.scene.addObject(makeManager());
99 bindPointer(app.scene.canvas);
100 refreshHud();
101}
102
103function returnToMenu ()
104{
105 unbindPointer();
106 if (app.scene)
107 {
108 app.scene.destroy();
109 app.scene = null;
110 }
111 app.manager = null;
112 app.core = null;
113 app.mode = 'menu';
114 app.sprites = Object.create(null);
115 app.flames = Object.create(null);
116 app.cells = [];
117
118 hideEl('hud');
119 hideEl('game-over');
120 showEl('menu');
121 var last = document.getElementById('last-score');
122 if (app.lastScore > 0)
123 {
124 last.hidden = false;
125 last.querySelector('strong').textContent = String(app.lastScore);
126 }
127}
128
129function buildCells ()
130{
131 if (!app.scene)
132 { return; }
133 var img = game.images.cell;
134 for (var row = 0; row < 13; row++)
135 {
136 for (var col = 0; col < 10; col++)
137 {
138 var obj = new GameObject(0, 0, img, 0);
139 placeTile(obj, col, row);
140 obj.renderer.alpha = 0.9;
141 app.scene.addObject(obj);
142 app.cells.push(obj);
143 }
144 }
145}
146
147function placeTile (obj, col, y)
148{
149 var t = app.tile;
150 obj.transform.position.x = col * t + t / 2;
151 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
152 obj.transform.size = { x: t, y: t };
153}
154
155function layout ()
156{
157 var vw = window.innerWidth || 320;
158 var vh = window.innerHeight || 480;
159 var safeTop = 0;
160 try
161 {
162 // env(safe-area) is a CSS thing; keep a conservative HUD height.
163 safeTop = 0;
164 }
165 catch (e) { /* ignore */ }
166 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
167 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
168 var availW = Math.max(80, vw - margin * 2);
169 var availH = Math.max(80, vh - app.hudH - margin);
170 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
171 app.fieldW = app.tile * 10;
172 app.fieldH = app.tile * 13;
173 app.fieldX = Math.floor((vw - app.fieldW) / 2);
174 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
175 if (app.fieldY < app.hudH)
176 { app.fieldY = app.hudH; }
177
178 if (app.scene)
179 {
180 app.scene.position.x = app.fieldX;
181 app.scene.position.y = app.fieldY;
182 app.scene.size.x = app.fieldW;
183 app.scene.size.y = app.fieldH;
184 }
185}
186
187function spriteFor (block)
188{
189 if (block.state === 'locked')
190 { return game.images.locked; }
191 if (block.color < 0)
192 { return game.images.gray; }
193 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
194}
195
196function syncSprites ()
197{
198 if (!app.core || !app.scene)
199 { return; }
200 var seen = Object.create(null);
201 var blocks = app.core.blocks;
202 for (var i = 0; i < blocks.length; i++)
203 {
204 var block = blocks[i];
205 seen[block.id] = true;
206 var obj = app.sprites[block.id];
207 if (!obj)
208 {
209 obj = new GameObject(0, 0, spriteFor(block), 2);
210 app.scene.addObject(obj);
211 app.sprites[block.id] = obj;
212 }
213 obj.renderer.sprite = spriteFor(block);
214 placeTile(obj, block.col, block.y);
215 obj.renderer.visible = true;
216 obj.renderer.alpha = 1;
217
218 if (block.flame)
219 {
220 var flame = app.flames[block.id];
221 if (!flame)
222 {
223 flame = new GameObject(0, 0, game.images.flame, 1);
224 flame.renderer.setAnimation('burn', 0, 0.08);
225 app.scene.addObject(flame);
226 app.flames[block.id] = flame;
227 }
228 flame.renderer.visible = true;
229 var t = app.tile;
230 flame.transform.position.x = block.col * t + t / 2;
231 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
232 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
233 }
234 else if (app.flames[block.id])
235 { app.flames[block.id].renderer.visible = false; }
236 }
237
238 var ids = Object.keys(app.sprites);
239 for (var i = 0; i < ids.length; i++)
240 {
241 if (!seen[ids[i]])
242 {
243 app.sprites[ids[i]].destroy();
244 delete app.sprites[ids[i]];
245 if (app.flames[ids[i]])
246 {
247 app.flames[ids[i]].destroy();
248 delete app.flames[ids[i]];
249 }
250 }
251 }
252}
253
254function refreshHud ()
255{
256 if (!app.core)
257 { return; }
258 document.getElementById('score').textContent = String(app.core.score);
259 var planet = app.planet;
260 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
261 var d = Planet.displayValues(planet);
262 document.getElementById('planet-stats').textContent =
263 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
264 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
265}
266
267function makeManager ()
268{
269 var obj = new GameObject(0, 0, game.images.pixel, 0);
270 obj.renderer.visible = false;
271 var base = obj.update.bind(obj);
272 obj.update = function (dt)
273 {
274 base(dt);
275 tickView(dt);
276 };
277 return obj;
278}
279
280function tickView (dt)
281{
282 if (app.mode !== 'playing' || !app.core)
283 { return; }
284
285 layout();
286 for (var i = 0; i < app.cells.length; i++)
287 {
288 var col = i % 10;
289 var row = Math.floor(i / 10);
290 placeTile(app.cells[i], col, row);
291 }
292
293 app.core.tick(dt);
294 syncSprites();
295 refreshHud();
296
297 if (app.core.state === 'gameover' && !app.gameOverShown)
298 {
299 app.gameOverShown = true;
300 app.lastScore = app.core.score;
301 document.getElementById('go-score').textContent = String(app.lastScore);
302 showEl('game-over');
303 }
304 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
305 { returnToMenu(); }
306}
307
308/* ---------- pointer input (mouse + touch) --------------------------- */
309
310var boundCanvas = null;
311
312function bindPointer (canvas)
313{
314 unbindPointer();
315 boundCanvas = canvas;
316 canvas.addEventListener('pointerdown', onPointerDown);
317 canvas.addEventListener('pointermove', onPointerMove);
318 canvas.addEventListener('pointerup', onPointerUp);
319 canvas.addEventListener('pointercancel', onPointerUp);
320 canvas.addEventListener('lostpointercapture', onPointerUp);
321 canvas.style.touchAction = 'none';
322 canvas.style.cursor = 'pointer';
323}
324
325function unbindPointer ()
326{
327 if (!boundCanvas)
328 { return; }
329 boundCanvas.removeEventListener('pointerdown', onPointerDown);
330 boundCanvas.removeEventListener('pointermove', onPointerMove);
331 boundCanvas.removeEventListener('pointerup', onPointerUp);
332 boundCanvas.removeEventListener('pointercancel', onPointerUp);
333 boundCanvas.removeEventListener('lostpointercapture', onPointerUp);
334 boundCanvas = null;
335 app.pointerId = null;
336}
337
338function fieldFromEvent (e)
339{
340 var canvas = app.scene && app.scene.canvas;
341 if (!canvas)
342 { return null; }
343 var rect = canvas.getBoundingClientRect();
344 if (rect.width <= 0 || rect.height <= 0)
345 { return null; }
346 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
347 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
348 var col = Math.floor(x / app.tile);
349 var fieldY = (canvas.height - y) / app.tile;
350 return { col: col, y: fieldY };
351}
352
353function onPointerDown (e)
354{
355 if (!app.core || app.core.state !== 'playing')
356 { return; }
357 if (app.pointerId != null)
358 { return; }
359 e.preventDefault();
360 app.pointerId = e.pointerId;
361 try
362 { boundCanvas.setPointerCapture(e.pointerId); }
363 catch (err) { /* ignore */ }
364 var pos = fieldFromEvent(e);
365 if (pos)
366 { app.core.beginDrag(pos.col, pos.y); }
367}
368
369function onPointerMove (e)
370{
371 if (app.pointerId == null || e.pointerId !== app.pointerId)
372 { return; }
373 if (!app.core || !app.core.drag)
374 { return; }
375 e.preventDefault();
376 var pos = fieldFromEvent(e);
377 if (pos)
378 { app.core.moveDrag(pos.y); }
379}
380
381function onPointerUp (e)
382{
383 if (app.pointerId == null)
384 { return; }
385 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
386 { return; }
387 if (e)
388 { e.preventDefault(); }
389 app.pointerId = null;
390 if (app.core)
391 { app.core.endDrag(); }
392}
393
394function hideEl (id)
395{
396 document.getElementById(id).hidden = true;
397}
398
399function showEl (id)
400{
401 document.getElementById(id).hidden = false;
402}
403
404window.addEventListener('resize', function ()
405{
406 if (app.mode === 'playing')
407 { layout(); }
408});
409
410window.addEventListener('orientationchange', function ()
411{
412 setTimeout(function ()
413 {
414 if (app.mode === 'playing')
415 { layout(); }
416 }, 120);
417});