BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 72.4 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 if (typeof Blocks !== 'undefined' && Blocks.images)
40 {
41 var extra = Blocks.images();
42 for (var b = 0; b < extra.length; b++)
43 { list.push(extra[b]); }
44 }
45 return list;
46}
47
48var IMAGES = planetImages();
49var GAME_OVER_DELAY = 2;
50
51var game = new Game();
52var app = {
53 mode: 'menu',
54 core: null,
55 scene: null,
56 manager: null,
57 planet: null,
58 lastScore: 0,
59 tile: 48,
60 fieldX: 0,
61 fieldY: 0,
62 fieldW: 0,
63 fieldH: 0,
64 hudH: 56,
65 sprites: Object.create(null),
66 flames: Object.create(null),
67 cells: [],
68 pointerId: null,
69 pointerType: null,
70 activeTouchId: null,
71 debugDrag: false,
72 debugPhysics: false,
73 gameOverShown: false,
74 selectTween: null,
75 online: false,
76 eliminatedReported: false,
77 spectating: false,
78 miniH: 0,
79 selectedPlanetId: 'terra',
80 planetSelectContext: 'solo',
81 offline: false,
82 battle: null,
83 swapTweens: null,
84 columnWarn: null,
85 warnClock: 0,
86 miniAcc: 0,
87 offlineResultShown: false,
88 roundWonDelay: 0,
89 roundWonHandled: false,
90 rewardActive: false,
91 onlineBefore: 0,
92 pendingLobbyReturn: null
93};
94
95window.onload = function ()
96{
97 app.debugDrag = isDragDebugEnabled();
98 app.debugPhysics = isPhysicsDebugEnabled();
99 var play = document.getElementById('btn-play');
100 play.addEventListener('click', onPlay);
101 bindGameMenu();
102 play.addEventListener('pointerup', function (e)
103 {
104 // A touch-friendly path: some mobile browsers swallow the click
105 // after a slightly sloppy tap. Ignore the following click.
106 if (e.pointerType === 'touch' || e.pointerType === 'pen')
107 {
108 e.preventDefault();
109 onPlay();
110 }
111 });
112
113 game.preloadImagesThenStart(IMAGES, function ()
114 {
115 if (game.images.flame && game.images.flame.addAnimationCycle)
116 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
117 });
118
119 if (typeof I18n !== 'undefined')
120 {
121 I18n.init();
122 I18n.bindPicker();
123 I18n.onChange(function ()
124 { refreshAllUi(); });
125 }
126 bindOnlineUi();
127 bindOfflineUi();
128 bindPlanetSelect();
129 restoreSelectedPlanet();
130 if (typeof Designer !== 'undefined' && Designer.bind)
131 { Designer.bind(); }
132 if (typeof Online !== 'undefined' && Online.refresh)
133 {
134 Online.refresh().then(function ()
135 {
136 applyProfileLocale();
137 refreshMenuAccount();
138 restoreSelectedPlanet();
139 renderPlanetGrid('planet-grid', false);
140 renderPlanetGrid('lobby-planet-grid', true);
141 });
142 }
143 else
144 { refreshMenuAccount(); }
145};
146
147function onPlay ()
148{
149 if (app.mode === 'playing')
150 { return; }
151 clearStartError();
152 openPlanetSelect('solo');
153}
154
155function startPlay (opts)
156{
157 opts = opts || {};
158 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
159 var planet = opts.planet || planetMod.planetById(selectedPlanetId());
160 var miss = opts.missChance;
161 if (typeof miss !== 'number' || !isFinite(miss))
162 { miss = planetMod.missChance(planet); }
163
164 hideEl('menu');
165 hideEl('game-over');
166 hideEl('online-panel');
167 hideEl('spectator');
168 hideEl('podium');
169 hideEl('planet-select');
170 hideEl('offline-result');
171 hideEl('designer');
172 hideEl('designer-edit');
173 if (typeof Designer !== 'undefined' && Designer.closeModal)
174 { Designer.closeModal(); }
175 // Do not show the HUD until the scene is on screen. Showing it first
176 // left the default "Terra" / "0" labels on a blank starfield when
177 // `new Scene` threw (WebGL unavailable) after inserting a transparent
178 // canvas — the t1143 live blank-screen report.
179
180 app.planet = planet;
181 app.core = new GameCore(planet, Math.random, miss);
182 if (app.debugPhysics)
183 { app.core.debugInvariants = true; }
184 app.mode = 'playing';
185 app.online = !!opts.online;
186 app.offline = !!opts.offline;
187 app.gameOverShown = false;
188 app.eliminatedReported = false;
189 app.spectating = false;
190 app.sprites = Object.create(null);
191 app.flames = Object.create(null);
192 app.cells = [];
193 app.pointerId = null;
194 app.selectTween = null;
195 app.swapTweens = Object.create(null);
196 app.columnWarn = [];
197 app.warnClock = 0;
198 app.miniAcc = 1; // draw minis on the first frame
199 app.offlineResultShown = false;
200 if (!opts.keepBattle)
201 {
202 app.roundWonDelay = 0;
203 app.roundWonHandled = false;
204 }
205 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
206 {
207 app.battle = Offline.createBattle({
208 playerPlanet: app.planet,
209 rng: Math.random,
210 round: opts.round || 1
211 });
212 }
213
214 layout();
215 if (app.scene)
216 {
217 app.scene.destroy();
218 app.scene = null;
219 }
220 try
221 {
222 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
223 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
224 app.scene.renderBackground = true;
225 game.loadScene(app.scene);
226 buildCells();
227 app.manager = app.scene.addObject(makeManager());
228 if (!app.spectating)
229 { bindPointer(app.scene.canvas); }
230 refreshHud();
231 showEl('hud');
232 setGameMenuButton(!app.online && !app.spectating);
233 }
234 catch (err)
235 {
236 abortStartPlay(err);
237 return;
238 }
239 if (app.online || app.offline)
240 { showEl('minis'); }
241 else
242 { hideEl('minis'); }
243 buildColumnWarn();
244 refreshOfflineHud();
245 refreshChainIndicator();
246 if (!opts.online)
247 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
248}
249
250function removeOrphanPlayCanvases ()
251{
252 // Scene's constructor inserts a body canvas, then GLContext may throw,
253 // leaving a transparent leftover that hides nothing and shows stars.
254 var nodes = document.querySelectorAll('body > canvas');
255 for (var i = 0; i < nodes.length; i++)
256 {
257 if (nodes[i].parentNode)
258 { nodes[i].parentNode.removeChild(nodes[i]); }
259 }
260}
261
262function abortStartPlay (err)
263{
264 if (typeof console !== 'undefined' && console.error)
265 { console.error('startPlay failed', err); }
266 try
267 {
268 unbindPointer();
269 if (app.scene && app.scene.destroy)
270 { app.scene.destroy(); }
271 }
272 catch (e) { /* ignore cleanup errors */ }
273 app.scene = null;
274 app.core = null;
275 app.manager = null;
276 app.mode = 'menu';
277 app.online = false;
278 app.offline = false;
279 app.battle = null;
280 app.cells = [];
281 removeOrphanPlayCanvases();
282 hideEl('hud');
283 hideEl('minis');
284 hideEl('planet-select');
285 showEl('menu');
286 refreshMenuAccount();
287 var box = document.getElementById('start-error');
288 if (box)
289 {
290 var msg = (err && err.message) ? String(err.message) : '';
291 var webgl = /webgl/i.test(msg);
292 if (typeof I18n !== 'undefined')
293 { box.textContent = I18n.t(webgl ? 'error.webgl' : 'error.startFailed'); }
294 else
295 {
296 box.textContent = webgl
297 ? 'This game needs WebGL. Please try another browser, or turn on hardware acceleration.'
298 : 'Could not start the game.';
299 }
300 box.hidden = false;
301 }
302}
303
304function clearStartError ()
305{
306 var box = document.getElementById('start-error');
307 if (box)
308 {
309 box.hidden = true;
310 box.textContent = '';
311 }
312}
313
314function teardownPlay ()
315{
316 unbindPointer();
317 if (app.scene)
318 {
319 app.scene.destroy();
320 app.scene = null;
321 }
322 app.manager = null;
323 app.core = null;
324 app.sprites = Object.create(null);
325 app.flames = Object.create(null);
326 app.cells = [];
327 app.selectTween = null;
328 app.swapTweens = Object.create(null);
329 app.columnWarn = [];
330 app.pointerId = null;
331 app.gameOverShown = false;
332 app.paused = false;
333 app.quitting = false;
334 hideEl('game-menu');
335 setGameMenuButton(false);
336 hideEl('hud');
337 hideEl('game-over');
338 hideEl('spectator');
339 hideEl('minis');
340 hideEl('offline-result');
341 hideOfflineHud();
342 hideChainIndicator();
343 if (typeof Online !== 'undefined')
344 { Online.clearFlights(); }
345 if (!app._keepBattleOnTeardown)
346 {
347 app.battle = null;
348 app.offline = false;
349 }
350 app._keepBattleOnTeardown = false;
351}
352
353function returnToMenu ()
354{
355 clearStartError();
356 if (app.online && typeof Online !== 'undefined')
357 {
358 // Online matches do not dump you back to the solo menu:
359 // elimination becomes spectating; a finished match shows the podium.
360 return;
361 }
362 teardownPlay();
363 app.mode = 'menu';
364 app.online = false;
365 app.offline = false;
366 app.battle = null;
367 hideEl('planet-select');
368 showEl('menu');
369 var last = document.getElementById('last-score');
370 if (app.lastScore > 0)
371 {
372 last.hidden = false;
373 last.querySelector('strong').textContent = String(app.lastScore);
374 }
375}
376
377function buildCells ()
378{
379 if (!app.scene)
380 { return; }
381 var img = game.images.cell;
382 for (var row = 0; row < 13; row++)
383 {
384 for (var col = 0; col < 10; col++)
385 {
386 var obj = new GameObject(0, 0, img, 0);
387 placeTile(obj, col, row);
388 obj.renderer.alpha = 0.9;
389 app.scene.addObject(obj);
390 app.cells.push(obj);
391 }
392 }
393}
394
395function placeTile (obj, col, y)
396{
397 var t = app.tile;
398 obj.transform.position.x = col * t + t / 2;
399 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
400 obj.transform.size = { x: t, y: t };
401}
402
403function opponentCount ()
404{
405 if (app.offline && app.battle && app.battle.bots)
406 { return app.battle.bots.length; }
407 if (app.online && typeof Online !== 'undefined' && Online.opponents)
408 { return Online.opponents().length; }
409 return 0;
410}
411
412function currentMiniSize ()
413{
414 if (app.miniLayout && app.miniLayout.mini)
415 { return { w: app.miniLayout.mini.w, h: app.miniLayout.mini.h }; }
416 var n = opponentCount();
417 var mode = (app.miniLayout && app.miniLayout.mode) || 'top';
418 if (typeof MiniLayout !== 'undefined' && MiniLayout.canvasSize)
419 { return MiniLayout.canvasSize(n, mode, 0); }
420 if (n >= 10)
421 { return { w: 40, h: 52 }; }
422 if (n >= 6)
423 { return { w: 56, h: 73 }; }
424 return { w: 80, h: 104 };
425}
426
427function applyMinisContainer (plan)
428{
429 var minis = document.getElementById('minis');
430 if (!minis)
431 { return; }
432 var n = plan ? plan.n : 0;
433 minis.classList.toggle('crowded', n > 5);
434 if (!plan || n === 0 || plan.mode !== 'sides')
435 {
436 minis.classList.remove('sides');
437 minis.style.top = (app.hudH || 56) + 'px';
438 minis.style.maxHeight = (plan && plan.miniH ? plan.miniH : 0) + 'px';
439 minis.style.bottom = '';
440 minis.style.left = '';
441 minis.style.right = '';
442 var kids = minis.querySelectorAll('.mini');
443 for (var i = 0; i < kids.length; i++)
444 {
445 kids[i].style.left = '';
446 kids[i].style.top = '';
447 kids[i].style.width = '';
448 kids[i].style.position = '';
449 }
450 return;
451 }
452 minis.classList.add('sides');
453 minis.style.top = '0';
454 minis.style.bottom = '0';
455 minis.style.left = '0';
456 minis.style.right = '0';
457 minis.style.maxHeight = 'none';
458}
459
460function applyMinisLayout ()
461{
462 var plan = app.miniLayout;
463 var minis = document.getElementById('minis');
464 if (!minis)
465 { return; }
466 applyMinisContainer(plan);
467 if (!plan || plan.mode !== 'sides')
468 { return; }
469 var positions = plan.positions || [];
470 var kids = minis.querySelectorAll('.mini');
471 for (var i = 0; i < positions.length && i < kids.length; i++)
472 {
473 var p = positions[i];
474 var el = kids[i];
475 el.style.position = 'absolute';
476 el.style.left = p.x + 'px';
477 el.style.top = p.y + 'px';
478 el.style.width = p.w + 'px';
479 var canvas = el.querySelector('canvas');
480 if (canvas)
481 {
482 canvas.style.width = p.canvasW + 'px';
483 canvas.style.height = p.canvasH + 'px';
484 }
485 }
486}
487
488function applyFlightsBackClip ()
489{
490 var back = document.getElementById('flights-back');
491 if (!back)
492 { return; }
493 var x = app.fieldX || 0;
494 var y = app.fieldY || 0;
495 var w = app.fieldW || 0;
496 var h = app.fieldH || 0;
497 if (!w || !h)
498 {
499 back.style.clipPath = '';
500 return;
501 }
502 // Even-odd polygon: full viewport with a hole over the player's field,
503 // so enemy-to-enemy arcs travel behind the field (t1125).
504 back.style.clipPath = 'polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, '
505 + x + 'px ' + y + 'px, ' + (x + w) + 'px ' + y + 'px, '
506 + (x + w) + 'px ' + (y + h) + 'px, ' + x + 'px ' + (y + h) + 'px, '
507 + x + 'px ' + y + 'px)';
508}
509
510function layoutIfNeeded ()
511{
512 if (app.core && app.core.drag)
513 { return; }
514 var vw = window.innerWidth || 320;
515 var vh = window.innerHeight || 480;
516 var n = (app.online || app.offline) ? opponentCount() : 0;
517 if (app._layoutVw === vw && app._layoutVh === vh && app._layoutN === n
518 && app.scene && app.tile)
519 { return; }
520 layout();
521}
522
523function layout ()
524{
525 if (app.core && app.core.drag)
526 { return; }
527 var vw = window.innerWidth || 320;
528 var vh = window.innerHeight || 480;
529 var n = (app.online || app.offline) ? opponentCount() : 0;
530 app._layoutVw = vw;
531 app._layoutVh = vh;
532 app._layoutN = n;
533 var safeTop = 0;
534 try
535 {
536 // env(safe-area) is a CSS thing; keep a conservative HUD height.
537 safeTop = 0;
538 }
539 catch (e) { /* ignore */ }
540 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
541 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
542 var plan;
543 if (typeof MiniLayout !== 'undefined' && MiniLayout.plan)
544 { plan = MiniLayout.plan(vw, vh, n, app.hudH, margin); }
545 else
546 {
547 plan = {
548 mode: 'top',
549 tile: 14,
550 fieldW: 140,
551 fieldH: 182,
552 fieldX: Math.floor((vw - 140) / 2),
553 fieldY: app.hudH,
554 miniH: n > 0 ? 100 : 0,
555 mini: { w: 80, h: 104 },
556 positions: [],
557 n: n
558 };
559 }
560 app.miniLayout = plan;
561 app.miniH = plan.miniH;
562 app.tile = plan.tile;
563 app.fieldW = plan.fieldW;
564 app.fieldH = plan.fieldH;
565 app.fieldX = plan.fieldX;
566 app.fieldY = plan.fieldY;
567 applyMinisLayout();
568 applyFlightsBackClip();
569
570 if (app.scene)
571 {
572 app.scene.position.x = app.fieldX;
573 app.scene.position.y = app.fieldY;
574 app.scene.size.x = app.fieldW;
575 app.scene.size.y = app.fieldH;
576 }
577}
578
579function spriteFor (block)
580{
581 if (block.state === 'locked')
582 { return game.images.locked; }
583 if (block.color < 0)
584 { return game.images.gray; }
585 var key = Planet.spriteKey(app.planet, block.color);
586 return game.images[key] || game.images.gray;
587}
588
589/** Frames in the flame sprite (from the loaded image, default 4). */
590function flameFrameCount ()
591{
592 var img = typeof game !== 'undefined' && game.images ? game.images.flame : null;
593 return img && img.subImages ? img.subImages : 4;
594}
595
596function syncSprites (dt)
597{
598 if (!app.core || !app.scene)
599 { return; }
600 dt = dt || 0;
601 consumeAndStartSwapTweens();
602 advanceSwapTweens(dt);
603 var seen = Object.create(null);
604 var blocks = app.core.blocks;
605 for (var i = 0; i < blocks.length; i++)
606 {
607 var block = blocks[i];
608 seen[block.id] = true;
609 var obj = app.sprites[block.id];
610 if (!obj)
611 {
612 obj = new GameObject(0, 0, spriteFor(block), 2);
613 app.scene.addObject(obj);
614 app.sprites[block.id] = obj;
615 }
616 obj.renderer.sprite = spriteFor(block);
617 placeTile(obj, block.col, blockVisualY(block));
618 applyBlockVisual(obj, block);
619 obj.renderer.visible = true;
620 obj.renderer.alpha = 1;
621 if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))
622 {
623 obj.renderer.visible = false;
624 obj.renderer.alpha = 0;
625 }
626
627 if (block.flame)
628 {
629 var flame = app.flames[block.id];
630 if (!flame)
631 {
632 flame = new GameObject(0, 0, game.images.flame, 1);
633 // t1183: frames are chosen by FlameFx, not the framework cycle.
634 flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion());
635 flame.renderer.setSubImage(flame.fx.frame);
636 app.scene.addObject(flame);
637 app.flames[block.id] = flame;
638 }
639 flame.renderer.visible = true;
640 FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion());
641 var t = app.tile;
642 // 3x as large (length and width, t1110). Keep the top of the
643 // flame at the same overlap into the block so the extra length
644 // extends downward under the rocket. t1183: random frame, flip,
645 // scale and rotation all pivot on that top-centre anchor.
646 var flameW = t * 0.85 * 3;
647 var flameH = t * 0.85 * 3;
648 var origCenter = app.fieldH - block.y * t + t * 0.15;
649 var origTop = origCenter - (t * 0.85) / 2;
650 var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH);
651 flame.renderer.subImage = pose.frame;
652 flame.renderer.mirrorX = pose.mirrorX;
653 flame.transform.rotation = pose.rotation;
654 flame.transform.position.x = pose.x;
655 flame.transform.position.y = pose.y;
656 flame.transform.size = { x: pose.w, y: pose.h };
657 }
658 else if (app.flames[block.id])
659 { app.flames[block.id].renderer.visible = false; }
660 if (block.flame && app.flames[block.id]
661 && typeof Online !== 'undefined' && Online.hasExitVisual
662 && Online.hasExitVisual(block.id))
663 { app.flames[block.id].renderer.visible = false; }
664 }
665
666 var ids = Object.keys(app.sprites);
667 for (var i = 0; i < ids.length; i++)
668 {
669 if (!seen[ids[i]])
670 {
671 app.sprites[ids[i]].destroy();
672 delete app.sprites[ids[i]];
673 if (app.flames[ids[i]])
674 {
675 app.flames[ids[i]].destroy();
676 delete app.flames[ids[i]];
677 }
678 }
679 }
680}
681
682function applyBlockVisual (obj, block)
683{
684 var t = app.tile;
685 var sx = 1;
686 var sy = 1;
687 var dy = 0;
688 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
689 && typeof Easing !== 'undefined' && Easing.bouncePose)
690 {
691 var u = block.bounceAge / app.planet.bounceDuration;
692 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
693 sx = pose.sx;
694 sy = pose.sy;
695 dy = pose.dy;
696 }
697 var sel = 1;
698 var tw = app.selectTween;
699 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
700 { sel = tw.scale; }
701 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
702 if (dy)
703 { obj.transform.position.y -= dy * t; }
704}
705
706function clickTween ()
707{
708 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
709}
710
711function startPressTween (blockId)
712{
713 var c = clickTween();
714 if (!c)
715 { return; }
716 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
717 app.selectTween = {
718 blockId: blockId,
719 from: from,
720 to: c.pressScale,
721 t: 0,
722 duration: c.pressDuration,
723 ease: c.pressEase,
724 scale: from,
725 phase: 'press'
726 };
727}
728
729function startReleaseTween ()
730{
731 var c = clickTween();
732 var tw = app.selectTween;
733 if (!c || !tw || tw.phase === 'idle')
734 { return; }
735 app.selectTween = {
736 blockId: tw.blockId,
737 from: tw.scale,
738 to: c.releaseScale,
739 t: 0,
740 duration: c.releaseDuration,
741 ease: c.releaseEase,
742 scale: tw.scale,
743 phase: 'release'
744 };
745}
746
747function updateSelectTween (dt)
748{
749 var tw = app.selectTween;
750 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
751 { return; }
752 tw.t += dt;
753 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
754 if (u >= 1)
755 {
756 tw.scale = tw.to;
757 tw.t = tw.duration;
758 if (tw.phase === 'press')
759 { tw.phase = 'hold'; }
760 else
761 {
762 tw.phase = 'idle';
763 tw.scale = 1;
764 tw.blockId = null;
765 }
766 return;
767 }
768 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
769 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
770}
771
772
773/* ---------- visual-only swap tween (t1121) -------------------------- */
774
775function swapTweenSpec ()
776{
777 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
778 { return Easing.SWAP_TWEEN; }
779 return { duration: 0.100, ease: null };
780}
781
782function swapEase (u)
783{
784 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
785 { return Easing.easeOutCubic(u); }
786 var v = 1 - Math.max(0, Math.min(1, u));
787 return 1 - v * v * v;
788}
789
790function tweenVisualY (tw)
791{
792 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
793 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
794}
795
796/**
797 * Consume GameCore swap events. The currently dragged block is skipped
798 * (it follows the pointer). A block that is mid-tween and is swapped
799 * again restarts from its current visual y, so rapid swaps chain
800 * smoothly without snapping.
801 */
802function consumeAndStartSwapTweens ()
803{
804 if (!app.core || !app.core.consumeSwapEvents)
805 { return; }
806 if (!app.swapTweens)
807 { app.swapTweens = Object.create(null); }
808 var ev = app.core.consumeSwapEvents();
809 if (!ev.length)
810 { return; }
811 var dragId = app.core.drag && app.core.drag.blockId;
812 var duration = swapTweenSpec().duration;
813 for (var i = 0; i < ev.length; i++)
814 {
815 var e = ev[i];
816 if (e.id === dragId)
817 {
818 delete app.swapTweens[e.id];
819 continue;
820 }
821 var fromY = e.fromY;
822 var existing = app.swapTweens[e.id];
823 if (existing)
824 { fromY = tweenVisualY(existing); }
825 app.swapTweens[e.id] = {
826 fromY: fromY,
827 toY: e.toY,
828 age: 0,
829 duration: duration
830 };
831 }
832}
833
834function advanceSwapTweens (dt)
835{
836 if (!app.swapTweens)
837 { return; }
838 var ids = Object.keys(app.swapTweens);
839 for (var i = 0; i < ids.length; i++)
840 {
841 var tw = app.swapTweens[ids[i]];
842 tw.age += dt;
843 if (tw.age >= tw.duration)
844 { delete app.swapTweens[ids[i]]; }
845 }
846}
847
848function blockVisualY (block)
849{
850 if (!app.swapTweens)
851 { return block.y; }
852 var dragId = app.core && app.core.drag && app.core.drag.blockId;
853 if (block.id === dragId)
854 { return block.y; }
855 var tw = app.swapTweens[block.id];
856 if (!tw)
857 { return block.y; }
858 return tweenVisualY(tw);
859}
860
861function refreshHud ()
862{
863 if (!app.core)
864 { return; }
865 document.getElementById('score').textContent = String(app.core.score);
866 var planet = app.planet;
867 var pname = (typeof I18n !== 'undefined') ? I18n.planetName(planet) : planet.name;
868 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(planet) : planet.people;
869 document.getElementById('planet-name').textContent = pname + ' · ' + people;
870 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
871}
872
873function makeManager ()
874{
875 var obj = new GameObject(0, 0, game.images.pixel, 0);
876 obj.renderer.visible = false;
877 var base = obj.update.bind(obj);
878 obj.update = function (dt)
879 {
880 base(dt);
881 tickView(dt);
882 };
883 return obj;
884}
885
886function tickView (dt)
887{
888 if (app.mode !== 'playing' || !app.core)
889 { return; }
890
891 // Never resize the canvas mid-drag: a URL-bar hide would move the
892 // field under the finger and jump the target row. Also skip work
893 // when the viewport has not actually changed.
894 if (!(app.core && app.core.drag))
895 { layoutIfNeeded(); }
896 for (var i = 0; i < app.cells.length; i++)
897 {
898 var col = i % 10;
899 var row = Math.floor(i / 10);
900 placeTile(app.cells[i], col, row);
901 }
902
903 // t1193: in-game menu open (Spelen / Offline Strijd) or quitting:
904 // the field, bots and timers stand still; only the view is kept.
905 if (app.paused)
906 {
907 syncSprites(0);
908 return;
909 }
910
911 app.core.tick(dt);
912 if (app.offline && app.battle)
913 { tickOffline(dt); }
914 updateSelectTween(dt);
915 syncSprites(dt);
916 updateColumnWarn(dt);
917 refreshHud();
918 refreshOfflineHud();
919 refreshChainIndicator();
920 tickOnline(dt);
921 if (app.debugPhysics)
922 { logPhysicsDebug(); }
923
924 if (app.core.state === 'gameover' && !app.gameOverShown)
925 {
926 app.gameOverShown = true;
927 app.lastScore = app.core.score;
928 document.getElementById('go-score').textContent = String(app.lastScore);
929 if (app.online)
930 { onOnlineEliminated(); }
931 else if (app.offline)
932 { /* Offline result is shown from tickOffline. */ }
933 else if (rewardEnabled())
934 { showReward(false, finishPlaySession(app.lastScore), returnToMenu); }
935 else
936 {
937 showEl('game-over');
938 finishPlaySession(app.lastScore);
939 }
940 }
941 if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover'
942 && app.core.gameOverTime >= GAME_OVER_DELAY)
943 { returnToMenu(); }
944}
945
946/* ---------- pointer input (mouse + touch) --------------------------- */
947/*
948 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
949 * on a real phone, pointer clientX/Y can disagree with the visual
950 * finger (zoomed visual viewport, gesture takeover, capture cancel)
951 * while changedTouches stays correct. When a touch is active, pointer
952 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
953 * walk the block to the top or bottom of the stack (t1106).
954 *
955 * After a down we also listen on the document, so a drag that leaves
956 * the canvas (needed to launch a block at the top of a full column)
957 * still reaches moveDrag. We do not call setPointerCapture: on mobile
958 * that is often cancelled when the browser takes the gesture, which
959 * would fire pointercancel mid-drag.
960 *
961 * A non-passive document touchstart/touchmove preventDefault during
962 * play stops scrolling, rubber-banding and the pointercancel that
963 * follows. pointercancel / touchcancel end the drag without launch.
964 *
965 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
966 */
967
968var boundCanvas = null;
969var windowListening = false;
970var touchListening = false;
971var lastDragDebug = null;
972
973function isDragDebugEnabled ()
974{
975 try
976 {
977 var q = window.location && window.location.search;
978 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
979 { return true; }
980 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
981 { return true; }
982 }
983 catch (err) { /* ignore */ }
984 return false;
985}
986
987/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
988function isPhysicsDebugEnabled ()
989{
990 try
991 {
992 var q = window.location && window.location.search;
993 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
994 { return true; }
995 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
996 || window.localStorage.getItem('meteors-debug-drag') === '1'))
997 { return true; }
998 }
999 catch (err) { /* ignore */ }
1000 return false;
1001}
1002
1003function eventClient (e)
1004{
1005 var t = null;
1006 if (e.changedTouches && e.changedTouches.length)
1007 { t = e.changedTouches[0]; }
1008 else if (e.touches && e.touches.length)
1009 { t = e.touches[0]; }
1010 if (t)
1011 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
1012 if (e.clientX != null && e.clientY != null)
1013 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
1014 return null;
1015}
1016
1017function addWindowPointer ()
1018{
1019 if (windowListening)
1020 { return; }
1021 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
1022 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
1023 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
1024 windowListening = true;
1025}
1026
1027function removeWindowPointer ()
1028{
1029 if (!windowListening)
1030 { return; }
1031 window.removeEventListener('pointermove', onPointerMove, { capture: true });
1032 window.removeEventListener('pointerup', onPointerUp, { capture: true });
1033 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
1034 windowListening = false;
1035}
1036
1037function addTouchListeners ()
1038{
1039 if (touchListening)
1040 { return; }
1041 var opts = { capture: true, passive: false };
1042 document.addEventListener('touchstart', onTouchStart, opts);
1043 document.addEventListener('touchmove', onTouchMove, opts);
1044 document.addEventListener('touchend', onTouchEnd, opts);
1045 document.addEventListener('touchcancel', onTouchCancel, opts);
1046 touchListening = true;
1047}
1048
1049function removeTouchListeners ()
1050{
1051 if (!touchListening)
1052 { return; }
1053 var opts = { capture: true };
1054 document.removeEventListener('touchstart', onTouchStart, opts);
1055 document.removeEventListener('touchmove', onTouchMove, opts);
1056 document.removeEventListener('touchend', onTouchEnd, opts);
1057 document.removeEventListener('touchcancel', onTouchCancel, opts);
1058 touchListening = false;
1059}
1060
1061function bindPointer (canvas)
1062{
1063 unbindPointer();
1064 boundCanvas = canvas;
1065 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
1066 canvas.style.touchAction = 'none';
1067 canvas.style.position = 'fixed';
1068 canvas.style.cursor = 'pointer';
1069 canvas.style.webkitUserSelect = 'none';
1070 canvas.style.userSelect = 'none';
1071 addTouchListeners();
1072 if (app.debugDrag)
1073 { ensureDragDebugOverlay(); }
1074}
1075
1076function unbindPointer ()
1077{
1078 removeWindowPointer();
1079 removeTouchListeners();
1080 if (boundCanvas)
1081 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
1082 boundCanvas = null;
1083 app.pointerId = null;
1084 app.pointerType = null;
1085 app.activeTouchId = null;
1086}
1087
1088function fieldFromEvent (e)
1089{
1090 var canvas = app.scene && app.scene.canvas;
1091 if (!canvas)
1092 { return null; }
1093 var rect = canvas.getBoundingClientRect();
1094 if (rect.width <= 0 || rect.height <= 0)
1095 { return null; }
1096 var pt = eventClient(e);
1097 if (!pt)
1098 { return null; }
1099 // Map through the CSS box only. Using canvas.width / app.tile would
1100 // scale the pointer by the backing-store ratio whenever that differs
1101 // from the layout size (high-DPR devices), so a short finger move
1102 // would look like a long swipe.
1103 var width = Planet.FIELD_WIDTH;
1104 var height = Planet.FIELD_HEIGHT;
1105 var col = ((pt.x - rect.left) / rect.width) * width;
1106 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
1107 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
1108}
1109
1110function playingForDrag ()
1111{
1112 return app.core && app.core.state === 'playing' && !app.paused;
1113}
1114
1115/** Touches on HUD buttons / menus are UI taps, not field drags (t1193). */
1116function isUiTouchTarget (e)
1117{
1118 var el = e && e.target;
1119 if (!el || !el.closest)
1120 { return false; }
1121 return !!el.closest('button, a, input, select, #game-menu, #reward');
1122}
1123
1124function startDragFromEvent (e)
1125{
1126 var pos = fieldFromEvent(e);
1127 if (!pos)
1128 { return; }
1129 if (app.core.drag)
1130 {
1131 app.core.moveDrag(pos.y);
1132 logDragDebug(e, pos, 'move-already');
1133 return;
1134 }
1135 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
1136 { startPressTween(app.core.drag.blockId); }
1137 logDragDebug(e, pos, 'down');
1138}
1139
1140function moveDragFromEvent (e)
1141{
1142 if (!app.core || !app.core.drag)
1143 { return; }
1144 var pos = fieldFromEvent(e);
1145 if (pos)
1146 { app.core.moveDrag(pos.y); }
1147 logDragDebug(e, pos, 'move');
1148}
1149
1150function finishDrag (opts)
1151{
1152 opts = opts || {};
1153 app.pointerId = null;
1154 app.pointerType = null;
1155 app.activeTouchId = null;
1156 removeWindowPointer();
1157 if (boundCanvas)
1158 {
1159 try
1160 {
1161 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
1162 { boundCanvas.releasePointerCapture(opts.pointerId); }
1163 }
1164 catch (err) { /* ignore */ }
1165 }
1166 startReleaseTween();
1167 if (app.core && app.core.drag)
1168 {
1169 if (opts.noLaunch)
1170 { app.core.drag.launchIntent = false; }
1171 app.core.endDrag();
1172 }
1173 else if (app.core)
1174 { app.core.endDrag(); }
1175 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
1176}
1177
1178function onPointerDown (e)
1179{
1180 if (!playingForDrag())
1181 { return; }
1182 if (app.pointerId != null && e.pointerId !== app.pointerId)
1183 { return; }
1184 if (e.preventDefault)
1185 { e.preventDefault(); }
1186 app.pointerId = e.pointerId;
1187 app.pointerType = e.pointerType || 'mouse';
1188 addWindowPointer();
1189 // If a touch is already in charge, do not reset the grab from pointerdown.
1190 if (app.activeTouchId != null)
1191 { return; }
1192 startDragFromEvent(e);
1193}
1194
1195function onPointerMove (e)
1196{
1197 if (app.pointerId == null || e.pointerId !== app.pointerId)
1198 { return; }
1199 if (!app.core || !app.core.drag)
1200 { return; }
1201 // Touch coordinates are the authority; ignore pointer moves for a
1202 // live touch so a wrong clientY cannot walk the whole column.
1203 // Only skip when touchstart has actually arrived — some environments
1204 // deliver touch-pointer events without a TouchEvent stream.
1205 if (app.activeTouchId != null)
1206 {
1207 if (e.preventDefault)
1208 { e.preventDefault(); }
1209 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
1210 return;
1211 }
1212 if (e.preventDefault)
1213 { e.preventDefault(); }
1214 moveDragFromEvent(e);
1215}
1216
1217function onPointerUp (e)
1218{
1219 if (app.pointerId == null)
1220 { return; }
1221 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1222 { return; }
1223 if (app.activeTouchId != null)
1224 {
1225 // touchend will finish the drag.
1226 if (e && e.preventDefault)
1227 { e.preventDefault(); }
1228 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
1229 return;
1230 }
1231 if (e && e.preventDefault)
1232 { e.preventDefault(); }
1233 finishDrag({ pointerId: e && e.pointerId });
1234}
1235
1236function onPointerCancel (e)
1237{
1238 if (app.pointerId == null)
1239 { return; }
1240 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1241 { return; }
1242 if (app.activeTouchId != null)
1243 {
1244 if (e && e.preventDefault)
1245 { e.preventDefault(); }
1246 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
1247 return;
1248 }
1249 if (e && e.preventDefault)
1250 { e.preventDefault(); }
1251 // A cancelled gesture is not a launch pull.
1252 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
1253}
1254
1255function touchById (list, id)
1256{
1257 if (!list)
1258 { return null; }
1259 for (var i = 0; i < list.length; i++)
1260 {
1261 if (list[i].identifier === id)
1262 { return list[i]; }
1263 }
1264 return null;
1265}
1266
1267function onTouchStart (e)
1268{
1269 if (!playingForDrag())
1270 { return; }
1271 if (app.activeTouchId == null && isUiTouchTarget(e))
1272 { return; }
1273 if (app.activeTouchId != null)
1274 {
1275 if (e.preventDefault)
1276 { e.preventDefault(); }
1277 return;
1278 }
1279 var t = e.changedTouches && e.changedTouches[0];
1280 if (!t)
1281 { return; }
1282 if (e.preventDefault)
1283 { e.preventDefault(); }
1284 app.activeTouchId = t.identifier;
1285 addWindowPointer();
1286 startDragFromEvent(e);
1287}
1288
1289function onTouchMove (e)
1290{
1291 if (app.activeTouchId == null)
1292 { return; }
1293 if (!touchById(e.changedTouches, app.activeTouchId)
1294 && !touchById(e.touches, app.activeTouchId))
1295 { return; }
1296 if (e.preventDefault)
1297 { e.preventDefault(); }
1298 moveDragFromEvent(e);
1299}
1300
1301function onTouchEnd (e)
1302{
1303 if (app.activeTouchId == null)
1304 { return; }
1305 if (!touchById(e.changedTouches, app.activeTouchId))
1306 { return; }
1307 if (e.preventDefault)
1308 { e.preventDefault(); }
1309 finishDrag({});
1310}
1311
1312function onTouchCancel (e)
1313{
1314 if (app.activeTouchId == null)
1315 { return; }
1316 if (!touchById(e.changedTouches, app.activeTouchId))
1317 { return; }
1318 if (e.preventDefault)
1319 { e.preventDefault(); }
1320 finishDrag({ noLaunch: true });
1321}
1322
1323function logPhysicsDebug ()
1324{
1325 if (!app.debugPhysics || !app.core)
1326 { return; }
1327 ensureDragDebugOverlay();
1328 var el = document.getElementById('drag-debug');
1329 if (!el)
1330 { return; }
1331 var issues = app.core.lastInvariantViolations || [];
1332 var flying = 0;
1333 var manuals = 0;
1334 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
1335 for (var i = 0; i < app.core.blocks.length; i++)
1336 {
1337 if (app.core.blocks[i].state === 'flying')
1338 { flying++; }
1339 if (app.core.blocks[i].state === 'manual')
1340 { manuals++; }
1341 }
1342 var status = issues.length
1343 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
1344 : ('physics ok blocks=' + app.core.blocks.length
1345 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
1346 // Keep any live drag line above the physics status.
1347 var dragLine = '';
1348 if (app.debugDrag && lastDragDebug)
1349 {
1350 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
1351 ? el.textContent.split('\n')[0] + '\n'
1352 : '';
1353 }
1354 el.textContent = dragLine + status;
1355 el.hidden = false;
1356 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
1357}
1358
1359function ensureDragDebugOverlay ()
1360{
1361 if (document.getElementById('drag-debug'))
1362 { return; }
1363 var el = document.createElement('div');
1364 el.id = 'drag-debug';
1365 el.setAttribute('aria-live', 'polite');
1366 document.body.appendChild(el);
1367}
1368
1369function logDragDebug (e, pos, phase)
1370{
1371 if (!app.debugDrag)
1372 { return; }
1373 ensureDragDebugOverlay();
1374 var el = document.getElementById('drag-debug');
1375 if (!el)
1376 { return; }
1377 var block = null;
1378 if (app.core && app.core.drag)
1379 { block = app.core.blockById(app.core.drag.blockId); }
1380 var pt = e ? eventClient(e) : null;
1381 var evType = e ? e.type : phase;
1382 var info = {
1383 phase: phase,
1384 ev: evType,
1385 src: pos && pos.src,
1386 fieldY: pos && Math.round(pos.y * 100) / 100,
1387 col: pos && Math.round(pos.col * 100) / 100,
1388 cy: pt && Math.round(pt.y * 10) / 10,
1389 blockY: block && Math.round(block.y * 100) / 100,
1390 target: block && Math.floor((pos && pos.y) + 1e-12),
1391 launch: app.core && app.core.drag && app.core.drag.launchIntent,
1392 touchId: app.activeTouchId,
1393 pid: app.pointerId,
1394 ptype: app.pointerType
1395 };
1396 lastDragDebug = info;
1397 el.textContent = 'drag ' + phase
1398 + ' ev=' + evType
1399 + ' src=' + (info.src || '-')
1400 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
1401 + ' → ' + (info.target != null ? info.target : '-')
1402 + ' block=' + (info.blockY != null ? info.blockY : '-')
1403 + (info.launch ? ' LAUNCH' : '')
1404 + ' tId=' + info.touchId
1405 + ' pId=' + info.pid;
1406 el.hidden = false;
1407}
1408
1409
1410function hideEl (id)
1411{
1412 document.getElementById(id).hidden = true;
1413}
1414
1415function showEl (id)
1416{
1417 document.getElementById(id).hidden = false;
1418}
1419
1420window.addEventListener('resize', function ()
1421{
1422 if (app.mode === 'playing')
1423 { layout(); }
1424});
1425
1426window.addEventListener('orientationchange', function ()
1427{
1428 setTimeout(function ()
1429 {
1430 if (app.mode === 'playing')
1431 { layout(); }
1432 }, 120);
1433});
1434
1435/* ---------- online play (stage 2) ---------------------------------- */
1436
1437function tickOnline (dt)
1438{
1439 if (!app.online || typeof Online === 'undefined')
1440 { return; }
1441 if (app.core)
1442 {
1443 var shots = app.core.consumeOutgoingShots();
1444 for (var i = 0; i < shots.length; i++)
1445 {
1446 var s = shots[i];
1447 var start = fieldToViewport(s.col, s.y);
1448 Online.rememberFlightLocal(s, start.x, start.y);
1449 // Draw the flight locally right away (t1181); the server
1450 // answer only retargets it.
1451 if (Online.startLocalShot)
1452 { Online.startLocalShot(s, start); }
1453 }
1454 Online.queueShots(shots);
1455 if (shots.length && Online.flushShotsSoon)
1456 { Online.flushShotsSoon(); }
1457 }
1458 Online.tickFlights();
1459 Online.renderMinis(document.getElementById('minis'));
1460 applyMinisLayout();
1461}
1462
1463
1464/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1465
1466function bindOfflineUi ()
1467{
1468 var btn = document.getElementById('btn-offline');
1469 if (btn)
1470 {
1471 btn.addEventListener('click', onOffline);
1472 btn.addEventListener('pointerup', function (e)
1473 {
1474 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1475 {
1476 e.preventDefault();
1477 onOffline();
1478 }
1479 });
1480 }
1481 var back = document.getElementById('btn-offline-menu');
1482 if (back)
1483 {
1484 back.addEventListener('click', function ()
1485 {
1486 teardownPlay();
1487 app.mode = 'menu';
1488 app.offline = false;
1489 app.battle = null;
1490 hideEl('offline-result');
1491 showEl('menu');
1492 });
1493 }
1494}
1495
1496function onOffline ()
1497{
1498 openPlanetSelect('offline');
1499}
1500
1501function tickOffline (dt)
1502{
1503 if (!app.battle || !app.core || typeof Offline === 'undefined')
1504 { return; }
1505
1506 if (app.battle.state === 'round_won')
1507 {
1508 if (!app.roundWonHandled)
1509 {
1510 app.roundWonHandled = true;
1511 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1512 if (rewardEnabled())
1513 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
1514 }
1515 if (app.rewardActive)
1516 {
1517 updateOfflineMinis(dt, true);
1518 return;
1519 }
1520 app.roundWonDelay -= dt;
1521 if (app.roundWonDelay <= 0)
1522 { startNextOfflineRound(); }
1523 updateOfflineMinis(dt, true);
1524 return;
1525 }
1526
1527 var result = app.battle.tick(dt, app.core);
1528 if (result && result.flights && result.flights.length
1529 && typeof Online !== 'undefined' && Online.spawnFlights)
1530 {
1531 var locals = Object.create(null);
1532 var list = result.locals || [];
1533 for (var i = 0; i < list.length; i++)
1534 {
1535 var s = list[i];
1536 var start;
1537 if (s.from_id === 'player')
1538 { start = fieldToViewport(s.col, s.y); }
1539 else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1540 { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1541 else
1542 { start = miniViewportCenter(s.from_id); }
1543 locals[s.client_id] = {
1544 col: s.col,
1545 y: s.y,
1546 color: s.color,
1547 startX: start.x,
1548 startY: start.y,
1549 from_id: s.from_id,
1550 land_col: s.land_col
1551 };
1552 }
1553 Online.spawnFlights(result.flights, locals);
1554 }
1555 if (typeof Online !== 'undefined' && Online.tickFlights)
1556 { Online.tickFlights(); }
1557 updateOfflineMinis(dt, false);
1558
1559 if (app.battle.state === 'lost' && !app.offlineResultShown)
1560 {
1561 if (rewardEnabled())
1562 {
1563 // Guard against starting the reward twice; showOfflineResult
1564 // sets the flag again when it runs afterwards.
1565 app.offlineResultShown = true;
1566 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
1567 }
1568 else
1569 { showOfflineResult(); }
1570 }
1571}
1572
1573function startNextOfflineRound ()
1574{
1575 if (!app.battle)
1576 { return; }
1577 app.battle.advanceRound();
1578 app.roundWonHandled = false;
1579 app.roundWonDelay = 0;
1580 app._keepBattleOnTeardown = true;
1581 // Tear down the current scene then start a fresh player field,
1582 // keeping the same battle (already advanced).
1583 var planet = app.battle.playerPlanet;
1584 var roundScore = app.core ? app.core.score : 0;
1585 finishPlaySession(roundScore);
1586 app._keepBattleOnTeardown = true;
1587 teardownPlay();
1588 app.offline = true;
1589 app.battle = app.battle; // kept
1590 startPlay({ planet: planet, offline: true, keepBattle: true });
1591}
1592
1593function showOfflineResult ()
1594{
1595 app.offlineResultShown = true;
1596 var battle = app.battle;
1597 var reached = document.getElementById('offline-reached');
1598 var sch = battle.schedule;
1599 var n = sch.opponents;
1600 var skill = Math.round(sch.skill * 100);
1601 var line = document.getElementById('offline-reached-line');
1602 if (line && typeof I18n !== 'undefined')
1603 { line.textContent = I18n.t('offline.reached', { n: battle.round }); }
1604 else if (reached)
1605 { reached.textContent = String(battle.round); }
1606 var detail = document.getElementById('offline-result-detail');
1607 if (detail)
1608 {
1609 if (typeof I18n !== 'undefined')
1610 {
1611 detail.textContent = I18n.t('offline.detail', {
1612 n: n,
1613 opponents: I18n.plural('hud.opponent', n),
1614 skill: skill
1615 });
1616 }
1617 else
1618 {
1619 var noun = n === 1 ? 'opponent' : 'opponents';
1620 detail.textContent = 'You played against ' + n + ' ' + noun
1621 + ' at skill ' + skill + '%.';
1622 }
1623 }
1624 hideEl('game-over');
1625 showEl('offline-result');
1626 finishPlaySession(app.core ? app.core.score : 0);
1627}
1628
1629function refreshOfflineHud ()
1630{
1631 var el = document.getElementById('offline-hud');
1632 if (!el)
1633 { return; }
1634 if (!(app.offline && app.battle && app.mode === 'playing'))
1635 {
1636 el.hidden = true;
1637 return;
1638 }
1639 el.hidden = false;
1640 var sch = app.battle.schedule;
1641 var n = sch.opponents;
1642 var r = document.getElementById('offline-round');
1643 var o = document.getElementById('offline-opponents');
1644 var s = document.getElementById('offline-skill');
1645 if (typeof I18n !== 'undefined')
1646 {
1647 if (r)
1648 { r.textContent = I18n.t('hud.round', { n: sch.round }); }
1649 if (o)
1650 {
1651 o.textContent = I18n.t('hud.opponentsLine', {
1652 n: n, word: I18n.plural('hud.opponent', n)
1653 });
1654 }
1655 if (s)
1656 { s.textContent = I18n.t('hud.skill', { n: Math.round(sch.skill * 100) }); }
1657 }
1658 else
1659 {
1660 var noun = n === 1 ? 'opponent' : 'opponents';
1661 if (r)
1662 { r.textContent = 'Round ' + sch.round; }
1663 if (o)
1664 { o.textContent = n + ' ' + noun; }
1665 if (s)
1666 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1667 }
1668}
1669
1670function hideOfflineHud ()
1671{
1672 var el = document.getElementById('offline-hud');
1673 if (el)
1674 { el.hidden = true; }
1675}
1676
1677function refreshChainIndicator ()
1678{
1679 var el = document.getElementById('chain-indicator');
1680 if (!el)
1681 { return; }
1682 var info = app.core && app.core.lastChainIndicator;
1683 var active = app.core && app.core.hasActiveLandingChain
1684 && app.core.hasActiveLandingChain();
1685 // Show only while a chained cluster is still in the air.
1686 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1687 {
1688 el.hidden = true;
1689 return;
1690 }
1691 el.hidden = false;
1692 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1693}
1694
1695function hideChainIndicator ()
1696{
1697 var el = document.getElementById('chain-indicator');
1698 if (el)
1699 { el.hidden = true; }
1700}
1701
1702function miniViewportCenter (botId)
1703{
1704 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1705 if (!el)
1706 { return { x: window.innerWidth / 2, y: 40 }; }
1707 var rect = el.getBoundingClientRect();
1708 var plan = app.miniLayout;
1709 if (plan && plan.mode === 'sides')
1710 {
1711 // Leave from the top of the mini, then the arc goes up and over (t1131).
1712 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1713 }
1714 return { x: rect.left + rect.width / 2, y: rect.bottom };
1715}
1716
1717function offlineMiniSize (n)
1718{
1719 return currentMiniSize();
1720}
1721
1722function updateOfflineMinis (dt, force)
1723{
1724 app.miniAcc = (app.miniAcc || 0) + dt;
1725 if (!force && app.miniAcc < 0.1)
1726 { return; }
1727 app.miniAcc = 0;
1728 renderOfflineMinis();
1729}
1730
1731function renderOfflineMinis ()
1732{
1733 var container = document.getElementById('minis');
1734 if (!container || !app.battle)
1735 { return; }
1736 var bots = app.battle.bots;
1737 var size = offlineMiniSize(bots.length);
1738 container.classList.toggle('crowded', bots.length > 5);
1739 var existing = {};
1740 var kids = container.querySelectorAll('[data-player]');
1741 for (var i = 0; i < kids.length; i++)
1742 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1743 var seen = Object.create(null);
1744 for (var i = 0; i < bots.length; i++)
1745 {
1746 var bot = bots[i];
1747 seen[bot.id] = true;
1748 var el = existing[bot.id];
1749 if (!el)
1750 {
1751 el = document.createElement('div');
1752 el.className = 'mini';
1753 el.setAttribute('data-player', bot.id);
1754 el.innerHTML = '<div class="mini-name"></div>'
1755 + '<canvas class="mini-canvas" width="' + size.w
1756 + '" height="' + size.h + '"></canvas>'
1757 + '<div class="mini-meta"></div>';
1758 container.appendChild(el);
1759 }
1760 var canvas = el.querySelector('canvas');
1761 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1762 {
1763 canvas.width = size.w;
1764 canvas.height = size.h;
1765 }
1766 el.classList.toggle('eliminated', !!bot.eliminated);
1767 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1768 var shownPlanet = planetName;
1769 if (bot.planet && typeof I18n !== 'undefined')
1770 { shownPlanet = I18n.planetName(bot.planet); }
1771 el.querySelector('.mini-name').textContent = bot.name
1772 + (shownPlanet ? ' · ' + shownPlanet : '');
1773 el.querySelector('.mini-meta').textContent = bot.eliminated
1774 ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out')
1775 : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (bot.score || 0)));
1776 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1777 if (typeof Online !== 'undefined' && Online._drawMini)
1778 { Online._drawMini(canvas, snap, bot.planet); }
1779 }
1780 for (var id in existing)
1781 {
1782 if (!seen[id])
1783 { existing[id].remove(); }
1784 }
1785 applyMinisLayout();
1786}
1787
1788function buildColumnWarn ()
1789{
1790 app.columnWarn = [];
1791 if (!app.scene)
1792 { return; }
1793 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1794 if (!img)
1795 { return; }
1796 for (var c = 0; c < 10; c++)
1797 {
1798 var obj = new GameObject(0, 0, img, 0);
1799 obj.renderer.alpha = 0;
1800 obj.renderer.visible = false;
1801 app.scene.addObject(obj);
1802 app.columnWarn.push(obj);
1803 }
1804 updateColumnWarn(0);
1805}
1806
1807function updateColumnWarn (dt)
1808{
1809 if (!app.columnWarn || !app.core)
1810 { return; }
1811 app.warnClock = (app.warnClock || 0) + (dt || 0);
1812 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1813 ? GameCore.columnWarnPulse(app.warnClock)
1814 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1815 var t = app.tile;
1816 for (var c = 0; c < app.columnWarn.length; c++)
1817 {
1818 var obj = app.columnWarn[c];
1819 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1820 obj.renderer.visible = !!on;
1821 obj.renderer.alpha = on ? pulse : 0;
1822 if (t)
1823 {
1824 obj.transform.position.x = c * t + t / 2;
1825 obj.transform.position.y = app.fieldH / 2;
1826 obj.transform.size = { x: t, y: app.fieldH };
1827 }
1828 }
1829}
1830
1831/**
1832 * A flight starts only when a block has actually left the field
1833 * (y ≥ height, the same threshold as cullOffTop). Rockets that
1834 * peak below the top and fall back must never get an arc (t1137).
1835 * Shared by the player's field, enemy minis, offline and online.
1836 */
1837function previewOutgoingFlights ()
1838{
1839 // Intentionally not called before core.tick: a block still on
1840 // the field (y < 13) is not a shot yet. Flights are spawned
1841 // from consumeOutgoingShots after cull, at the exit pose.
1842 if (typeof Online === 'undefined' || !Online.previewExit)
1843 { return; }
1844 if (app.core)
1845 { previewCoreExits(app.core, null); }
1846 if (app.offline && app.battle && app.battle.bots)
1847 {
1848 var bots = app.battle.bots;
1849 for (var i = 0; i < bots.length; i++)
1850 {
1851 var bot = bots[i];
1852 if (bot && bot.core && !bot.eliminated)
1853 { previewCoreExits(bot.core, bot.id); }
1854 }
1855 }
1856}
1857
1858function previewCoreExits (core, fromId)
1859{
1860 if (!core || !core.blocks)
1861 { return; }
1862 var height = core.height != null ? core.height : 13;
1863 var blocks = core.blocks;
1864 for (var i = 0; i < blocks.length; i++)
1865 {
1866 var b = blocks[i];
1867 if (b.state === 'manual')
1868 { continue; }
1869 if (typeof Online.hasLeftTheField === 'function'
1870 ? !Online.hasLeftTheField(b.y, height)
1871 : !(b.y >= height - 1e-9))
1872 { continue; }
1873 if (!(b.vy > 0))
1874 { continue; }
1875 var start = fromId
1876 ? (Online.miniCellViewport
1877 ? Online.miniCellViewport(fromId, b.col, b.y)
1878 : miniViewportCenter(fromId))
1879 : fieldToViewport(b.col, b.y);
1880 Online.previewExit({
1881 id: b.id,
1882 col: b.col,
1883 y: b.y,
1884 vy: b.vy,
1885 color: b.color,
1886 start: start,
1887 from_id: fromId || null
1888 });
1889 }
1890}
1891
1892function fieldToViewport (col, fieldY)
1893{
1894 var canvas = app.scene && app.scene.canvas;
1895 if (!canvas)
1896 { return { x: window.innerWidth / 2, y: 40 }; }
1897 var rect = canvas.getBoundingClientRect();
1898 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1899 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1900 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1901 return { x: x, y: y };
1902}
1903
1904function onlinePayload ()
1905{
1906 if (!app.online || !app.core)
1907 { return {}; }
1908 var snap = app.core.fieldSnapshot();
1909 // t1182: sender time (ms) so opponents can place the snapshot in
1910 // time and predict falling blocks smoothly. Visual only.
1911 snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
1912 return {
1913 snapshot: snap,
1914 score: app.core.score,
1915 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1916 };
1917}
1918
1919function onOnlineEliminated ()
1920{
1921 app.eliminatedReported = true;
1922 app.spectating = true;
1923 unbindPointer();
1924 hideEl('game-over');
1925 if (app.rewardActive)
1926 { return; }
1927 var lobby = typeof Online !== 'undefined' && Online.lobby;
1928 if (lobby && lobby.status === 'finished')
1929 {
1930 showPodium(lobby);
1931 return;
1932 }
1933 showEl('spectator');
1934}
1935
1936function showPodium (lobby)
1937{
1938 hideEl('spectator');
1939 hideEl('game-over');
1940 hideEl('online-panel');
1941 showEl('podium');
1942 var list = document.getElementById('podium-list');
1943 list.innerHTML = '';
1944 var ranks = (lobby && lobby.rankings) || [];
1945 for (var i = 0; i < ranks.length; i++)
1946 {
1947 var r = ranks[i];
1948 var li = document.createElement('li');
1949 var medal = (typeof I18n !== 'undefined') ? I18n.place(r.place)
1950 : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th')));
1951 li.textContent = (typeof I18n !== 'undefined')
1952 ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score })
1953 : (medal + ' ' + r.name + ' · ' + r.score + ' points');
1954 list.appendChild(li);
1955 }
1956 var hint = document.getElementById('podium-hint');
1957 var secs = (lobby && lobby.podium_seconds) || 5;
1958 if (hint)
1959 {
1960 hint.textContent = (typeof I18n !== 'undefined')
1961 ? I18n.t('podium.hint', { n: secs })
1962 : ('Returning to the lobby in ' + secs + ' seconds…');
1963 }
1964}
1965
1966function startOnlineMatch ()
1967{
1968 if (app.mode === 'playing' && app.online)
1969 { return; }
1970 var planet = Planet.planetById(selectedPlanetId());
1971 var miss = Planet.missChance(planet);
1972 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1973 if (me && me.planet)
1974 {
1975 if (typeof Planet.rememberPlanet === 'function')
1976 { planet = Planet.rememberPlanet(me.planet) || planet; }
1977 else if (me.planet.id)
1978 { planet = Planet.planetById(me.planet.id); }
1979 if (typeof me.planet.miss_chance === 'number')
1980 { miss = me.planet.miss_chance; }
1981 }
1982 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
1983 app.pendingLobbyReturn = null;
1984 startPlay({ online: true, planet: planet, missChance: miss });
1985 if (typeof Online !== 'undefined')
1986 { Online.startPolling(onlinePayload); }
1987}
1988
1989function leaveOnlineMatch (goMenu)
1990{
1991 if (typeof Online !== 'undefined')
1992 {
1993 Online.stopPolling();
1994 Online.leaveLobby();
1995 Online.clearFlights();
1996 }
1997 teardownPlay();
1998 app.online = false;
1999 if (goMenu)
2000 {
2001 app.mode = 'menu';
2002 showEl('menu');
2003 }
2004 else
2005 {
2006 app.mode = 'online';
2007 openOnlinePanel();
2008 }
2009}
2010
2011function bindOnlineUi ()
2012{
2013 var onlineBtn = document.getElementById('btn-online');
2014 if (!onlineBtn)
2015 { return; }
2016 onlineBtn.addEventListener('click', function ()
2017 { openOnlinePanel(); });
2018
2019 var backs = document.querySelectorAll('[data-back-menu]');
2020 for (var i = 0; i < backs.length; i++)
2021 {
2022 backs[i].addEventListener('click', function ()
2023 {
2024 if (typeof Online !== 'undefined')
2025 { Online.stopPolling(); }
2026 hideEl('online-panel');
2027 app.mode = 'menu';
2028 app.online = false;
2029 showEl('menu');
2030 });
2031 }
2032
2033 document.getElementById('btn-create').addEventListener('click', function ()
2034 {
2035 Online.createLobby().then(function (data)
2036 {
2037 if (data && data.ok)
2038 {
2039 renderOnline();
2040 Online.startPolling(onlinePayload);
2041 }
2042 else
2043 { renderOnline(); }
2044 });
2045 });
2046
2047 document.getElementById('join-form').addEventListener('submit', function (e)
2048 {
2049 e.preventDefault();
2050 var code = (document.getElementById('join-code').value || '').trim();
2051 if (!code)
2052 { return; }
2053 Online.joinLobby(code).then(function ()
2054 {
2055 renderOnline();
2056 if (Online.lobby)
2057 { Online.startPolling(onlinePayload); }
2058 });
2059 });
2060
2061 document.getElementById('btn-ready').addEventListener('click', function ()
2062 {
2063 var me = Online.mePlayer();
2064 Online.setReady(!(me && me.ready)).then(renderOnline);
2065 });
2066
2067 document.getElementById('btn-start').addEventListener('click', function ()
2068 {
2069 Online.startGame().then(function (data)
2070 {
2071 if (data && data.ok)
2072 { startOnlineMatch(); }
2073 else
2074 { renderOnline(); }
2075 });
2076 });
2077
2078 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
2079 {
2080 Online.leaveLobby().then(function ()
2081 {
2082 Online.stopPolling();
2083 renderOnline();
2084 });
2085 });
2086
2087 document.getElementById('btn-copy-code').addEventListener('click', function ()
2088 {
2089 var code = document.getElementById('lobby-code').textContent;
2090 var btn = document.getElementById('btn-copy-code');
2091 var done = function ()
2092 {
2093 if (!btn)
2094 { return; }
2095 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied';
2096 setTimeout(function ()
2097 {
2098 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy';
2099 }, 1500);
2100 };
2101 if (navigator.clipboard && navigator.clipboard.writeText)
2102 { navigator.clipboard.writeText(code).then(done, done); }
2103 else
2104 { done(); }
2105 });
2106
2107 document.getElementById('btn-spectate').addEventListener('click', function ()
2108 {
2109 hideEl('spectator');
2110 app.spectating = true;
2111 });
2112
2113 document.getElementById('btn-leave-game').addEventListener('click', function ()
2114 { leaveOnlineMatch(false); });
2115
2116 if (typeof Online !== 'undefined')
2117 {
2118 Online.onChange = function ()
2119 { renderOnline(); };
2120 Online.onGameStart = function ()
2121 { startOnlineMatch(); };
2122 Online.onIncoming = function (incoming)
2123 {
2124 if (!app.core || app.core.state !== 'playing')
2125 { return; }
2126 for (var i = 0; i < incoming.length; i++)
2127 {
2128 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
2129 app.core.ingestGarbage(col);
2130 }
2131 };
2132 Online.onFinished = function (lobby)
2133 {
2134 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2135 {
2136 // Lifetime points in this same poll already include the
2137 // server's online award (maybeAwardOnlineLobby).
2138 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2139 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2140 {
2141 var pending = app.pendingLobbyReturn;
2142 app.pendingLobbyReturn = null;
2143 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2144 { Online.onLobbyReturn(pending || Online.lobby); }
2145 else
2146 { showPodium(Online.lobby); }
2147 });
2148 return;
2149 }
2150 showPodium(lobby);
2151 };
2152 Online.onLobbyReturn = function (lobby)
2153 {
2154 if (app.rewardActive)
2155 {
2156 app.pendingLobbyReturn = lobby;
2157 return;
2158 }
2159 teardownPlay();
2160 app.online = false;
2161 app.mode = 'online';
2162 hideEl('podium');
2163 showEl('online-panel');
2164 renderOnline();
2165 Online.startPolling(onlinePayload);
2166 };
2167 }
2168
2169 var params = new URLSearchParams(window.location.search);
2170 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
2171 {
2172 openOnlinePanel();
2173 // t1193: one-shot; a reload must not jump to online play again.
2174 try
2175 {
2176 params.delete('online');
2177 var rest = params.toString();
2178 window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash);
2179 }
2180 catch (e) { /* ignore */ }
2181 }
2182}
2183
2184function openOnlinePanel ()
2185{
2186 hideEl('menu');
2187 hideEl('game-over');
2188 hideEl('podium');
2189 hideEl('spectator');
2190 hideEl('planet-select');
2191 showEl('online-panel');
2192 app.mode = 'online';
2193 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…');
2194 if (typeof Online === 'undefined')
2195 {
2196 showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play solo.');
2197 showOnly('online-unconfigured');
2198 return;
2199 }
2200 Online.refresh().then(function (data)
2201 {
2202 if (!data || data.ok === false)
2203 {
2204 var msg = (data && data.error)
2205 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2206 : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.');
2207 showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play solo.'));
2208 if (data && data.configured === false)
2209 { showOnly('online-unconfigured'); }
2210 else
2211 { showOnly('online-login'); }
2212 document.getElementById('btn-login').style.display = 'none';
2213 return;
2214 }
2215 renderOnline();
2216 if (Online.lobby)
2217 { Online.startPolling(onlinePayload); }
2218 });
2219}
2220
2221function setOnlineStatus (text)
2222{
2223 var el = document.getElementById('online-status');
2224 if (el)
2225 { el.textContent = text; }
2226}
2227
2228function showOnlineError (text)
2229{
2230 var el = document.getElementById('online-error');
2231 if (!el)
2232 { return; }
2233 if (!text)
2234 {
2235 el.hidden = true;
2236 el.textContent = '';
2237 return;
2238 }
2239 el.hidden = false;
2240 el.textContent = text;
2241}
2242
2243function showOnly (id)
2244{
2245 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
2246 for (var i = 0; i < ids.length; i++)
2247 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
2248}
2249
2250function renderOnline ()
2251{
2252 if (typeof Online === 'undefined')
2253 { return; }
2254 if (app.mode === 'playing' && app.online)
2255 {
2256 Online.renderMinis(document.getElementById('minis'));
2257 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2258 { showPodium(Online.lobby); }
2259 return;
2260 }
2261 showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error);
2262 if (!Online.configured && !Online.me && !Online.local)
2263 {
2264 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.');
2265 showOnly('online-unconfigured');
2266 return;
2267 }
2268 if (!Online.me)
2269 {
2270 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.');
2271 showOnly('online-login');
2272 document.getElementById('btn-login').style.display = '';
2273 document.getElementById('btn-login').href = Online.loginUrl();
2274 document.getElementById('local-login').hidden = !Online.local;
2275 return;
2276 }
2277 if (Online.lobby)
2278 {
2279 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby');
2280 showOnly('online-lobby');
2281 document.getElementById('lobby-me-name').textContent = Online.me.name;
2282 document.getElementById('lobby-code').textContent = Online.lobby.code;
2283 var list = document.getElementById('lobby-players');
2284 list.innerHTML = '';
2285 var players = Online.lobby.players || [];
2286 for (var i = 0; i < players.length; i++)
2287 {
2288 var p = players[i];
2289 var li = document.createElement('li');
2290 if (p.is_me)
2291 { li.classList.add('you'); }
2292 var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
2293 var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you';
2294 var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : '');
2295 var state = p.ready ? 'Gereed' : 'Wacht…';
2296 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2297 li.innerHTML = '<span>' + escapeText(label)
2298 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2299 + '</span><span class="'
2300 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2301 list.appendChild(li);
2302 }
2303 renderPlanetGrid('lobby-planet-grid', true);
2304 var me = Online.mePlayer();
2305 document.getElementById('btn-ready').textContent = (me && me.ready)
2306 ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready')
2307 : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready');
2308 var start = document.getElementById('btn-start');
2309 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2310 start.disabled = !Online.lobby.can_start;
2311 var hint = document.getElementById('lobby-hint');
2312 if (Online.lobby.status === 'playing')
2313 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; }
2314 else if (players.length < 2)
2315 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; }
2316 else if (!Online.lobby.all_ready)
2317 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; }
2318 else if (Online.lobby.can_start)
2319 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; }
2320 else
2321 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; }
2322 return;
2323 }
2324 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.'));
2325 showOnly('online-home');
2326 document.getElementById('me-name').textContent = Online.me.name;
2327 document.getElementById('local-login').hidden = !Online.local;
2328}
2329
2330function escapeText (s)
2331{
2332 return String(s)
2333 .replace(/&/g, '&amp;')
2334 .replace(/</g, '&lt;')
2335 .replace(/>/g, '&gt;')
2336 .replace(/"/g, '&quot;');
2337}
2338
2339
2340function selectedPlanetId ()
2341{
2342 if (app.selectedPlanetId)
2343 { return app.selectedPlanetId; }
2344 return 'terra';
2345}
2346
2347function restoreSelectedPlanet ()
2348{
2349 var id = 'terra';
2350 try
2351 { id = localStorage.getItem('meteors-planet') || 'terra'; }
2352 catch (e) {}
2353 setSelectedPlanet(id, true);
2354}
2355
2356function setSelectedPlanet (id, silent)
2357{
2358 var all = Planet.allPlanets();
2359 var found = null;
2360 for (var i = 0; i < all.length; i++)
2361 {
2362 if (all[i].id === id)
2363 { found = all[i]; break; }
2364 }
2365 if (!found)
2366 { found = Planet.defaultPlanet(); }
2367 app.selectedPlanetId = found.id;
2368 try
2369 { localStorage.setItem('meteors-planet', found.id); }
2370 catch (e) {}
2371 if (!silent)
2372 {
2373 var grid = document.getElementById('planet-grid');
2374 if (grid && !grid.hidden && grid.children.length)
2375 { renderPlanetGrid('planet-grid', false); }
2376 var lobby = document.getElementById('lobby-planet-grid');
2377 if (lobby && lobby.children.length)
2378 { renderPlanetGrid('lobby-planet-grid', true); }
2379 }
2380 return found;
2381}
2382
2383function openPlanetSelect (context)
2384{
2385 if (app.mode === 'playing')
2386 { return; }
2387 app.planetSelectContext = context || 'solo';
2388 app.mode = 'planet-select';
2389 hideEl('menu');
2390 hideEl('online-panel');
2391 hideEl('game-over');
2392 showEl('planet-select');
2393 renderPlanetGrid('planet-grid', false);
2394 var go = document.getElementById('btn-planet-go');
2395 if (go)
2396 { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; }
2397}
2398
2399function renderPlanetGrid (containerId, compact)
2400{
2401 var grid = document.getElementById(containerId);
2402 if (!grid)
2403 { return; }
2404 var current = selectedPlanetId();
2405 var all = Planet.allPlanets();
2406 grid.innerHTML = '';
2407 if (compact)
2408 { grid.classList.add('compact'); }
2409 for (var i = 0; i < all.length; i++)
2410 {
2411 var pl = all[i];
2412 var btn = document.createElement('button');
2413 btn.type = 'button';
2414 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2415 + (pl.custom ? ' custom' : '');
2416 btn.setAttribute('role', 'listitem');
2417 btn.dataset.planet = pl.id;
2418 var swatches = '';
2419 var colors = pl.colors || [];
2420 for (var c = 0; c < colors.length; c++)
2421 {
2422 var cname = colors[c].name;
2423 if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name)))
2424 { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); }
2425 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2426 + escapeText(cname) + '" title="' + escapeText(cname) + '">';
2427 }
2428 var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name;
2429 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people;
2430 var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours';
2431 btn.innerHTML = '<div class="planet-title">' + escapeText(title) + '</div>'
2432 + '<div class="planet-people">' + escapeText(people) + '</div>'
2433 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2434 + '<div class="planet-swatches">' + swatches + '</div>'
2435 + (pl.custom ? '<span class="custom-badge">' + escapeText(badge) + '</span>' : '');
2436 btn.addEventListener('click', (function (id, isCompact)
2437 {
2438 return function ()
2439 { onPlanetPicked(id, isCompact); };
2440 })(pl.id, !!compact));
2441 grid.appendChild(btn);
2442 }
2443}
2444
2445function onPlanetPicked (id, fromLobby)
2446{
2447 setSelectedPlanet(id);
2448 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2449 {
2450 Online.setPlanet(id).then(function ()
2451 { renderOnline(); });
2452 }
2453 else
2454 {
2455 renderPlanetGrid('planet-grid', false);
2456 }
2457}
2458
2459function confirmPlanetSelect ()
2460{
2461 var planet = setSelectedPlanet(selectedPlanetId());
2462 hideEl('planet-select');
2463 if (app.planetSelectContext === 'online')
2464 {
2465 openOnlinePanel();
2466 return;
2467 }
2468 if (app.planetSelectContext === 'offline')
2469 {
2470 startPlay({ planet: planet, offline: true });
2471 return;
2472 }
2473 startPlay({ planet: planet });
2474}
2475
2476function cancelPlanetSelect ()
2477{
2478 hideEl('planet-select');
2479 app.mode = 'menu';
2480 showEl('menu');
2481}
2482
2483function bindPlanetSelect ()
2484{
2485 var go = document.getElementById('btn-planet-go');
2486 var back = document.getElementById('btn-planet-back');
2487 if (go)
2488 {
2489 go.addEventListener('click', confirmPlanetSelect);
2490 }
2491 if (back)
2492 {
2493 back.addEventListener('click', cancelPlanetSelect);
2494 }
2495}
2496
2497
2498function refreshMenuAccount ()
2499{
2500 var guest = document.getElementById('menu-guest');
2501 var user = document.getElementById('menu-user');
2502 var designerBtn = document.getElementById('btn-designer');
2503 var localLogin = document.getElementById('menu-local-login');
2504 var me = (typeof Online !== 'undefined') ? Online.me : null;
2505 if (me)
2506 {
2507 if (guest)
2508 { guest.hidden = true; }
2509 if (user)
2510 { user.hidden = false; }
2511 var name = document.getElementById('menu-name');
2512 if (name)
2513 { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); }
2514 var pts = document.getElementById('menu-points');
2515 if (pts)
2516 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2517 if (designerBtn)
2518 { designerBtn.hidden = false; }
2519 }
2520 else
2521 {
2522 if (guest)
2523 { guest.hidden = false; }
2524 if (user)
2525 { user.hidden = true; }
2526 if (designerBtn)
2527 { designerBtn.hidden = true; }
2528 }
2529 if (localLogin)
2530 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2531}
2532
2533/* ---------- t1193 in-game menu (Spelen / Offline Strijd) ----------- */
2534
2535function setGameMenuButton (show)
2536{
2537 var btn = document.getElementById('btn-game-menu');
2538 if (btn)
2539 { btn.hidden = !show; }
2540}
2541
2542/** The menu can open during a running solo / offline field only. */
2543function canOpenGameMenu ()
2544{
2545 return app.mode === 'playing' && !!app.core && !app.online && !app.spectating
2546 && app.core.state === 'playing' && !app.rewardActive && !app.quitting
2547 && !(app.offline && app.battle && app.battle.state !== 'playing');
2548}
2549
2550function openGameMenu ()
2551{
2552 if (!canOpenGameMenu())
2553 { return false; }
2554 if (app.core.drag)
2555 { finishDrag({ noLaunch: true }); }
2556 app.paused = true;
2557 showEl('game-menu');
2558 var resume = document.getElementById('btn-game-resume');
2559 if (resume && resume.focus)
2560 { resume.focus(); }
2561 return true;
2562}
2563
2564function resumeFromGameMenu ()
2565{
2566 hideEl('game-menu');
2567 if (!app.quitting)
2568 { app.paused = false; }
2569}
2570
2571/**
2572 * "Back to main menu": ends the match now. Logged in, the points so far
2573 * go through the normal play_finish + reward screen first (the server
2574 * still applies its caps); logged out, straight to the menu. Offline
2575 * Strijd ends the whole battle (no next round).
2576 */
2577function quitToMainMenu ()
2578{
2579 if (!app.core || app.quitting)
2580 { return; }
2581 hideEl('game-menu');
2582 app.paused = true;
2583 app.quitting = true;
2584 app.gameOverShown = true;
2585 app.lastScore = app.core.score || 0;
2586 setGameMenuButton(false);
2587 var score = app.lastScore;
2588 var done = function ()
2589 {
2590 app.quitting = false;
2591 app.paused = false;
2592 returnToMenu();
2593 };
2594 if (rewardEnabled())
2595 {
2596 var title = (typeof I18n !== 'undefined') ? I18n.t('reward.ended') : 'Game ended';
2597 showReward(false, finishPlaySession(score), done, title);
2598 }
2599 else
2600 {
2601 finishPlaySession(score);
2602 done();
2603 }
2604}
2605
2606function bindGameMenu ()
2607{
2608 var btn = document.getElementById('btn-game-menu');
2609 if (btn)
2610 { btn.addEventListener('click', function () { openGameMenu(); }); }
2611 var resume = document.getElementById('btn-game-resume');
2612 if (resume)
2613 { resume.addEventListener('click', resumeFromGameMenu); }
2614 var quit = document.getElementById('btn-game-quit');
2615 if (quit)
2616 { quit.addEventListener('click', quitToMainMenu); }
2617 document.addEventListener('keydown', function (e)
2618 {
2619 if (e.key !== 'Escape')
2620 { return; }
2621 var menu = document.getElementById('game-menu');
2622 if (menu && !menu.hidden)
2623 { resumeFromGameMenu(); }
2624 else
2625 { openGameMenu(); }
2626 });
2627}
2628
2629function beginPlaySession (mode)
2630{
2631 if (app.playToken)
2632 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2633 app.playToken = null;
2634 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2635 { return; }
2636 Online.playBegin(mode || 'solo').then(function (data)
2637 {
2638 if (data && data.ok && data.token)
2639 { app.playToken = data.token; }
2640 });
2641}
2642
2643/**
2644 * Ends the solo/offline play session. Resolves to the server-confirmed
2645 * { before, after } profile totals (t1173), or null when there is no
2646 * logged-in user or the server did not confirm. Without a token (e.g.
2647 * play_begin failed) a logged-in player gets { before = after = current }.
2648 */
2649function finishPlaySession (score)
2650{
2651 var token = app.playToken;
2652 app.playToken = null;
2653 var hasOnline = typeof Online !== 'undefined';
2654 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2655 if (!token || !hasOnline || !Online.playFinish)
2656 {
2657 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2658 }
2659 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2660 {
2661 refreshMenuAccount();
2662 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2663 {
2664 var awarded = Math.max(0, Number(data.awarded) || 0);
2665 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2666 }
2667 return null;
2668 }, function ()
2669 { return null; });
2670}
2671
2672/* ---------- t1173 reward screen (logged in only) ------------------- */
2673
2674function rewardEnabled ()
2675{
2676 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2677}
2678
2679/**
2680 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2681 * next() — the same destination the mode used before (menu, next
2682 * offline round, offline result, or the online lobby/podium).
2683 */
2684function showReward (won, resultPromise, next, title)
2685{
2686 app.rewardActive = true;
2687 hideEl('game-over');
2688 hideEl('spectator');
2689 hideEl('podium');
2690 var handle = Reward.play({
2691 won: won,
2692 title: title || null,
2693 planet: app.planet,
2694 result: resultPromise,
2695 onDone: function ()
2696 {
2697 app.rewardActive = false;
2698 if (next)
2699 { next(); }
2700 }
2701 });
2702 if (!handle)
2703 {
2704 app.rewardActive = false;
2705 // No reward overlay (e.g. missing DOM): still continue (t1193).
2706 if (title && next)
2707 { next(); }
2708 }
2709}
2710
2711function myOnlinePlace (lobby)
2712{
2713 var me = typeof Online !== 'undefined' ? Online.me : null;
2714 var ranks = (lobby && lobby.rankings) || [];
2715 for (var i = 0; i < ranks.length; i++)
2716 {
2717 if (me && ranks[i].id === me.id)
2718 { return ranks[i].place; }
2719 }
2720 return null;
2721}
2722
2723
2724
2725function applyProfileLocale ()
2726{
2727 if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2728 { return; }
2729 if (Online.locale)
2730 { I18n.applyFromProfile(Online.locale); }
2731 else if (Online.me)
2732 { Online.setLocale(I18n.locale); }
2733}
2734
2735function refreshAllUi ()
2736{
2737 if (typeof I18n !== 'undefined')
2738 { I18n.apply(); }
2739 refreshMenuAccount();
2740 if (typeof renderPlanetGrid === 'function')
2741 {
2742 renderPlanetGrid('planet-grid', false);
2743 renderPlanetGrid('lobby-planet-grid', true);
2744 }
2745 if (app && app.mode === 'online' && typeof renderOnline === 'function')
2746 { renderOnline(); }
2747 if (typeof Designer !== 'undefined')
2748 {
2749 var des = document.getElementById('designer');
2750 var edit = document.getElementById('designer-edit');
2751 if (des && !des.hidden)
2752 { Designer.renderList(); }
2753 if (edit && !edit.hidden)
2754 {
2755 Designer.syncPreview();
2756 Designer.renderSlots();
2757 var modal = document.getElementById('des-modal');
2758 if (modal && !modal.hidden)
2759 { Designer.openModal(Designer.openSlot); }
2760 }
2761 }
2762 if (app && app.mode === 'playing')
2763 {
2764 if (typeof refreshHud === 'function')
2765 { refreshHud(); }
2766 if (typeof refreshOfflineHud === 'function')
2767 { refreshOfflineHud(); }
2768 }
2769}