BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 54.5 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 previewOutgoingFlights();
765 app.core.tick(dt);
766 if (app.offline && app.battle)
767 { tickOffline(dt); }
768 updateSelectTween(dt);
769 syncSprites(dt);
770 updateColumnWarn(dt);
771 refreshHud();
772 refreshOfflineHud();
773 refreshChainIndicator();
774 tickOnline(dt);
775 if (app.debugPhysics)
776 { logPhysicsDebug(); }
777
778 if (app.core.state === 'gameover' && !app.gameOverShown)
779 {
780 app.gameOverShown = true;
781 app.lastScore = app.core.score;
782 document.getElementById('go-score').textContent = String(app.lastScore);
783 if (app.online)
784 { onOnlineEliminated(); }
785 else if (app.offline)
786 { /* Offline result is shown from tickOffline. */ }
787 else
788 { showEl('game-over'); }
789 }
790 if (!app.online && !app.offline && app.core.state === 'gameover'
791 && app.core.gameOverTime >= GAME_OVER_DELAY)
792 { returnToMenu(); }
793}
794
795/* ---------- pointer input (mouse + touch) --------------------------- */
796/*
797 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
798 * on a real phone, pointer clientX/Y can disagree with the visual
799 * finger (zoomed visual viewport, gesture takeover, capture cancel)
800 * while changedTouches stays correct. When a touch is active, pointer
801 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
802 * walk the block to the top or bottom of the stack (t1106).
803 *
804 * After a down we also listen on the document, so a drag that leaves
805 * the canvas (needed to launch a block at the top of a full column)
806 * still reaches moveDrag. We do not call setPointerCapture: on mobile
807 * that is often cancelled when the browser takes the gesture, which
808 * would fire pointercancel mid-drag.
809 *
810 * A non-passive document touchstart/touchmove preventDefault during
811 * play stops scrolling, rubber-banding and the pointercancel that
812 * follows. pointercancel / touchcancel end the drag without launch.
813 *
814 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
815 */
816
817var boundCanvas = null;
818var windowListening = false;
819var touchListening = false;
820var lastDragDebug = null;
821
822function isDragDebugEnabled ()
823{
824 try
825 {
826 var q = window.location && window.location.search;
827 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
828 { return true; }
829 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
830 { return true; }
831 }
832 catch (err) { /* ignore */ }
833 return false;
834}
835
836/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
837function isPhysicsDebugEnabled ()
838{
839 try
840 {
841 var q = window.location && window.location.search;
842 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
843 { return true; }
844 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
845 || window.localStorage.getItem('meteors-debug-drag') === '1'))
846 { return true; }
847 }
848 catch (err) { /* ignore */ }
849 return false;
850}
851
852function eventClient (e)
853{
854 var t = null;
855 if (e.changedTouches && e.changedTouches.length)
856 { t = e.changedTouches[0]; }
857 else if (e.touches && e.touches.length)
858 { t = e.touches[0]; }
859 if (t)
860 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
861 if (e.clientX != null && e.clientY != null)
862 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
863 return null;
864}
865
866function addWindowPointer ()
867{
868 if (windowListening)
869 { return; }
870 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
871 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
872 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
873 windowListening = true;
874}
875
876function removeWindowPointer ()
877{
878 if (!windowListening)
879 { return; }
880 window.removeEventListener('pointermove', onPointerMove, { capture: true });
881 window.removeEventListener('pointerup', onPointerUp, { capture: true });
882 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
883 windowListening = false;
884}
885
886function addTouchListeners ()
887{
888 if (touchListening)
889 { return; }
890 var opts = { capture: true, passive: false };
891 document.addEventListener('touchstart', onTouchStart, opts);
892 document.addEventListener('touchmove', onTouchMove, opts);
893 document.addEventListener('touchend', onTouchEnd, opts);
894 document.addEventListener('touchcancel', onTouchCancel, opts);
895 touchListening = true;
896}
897
898function removeTouchListeners ()
899{
900 if (!touchListening)
901 { return; }
902 var opts = { capture: true };
903 document.removeEventListener('touchstart', onTouchStart, opts);
904 document.removeEventListener('touchmove', onTouchMove, opts);
905 document.removeEventListener('touchend', onTouchEnd, opts);
906 document.removeEventListener('touchcancel', onTouchCancel, opts);
907 touchListening = false;
908}
909
910function bindPointer (canvas)
911{
912 unbindPointer();
913 boundCanvas = canvas;
914 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
915 canvas.style.touchAction = 'none';
916 canvas.style.position = 'fixed';
917 canvas.style.cursor = 'pointer';
918 canvas.style.webkitUserSelect = 'none';
919 canvas.style.userSelect = 'none';
920 addTouchListeners();
921 if (app.debugDrag)
922 { ensureDragDebugOverlay(); }
923}
924
925function unbindPointer ()
926{
927 removeWindowPointer();
928 removeTouchListeners();
929 if (boundCanvas)
930 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
931 boundCanvas = null;
932 app.pointerId = null;
933 app.pointerType = null;
934 app.activeTouchId = null;
935}
936
937function fieldFromEvent (e)
938{
939 var canvas = app.scene && app.scene.canvas;
940 if (!canvas)
941 { return null; }
942 var rect = canvas.getBoundingClientRect();
943 if (rect.width <= 0 || rect.height <= 0)
944 { return null; }
945 var pt = eventClient(e);
946 if (!pt)
947 { return null; }
948 // Map through the CSS box only. Using canvas.width / app.tile would
949 // scale the pointer by the backing-store ratio whenever that differs
950 // from the layout size (high-DPR devices), so a short finger move
951 // would look like a long swipe.
952 var width = Planet.FIELD_WIDTH;
953 var height = Planet.FIELD_HEIGHT;
954 var col = ((pt.x - rect.left) / rect.width) * width;
955 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
956 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
957}
958
959function playingForDrag ()
960{
961 return app.core && app.core.state === 'playing';
962}
963
964function startDragFromEvent (e)
965{
966 var pos = fieldFromEvent(e);
967 if (!pos)
968 { return; }
969 if (app.core.drag)
970 {
971 app.core.moveDrag(pos.y);
972 logDragDebug(e, pos, 'move-already');
973 return;
974 }
975 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
976 { startPressTween(app.core.drag.blockId); }
977 logDragDebug(e, pos, 'down');
978}
979
980function moveDragFromEvent (e)
981{
982 if (!app.core || !app.core.drag)
983 { return; }
984 var pos = fieldFromEvent(e);
985 if (pos)
986 { app.core.moveDrag(pos.y); }
987 logDragDebug(e, pos, 'move');
988}
989
990function finishDrag (opts)
991{
992 opts = opts || {};
993 app.pointerId = null;
994 app.pointerType = null;
995 app.activeTouchId = null;
996 removeWindowPointer();
997 if (boundCanvas)
998 {
999 try
1000 {
1001 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
1002 { boundCanvas.releasePointerCapture(opts.pointerId); }
1003 }
1004 catch (err) { /* ignore */ }
1005 }
1006 startReleaseTween();
1007 if (app.core && app.core.drag)
1008 {
1009 if (opts.noLaunch)
1010 { app.core.drag.launchIntent = false; }
1011 app.core.endDrag();
1012 }
1013 else if (app.core)
1014 { app.core.endDrag(); }
1015 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
1016}
1017
1018function onPointerDown (e)
1019{
1020 if (!playingForDrag())
1021 { return; }
1022 if (app.pointerId != null && e.pointerId !== app.pointerId)
1023 { return; }
1024 if (e.preventDefault)
1025 { e.preventDefault(); }
1026 app.pointerId = e.pointerId;
1027 app.pointerType = e.pointerType || 'mouse';
1028 addWindowPointer();
1029 // If a touch is already in charge, do not reset the grab from pointerdown.
1030 if (app.activeTouchId != null)
1031 { return; }
1032 startDragFromEvent(e);
1033}
1034
1035function onPointerMove (e)
1036{
1037 if (app.pointerId == null || e.pointerId !== app.pointerId)
1038 { return; }
1039 if (!app.core || !app.core.drag)
1040 { return; }
1041 // Touch coordinates are the authority; ignore pointer moves for a
1042 // live touch so a wrong clientY cannot walk the whole column.
1043 // Only skip when touchstart has actually arrived — some environments
1044 // deliver touch-pointer events without a TouchEvent stream.
1045 if (app.activeTouchId != null)
1046 {
1047 if (e.preventDefault)
1048 { e.preventDefault(); }
1049 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
1050 return;
1051 }
1052 if (e.preventDefault)
1053 { e.preventDefault(); }
1054 moveDragFromEvent(e);
1055}
1056
1057function onPointerUp (e)
1058{
1059 if (app.pointerId == null)
1060 { return; }
1061 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1062 { return; }
1063 if (app.activeTouchId != null)
1064 {
1065 // touchend will finish the drag.
1066 if (e && e.preventDefault)
1067 { e.preventDefault(); }
1068 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
1069 return;
1070 }
1071 if (e && e.preventDefault)
1072 { e.preventDefault(); }
1073 finishDrag({ pointerId: e && e.pointerId });
1074}
1075
1076function onPointerCancel (e)
1077{
1078 if (app.pointerId == null)
1079 { return; }
1080 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1081 { return; }
1082 if (app.activeTouchId != null)
1083 {
1084 if (e && e.preventDefault)
1085 { e.preventDefault(); }
1086 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
1087 return;
1088 }
1089 if (e && e.preventDefault)
1090 { e.preventDefault(); }
1091 // A cancelled gesture is not a launch pull.
1092 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
1093}
1094
1095function touchById (list, id)
1096{
1097 if (!list)
1098 { return null; }
1099 for (var i = 0; i < list.length; i++)
1100 {
1101 if (list[i].identifier === id)
1102 { return list[i]; }
1103 }
1104 return null;
1105}
1106
1107function onTouchStart (e)
1108{
1109 if (!playingForDrag())
1110 { return; }
1111 if (app.activeTouchId != null)
1112 {
1113 if (e.preventDefault)
1114 { e.preventDefault(); }
1115 return;
1116 }
1117 var t = e.changedTouches && e.changedTouches[0];
1118 if (!t)
1119 { return; }
1120 if (e.preventDefault)
1121 { e.preventDefault(); }
1122 app.activeTouchId = t.identifier;
1123 addWindowPointer();
1124 startDragFromEvent(e);
1125}
1126
1127function onTouchMove (e)
1128{
1129 if (app.activeTouchId == null)
1130 { return; }
1131 if (!touchById(e.changedTouches, app.activeTouchId)
1132 && !touchById(e.touches, app.activeTouchId))
1133 { return; }
1134 if (e.preventDefault)
1135 { e.preventDefault(); }
1136 moveDragFromEvent(e);
1137}
1138
1139function onTouchEnd (e)
1140{
1141 if (app.activeTouchId == null)
1142 { return; }
1143 if (!touchById(e.changedTouches, app.activeTouchId))
1144 { return; }
1145 if (e.preventDefault)
1146 { e.preventDefault(); }
1147 finishDrag({});
1148}
1149
1150function onTouchCancel (e)
1151{
1152 if (app.activeTouchId == null)
1153 { return; }
1154 if (!touchById(e.changedTouches, app.activeTouchId))
1155 { return; }
1156 if (e.preventDefault)
1157 { e.preventDefault(); }
1158 finishDrag({ noLaunch: true });
1159}
1160
1161function logPhysicsDebug ()
1162{
1163 if (!app.debugPhysics || !app.core)
1164 { return; }
1165 ensureDragDebugOverlay();
1166 var el = document.getElementById('drag-debug');
1167 if (!el)
1168 { return; }
1169 var issues = app.core.lastInvariantViolations || [];
1170 var flying = 0;
1171 var manuals = 0;
1172 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
1173 for (var i = 0; i < app.core.blocks.length; i++)
1174 {
1175 if (app.core.blocks[i].state === 'flying')
1176 { flying++; }
1177 if (app.core.blocks[i].state === 'manual')
1178 { manuals++; }
1179 }
1180 var status = issues.length
1181 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
1182 : ('physics ok blocks=' + app.core.blocks.length
1183 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
1184 // Keep any live drag line above the physics status.
1185 var dragLine = '';
1186 if (app.debugDrag && lastDragDebug)
1187 {
1188 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
1189 ? el.textContent.split('\n')[0] + '\n'
1190 : '';
1191 }
1192 el.textContent = dragLine + status;
1193 el.hidden = false;
1194 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
1195}
1196
1197function ensureDragDebugOverlay ()
1198{
1199 if (document.getElementById('drag-debug'))
1200 { return; }
1201 var el = document.createElement('div');
1202 el.id = 'drag-debug';
1203 el.setAttribute('aria-live', 'polite');
1204 document.body.appendChild(el);
1205}
1206
1207function logDragDebug (e, pos, phase)
1208{
1209 if (!app.debugDrag)
1210 { return; }
1211 ensureDragDebugOverlay();
1212 var el = document.getElementById('drag-debug');
1213 if (!el)
1214 { return; }
1215 var block = null;
1216 if (app.core && app.core.drag)
1217 { block = app.core.blockById(app.core.drag.blockId); }
1218 var pt = e ? eventClient(e) : null;
1219 var evType = e ? e.type : phase;
1220 var info = {
1221 phase: phase,
1222 ev: evType,
1223 src: pos && pos.src,
1224 fieldY: pos && Math.round(pos.y * 100) / 100,
1225 col: pos && Math.round(pos.col * 100) / 100,
1226 cy: pt && Math.round(pt.y * 10) / 10,
1227 blockY: block && Math.round(block.y * 100) / 100,
1228 target: block && Math.floor((pos && pos.y) + 1e-12),
1229 launch: app.core && app.core.drag && app.core.drag.launchIntent,
1230 touchId: app.activeTouchId,
1231 pid: app.pointerId,
1232 ptype: app.pointerType
1233 };
1234 lastDragDebug = info;
1235 el.textContent = 'drag ' + phase
1236 + ' ev=' + evType
1237 + ' src=' + (info.src || '-')
1238 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
1239 + ' → ' + (info.target != null ? info.target : '-')
1240 + ' block=' + (info.blockY != null ? info.blockY : '-')
1241 + (info.launch ? ' LAUNCH' : '')
1242 + ' tId=' + info.touchId
1243 + ' pId=' + info.pid;
1244 el.hidden = false;
1245}
1246
1247
1248function hideEl (id)
1249{
1250 document.getElementById(id).hidden = true;
1251}
1252
1253function showEl (id)
1254{
1255 document.getElementById(id).hidden = false;
1256}
1257
1258window.addEventListener('resize', function ()
1259{
1260 if (app.mode === 'playing')
1261 { layout(); }
1262});
1263
1264window.addEventListener('orientationchange', function ()
1265{
1266 setTimeout(function ()
1267 {
1268 if (app.mode === 'playing')
1269 { layout(); }
1270 }, 120);
1271});
1272
1273/* ---------- online play (stage 2) ---------------------------------- */
1274
1275function tickOnline (dt)
1276{
1277 if (!app.online || typeof Online === 'undefined')
1278 { return; }
1279 if (app.core)
1280 {
1281 var shots = app.core.consumeOutgoingShots();
1282 for (var i = 0; i < shots.length; i++)
1283 {
1284 var s = shots[i];
1285 var start = fieldToViewport(s.col, s.y);
1286 Online.rememberFlightLocal(s, start.x, start.y);
1287 }
1288 Online.queueShots(shots);
1289 }
1290 Online.tickFlights();
1291 Online.renderMinis(document.getElementById('minis'));
1292 applyMinisLayout();
1293}
1294
1295
1296/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1297
1298function bindOfflineUi ()
1299{
1300 var btn = document.getElementById('btn-offline');
1301 if (btn)
1302 {
1303 btn.addEventListener('click', onOffline);
1304 btn.addEventListener('pointerup', function (e)
1305 {
1306 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1307 {
1308 e.preventDefault();
1309 onOffline();
1310 }
1311 });
1312 }
1313 var back = document.getElementById('btn-offline-menu');
1314 if (back)
1315 {
1316 back.addEventListener('click', function ()
1317 {
1318 teardownPlay();
1319 app.mode = 'menu';
1320 app.offline = false;
1321 app.battle = null;
1322 hideEl('offline-result');
1323 showEl('menu');
1324 });
1325 }
1326}
1327
1328function onOffline ()
1329{
1330 openPlanetSelect('offline');
1331}
1332
1333function tickOffline (dt)
1334{
1335 if (!app.battle || !app.core || typeof Offline === 'undefined')
1336 { return; }
1337
1338 if (app.battle.state === 'round_won')
1339 {
1340 if (!app.roundWonHandled)
1341 {
1342 app.roundWonHandled = true;
1343 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1344 }
1345 app.roundWonDelay -= dt;
1346 if (app.roundWonDelay <= 0)
1347 { startNextOfflineRound(); }
1348 updateOfflineMinis(dt, true);
1349 return;
1350 }
1351
1352 var result = app.battle.tick(dt, app.core);
1353 if (result && result.flights && result.flights.length
1354 && typeof Online !== 'undefined' && Online.spawnFlights)
1355 {
1356 var locals = Object.create(null);
1357 var list = result.locals || [];
1358 for (var i = 0; i < list.length; i++)
1359 {
1360 var s = list[i];
1361 var start;
1362 if (s.from_id === 'player')
1363 { start = fieldToViewport(s.col, s.y); }
1364 else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1365 { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1366 else
1367 { start = miniViewportCenter(s.from_id); }
1368 locals[s.client_id] = {
1369 col: s.col,
1370 y: s.y,
1371 color: s.color,
1372 startX: start.x,
1373 startY: start.y,
1374 from_id: s.from_id,
1375 land_col: s.land_col
1376 };
1377 }
1378 Online.spawnFlights(result.flights, locals);
1379 }
1380 if (typeof Online !== 'undefined' && Online.tickFlights)
1381 { Online.tickFlights(); }
1382 updateOfflineMinis(dt, false);
1383
1384 if (app.battle.state === 'lost' && !app.offlineResultShown)
1385 { showOfflineResult(); }
1386}
1387
1388function startNextOfflineRound ()
1389{
1390 if (!app.battle)
1391 { return; }
1392 app.battle.advanceRound();
1393 app.roundWonHandled = false;
1394 app.roundWonDelay = 0;
1395 app._keepBattleOnTeardown = true;
1396 // Tear down the current scene then start a fresh player field,
1397 // keeping the same battle (already advanced).
1398 var planet = app.battle.playerPlanet;
1399 app._keepBattleOnTeardown = true;
1400 teardownPlay();
1401 app.offline = true;
1402 app.battle = app.battle; // kept
1403 startPlay({ planet: planet, offline: true, keepBattle: true });
1404}
1405
1406function showOfflineResult ()
1407{
1408 app.offlineResultShown = true;
1409 var battle = app.battle;
1410 var reached = document.getElementById('offline-reached');
1411 if (reached)
1412 { reached.textContent = String(battle.round); }
1413 var detail = document.getElementById('offline-result-detail');
1414 if (detail)
1415 {
1416 var sch = battle.schedule;
1417 var n = sch.opponents;
1418 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1419 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
1420 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
1421 }
1422 hideEl('game-over');
1423 showEl('offline-result');
1424}
1425
1426function refreshOfflineHud ()
1427{
1428 var el = document.getElementById('offline-hud');
1429 if (!el)
1430 { return; }
1431 if (!(app.offline && app.battle && app.mode === 'playing'))
1432 {
1433 el.hidden = true;
1434 return;
1435 }
1436 el.hidden = false;
1437 var sch = app.battle.schedule;
1438 var n = sch.opponents;
1439 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1440 var r = document.getElementById('offline-round');
1441 var o = document.getElementById('offline-opponents');
1442 var s = document.getElementById('offline-skill');
1443 if (r)
1444 { r.textContent = 'Ronde ' + sch.round; }
1445 if (o)
1446 { o.textContent = n + ' ' + noun; }
1447 if (s)
1448 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1449}
1450
1451function hideOfflineHud ()
1452{
1453 var el = document.getElementById('offline-hud');
1454 if (el)
1455 { el.hidden = true; }
1456}
1457
1458function refreshChainIndicator ()
1459{
1460 var el = document.getElementById('chain-indicator');
1461 if (!el)
1462 { return; }
1463 var info = app.core && app.core.lastChainIndicator;
1464 var active = app.core && app.core.hasActiveLandingChain
1465 && app.core.hasActiveLandingChain();
1466 // Show only while a chained cluster is still in the air.
1467 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1468 {
1469 el.hidden = true;
1470 return;
1471 }
1472 el.hidden = false;
1473 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1474}
1475
1476function hideChainIndicator ()
1477{
1478 var el = document.getElementById('chain-indicator');
1479 if (el)
1480 { el.hidden = true; }
1481}
1482
1483function miniViewportCenter (botId)
1484{
1485 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1486 if (!el)
1487 { return { x: window.innerWidth / 2, y: 40 }; }
1488 var rect = el.getBoundingClientRect();
1489 var plan = app.miniLayout;
1490 if (plan && plan.mode === 'sides')
1491 {
1492 // Leave from the top of the mini, then the arc goes up and over (t1131).
1493 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1494 }
1495 return { x: rect.left + rect.width / 2, y: rect.bottom };
1496}
1497
1498function offlineMiniSize (n)
1499{
1500 return currentMiniSize();
1501}
1502
1503function updateOfflineMinis (dt, force)
1504{
1505 app.miniAcc = (app.miniAcc || 0) + dt;
1506 if (!force && app.miniAcc < 0.1)
1507 { return; }
1508 app.miniAcc = 0;
1509 renderOfflineMinis();
1510}
1511
1512function renderOfflineMinis ()
1513{
1514 var container = document.getElementById('minis');
1515 if (!container || !app.battle)
1516 { return; }
1517 var bots = app.battle.bots;
1518 var size = offlineMiniSize(bots.length);
1519 container.classList.toggle('crowded', bots.length > 5);
1520 var existing = {};
1521 var kids = container.querySelectorAll('[data-player]');
1522 for (var i = 0; i < kids.length; i++)
1523 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1524 var seen = Object.create(null);
1525 for (var i = 0; i < bots.length; i++)
1526 {
1527 var bot = bots[i];
1528 seen[bot.id] = true;
1529 var el = existing[bot.id];
1530 if (!el)
1531 {
1532 el = document.createElement('div');
1533 el.className = 'mini';
1534 el.setAttribute('data-player', bot.id);
1535 el.innerHTML = '<div class="mini-name"></div>'
1536 + '<canvas class="mini-canvas" width="' + size.w
1537 + '" height="' + size.h + '"></canvas>'
1538 + '<div class="mini-meta"></div>';
1539 container.appendChild(el);
1540 }
1541 var canvas = el.querySelector('canvas');
1542 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1543 {
1544 canvas.width = size.w;
1545 canvas.height = size.h;
1546 }
1547 el.classList.toggle('eliminated', !!bot.eliminated);
1548 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1549 el.querySelector('.mini-name').textContent = bot.name
1550 + (planetName ? ' · ' + planetName : '');
1551 el.querySelector('.mini-meta').textContent = bot.eliminated
1552 ? 'Uit'
1553 : ('Punten ' + (bot.score || 0));
1554 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1555 if (typeof Online !== 'undefined' && Online._drawMini)
1556 { Online._drawMini(canvas, snap, bot.planet); }
1557 }
1558 for (var id in existing)
1559 {
1560 if (!seen[id])
1561 { existing[id].remove(); }
1562 }
1563 applyMinisLayout();
1564}
1565
1566function buildColumnWarn ()
1567{
1568 app.columnWarn = [];
1569 if (!app.scene)
1570 { return; }
1571 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1572 if (!img)
1573 { return; }
1574 for (var c = 0; c < 10; c++)
1575 {
1576 var obj = new GameObject(0, 0, img, 0);
1577 obj.renderer.alpha = 0;
1578 obj.renderer.visible = false;
1579 app.scene.addObject(obj);
1580 app.columnWarn.push(obj);
1581 }
1582 updateColumnWarn(0);
1583}
1584
1585function updateColumnWarn (dt)
1586{
1587 if (!app.columnWarn || !app.core)
1588 { return; }
1589 app.warnClock = (app.warnClock || 0) + (dt || 0);
1590 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1591 ? GameCore.columnWarnPulse(app.warnClock)
1592 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1593 var t = app.tile;
1594 for (var c = 0; c < app.columnWarn.length; c++)
1595 {
1596 var obj = app.columnWarn[c];
1597 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1598 obj.renderer.visible = !!on;
1599 obj.renderer.alpha = on ? pulse : 0;
1600 if (t)
1601 {
1602 obj.transform.position.x = c * t + t / 2;
1603 obj.transform.position.y = app.fieldH / 2;
1604 obj.transform.size = { x: t, y: app.fieldH };
1605 }
1606 }
1607}
1608
1609/**
1610 * Take over a rocket that is about to leave the top of a field (the
1611 * player's, or a bot's) so the flight starts at the real cell and
1612 * continues its upward motion (t1134). Shared by offline and online.
1613 */
1614function previewOutgoingFlights ()
1615{
1616 if (typeof Online === 'undefined' || !Online.previewExit)
1617 { return; }
1618 if (app.core)
1619 { previewCoreExits(app.core, null); }
1620 if (app.offline && app.battle && app.battle.bots)
1621 {
1622 var bots = app.battle.bots;
1623 for (var i = 0; i < bots.length; i++)
1624 {
1625 var bot = bots[i];
1626 if (bot && bot.core && !bot.eliminated)
1627 { previewCoreExits(bot.core, bot.id); }
1628 }
1629 }
1630}
1631
1632function previewCoreExits (core, fromId)
1633{
1634 if (!core || !core.blocks)
1635 { return; }
1636 var blocks = core.blocks;
1637 for (var i = 0; i < blocks.length; i++)
1638 {
1639 var b = blocks[i];
1640 if (b.y < 11.6)
1641 { continue; }
1642 if (!(b.vy > 0))
1643 { continue; }
1644 var start = fromId
1645 ? (Online.miniCellViewport
1646 ? Online.miniCellViewport(fromId, b.col, b.y)
1647 : miniViewportCenter(fromId))
1648 : fieldToViewport(b.col, b.y);
1649 Online.previewExit({
1650 id: b.id,
1651 col: b.col,
1652 y: b.y,
1653 vy: b.vy,
1654 color: b.color,
1655 start: start,
1656 from_id: fromId || null
1657 });
1658 }
1659}
1660
1661function fieldToViewport (col, fieldY)
1662{
1663 var canvas = app.scene && app.scene.canvas;
1664 if (!canvas)
1665 { return { x: window.innerWidth / 2, y: 40 }; }
1666 var rect = canvas.getBoundingClientRect();
1667 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1668 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1669 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1670 return { x: x, y: y };
1671}
1672
1673function onlinePayload ()
1674{
1675 if (!app.online || !app.core)
1676 { return {}; }
1677 return {
1678 snapshot: app.core.fieldSnapshot(),
1679 score: app.core.score,
1680 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1681 };
1682}
1683
1684function onOnlineEliminated ()
1685{
1686 app.eliminatedReported = true;
1687 app.spectating = true;
1688 unbindPointer();
1689 hideEl('game-over');
1690 var lobby = typeof Online !== 'undefined' && Online.lobby;
1691 if (lobby && lobby.status === 'finished')
1692 {
1693 showPodium(lobby);
1694 return;
1695 }
1696 showEl('spectator');
1697}
1698
1699function showPodium (lobby)
1700{
1701 hideEl('spectator');
1702 hideEl('game-over');
1703 hideEl('online-panel');
1704 showEl('podium');
1705 var list = document.getElementById('podium-list');
1706 list.innerHTML = '';
1707 var ranks = (lobby && lobby.rankings) || [];
1708 for (var i = 0; i < ranks.length; i++)
1709 {
1710 var r = ranks[i];
1711 var li = document.createElement('li');
1712 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
1713 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
1714 list.appendChild(li);
1715 }
1716 var hint = document.getElementById('podium-hint');
1717 var secs = (lobby && lobby.podium_seconds) || 5;
1718 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
1719}
1720
1721function startOnlineMatch ()
1722{
1723 if (app.mode === 'playing' && app.online)
1724 { return; }
1725 var planet = Planet.planetById(selectedPlanetId());
1726 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1727 if (me && me.planet && me.planet.id)
1728 { planet = Planet.planetById(me.planet.id); }
1729 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1730 if (typeof Online !== 'undefined')
1731 { Online.startPolling(onlinePayload); }
1732}
1733
1734function leaveOnlineMatch (goMenu)
1735{
1736 if (typeof Online !== 'undefined')
1737 {
1738 Online.stopPolling();
1739 Online.leaveLobby();
1740 Online.clearFlights();
1741 }
1742 teardownPlay();
1743 app.online = false;
1744 if (goMenu)
1745 {
1746 app.mode = 'menu';
1747 showEl('menu');
1748 }
1749 else
1750 {
1751 app.mode = 'online';
1752 openOnlinePanel();
1753 }
1754}
1755
1756function bindOnlineUi ()
1757{
1758 var onlineBtn = document.getElementById('btn-online');
1759 if (!onlineBtn)
1760 { return; }
1761 onlineBtn.addEventListener('click', function ()
1762 { openOnlinePanel(); });
1763
1764 var backs = document.querySelectorAll('[data-back-menu]');
1765 for (var i = 0; i < backs.length; i++)
1766 {
1767 backs[i].addEventListener('click', function ()
1768 {
1769 if (typeof Online !== 'undefined')
1770 { Online.stopPolling(); }
1771 hideEl('online-panel');
1772 app.mode = 'menu';
1773 app.online = false;
1774 showEl('menu');
1775 });
1776 }
1777
1778 document.getElementById('btn-create').addEventListener('click', function ()
1779 {
1780 Online.createLobby().then(function (data)
1781 {
1782 if (data && data.ok)
1783 {
1784 renderOnline();
1785 Online.startPolling(onlinePayload);
1786 }
1787 else
1788 { renderOnline(); }
1789 });
1790 });
1791
1792 document.getElementById('join-form').addEventListener('submit', function (e)
1793 {
1794 e.preventDefault();
1795 var code = (document.getElementById('join-code').value || '').trim();
1796 if (!code)
1797 { return; }
1798 Online.joinLobby(code).then(function ()
1799 {
1800 renderOnline();
1801 if (Online.lobby)
1802 { Online.startPolling(onlinePayload); }
1803 });
1804 });
1805
1806 document.getElementById('btn-ready').addEventListener('click', function ()
1807 {
1808 var me = Online.mePlayer();
1809 Online.setReady(!(me && me.ready)).then(renderOnline);
1810 });
1811
1812 document.getElementById('btn-start').addEventListener('click', function ()
1813 {
1814 Online.startGame().then(function (data)
1815 {
1816 if (data && data.ok)
1817 { startOnlineMatch(); }
1818 else
1819 { renderOnline(); }
1820 });
1821 });
1822
1823 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
1824 {
1825 Online.leaveLobby().then(function ()
1826 {
1827 Online.stopPolling();
1828 renderOnline();
1829 });
1830 });
1831
1832 document.getElementById('btn-copy-code').addEventListener('click', function ()
1833 {
1834 var code = document.getElementById('lobby-code').textContent;
1835 if (navigator.clipboard && navigator.clipboard.writeText)
1836 { navigator.clipboard.writeText(code); }
1837 });
1838
1839 document.getElementById('btn-spectate').addEventListener('click', function ()
1840 {
1841 hideEl('spectator');
1842 app.spectating = true;
1843 });
1844
1845 document.getElementById('btn-leave-game').addEventListener('click', function ()
1846 { leaveOnlineMatch(false); });
1847
1848 if (typeof Online !== 'undefined')
1849 {
1850 Online.onChange = function ()
1851 { renderOnline(); };
1852 Online.onGameStart = function ()
1853 { startOnlineMatch(); };
1854 Online.onIncoming = function (incoming)
1855 {
1856 if (!app.core || app.core.state !== 'playing')
1857 { return; }
1858 for (var i = 0; i < incoming.length; i++)
1859 {
1860 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
1861 app.core.ingestGarbage(col);
1862 }
1863 };
1864 Online.onFinished = function (lobby)
1865 { showPodium(lobby); };
1866 Online.onLobbyReturn = function (lobby)
1867 {
1868 teardownPlay();
1869 app.online = false;
1870 app.mode = 'online';
1871 hideEl('podium');
1872 showEl('online-panel');
1873 renderOnline();
1874 Online.startPolling(onlinePayload);
1875 };
1876 }
1877
1878 var params = new URLSearchParams(window.location.search);
1879 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
1880 { openOnlinePanel(); }
1881}
1882
1883function openOnlinePanel ()
1884{
1885 hideEl('menu');
1886 hideEl('game-over');
1887 hideEl('podium');
1888 hideEl('spectator');
1889 hideEl('planet-select');
1890 showEl('online-panel');
1891 app.mode = 'online';
1892 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
1893 if (typeof Online === 'undefined')
1894 {
1895 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
1896 showOnly('online-unconfigured');
1897 return;
1898 }
1899 Online.refresh().then(function (data)
1900 {
1901 if (!data || data.ok === false)
1902 {
1903 var msg = (data && data.error) || 'Geen verbinding met de server.';
1904 showOnlineError(msg + ' Je kunt wel alleen spelen.');
1905 if (data && data.configured === false)
1906 { showOnly('online-unconfigured'); }
1907 else
1908 { showOnly('online-login'); }
1909 document.getElementById('btn-login').style.display = 'none';
1910 return;
1911 }
1912 renderOnline();
1913 if (Online.lobby)
1914 { Online.startPolling(onlinePayload); }
1915 });
1916}
1917
1918function setOnlineStatus (text)
1919{
1920 var el = document.getElementById('online-status');
1921 if (el)
1922 { el.textContent = text; }
1923}
1924
1925function showOnlineError (text)
1926{
1927 var el = document.getElementById('online-error');
1928 if (!el)
1929 { return; }
1930 if (!text)
1931 {
1932 el.hidden = true;
1933 el.textContent = '';
1934 return;
1935 }
1936 el.hidden = false;
1937 el.textContent = text;
1938}
1939
1940function showOnly (id)
1941{
1942 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
1943 for (var i = 0; i < ids.length; i++)
1944 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
1945}
1946
1947function renderOnline ()
1948{
1949 if (typeof Online === 'undefined')
1950 { return; }
1951 if (app.mode === 'playing' && app.online)
1952 {
1953 Online.renderMinis(document.getElementById('minis'));
1954 if (Online.lobby && Online.lobby.status === 'finished')
1955 { showPodium(Online.lobby); }
1956 return;
1957 }
1958 showOnlineError(Online.error);
1959 if (!Online.configured && !Online.me && !Online.local)
1960 {
1961 setOnlineStatus('Online spelen is nog niet ingesteld.');
1962 showOnly('online-unconfigured');
1963 return;
1964 }
1965 if (!Online.me)
1966 {
1967 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
1968 showOnly('online-login');
1969 document.getElementById('btn-login').style.display = '';
1970 document.getElementById('btn-login').href = Online.loginUrl();
1971 document.getElementById('local-login').hidden = !Online.local;
1972 return;
1973 }
1974 if (Online.lobby)
1975 {
1976 setOnlineStatus('Lobby');
1977 showOnly('online-lobby');
1978 document.getElementById('lobby-me-name').textContent = Online.me.name;
1979 document.getElementById('lobby-code').textContent = Online.lobby.code;
1980 var list = document.getElementById('lobby-players');
1981 list.innerHTML = '';
1982 var players = Online.lobby.players || [];
1983 for (var i = 0; i < players.length; i++)
1984 {
1985 var p = players[i];
1986 var li = document.createElement('li');
1987 if (p.is_me)
1988 { li.classList.add('you'); }
1989 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
1990 var state = p.ready ? 'Gereed' : 'Wacht…';
1991 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
1992 li.innerHTML = '<span>' + escapeText(label)
1993 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
1994 + '</span><span class="'
1995 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
1996 list.appendChild(li);
1997 }
1998 renderPlanetGrid('lobby-planet-grid', true);
1999 var me = Online.mePlayer();
2000 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
2001 var start = document.getElementById('btn-start');
2002 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2003 start.disabled = !Online.lobby.can_start;
2004 var hint = document.getElementById('lobby-hint');
2005 if (Online.lobby.status === 'playing')
2006 { hint.textContent = 'Het spel start…'; }
2007 else if (players.length < 2)
2008 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
2009 else if (!Online.lobby.all_ready)
2010 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
2011 else if (Online.lobby.can_start)
2012 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
2013 else
2014 { hint.textContent = 'Wachten tot de host start.'; }
2015 return;
2016 }
2017 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
2018 showOnly('online-home');
2019 document.getElementById('me-name').textContent = Online.me.name;
2020 document.getElementById('local-login').hidden = !Online.local;
2021}
2022
2023function escapeText (s)
2024{
2025 return String(s)
2026 .replace(/&/g, '&amp;')
2027 .replace(/</g, '&lt;')
2028 .replace(/>/g, '&gt;')
2029 .replace(/"/g, '&quot;');
2030}
2031
2032
2033function selectedPlanetId ()
2034{
2035 if (app.selectedPlanetId)
2036 { return app.selectedPlanetId; }
2037 return 'terra';
2038}
2039
2040function restoreSelectedPlanet ()
2041{
2042 var id = 'terra';
2043 try
2044 { id = localStorage.getItem('meteors-planet') || 'terra'; }
2045 catch (e) {}
2046 setSelectedPlanet(id, true);
2047}
2048
2049function setSelectedPlanet (id, silent)
2050{
2051 var all = Planet.allPlanets();
2052 var found = null;
2053 for (var i = 0; i < all.length; i++)
2054 {
2055 if (all[i].id === id)
2056 { found = all[i]; break; }
2057 }
2058 if (!found)
2059 { found = Planet.defaultPlanet(); }
2060 app.selectedPlanetId = found.id;
2061 try
2062 { localStorage.setItem('meteors-planet', found.id); }
2063 catch (e) {}
2064 if (!silent)
2065 {
2066 var grid = document.getElementById('planet-grid');
2067 if (grid && !grid.hidden && grid.children.length)
2068 { renderPlanetGrid('planet-grid', false); }
2069 var lobby = document.getElementById('lobby-planet-grid');
2070 if (lobby && lobby.children.length)
2071 { renderPlanetGrid('lobby-planet-grid', true); }
2072 }
2073 return found;
2074}
2075
2076function openPlanetSelect (context)
2077{
2078 if (app.mode === 'playing')
2079 { return; }
2080 app.planetSelectContext = context || 'solo';
2081 app.mode = 'planet-select';
2082 hideEl('menu');
2083 hideEl('online-panel');
2084 hideEl('game-over');
2085 showEl('planet-select');
2086 renderPlanetGrid('planet-grid', false);
2087 var go = document.getElementById('btn-planet-go');
2088 if (go)
2089 { go.textContent = 'Spelen'; }
2090}
2091
2092function renderPlanetGrid (containerId, compact)
2093{
2094 var grid = document.getElementById(containerId);
2095 if (!grid)
2096 { return; }
2097 var current = selectedPlanetId();
2098 var all = Planet.allPlanets();
2099 grid.innerHTML = '';
2100 if (compact)
2101 { grid.classList.add('compact'); }
2102 for (var i = 0; i < all.length; i++)
2103 {
2104 var pl = all[i];
2105 var btn = document.createElement('button');
2106 btn.type = 'button';
2107 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
2108 btn.setAttribute('role', 'listitem');
2109 btn.dataset.planet = pl.id;
2110 var swatches = '';
2111 for (var c = 0; c < pl.colors.length; c++)
2112 {
2113 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
2114 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
2115 }
2116 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
2117 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
2118 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2119 + '<div class="planet-swatches">' + swatches + '</div>';
2120 btn.addEventListener('click', (function (id, isCompact)
2121 {
2122 return function ()
2123 { onPlanetPicked(id, isCompact); };
2124 })(pl.id, !!compact));
2125 grid.appendChild(btn);
2126 }
2127}
2128
2129function onPlanetPicked (id, fromLobby)
2130{
2131 setSelectedPlanet(id);
2132 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2133 {
2134 Online.setPlanet(id).then(function ()
2135 { renderOnline(); });
2136 }
2137 else
2138 {
2139 renderPlanetGrid('planet-grid', false);
2140 }
2141}
2142
2143function confirmPlanetSelect ()
2144{
2145 var planet = setSelectedPlanet(selectedPlanetId());
2146 hideEl('planet-select');
2147 if (app.planetSelectContext === 'online')
2148 {
2149 openOnlinePanel();
2150 return;
2151 }
2152 if (app.planetSelectContext === 'offline')
2153 {
2154 startPlay({ planet: planet, offline: true });
2155 return;
2156 }
2157 startPlay({ planet: planet });
2158}
2159
2160function cancelPlanetSelect ()
2161{
2162 hideEl('planet-select');
2163 app.mode = 'menu';
2164 showEl('menu');
2165}
2166
2167function bindPlanetSelect ()
2168{
2169 var go = document.getElementById('btn-planet-go');
2170 var back = document.getElementById('btn-planet-back');
2171 if (go)
2172 {
2173 go.addEventListener('click', confirmPlanetSelect);
2174 }
2175 if (back)
2176 {
2177 back.addEventListener('click', cancelPlanetSelect);
2178 }
2179}