BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 54.9 KiB Download Raw
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. Online play (stage 2) is wired
7 * through Online (src/online.js) and the same GameCore. Offline Strijd
8 * (t1119) uses Offline (src/offline.js) against local bots.
9 */
10
11function planetImages ()
12{
13 var list = [
14 { name: 'gray', url: 'images/block-gray.png' },
15 { name: 'locked', url: 'images/block-locked.png' },
16 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
17 { name: 'cell', url: 'images/cell.png' },
18 { name: 'pixel', url: 'images/pixel.png' },
19 { name: 'columnWarn', url: 'images/column-warn.png' },
20 // Keep the original Terra placeholders as aliases (Tim may still have them).
21 { name: 'ember', url: 'images/block-ember.png' },
22 { name: 'aqua', url: 'images/block-aqua.png' },
23 { name: 'leaf', url: 'images/block-leaf.png' },
24 { name: 'sun', url: 'images/block-sun.png' },
25 { name: 'orchid', url: 'images/block-orchid.png' }
26 ];
27 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
28 for (var i = 0; i < planets.length; i++)
29 {
30 var pl = planets[i];
31 for (var c = 0; c < pl.colors.length; c++)
32 {
33 list.push({
34 name: Planet.spriteKey(pl, c),
35 url: pl.colors[c].image
36 });
37 }
38 }
39 return list;
40}
41
42var IMAGES = planetImages();
43var GAME_OVER_DELAY = 2;
44
45var game = new Game();
46var app = {
47 mode: 'menu',
48 core: null,
49 scene: null,
50 manager: null,
51 planet: null,
52 lastScore: 0,
53 tile: 48,
54 fieldX: 0,
55 fieldY: 0,
56 fieldW: 0,
57 fieldH: 0,
58 hudH: 56,
59 sprites: Object.create(null),
60 flames: Object.create(null),
61 cells: [],
62 pointerId: null,
63 pointerType: null,
64 activeTouchId: null,
65 debugDrag: false,
66 debugPhysics: false,
67 gameOverShown: false,
68 selectTween: null,
69 online: false,
70 eliminatedReported: false,
71 spectating: false,
72 miniH: 0,
73 selectedPlanetId: 'terra',
74 planetSelectContext: 'solo',
75 offline: false,
76 battle: null,
77 swapTweens: null,
78 columnWarn: null,
79 warnClock: 0,
80 miniAcc: 0,
81 offlineResultShown: false,
82 roundWonDelay: 0,
83 roundWonHandled: false
84};
85
86window.onload = function ()
87{
88 app.debugDrag = isDragDebugEnabled();
89 app.debugPhysics = isPhysicsDebugEnabled();
90 var play = document.getElementById('btn-play');
91 play.addEventListener('click', onPlay);
92 play.addEventListener('pointerup', function (e)
93 {
94 // A touch-friendly path: some mobile browsers swallow the click
95 // after a slightly sloppy tap. Ignore the following click.
96 if (e.pointerType === 'touch' || e.pointerType === 'pen')
97 {
98 e.preventDefault();
99 onPlay();
100 }
101 });
102
103 game.preloadImagesThenStart(IMAGES, function ()
104 {
105 if (game.images.flame && game.images.flame.addAnimationCycle)
106 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
107 });
108
109 bindOnlineUi();
110 bindOfflineUi();
111 bindPlanetSelect();
112 restoreSelectedPlanet();
113};
114
115function onPlay ()
116{
117 if (app.mode === 'playing')
118 { return; }
119 openPlanetSelect('solo');
120}
121
122function startPlay (opts)
123{
124 opts = opts || {};
125 hideEl('menu');
126 hideEl('game-over');
127 hideEl('online-panel');
128 hideEl('spectator');
129 hideEl('podium');
130 hideEl('planet-select');
131 hideEl('offline-result');
132 showEl('hud');
133
134 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
135 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
136 var miss = opts.missChance;
137 if (typeof miss !== 'number' || !isFinite(miss))
138 { miss = planetMod.missChance(app.planet); }
139 app.core = new GameCore(app.planet, Math.random, miss);
140 if (app.debugPhysics)
141 { app.core.debugInvariants = true; }
142 app.mode = 'playing';
143 app.online = !!opts.online;
144 app.offline = !!opts.offline;
145 app.gameOverShown = false;
146 app.eliminatedReported = false;
147 app.spectating = false;
148 app.sprites = Object.create(null);
149 app.flames = Object.create(null);
150 app.cells = [];
151 app.pointerId = null;
152 app.selectTween = null;
153 app.swapTweens = Object.create(null);
154 app.columnWarn = [];
155 app.warnClock = 0;
156 app.miniAcc = 1; // draw minis on the first frame
157 app.offlineResultShown = false;
158 if (!opts.keepBattle)
159 {
160 app.roundWonDelay = 0;
161 app.roundWonHandled = false;
162 }
163 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
164 {
165 app.battle = Offline.createBattle({
166 playerPlanet: app.planet,
167 rng: Math.random,
168 round: opts.round || 1
169 });
170 }
171
172 layout();
173 if (app.scene)
174 {
175 app.scene.destroy();
176 app.scene = null;
177 }
178 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
179 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
180 app.scene.renderBackground = true;
181 game.loadScene(app.scene);
182
183 buildCells();
184 app.manager = app.scene.addObject(makeManager());
185 if (!app.spectating)
186 { bindPointer(app.scene.canvas); }
187 refreshHud();
188 if (app.online || app.offline)
189 { showEl('minis'); }
190 else
191 { hideEl('minis'); }
192 buildColumnWarn();
193 refreshOfflineHud();
194 refreshChainIndicator();
195}
196
197function teardownPlay ()
198{
199 unbindPointer();
200 if (app.scene)
201 {
202 app.scene.destroy();
203 app.scene = null;
204 }
205 app.manager = null;
206 app.core = null;
207 app.sprites = Object.create(null);
208 app.flames = Object.create(null);
209 app.cells = [];
210 app.selectTween = null;
211 app.swapTweens = Object.create(null);
212 app.columnWarn = [];
213 app.pointerId = null;
214 app.gameOverShown = false;
215 hideEl('hud');
216 hideEl('game-over');
217 hideEl('spectator');
218 hideEl('minis');
219 hideEl('offline-result');
220 hideOfflineHud();
221 hideChainIndicator();
222 if (typeof Online !== 'undefined')
223 { Online.clearFlights(); }
224 if (!app._keepBattleOnTeardown)
225 {
226 app.battle = null;
227 app.offline = false;
228 }
229 app._keepBattleOnTeardown = false;
230}
231
232function returnToMenu ()
233{
234 if (app.online && typeof Online !== 'undefined')
235 {
236 // Online matches do not dump you back to the solo menu:
237 // elimination becomes spectating; a finished match shows the podium.
238 return;
239 }
240 teardownPlay();
241 app.mode = 'menu';
242 app.online = false;
243 app.offline = false;
244 app.battle = null;
245 hideEl('planet-select');
246 showEl('menu');
247 var last = document.getElementById('last-score');
248 if (app.lastScore > 0)
249 {
250 last.hidden = false;
251 last.querySelector('strong').textContent = String(app.lastScore);
252 }
253}
254
255function buildCells ()
256{
257 if (!app.scene)
258 { return; }
259 var img = game.images.cell;
260 for (var row = 0; row < 13; row++)
261 {
262 for (var col = 0; col < 10; col++)
263 {
264 var obj = new GameObject(0, 0, img, 0);
265 placeTile(obj, col, row);
266 obj.renderer.alpha = 0.9;
267 app.scene.addObject(obj);
268 app.cells.push(obj);
269 }
270 }
271}
272
273function placeTile (obj, col, y)
274{
275 var t = app.tile;
276 obj.transform.position.x = col * t + t / 2;
277 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
278 obj.transform.size = { x: t, y: t };
279}
280
281function opponentCount ()
282{
283 if (app.offline && app.battle && app.battle.bots)
284 { return app.battle.bots.length; }
285 if (app.online && typeof Online !== 'undefined' && Online.opponents)
286 { return Online.opponents().length; }
287 return 0;
288}
289
290function currentMiniSize ()
291{
292 if (app.miniLayout && app.miniLayout.mini)
293 { return { w: app.miniLayout.mini.w, h: app.miniLayout.mini.h }; }
294 var n = opponentCount();
295 var mode = (app.miniLayout && app.miniLayout.mode) || 'top';
296 if (typeof MiniLayout !== 'undefined' && MiniLayout.canvasSize)
297 { return MiniLayout.canvasSize(n, mode, 0); }
298 if (n >= 10)
299 { return { w: 40, h: 52 }; }
300 if (n >= 6)
301 { return { w: 56, h: 73 }; }
302 return { w: 80, h: 104 };
303}
304
305function applyMinisContainer (plan)
306{
307 var minis = document.getElementById('minis');
308 if (!minis)
309 { return; }
310 var n = plan ? plan.n : 0;
311 minis.classList.toggle('crowded', n > 5);
312 if (!plan || n === 0 || plan.mode !== 'sides')
313 {
314 minis.classList.remove('sides');
315 minis.style.top = (app.hudH || 56) + 'px';
316 minis.style.maxHeight = (plan && plan.miniH ? plan.miniH : 0) + 'px';
317 minis.style.bottom = '';
318 minis.style.left = '';
319 minis.style.right = '';
320 var kids = minis.querySelectorAll('.mini');
321 for (var i = 0; i < kids.length; i++)
322 {
323 kids[i].style.left = '';
324 kids[i].style.top = '';
325 kids[i].style.width = '';
326 kids[i].style.position = '';
327 }
328 return;
329 }
330 minis.classList.add('sides');
331 minis.style.top = '0';
332 minis.style.bottom = '0';
333 minis.style.left = '0';
334 minis.style.right = '0';
335 minis.style.maxHeight = 'none';
336}
337
338function applyMinisLayout ()
339{
340 var plan = app.miniLayout;
341 var minis = document.getElementById('minis');
342 if (!minis)
343 { return; }
344 applyMinisContainer(plan);
345 if (!plan || plan.mode !== 'sides')
346 { return; }
347 var positions = plan.positions || [];
348 var kids = minis.querySelectorAll('.mini');
349 for (var i = 0; i < positions.length && i < kids.length; i++)
350 {
351 var p = positions[i];
352 var el = kids[i];
353 el.style.position = 'absolute';
354 el.style.left = p.x + 'px';
355 el.style.top = p.y + 'px';
356 el.style.width = p.w + 'px';
357 var canvas = el.querySelector('canvas');
358 if (canvas)
359 {
360 canvas.style.width = p.canvasW + 'px';
361 canvas.style.height = p.canvasH + 'px';
362 }
363 }
364}
365
366function applyFlightsBackClip ()
367{
368 var back = document.getElementById('flights-back');
369 if (!back)
370 { return; }
371 var x = app.fieldX || 0;
372 var y = app.fieldY || 0;
373 var w = app.fieldW || 0;
374 var h = app.fieldH || 0;
375 if (!w || !h)
376 {
377 back.style.clipPath = '';
378 return;
379 }
380 // Even-odd polygon: full viewport with a hole over the player's field,
381 // so enemy-to-enemy arcs travel behind the field (t1125).
382 back.style.clipPath = 'polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, '
383 + x + 'px ' + y + 'px, ' + (x + w) + 'px ' + y + 'px, '
384 + (x + w) + 'px ' + (y + h) + 'px, ' + x + 'px ' + (y + h) + 'px, '
385 + x + 'px ' + y + 'px)';
386}
387
388function layoutIfNeeded ()
389{
390 if (app.core && app.core.drag)
391 { return; }
392 var vw = window.innerWidth || 320;
393 var vh = window.innerHeight || 480;
394 var n = (app.online || app.offline) ? opponentCount() : 0;
395 if (app._layoutVw === vw && app._layoutVh === vh && app._layoutN === n
396 && app.scene && app.tile)
397 { return; }
398 layout();
399}
400
401function layout ()
402{
403 if (app.core && app.core.drag)
404 { return; }
405 var vw = window.innerWidth || 320;
406 var vh = window.innerHeight || 480;
407 var n = (app.online || app.offline) ? opponentCount() : 0;
408 app._layoutVw = vw;
409 app._layoutVh = vh;
410 app._layoutN = n;
411 var safeTop = 0;
412 try
413 {
414 // env(safe-area) is a CSS thing; keep a conservative HUD height.
415 safeTop = 0;
416 }
417 catch (e) { /* ignore */ }
418 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
419 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
420 var plan;
421 if (typeof MiniLayout !== 'undefined' && MiniLayout.plan)
422 { plan = MiniLayout.plan(vw, vh, n, app.hudH, margin); }
423 else
424 {
425 plan = {
426 mode: 'top',
427 tile: 14,
428 fieldW: 140,
429 fieldH: 182,
430 fieldX: Math.floor((vw - 140) / 2),
431 fieldY: app.hudH,
432 miniH: n > 0 ? 100 : 0,
433 mini: { w: 80, h: 104 },
434 positions: [],
435 n: n
436 };
437 }
438 app.miniLayout = plan;
439 app.miniH = plan.miniH;
440 app.tile = plan.tile;
441 app.fieldW = plan.fieldW;
442 app.fieldH = plan.fieldH;
443 app.fieldX = plan.fieldX;
444 app.fieldY = plan.fieldY;
445 applyMinisLayout();
446 applyFlightsBackClip();
447
448 if (app.scene)
449 {
450 app.scene.position.x = app.fieldX;
451 app.scene.position.y = app.fieldY;
452 app.scene.size.x = app.fieldW;
453 app.scene.size.y = app.fieldH;
454 }
455}
456
457function spriteFor (block)
458{
459 if (block.state === 'locked')
460 { return game.images.locked; }
461 if (block.color < 0)
462 { return game.images.gray; }
463 var key = Planet.spriteKey(app.planet, block.color);
464 return game.images[key] || game.images.gray;
465}
466
467function syncSprites (dt)
468{
469 if (!app.core || !app.scene)
470 { return; }
471 dt = dt || 0;
472 consumeAndStartSwapTweens();
473 advanceSwapTweens(dt);
474 var seen = Object.create(null);
475 var blocks = app.core.blocks;
476 for (var i = 0; i < blocks.length; i++)
477 {
478 var block = blocks[i];
479 seen[block.id] = true;
480 var obj = app.sprites[block.id];
481 if (!obj)
482 {
483 obj = new GameObject(0, 0, spriteFor(block), 2);
484 app.scene.addObject(obj);
485 app.sprites[block.id] = obj;
486 }
487 obj.renderer.sprite = spriteFor(block);
488 placeTile(obj, block.col, blockVisualY(block));
489 applyBlockVisual(obj, block);
490 obj.renderer.visible = true;
491 obj.renderer.alpha = 1;
492 if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))
493 {
494 obj.renderer.visible = false;
495 obj.renderer.alpha = 0;
496 }
497
498 if (block.flame)
499 {
500 var flame = app.flames[block.id];
501 if (!flame)
502 {
503 flame = new GameObject(0, 0, game.images.flame, 1);
504 flame.renderer.setAnimation('burn', 0, 0.08);
505 app.scene.addObject(flame);
506 app.flames[block.id] = flame;
507 }
508 flame.renderer.visible = true;
509 var t = app.tile;
510 // 3x as large (length and width, t1110). Keep the top of the
511 // flame at the same overlap into the block so the extra length
512 // extends downward under the rocket.
513 var flameW = t * 0.85 * 3;
514 var flameH = t * 0.85 * 3;
515 var origCenter = app.fieldH - block.y * t + t * 0.15;
516 var origTop = origCenter - (t * 0.85) / 2;
517 flame.transform.position.x = block.col * t + t / 2;
518 flame.transform.position.y = origTop + flameH / 2;
519 flame.transform.size = { x: flameW, y: flameH };
520 }
521 else if (app.flames[block.id])
522 { app.flames[block.id].renderer.visible = false; }
523 if (block.flame && app.flames[block.id]
524 && typeof Online !== 'undefined' && Online.hasExitVisual
525 && Online.hasExitVisual(block.id))
526 { app.flames[block.id].renderer.visible = false; }
527 }
528
529 var ids = Object.keys(app.sprites);
530 for (var i = 0; i < ids.length; i++)
531 {
532 if (!seen[ids[i]])
533 {
534 app.sprites[ids[i]].destroy();
535 delete app.sprites[ids[i]];
536 if (app.flames[ids[i]])
537 {
538 app.flames[ids[i]].destroy();
539 delete app.flames[ids[i]];
540 }
541 }
542 }
543}
544
545function applyBlockVisual (obj, block)
546{
547 var t = app.tile;
548 var sx = 1;
549 var sy = 1;
550 var dy = 0;
551 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
552 && typeof Easing !== 'undefined' && Easing.bouncePose)
553 {
554 var u = block.bounceAge / app.planet.bounceDuration;
555 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
556 sx = pose.sx;
557 sy = pose.sy;
558 dy = pose.dy;
559 }
560 var sel = 1;
561 var tw = app.selectTween;
562 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
563 { sel = tw.scale; }
564 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
565 if (dy)
566 { obj.transform.position.y -= dy * t; }
567}
568
569function clickTween ()
570{
571 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
572}
573
574function startPressTween (blockId)
575{
576 var c = clickTween();
577 if (!c)
578 { return; }
579 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
580 app.selectTween = {
581 blockId: blockId,
582 from: from,
583 to: c.pressScale,
584 t: 0,
585 duration: c.pressDuration,
586 ease: c.pressEase,
587 scale: from,
588 phase: 'press'
589 };
590}
591
592function startReleaseTween ()
593{
594 var c = clickTween();
595 var tw = app.selectTween;
596 if (!c || !tw || tw.phase === 'idle')
597 { return; }
598 app.selectTween = {
599 blockId: tw.blockId,
600 from: tw.scale,
601 to: c.releaseScale,
602 t: 0,
603 duration: c.releaseDuration,
604 ease: c.releaseEase,
605 scale: tw.scale,
606 phase: 'release'
607 };
608}
609
610function updateSelectTween (dt)
611{
612 var tw = app.selectTween;
613 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
614 { return; }
615 tw.t += dt;
616 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
617 if (u >= 1)
618 {
619 tw.scale = tw.to;
620 tw.t = tw.duration;
621 if (tw.phase === 'press')
622 { tw.phase = 'hold'; }
623 else
624 {
625 tw.phase = 'idle';
626 tw.scale = 1;
627 tw.blockId = null;
628 }
629 return;
630 }
631 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
632 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
633}
634
635
636/* ---------- visual-only swap tween (t1121) -------------------------- */
637
638function swapTweenSpec ()
639{
640 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
641 { return Easing.SWAP_TWEEN; }
642 return { duration: 0.100, ease: null };
643}
644
645function swapEase (u)
646{
647 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
648 { return Easing.easeOutCubic(u); }
649 var v = 1 - Math.max(0, Math.min(1, u));
650 return 1 - v * v * v;
651}
652
653function tweenVisualY (tw)
654{
655 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
656 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
657}
658
659/**
660 * Consume GameCore swap events. The currently dragged block is skipped
661 * (it follows the pointer). A block that is mid-tween and is swapped
662 * again restarts from its current visual y, so rapid swaps chain
663 * smoothly without snapping.
664 */
665function consumeAndStartSwapTweens ()
666{
667 if (!app.core || !app.core.consumeSwapEvents)
668 { return; }
669 if (!app.swapTweens)
670 { app.swapTweens = Object.create(null); }
671 var ev = app.core.consumeSwapEvents();
672 if (!ev.length)
673 { return; }
674 var dragId = app.core.drag && app.core.drag.blockId;
675 var duration = swapTweenSpec().duration;
676 for (var i = 0; i < ev.length; i++)
677 {
678 var e = ev[i];
679 if (e.id === dragId)
680 {
681 delete app.swapTweens[e.id];
682 continue;
683 }
684 var fromY = e.fromY;
685 var existing = app.swapTweens[e.id];
686 if (existing)
687 { fromY = tweenVisualY(existing); }
688 app.swapTweens[e.id] = {
689 fromY: fromY,
690 toY: e.toY,
691 age: 0,
692 duration: duration
693 };
694 }
695}
696
697function advanceSwapTweens (dt)
698{
699 if (!app.swapTweens)
700 { return; }
701 var ids = Object.keys(app.swapTweens);
702 for (var i = 0; i < ids.length; i++)
703 {
704 var tw = app.swapTweens[ids[i]];
705 tw.age += dt;
706 if (tw.age >= tw.duration)
707 { delete app.swapTweens[ids[i]]; }
708 }
709}
710
711function blockVisualY (block)
712{
713 if (!app.swapTweens)
714 { return block.y; }
715 var dragId = app.core && app.core.drag && app.core.drag.blockId;
716 if (block.id === dragId)
717 { return block.y; }
718 var tw = app.swapTweens[block.id];
719 if (!tw)
720 { return block.y; }
721 return tweenVisualY(tw);
722}
723
724function refreshHud ()
725{
726 if (!app.core)
727 { return; }
728 document.getElementById('score').textContent = String(app.core.score);
729 var planet = app.planet;
730 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
731 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
732}
733
734function makeManager ()
735{
736 var obj = new GameObject(0, 0, game.images.pixel, 0);
737 obj.renderer.visible = false;
738 var base = obj.update.bind(obj);
739 obj.update = function (dt)
740 {
741 base(dt);
742 tickView(dt);
743 };
744 return obj;
745}
746
747function tickView (dt)
748{
749 if (app.mode !== 'playing' || !app.core)
750 { return; }
751
752 // Never resize the canvas mid-drag: a URL-bar hide would move the
753 // field under the finger and jump the target row. Also skip work
754 // when the viewport has not actually changed.
755 if (!(app.core && app.core.drag))
756 { layoutIfNeeded(); }
757 for (var i = 0; i < app.cells.length; i++)
758 {
759 var col = i % 10;
760 var row = Math.floor(i / 10);
761 placeTile(app.cells[i], col, row);
762 }
763
764 app.core.tick(dt);
765 if (app.offline && app.battle)
766 { tickOffline(dt); }
767 updateSelectTween(dt);
768 syncSprites(dt);
769 updateColumnWarn(dt);
770 refreshHud();
771 refreshOfflineHud();
772 refreshChainIndicator();
773 tickOnline(dt);
774 if (app.debugPhysics)
775 { logPhysicsDebug(); }
776
777 if (app.core.state === 'gameover' && !app.gameOverShown)
778 {
779 app.gameOverShown = true;
780 app.lastScore = app.core.score;
781 document.getElementById('go-score').textContent = String(app.lastScore);
782 if (app.online)
783 { onOnlineEliminated(); }
784 else if (app.offline)
785 { /* Offline result is shown from tickOffline. */ }
786 else
787 { showEl('game-over'); }
788 }
789 if (!app.online && !app.offline && app.core.state === 'gameover'
790 && app.core.gameOverTime >= GAME_OVER_DELAY)
791 { returnToMenu(); }
792}
793
794/* ---------- pointer input (mouse + touch) --------------------------- */
795/*
796 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
797 * on a real phone, pointer clientX/Y can disagree with the visual
798 * finger (zoomed visual viewport, gesture takeover, capture cancel)
799 * while changedTouches stays correct. When a touch is active, pointer
800 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
801 * walk the block to the top or bottom of the stack (t1106).
802 *
803 * After a down we also listen on the document, so a drag that leaves
804 * the canvas (needed to launch a block at the top of a full column)
805 * still reaches moveDrag. We do not call setPointerCapture: on mobile
806 * that is often cancelled when the browser takes the gesture, which
807 * would fire pointercancel mid-drag.
808 *
809 * A non-passive document touchstart/touchmove preventDefault during
810 * play stops scrolling, rubber-banding and the pointercancel that
811 * follows. pointercancel / touchcancel end the drag without launch.
812 *
813 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
814 */
815
816var boundCanvas = null;
817var windowListening = false;
818var touchListening = false;
819var lastDragDebug = null;
820
821function isDragDebugEnabled ()
822{
823 try
824 {
825 var q = window.location && window.location.search;
826 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
827 { return true; }
828 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
829 { return true; }
830 }
831 catch (err) { /* ignore */ }
832 return false;
833}
834
835/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
836function isPhysicsDebugEnabled ()
837{
838 try
839 {
840 var q = window.location && window.location.search;
841 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
842 { return true; }
843 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
844 || window.localStorage.getItem('meteors-debug-drag') === '1'))
845 { return true; }
846 }
847 catch (err) { /* ignore */ }
848 return false;
849}
850
851function eventClient (e)
852{
853 var t = null;
854 if (e.changedTouches && e.changedTouches.length)
855 { t = e.changedTouches[0]; }
856 else if (e.touches && e.touches.length)
857 { t = e.touches[0]; }
858 if (t)
859 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
860 if (e.clientX != null && e.clientY != null)
861 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
862 return null;
863}
864
865function addWindowPointer ()
866{
867 if (windowListening)
868 { return; }
869 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
870 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
871 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
872 windowListening = true;
873}
874
875function removeWindowPointer ()
876{
877 if (!windowListening)
878 { return; }
879 window.removeEventListener('pointermove', onPointerMove, { capture: true });
880 window.removeEventListener('pointerup', onPointerUp, { capture: true });
881 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
882 windowListening = false;
883}
884
885function addTouchListeners ()
886{
887 if (touchListening)
888 { return; }
889 var opts = { capture: true, passive: false };
890 document.addEventListener('touchstart', onTouchStart, opts);
891 document.addEventListener('touchmove', onTouchMove, opts);
892 document.addEventListener('touchend', onTouchEnd, opts);
893 document.addEventListener('touchcancel', onTouchCancel, opts);
894 touchListening = true;
895}
896
897function removeTouchListeners ()
898{
899 if (!touchListening)
900 { return; }
901 var opts = { capture: true };
902 document.removeEventListener('touchstart', onTouchStart, opts);
903 document.removeEventListener('touchmove', onTouchMove, opts);
904 document.removeEventListener('touchend', onTouchEnd, opts);
905 document.removeEventListener('touchcancel', onTouchCancel, opts);
906 touchListening = false;
907}
908
909function bindPointer (canvas)
910{
911 unbindPointer();
912 boundCanvas = canvas;
913 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
914 canvas.style.touchAction = 'none';
915 canvas.style.position = 'fixed';
916 canvas.style.cursor = 'pointer';
917 canvas.style.webkitUserSelect = 'none';
918 canvas.style.userSelect = 'none';
919 addTouchListeners();
920 if (app.debugDrag)
921 { ensureDragDebugOverlay(); }
922}
923
924function unbindPointer ()
925{
926 removeWindowPointer();
927 removeTouchListeners();
928 if (boundCanvas)
929 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
930 boundCanvas = null;
931 app.pointerId = null;
932 app.pointerType = null;
933 app.activeTouchId = null;
934}
935
936function fieldFromEvent (e)
937{
938 var canvas = app.scene && app.scene.canvas;
939 if (!canvas)
940 { return null; }
941 var rect = canvas.getBoundingClientRect();
942 if (rect.width <= 0 || rect.height <= 0)
943 { return null; }
944 var pt = eventClient(e);
945 if (!pt)
946 { return null; }
947 // Map through the CSS box only. Using canvas.width / app.tile would
948 // scale the pointer by the backing-store ratio whenever that differs
949 // from the layout size (high-DPR devices), so a short finger move
950 // would look like a long swipe.
951 var width = Planet.FIELD_WIDTH;
952 var height = Planet.FIELD_HEIGHT;
953 var col = ((pt.x - rect.left) / rect.width) * width;
954 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
955 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
956}
957
958function playingForDrag ()
959{
960 return app.core && app.core.state === 'playing';
961}
962
963function startDragFromEvent (e)
964{
965 var pos = fieldFromEvent(e);
966 if (!pos)
967 { return; }
968 if (app.core.drag)
969 {
970 app.core.moveDrag(pos.y);
971 logDragDebug(e, pos, 'move-already');
972 return;
973 }
974 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
975 { startPressTween(app.core.drag.blockId); }
976 logDragDebug(e, pos, 'down');
977}
978
979function moveDragFromEvent (e)
980{
981 if (!app.core || !app.core.drag)
982 { return; }
983 var pos = fieldFromEvent(e);
984 if (pos)
985 { app.core.moveDrag(pos.y); }
986 logDragDebug(e, pos, 'move');
987}
988
989function finishDrag (opts)
990{
991 opts = opts || {};
992 app.pointerId = null;
993 app.pointerType = null;
994 app.activeTouchId = null;
995 removeWindowPointer();
996 if (boundCanvas)
997 {
998 try
999 {
1000 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
1001 { boundCanvas.releasePointerCapture(opts.pointerId); }
1002 }
1003 catch (err) { /* ignore */ }
1004 }
1005 startReleaseTween();
1006 if (app.core && app.core.drag)
1007 {
1008 if (opts.noLaunch)
1009 { app.core.drag.launchIntent = false; }
1010 app.core.endDrag();
1011 }
1012 else if (app.core)
1013 { app.core.endDrag(); }
1014 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
1015}
1016
1017function onPointerDown (e)
1018{
1019 if (!playingForDrag())
1020 { return; }
1021 if (app.pointerId != null && e.pointerId !== app.pointerId)
1022 { return; }
1023 if (e.preventDefault)
1024 { e.preventDefault(); }
1025 app.pointerId = e.pointerId;
1026 app.pointerType = e.pointerType || 'mouse';
1027 addWindowPointer();
1028 // If a touch is already in charge, do not reset the grab from pointerdown.
1029 if (app.activeTouchId != null)
1030 { return; }
1031 startDragFromEvent(e);
1032}
1033
1034function onPointerMove (e)
1035{
1036 if (app.pointerId == null || e.pointerId !== app.pointerId)
1037 { return; }
1038 if (!app.core || !app.core.drag)
1039 { return; }
1040 // Touch coordinates are the authority; ignore pointer moves for a
1041 // live touch so a wrong clientY cannot walk the whole column.
1042 // Only skip when touchstart has actually arrived — some environments
1043 // deliver touch-pointer events without a TouchEvent stream.
1044 if (app.activeTouchId != null)
1045 {
1046 if (e.preventDefault)
1047 { e.preventDefault(); }
1048 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
1049 return;
1050 }
1051 if (e.preventDefault)
1052 { e.preventDefault(); }
1053 moveDragFromEvent(e);
1054}
1055
1056function onPointerUp (e)
1057{
1058 if (app.pointerId == null)
1059 { return; }
1060 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1061 { return; }
1062 if (app.activeTouchId != null)
1063 {
1064 // touchend will finish the drag.
1065 if (e && e.preventDefault)
1066 { e.preventDefault(); }
1067 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
1068 return;
1069 }
1070 if (e && e.preventDefault)
1071 { e.preventDefault(); }
1072 finishDrag({ pointerId: e && e.pointerId });
1073}
1074
1075function onPointerCancel (e)
1076{
1077 if (app.pointerId == null)
1078 { return; }
1079 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1080 { return; }
1081 if (app.activeTouchId != null)
1082 {
1083 if (e && e.preventDefault)
1084 { e.preventDefault(); }
1085 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
1086 return;
1087 }
1088 if (e && e.preventDefault)
1089 { e.preventDefault(); }
1090 // A cancelled gesture is not a launch pull.
1091 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
1092}
1093
1094function touchById (list, id)
1095{
1096 if (!list)
1097 { return null; }
1098 for (var i = 0; i < list.length; i++)
1099 {
1100 if (list[i].identifier === id)
1101 { return list[i]; }
1102 }
1103 return null;
1104}
1105
1106function onTouchStart (e)
1107{
1108 if (!playingForDrag())
1109 { return; }
1110 if (app.activeTouchId != null)
1111 {
1112 if (e.preventDefault)
1113 { e.preventDefault(); }
1114 return;
1115 }
1116 var t = e.changedTouches && e.changedTouches[0];
1117 if (!t)
1118 { return; }
1119 if (e.preventDefault)
1120 { e.preventDefault(); }
1121 app.activeTouchId = t.identifier;
1122 addWindowPointer();
1123 startDragFromEvent(e);
1124}
1125
1126function onTouchMove (e)
1127{
1128 if (app.activeTouchId == null)
1129 { return; }
1130 if (!touchById(e.changedTouches, app.activeTouchId)
1131 && !touchById(e.touches, app.activeTouchId))
1132 { return; }
1133 if (e.preventDefault)
1134 { e.preventDefault(); }
1135 moveDragFromEvent(e);
1136}
1137
1138function onTouchEnd (e)
1139{
1140 if (app.activeTouchId == null)
1141 { return; }
1142 if (!touchById(e.changedTouches, app.activeTouchId))
1143 { return; }
1144 if (e.preventDefault)
1145 { e.preventDefault(); }
1146 finishDrag({});
1147}
1148
1149function onTouchCancel (e)
1150{
1151 if (app.activeTouchId == null)
1152 { return; }
1153 if (!touchById(e.changedTouches, app.activeTouchId))
1154 { return; }
1155 if (e.preventDefault)
1156 { e.preventDefault(); }
1157 finishDrag({ noLaunch: true });
1158}
1159
1160function logPhysicsDebug ()
1161{
1162 if (!app.debugPhysics || !app.core)
1163 { return; }
1164 ensureDragDebugOverlay();
1165 var el = document.getElementById('drag-debug');
1166 if (!el)
1167 { return; }
1168 var issues = app.core.lastInvariantViolations || [];
1169 var flying = 0;
1170 var manuals = 0;
1171 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
1172 for (var i = 0; i < app.core.blocks.length; i++)
1173 {
1174 if (app.core.blocks[i].state === 'flying')
1175 { flying++; }
1176 if (app.core.blocks[i].state === 'manual')
1177 { manuals++; }
1178 }
1179 var status = issues.length
1180 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
1181 : ('physics ok blocks=' + app.core.blocks.length
1182 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
1183 // Keep any live drag line above the physics status.
1184 var dragLine = '';
1185 if (app.debugDrag && lastDragDebug)
1186 {
1187 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
1188 ? el.textContent.split('\n')[0] + '\n'
1189 : '';
1190 }
1191 el.textContent = dragLine + status;
1192 el.hidden = false;
1193 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
1194}
1195
1196function ensureDragDebugOverlay ()
1197{
1198 if (document.getElementById('drag-debug'))
1199 { return; }
1200 var el = document.createElement('div');
1201 el.id = 'drag-debug';
1202 el.setAttribute('aria-live', 'polite');
1203 document.body.appendChild(el);
1204}
1205
1206function logDragDebug (e, pos, phase)
1207{
1208 if (!app.debugDrag)
1209 { return; }
1210 ensureDragDebugOverlay();
1211 var el = document.getElementById('drag-debug');
1212 if (!el)
1213 { return; }
1214 var block = null;
1215 if (app.core && app.core.drag)
1216 { block = app.core.blockById(app.core.drag.blockId); }
1217 var pt = e ? eventClient(e) : null;
1218 var evType = e ? e.type : phase;
1219 var info = {
1220 phase: phase,
1221 ev: evType,
1222 src: pos && pos.src,
1223 fieldY: pos && Math.round(pos.y * 100) / 100,
1224 col: pos && Math.round(pos.col * 100) / 100,
1225 cy: pt && Math.round(pt.y * 10) / 10,
1226 blockY: block && Math.round(block.y * 100) / 100,
1227 target: block && Math.floor((pos && pos.y) + 1e-12),
1228 launch: app.core && app.core.drag && app.core.drag.launchIntent,
1229 touchId: app.activeTouchId,
1230 pid: app.pointerId,
1231 ptype: app.pointerType
1232 };
1233 lastDragDebug = info;
1234 el.textContent = 'drag ' + phase
1235 + ' ev=' + evType
1236 + ' src=' + (info.src || '-')
1237 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
1238 + ' → ' + (info.target != null ? info.target : '-')
1239 + ' block=' + (info.blockY != null ? info.blockY : '-')
1240 + (info.launch ? ' LAUNCH' : '')
1241 + ' tId=' + info.touchId
1242 + ' pId=' + info.pid;
1243 el.hidden = false;
1244}
1245
1246
1247function hideEl (id)
1248{
1249 document.getElementById(id).hidden = true;
1250}
1251
1252function showEl (id)
1253{
1254 document.getElementById(id).hidden = false;
1255}
1256
1257window.addEventListener('resize', function ()
1258{
1259 if (app.mode === 'playing')
1260 { layout(); }
1261});
1262
1263window.addEventListener('orientationchange', function ()
1264{
1265 setTimeout(function ()
1266 {
1267 if (app.mode === 'playing')
1268 { layout(); }
1269 }, 120);
1270});
1271
1272/* ---------- online play (stage 2) ---------------------------------- */
1273
1274function tickOnline (dt)
1275{
1276 if (!app.online || typeof Online === 'undefined')
1277 { return; }
1278 if (app.core)
1279 {
1280 var shots = app.core.consumeOutgoingShots();
1281 for (var i = 0; i < shots.length; i++)
1282 {
1283 var s = shots[i];
1284 var start = fieldToViewport(s.col, s.y);
1285 Online.rememberFlightLocal(s, start.x, start.y);
1286 }
1287 Online.queueShots(shots);
1288 }
1289 Online.tickFlights();
1290 Online.renderMinis(document.getElementById('minis'));
1291 applyMinisLayout();
1292}
1293
1294
1295/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1296
1297function bindOfflineUi ()
1298{
1299 var btn = document.getElementById('btn-offline');
1300 if (btn)
1301 {
1302 btn.addEventListener('click', onOffline);
1303 btn.addEventListener('pointerup', function (e)
1304 {
1305 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1306 {
1307 e.preventDefault();
1308 onOffline();
1309 }
1310 });
1311 }
1312 var back = document.getElementById('btn-offline-menu');
1313 if (back)
1314 {
1315 back.addEventListener('click', function ()
1316 {
1317 teardownPlay();
1318 app.mode = 'menu';
1319 app.offline = false;
1320 app.battle = null;
1321 hideEl('offline-result');
1322 showEl('menu');
1323 });
1324 }
1325}
1326
1327function onOffline ()
1328{
1329 openPlanetSelect('offline');
1330}
1331
1332function tickOffline (dt)
1333{
1334 if (!app.battle || !app.core || typeof Offline === 'undefined')
1335 { return; }
1336
1337 if (app.battle.state === 'round_won')
1338 {
1339 if (!app.roundWonHandled)
1340 {
1341 app.roundWonHandled = true;
1342 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1343 }
1344 app.roundWonDelay -= dt;
1345 if (app.roundWonDelay <= 0)
1346 { startNextOfflineRound(); }
1347 updateOfflineMinis(dt, true);
1348 return;
1349 }
1350
1351 var result = app.battle.tick(dt, app.core);
1352 if (result && result.flights && result.flights.length
1353 && typeof Online !== 'undefined' && Online.spawnFlights)
1354 {
1355 var locals = Object.create(null);
1356 var list = result.locals || [];
1357 for (var i = 0; i < list.length; i++)
1358 {
1359 var s = list[i];
1360 var start;
1361 if (s.from_id === 'player')
1362 { start = fieldToViewport(s.col, s.y); }
1363 else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1364 { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1365 else
1366 { start = miniViewportCenter(s.from_id); }
1367 locals[s.client_id] = {
1368 col: s.col,
1369 y: s.y,
1370 color: s.color,
1371 startX: start.x,
1372 startY: start.y,
1373 from_id: s.from_id,
1374 land_col: s.land_col
1375 };
1376 }
1377 Online.spawnFlights(result.flights, locals);
1378 }
1379 if (typeof Online !== 'undefined' && Online.tickFlights)
1380 { Online.tickFlights(); }
1381 updateOfflineMinis(dt, false);
1382
1383 if (app.battle.state === 'lost' && !app.offlineResultShown)
1384 { showOfflineResult(); }
1385}
1386
1387function startNextOfflineRound ()
1388{
1389 if (!app.battle)
1390 { return; }
1391 app.battle.advanceRound();
1392 app.roundWonHandled = false;
1393 app.roundWonDelay = 0;
1394 app._keepBattleOnTeardown = true;
1395 // Tear down the current scene then start a fresh player field,
1396 // keeping the same battle (already advanced).
1397 var planet = app.battle.playerPlanet;
1398 app._keepBattleOnTeardown = true;
1399 teardownPlay();
1400 app.offline = true;
1401 app.battle = app.battle; // kept
1402 startPlay({ planet: planet, offline: true, keepBattle: true });
1403}
1404
1405function showOfflineResult ()
1406{
1407 app.offlineResultShown = true;
1408 var battle = app.battle;
1409 var reached = document.getElementById('offline-reached');
1410 if (reached)
1411 { reached.textContent = String(battle.round); }
1412 var detail = document.getElementById('offline-result-detail');
1413 if (detail)
1414 {
1415 var sch = battle.schedule;
1416 var n = sch.opponents;
1417 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1418 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
1419 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
1420 }
1421 hideEl('game-over');
1422 showEl('offline-result');
1423}
1424
1425function refreshOfflineHud ()
1426{
1427 var el = document.getElementById('offline-hud');
1428 if (!el)
1429 { return; }
1430 if (!(app.offline && app.battle && app.mode === 'playing'))
1431 {
1432 el.hidden = true;
1433 return;
1434 }
1435 el.hidden = false;
1436 var sch = app.battle.schedule;
1437 var n = sch.opponents;
1438 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1439 var r = document.getElementById('offline-round');
1440 var o = document.getElementById('offline-opponents');
1441 var s = document.getElementById('offline-skill');
1442 if (r)
1443 { r.textContent = 'Ronde ' + sch.round; }
1444 if (o)
1445 { o.textContent = n + ' ' + noun; }
1446 if (s)
1447 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1448}
1449
1450function hideOfflineHud ()
1451{
1452 var el = document.getElementById('offline-hud');
1453 if (el)
1454 { el.hidden = true; }
1455}
1456
1457function refreshChainIndicator ()
1458{
1459 var el = document.getElementById('chain-indicator');
1460 if (!el)
1461 { return; }
1462 var info = app.core && app.core.lastChainIndicator;
1463 var active = app.core && app.core.hasActiveLandingChain
1464 && app.core.hasActiveLandingChain();
1465 // Show only while a chained cluster is still in the air.
1466 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1467 {
1468 el.hidden = true;
1469 return;
1470 }
1471 el.hidden = false;
1472 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1473}
1474
1475function hideChainIndicator ()
1476{
1477 var el = document.getElementById('chain-indicator');
1478 if (el)
1479 { el.hidden = true; }
1480}
1481
1482function miniViewportCenter (botId)
1483{
1484 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1485 if (!el)
1486 { return { x: window.innerWidth / 2, y: 40 }; }
1487 var rect = el.getBoundingClientRect();
1488 var plan = app.miniLayout;
1489 if (plan && plan.mode === 'sides')
1490 {
1491 // Leave from the top of the mini, then the arc goes up and over (t1131).
1492 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1493 }
1494 return { x: rect.left + rect.width / 2, y: rect.bottom };
1495}
1496
1497function offlineMiniSize (n)
1498{
1499 return currentMiniSize();
1500}
1501
1502function updateOfflineMinis (dt, force)
1503{
1504 app.miniAcc = (app.miniAcc || 0) + dt;
1505 if (!force && app.miniAcc < 0.1)
1506 { return; }
1507 app.miniAcc = 0;
1508 renderOfflineMinis();
1509}
1510
1511function renderOfflineMinis ()
1512{
1513 var container = document.getElementById('minis');
1514 if (!container || !app.battle)
1515 { return; }
1516 var bots = app.battle.bots;
1517 var size = offlineMiniSize(bots.length);
1518 container.classList.toggle('crowded', bots.length > 5);
1519 var existing = {};
1520 var kids = container.querySelectorAll('[data-player]');
1521 for (var i = 0; i < kids.length; i++)
1522 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1523 var seen = Object.create(null);
1524 for (var i = 0; i < bots.length; i++)
1525 {
1526 var bot = bots[i];
1527 seen[bot.id] = true;
1528 var el = existing[bot.id];
1529 if (!el)
1530 {
1531 el = document.createElement('div');
1532 el.className = 'mini';
1533 el.setAttribute('data-player', bot.id);
1534 el.innerHTML = '<div class="mini-name"></div>'
1535 + '<canvas class="mini-canvas" width="' + size.w
1536 + '" height="' + size.h + '"></canvas>'
1537 + '<div class="mini-meta"></div>';
1538 container.appendChild(el);
1539 }
1540 var canvas = el.querySelector('canvas');
1541 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1542 {
1543 canvas.width = size.w;
1544 canvas.height = size.h;
1545 }
1546 el.classList.toggle('eliminated', !!bot.eliminated);
1547 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1548 el.querySelector('.mini-name').textContent = bot.name
1549 + (planetName ? ' · ' + planetName : '');
1550 el.querySelector('.mini-meta').textContent = bot.eliminated
1551 ? 'Uit'
1552 : ('Punten ' + (bot.score || 0));
1553 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1554 if (typeof Online !== 'undefined' && Online._drawMini)
1555 { Online._drawMini(canvas, snap, bot.planet); }
1556 }
1557 for (var id in existing)
1558 {
1559 if (!seen[id])
1560 { existing[id].remove(); }
1561 }
1562 applyMinisLayout();
1563}
1564
1565function buildColumnWarn ()
1566{
1567 app.columnWarn = [];
1568 if (!app.scene)
1569 { return; }
1570 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1571 if (!img)
1572 { return; }
1573 for (var c = 0; c < 10; c++)
1574 {
1575 var obj = new GameObject(0, 0, img, 0);
1576 obj.renderer.alpha = 0;
1577 obj.renderer.visible = false;
1578 app.scene.addObject(obj);
1579 app.columnWarn.push(obj);
1580 }
1581 updateColumnWarn(0);
1582}
1583
1584function updateColumnWarn (dt)
1585{
1586 if (!app.columnWarn || !app.core)
1587 { return; }
1588 app.warnClock = (app.warnClock || 0) + (dt || 0);
1589 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1590 ? GameCore.columnWarnPulse(app.warnClock)
1591 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1592 var t = app.tile;
1593 for (var c = 0; c < app.columnWarn.length; c++)
1594 {
1595 var obj = app.columnWarn[c];
1596 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1597 obj.renderer.visible = !!on;
1598 obj.renderer.alpha = on ? pulse : 0;
1599 if (t)
1600 {
1601 obj.transform.position.x = c * t + t / 2;
1602 obj.transform.position.y = app.fieldH / 2;
1603 obj.transform.size = { x: t, y: app.fieldH };
1604 }
1605 }
1606}
1607
1608/**
1609 * A flight starts only when a block has actually left the field
1610 * (y ≥ height, the same threshold as cullOffTop). Rockets that
1611 * peak below the top and fall back must never get an arc (t1137).
1612 * Shared by the player's field, enemy minis, offline and online.
1613 */
1614function previewOutgoingFlights ()
1615{
1616 // Intentionally not called before core.tick: a block still on
1617 // the field (y < 13) is not a shot yet. Flights are spawned
1618 // from consumeOutgoingShots after cull, at the exit pose.
1619 if (typeof Online === 'undefined' || !Online.previewExit)
1620 { return; }
1621 if (app.core)
1622 { previewCoreExits(app.core, null); }
1623 if (app.offline && app.battle && app.battle.bots)
1624 {
1625 var bots = app.battle.bots;
1626 for (var i = 0; i < bots.length; i++)
1627 {
1628 var bot = bots[i];
1629 if (bot && bot.core && !bot.eliminated)
1630 { previewCoreExits(bot.core, bot.id); }
1631 }
1632 }
1633}
1634
1635function previewCoreExits (core, fromId)
1636{
1637 if (!core || !core.blocks)
1638 { return; }
1639 var height = core.height != null ? core.height : 13;
1640 var blocks = core.blocks;
1641 for (var i = 0; i < blocks.length; i++)
1642 {
1643 var b = blocks[i];
1644 if (b.state === 'manual')
1645 { continue; }
1646 if (typeof Online.hasLeftTheField === 'function'
1647 ? !Online.hasLeftTheField(b.y, height)
1648 : !(b.y >= height - 1e-9))
1649 { continue; }
1650 if (!(b.vy > 0))
1651 { continue; }
1652 var start = fromId
1653 ? (Online.miniCellViewport
1654 ? Online.miniCellViewport(fromId, b.col, b.y)
1655 : miniViewportCenter(fromId))
1656 : fieldToViewport(b.col, b.y);
1657 Online.previewExit({
1658 id: b.id,
1659 col: b.col,
1660 y: b.y,
1661 vy: b.vy,
1662 color: b.color,
1663 start: start,
1664 from_id: fromId || null
1665 });
1666 }
1667}
1668
1669function fieldToViewport (col, fieldY)
1670{
1671 var canvas = app.scene && app.scene.canvas;
1672 if (!canvas)
1673 { return { x: window.innerWidth / 2, y: 40 }; }
1674 var rect = canvas.getBoundingClientRect();
1675 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1676 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1677 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1678 return { x: x, y: y };
1679}
1680
1681function onlinePayload ()
1682{
1683 if (!app.online || !app.core)
1684 { return {}; }
1685 return {
1686 snapshot: app.core.fieldSnapshot(),
1687 score: app.core.score,
1688 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1689 };
1690}
1691
1692function onOnlineEliminated ()
1693{
1694 app.eliminatedReported = true;
1695 app.spectating = true;
1696 unbindPointer();
1697 hideEl('game-over');
1698 var lobby = typeof Online !== 'undefined' && Online.lobby;
1699 if (lobby && lobby.status === 'finished')
1700 {
1701 showPodium(lobby);
1702 return;
1703 }
1704 showEl('spectator');
1705}
1706
1707function showPodium (lobby)
1708{
1709 hideEl('spectator');
1710 hideEl('game-over');
1711 hideEl('online-panel');
1712 showEl('podium');
1713 var list = document.getElementById('podium-list');
1714 list.innerHTML = '';
1715 var ranks = (lobby && lobby.rankings) || [];
1716 for (var i = 0; i < ranks.length; i++)
1717 {
1718 var r = ranks[i];
1719 var li = document.createElement('li');
1720 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
1721 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
1722 list.appendChild(li);
1723 }
1724 var hint = document.getElementById('podium-hint');
1725 var secs = (lobby && lobby.podium_seconds) || 5;
1726 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
1727}
1728
1729function startOnlineMatch ()
1730{
1731 if (app.mode === 'playing' && app.online)
1732 { return; }
1733 var planet = Planet.planetById(selectedPlanetId());
1734 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1735 if (me && me.planet && me.planet.id)
1736 { planet = Planet.planetById(me.planet.id); }
1737 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1738 if (typeof Online !== 'undefined')
1739 { Online.startPolling(onlinePayload); }
1740}
1741
1742function leaveOnlineMatch (goMenu)
1743{
1744 if (typeof Online !== 'undefined')
1745 {
1746 Online.stopPolling();
1747 Online.leaveLobby();
1748 Online.clearFlights();
1749 }
1750 teardownPlay();
1751 app.online = false;
1752 if (goMenu)
1753 {
1754 app.mode = 'menu';
1755 showEl('menu');
1756 }
1757 else
1758 {
1759 app.mode = 'online';
1760 openOnlinePanel();
1761 }
1762}
1763
1764function bindOnlineUi ()
1765{
1766 var onlineBtn = document.getElementById('btn-online');
1767 if (!onlineBtn)
1768 { return; }
1769 onlineBtn.addEventListener('click', function ()
1770 { openOnlinePanel(); });
1771
1772 var backs = document.querySelectorAll('[data-back-menu]');
1773 for (var i = 0; i < backs.length; i++)
1774 {
1775 backs[i].addEventListener('click', function ()
1776 {
1777 if (typeof Online !== 'undefined')
1778 { Online.stopPolling(); }
1779 hideEl('online-panel');
1780 app.mode = 'menu';
1781 app.online = false;
1782 showEl('menu');
1783 });
1784 }
1785
1786 document.getElementById('btn-create').addEventListener('click', function ()
1787 {
1788 Online.createLobby().then(function (data)
1789 {
1790 if (data && data.ok)
1791 {
1792 renderOnline();
1793 Online.startPolling(onlinePayload);
1794 }
1795 else
1796 { renderOnline(); }
1797 });
1798 });
1799
1800 document.getElementById('join-form').addEventListener('submit', function (e)
1801 {
1802 e.preventDefault();
1803 var code = (document.getElementById('join-code').value || '').trim();
1804 if (!code)
1805 { return; }
1806 Online.joinLobby(code).then(function ()
1807 {
1808 renderOnline();
1809 if (Online.lobby)
1810 { Online.startPolling(onlinePayload); }
1811 });
1812 });
1813
1814 document.getElementById('btn-ready').addEventListener('click', function ()
1815 {
1816 var me = Online.mePlayer();
1817 Online.setReady(!(me && me.ready)).then(renderOnline);
1818 });
1819
1820 document.getElementById('btn-start').addEventListener('click', function ()
1821 {
1822 Online.startGame().then(function (data)
1823 {
1824 if (data && data.ok)
1825 { startOnlineMatch(); }
1826 else
1827 { renderOnline(); }
1828 });
1829 });
1830
1831 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
1832 {
1833 Online.leaveLobby().then(function ()
1834 {
1835 Online.stopPolling();
1836 renderOnline();
1837 });
1838 });
1839
1840 document.getElementById('btn-copy-code').addEventListener('click', function ()
1841 {
1842 var code = document.getElementById('lobby-code').textContent;
1843 if (navigator.clipboard && navigator.clipboard.writeText)
1844 { navigator.clipboard.writeText(code); }
1845 });
1846
1847 document.getElementById('btn-spectate').addEventListener('click', function ()
1848 {
1849 hideEl('spectator');
1850 app.spectating = true;
1851 });
1852
1853 document.getElementById('btn-leave-game').addEventListener('click', function ()
1854 { leaveOnlineMatch(false); });
1855
1856 if (typeof Online !== 'undefined')
1857 {
1858 Online.onChange = function ()
1859 { renderOnline(); };
1860 Online.onGameStart = function ()
1861 { startOnlineMatch(); };
1862 Online.onIncoming = function (incoming)
1863 {
1864 if (!app.core || app.core.state !== 'playing')
1865 { return; }
1866 for (var i = 0; i < incoming.length; i++)
1867 {
1868 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
1869 app.core.ingestGarbage(col);
1870 }
1871 };
1872 Online.onFinished = function (lobby)
1873 { showPodium(lobby); };
1874 Online.onLobbyReturn = function (lobby)
1875 {
1876 teardownPlay();
1877 app.online = false;
1878 app.mode = 'online';
1879 hideEl('podium');
1880 showEl('online-panel');
1881 renderOnline();
1882 Online.startPolling(onlinePayload);
1883 };
1884 }
1885
1886 var params = new URLSearchParams(window.location.search);
1887 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
1888 { openOnlinePanel(); }
1889}
1890
1891function openOnlinePanel ()
1892{
1893 hideEl('menu');
1894 hideEl('game-over');
1895 hideEl('podium');
1896 hideEl('spectator');
1897 hideEl('planet-select');
1898 showEl('online-panel');
1899 app.mode = 'online';
1900 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
1901 if (typeof Online === 'undefined')
1902 {
1903 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
1904 showOnly('online-unconfigured');
1905 return;
1906 }
1907 Online.refresh().then(function (data)
1908 {
1909 if (!data || data.ok === false)
1910 {
1911 var msg = (data && data.error) || 'Geen verbinding met de server.';
1912 showOnlineError(msg + ' Je kunt wel alleen spelen.');
1913 if (data && data.configured === false)
1914 { showOnly('online-unconfigured'); }
1915 else
1916 { showOnly('online-login'); }
1917 document.getElementById('btn-login').style.display = 'none';
1918 return;
1919 }
1920 renderOnline();
1921 if (Online.lobby)
1922 { Online.startPolling(onlinePayload); }
1923 });
1924}
1925
1926function setOnlineStatus (text)
1927{
1928 var el = document.getElementById('online-status');
1929 if (el)
1930 { el.textContent = text; }
1931}
1932
1933function showOnlineError (text)
1934{
1935 var el = document.getElementById('online-error');
1936 if (!el)
1937 { return; }
1938 if (!text)
1939 {
1940 el.hidden = true;
1941 el.textContent = '';
1942 return;
1943 }
1944 el.hidden = false;
1945 el.textContent = text;
1946}
1947
1948function showOnly (id)
1949{
1950 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
1951 for (var i = 0; i < ids.length; i++)
1952 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
1953}
1954
1955function renderOnline ()
1956{
1957 if (typeof Online === 'undefined')
1958 { return; }
1959 if (app.mode === 'playing' && app.online)
1960 {
1961 Online.renderMinis(document.getElementById('minis'));
1962 if (Online.lobby && Online.lobby.status === 'finished')
1963 { showPodium(Online.lobby); }
1964 return;
1965 }
1966 showOnlineError(Online.error);
1967 if (!Online.configured && !Online.me && !Online.local)
1968 {
1969 setOnlineStatus('Online spelen is nog niet ingesteld.');
1970 showOnly('online-unconfigured');
1971 return;
1972 }
1973 if (!Online.me)
1974 {
1975 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
1976 showOnly('online-login');
1977 document.getElementById('btn-login').style.display = '';
1978 document.getElementById('btn-login').href = Online.loginUrl();
1979 document.getElementById('local-login').hidden = !Online.local;
1980 return;
1981 }
1982 if (Online.lobby)
1983 {
1984 setOnlineStatus('Lobby');
1985 showOnly('online-lobby');
1986 document.getElementById('lobby-me-name').textContent = Online.me.name;
1987 document.getElementById('lobby-code').textContent = Online.lobby.code;
1988 var list = document.getElementById('lobby-players');
1989 list.innerHTML = '';
1990 var players = Online.lobby.players || [];
1991 for (var i = 0; i < players.length; i++)
1992 {
1993 var p = players[i];
1994 var li = document.createElement('li');
1995 if (p.is_me)
1996 { li.classList.add('you'); }
1997 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
1998 var state = p.ready ? 'Gereed' : 'Wacht…';
1999 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2000 li.innerHTML = '<span>' + escapeText(label)
2001 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2002 + '</span><span class="'
2003 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2004 list.appendChild(li);
2005 }
2006 renderPlanetGrid('lobby-planet-grid', true);
2007 var me = Online.mePlayer();
2008 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
2009 var start = document.getElementById('btn-start');
2010 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2011 start.disabled = !Online.lobby.can_start;
2012 var hint = document.getElementById('lobby-hint');
2013 if (Online.lobby.status === 'playing')
2014 { hint.textContent = 'Het spel start…'; }
2015 else if (players.length < 2)
2016 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
2017 else if (!Online.lobby.all_ready)
2018 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
2019 else if (Online.lobby.can_start)
2020 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
2021 else
2022 { hint.textContent = 'Wachten tot de host start.'; }
2023 return;
2024 }
2025 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
2026 showOnly('online-home');
2027 document.getElementById('me-name').textContent = Online.me.name;
2028 document.getElementById('local-login').hidden = !Online.local;
2029}
2030
2031function escapeText (s)
2032{
2033 return String(s)
2034 .replace(/&/g, '&amp;')
2035 .replace(/</g, '&lt;')
2036 .replace(/>/g, '&gt;')
2037 .replace(/"/g, '&quot;');
2038}
2039
2040
2041function selectedPlanetId ()
2042{
2043 if (app.selectedPlanetId)
2044 { return app.selectedPlanetId; }
2045 return 'terra';
2046}
2047
2048function restoreSelectedPlanet ()
2049{
2050 var id = 'terra';
2051 try
2052 { id = localStorage.getItem('meteors-planet') || 'terra'; }
2053 catch (e) {}
2054 setSelectedPlanet(id, true);
2055}
2056
2057function setSelectedPlanet (id, silent)
2058{
2059 var all = Planet.allPlanets();
2060 var found = null;
2061 for (var i = 0; i < all.length; i++)
2062 {
2063 if (all[i].id === id)
2064 { found = all[i]; break; }
2065 }
2066 if (!found)
2067 { found = Planet.defaultPlanet(); }
2068 app.selectedPlanetId = found.id;
2069 try
2070 { localStorage.setItem('meteors-planet', found.id); }
2071 catch (e) {}
2072 if (!silent)
2073 {
2074 var grid = document.getElementById('planet-grid');
2075 if (grid && !grid.hidden && grid.children.length)
2076 { renderPlanetGrid('planet-grid', false); }
2077 var lobby = document.getElementById('lobby-planet-grid');
2078 if (lobby && lobby.children.length)
2079 { renderPlanetGrid('lobby-planet-grid', true); }
2080 }
2081 return found;
2082}
2083
2084function openPlanetSelect (context)
2085{
2086 if (app.mode === 'playing')
2087 { return; }
2088 app.planetSelectContext = context || 'solo';
2089 app.mode = 'planet-select';
2090 hideEl('menu');
2091 hideEl('online-panel');
2092 hideEl('game-over');
2093 showEl('planet-select');
2094 renderPlanetGrid('planet-grid', false);
2095 var go = document.getElementById('btn-planet-go');
2096 if (go)
2097 { go.textContent = 'Spelen'; }
2098}
2099
2100function renderPlanetGrid (containerId, compact)
2101{
2102 var grid = document.getElementById(containerId);
2103 if (!grid)
2104 { return; }
2105 var current = selectedPlanetId();
2106 var all = Planet.allPlanets();
2107 grid.innerHTML = '';
2108 if (compact)
2109 { grid.classList.add('compact'); }
2110 for (var i = 0; i < all.length; i++)
2111 {
2112 var pl = all[i];
2113 var btn = document.createElement('button');
2114 btn.type = 'button';
2115 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
2116 btn.setAttribute('role', 'listitem');
2117 btn.dataset.planet = pl.id;
2118 var swatches = '';
2119 for (var c = 0; c < pl.colors.length; c++)
2120 {
2121 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
2122 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
2123 }
2124 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
2125 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
2126 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2127 + '<div class="planet-swatches">' + swatches + '</div>';
2128 btn.addEventListener('click', (function (id, isCompact)
2129 {
2130 return function ()
2131 { onPlanetPicked(id, isCompact); };
2132 })(pl.id, !!compact));
2133 grid.appendChild(btn);
2134 }
2135}
2136
2137function onPlanetPicked (id, fromLobby)
2138{
2139 setSelectedPlanet(id);
2140 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2141 {
2142 Online.setPlanet(id).then(function ()
2143 { renderOnline(); });
2144 }
2145 else
2146 {
2147 renderPlanetGrid('planet-grid', false);
2148 }
2149}
2150
2151function confirmPlanetSelect ()
2152{
2153 var planet = setSelectedPlanet(selectedPlanetId());
2154 hideEl('planet-select');
2155 if (app.planetSelectContext === 'online')
2156 {
2157 openOnlinePanel();
2158 return;
2159 }
2160 if (app.planetSelectContext === 'offline')
2161 {
2162 startPlay({ planet: planet, offline: true });
2163 return;
2164 }
2165 startPlay({ planet: planet });
2166}
2167
2168function cancelPlanetSelect ()
2169{
2170 hideEl('planet-select');
2171 app.mode = 'menu';
2172 showEl('menu');
2173}
2174
2175function bindPlanetSelect ()
2176{
2177 var go = document.getElementById('btn-planet-go');
2178 var back = document.getElementById('btn-planet-back');
2179 if (go)
2180 {
2181 go.addEventListener('click', confirmPlanetSelect);
2182 }
2183 if (back)
2184 {
2185 back.addEventListener('click', cancelPlanetSelect);
2186 }
2187}