BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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