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 line = document.getElementById('offline-reached-line');
1599 if (line && typeof I18n !== 'undefined')
1600 { line.textContent = I18n.t('offline.reached', { n: battle.round }); }
1601 else if (reached)
1602 { reached.textContent = String(battle.round); }
1603 // t1198: "X opponents defeated" over all rounds (replaces the
1604 // opponents / skill line).
1605 var detail = document.getElementById('offline-result-detail');
1606 if (detail)
1607 {
1608 var beaten = battle.defeated || 0;
1609 detail.textContent = (typeof I18n !== 'undefined')
1610 ? I18n.plural('offline.defeated', beaten, { n: beaten })
1611 : beaten + (beaten === 1 ? ' opponent defeated' : ' opponents defeated');
1612 }
1613 hideEl('game-over');
1614 showEl('offline-result');
1615 finishPlaySession(app.core ? app.core.score : 0);
1616}
1617
1618function refreshOfflineHud ()
1619{
1620 var el = document.getElementById('offline-hud');
1621 if (!el)
1622 { return; }
1623 if (!(app.offline && app.battle && app.mode === 'playing'))
1624 {
1625 el.hidden = true;
1626 return;
1627 }
1628 el.hidden = false;
1629 // t1195: the Offline Strijd HUD shows only "Round N".
1630 var sch = app.battle.schedule;
1631 var r = document.getElementById('offline-round');
1632 if (r)
1633 { r.textContent = (typeof I18n !== 'undefined') ? I18n.t('hud.round', { n: sch.round }) : 'Round ' + sch.round; }
1634}
1635
1636function hideOfflineHud ()
1637{
1638 var el = document.getElementById('offline-hud');
1639 if (el)
1640 { el.hidden = true; }
1641}
1642
1643function refreshChainIndicator ()
1644{
1645 var el = document.getElementById('chain-indicator');
1646 if (!el)
1647 { return; }
1648 var info = app.core && app.core.lastChainIndicator;
1649 var active = app.core && app.core.hasActiveLandingChain
1650 && app.core.hasActiveLandingChain();
1651 // Show only while a chained cluster is still in the air.
1652 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1653 {
1654 el.hidden = true;
1655 return;
1656 }
1657 el.hidden = false;
1658 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1659}
1660
1661function hideChainIndicator ()
1662{
1663 var el = document.getElementById('chain-indicator');
1664 if (el)
1665 { el.hidden = true; }
1666}
1667
1668function miniViewportCenter (botId)
1669{
1670 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1671 if (!el)
1672 { return { x: window.innerWidth / 2, y: 40 }; }
1673 var rect = el.getBoundingClientRect();
1674 var plan = app.miniLayout;
1675 if (plan && plan.mode === 'sides')
1676 {
1677 // Leave from the top of the mini, then the arc goes up and over (t1131).
1678 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1679 }
1680 return { x: rect.left + rect.width / 2, y: rect.bottom };
1681}
1682
1683function offlineMiniSize (n)
1684{
1685 return currentMiniSize();
1686}
1687
1688function updateOfflineMinis (dt, force)
1689{
1690 app.miniAcc = (app.miniAcc || 0) + dt;
1691 if (!force && app.miniAcc < 0.1)
1692 { return; }
1693 app.miniAcc = 0;
1694 renderOfflineMinis();
1695}
1696
1697function renderOfflineMinis ()
1698{
1699 var container = document.getElementById('minis');
1700 if (!container || !app.battle)
1701 { return; }
1702 var bots = app.battle.bots;
1703 var size = offlineMiniSize(bots.length);
1704 container.classList.toggle('crowded', bots.length > 5);
1705 var existing = {};
1706 var kids = container.querySelectorAll('[data-player]');
1707 for (var i = 0; i < kids.length; i++)
1708 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1709 var seen = Object.create(null);
1710 for (var i = 0; i < bots.length; i++)
1711 {
1712 var bot = bots[i];
1713 seen[bot.id] = true;
1714 var el = existing[bot.id];
1715 if (!el)
1716 {
1717 el = document.createElement('div');
1718 el.className = 'mini';
1719 el.setAttribute('data-player', bot.id);
1720 el.innerHTML = '<div class="mini-name"></div>'
1721 + '<canvas class="mini-canvas" width="' + size.w
1722 + '" height="' + size.h + '"></canvas>'
1723 + '<div class="mini-meta"></div>';
1724 container.appendChild(el);
1725 }
1726 var canvas = el.querySelector('canvas');
1727 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1728 {
1729 canvas.width = size.w;
1730 canvas.height = size.h;
1731 }
1732 el.classList.toggle('eliminated', !!bot.eliminated);
1733 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1734 var shownPlanet = planetName;
1735 if (bot.planet && typeof I18n !== 'undefined')
1736 { shownPlanet = I18n.planetName(bot.planet); }
1737 el.querySelector('.mini-name').textContent = bot.name
1738 + (shownPlanet ? ' · ' + shownPlanet : '');
1739 el.querySelector('.mini-meta').textContent = bot.eliminated
1740 ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out')
1741 : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (bot.score || 0)));
1742 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1743 if (typeof Online !== 'undefined' && Online._drawMini)
1744 { Online._drawMini(canvas, snap, bot.planet); }
1745 }
1746 for (var id in existing)
1747 {
1748 if (!seen[id])
1749 { existing[id].remove(); }
1750 }
1751 applyMinisLayout();
1752}
1753
1754function buildColumnWarn ()
1755{
1756 app.columnWarn = [];
1757 if (!app.scene)
1758 { return; }
1759 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1760 if (!img)
1761 { return; }
1762 for (var c = 0; c < 10; c++)
1763 {
1764 var obj = new GameObject(0, 0, img, 0);
1765 obj.renderer.alpha = 0;
1766 obj.renderer.visible = false;
1767 app.scene.addObject(obj);
1768 app.columnWarn.push(obj);
1769 }
1770 updateColumnWarn(0);
1771}
1772
1773function updateColumnWarn (dt)
1774{
1775 if (!app.columnWarn || !app.core)
1776 { return; }
1777 app.warnClock = (app.warnClock || 0) + (dt || 0);
1778 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1779 ? GameCore.columnWarnPulse(app.warnClock)
1780 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1781 var t = app.tile;
1782 for (var c = 0; c < app.columnWarn.length; c++)
1783 {
1784 var obj = app.columnWarn[c];
1785 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1786 obj.renderer.visible = !!on;
1787 obj.renderer.alpha = on ? pulse : 0;
1788 if (t)
1789 {
1790 obj.transform.position.x = c * t + t / 2;
1791 obj.transform.position.y = app.fieldH / 2;
1792 obj.transform.size = { x: t, y: app.fieldH };
1793 }
1794 }
1795}
1796
1797/**
1798 * A flight starts only when a block has actually left the field
1799 * (y ≥ height, the same threshold as cullOffTop). Rockets that
1800 * peak below the top and fall back must never get an arc (t1137).
1801 * Shared by the player's field, enemy minis, offline and online.
1802 */
1803function previewOutgoingFlights ()
1804{
1805 // Intentionally not called before core.tick: a block still on
1806 // the field (y < 13) is not a shot yet. Flights are spawned
1807 // from consumeOutgoingShots after cull, at the exit pose.
1808 if (typeof Online === 'undefined' || !Online.previewExit)
1809 { return; }
1810 if (app.core)
1811 { previewCoreExits(app.core, null); }
1812 if (app.offline && app.battle && app.battle.bots)
1813 {
1814 var bots = app.battle.bots;
1815 for (var i = 0; i < bots.length; i++)
1816 {
1817 var bot = bots[i];
1818 if (bot && bot.core && !bot.eliminated)
1819 { previewCoreExits(bot.core, bot.id); }
1820 }
1821 }
1822}
1823
1824function previewCoreExits (core, fromId)
1825{
1826 if (!core || !core.blocks)
1827 { return; }
1828 var height = core.height != null ? core.height : 13;
1829 var blocks = core.blocks;
1830 for (var i = 0; i < blocks.length; i++)
1831 {
1832 var b = blocks[i];
1833 if (b.state === 'manual')
1834 { continue; }
1835 if (typeof Online.hasLeftTheField === 'function'
1836 ? !Online.hasLeftTheField(b.y, height)
1837 : !(b.y >= height - 1e-9))
1838 { continue; }
1839 if (!(b.vy > 0))
1840 { continue; }
1841 var start = fromId
1842 ? (Online.miniCellViewport
1843 ? Online.miniCellViewport(fromId, b.col, b.y)
1844 : miniViewportCenter(fromId))
1845 : fieldToViewport(b.col, b.y);
1846 Online.previewExit({
1847 id: b.id,
1848 col: b.col,
1849 y: b.y,
1850 vy: b.vy,
1851 color: b.color,
1852 start: start,
1853 from_id: fromId || null
1854 });
1855 }
1856}
1857
1858function fieldToViewport (col, fieldY)
1859{
1860 var canvas = app.scene && app.scene.canvas;
1861 if (!canvas)
1862 { return { x: window.innerWidth / 2, y: 40 }; }
1863 var rect = canvas.getBoundingClientRect();
1864 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1865 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1866 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1867 return { x: x, y: y };
1868}
1869
1870function onlinePayload ()
1871{
1872 if (!app.online || !app.core)
1873 { return {}; }
1874 var snap = app.core.fieldSnapshot();
1875 // t1182: sender time (ms) so opponents can place the snapshot in
1876 // time and predict falling blocks smoothly. Visual only.
1877 snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
1878 return {
1879 snapshot: snap,
1880 score: app.core.score,
1881 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1882 };
1883}
1884
1885function onOnlineEliminated ()
1886{
1887 app.eliminatedReported = true;
1888 app.spectating = true;
1889 unbindPointer();
1890 hideEl('game-over');
1891 if (app.rewardActive)
1892 { return; }
1893 var lobby = typeof Online !== 'undefined' && Online.lobby;
1894 if (lobby && lobby.status === 'finished')
1895 {
1896 showPodium(lobby);
1897 return;
1898 }
1899 showEl('spectator');
1900}
1901
1902function showPodium (lobby)
1903{
1904 hideEl('spectator');
1905 hideEl('game-over');
1906 hideEl('online-panel');
1907 showEl('podium');
1908 var list = document.getElementById('podium-list');
1909 list.innerHTML = '';
1910 var ranks = (lobby && lobby.rankings) || [];
1911 for (var i = 0; i < ranks.length; i++)
1912 {
1913 var r = ranks[i];
1914 var li = document.createElement('li');
1915 var medal = (typeof I18n !== 'undefined') ? I18n.place(r.place)
1916 : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th')));
1917 li.textContent = (typeof I18n !== 'undefined')
1918 ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score })
1919 : (medal + ' ' + r.name + ' · ' + r.score + ' points');
1920 list.appendChild(li);
1921 }
1922 var hint = document.getElementById('podium-hint');
1923 var secs = (lobby && lobby.podium_seconds) || 5;
1924 if (hint)
1925 {
1926 hint.textContent = (typeof I18n !== 'undefined')
1927 ? I18n.t('podium.hint', { n: secs })
1928 : ('Returning to the lobby in ' + secs + ' seconds…');
1929 }
1930}
1931
1932function startOnlineMatch ()
1933{
1934 if (app.mode === 'playing' && app.online)
1935 { return; }
1936 var planet = Planet.planetById(selectedPlanetId());
1937 var miss = Planet.missChance(planet);
1938 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1939 if (me && me.planet)
1940 {
1941 if (typeof Planet.rememberPlanet === 'function')
1942 { planet = Planet.rememberPlanet(me.planet) || planet; }
1943 else if (me.planet.id)
1944 { planet = Planet.planetById(me.planet.id); }
1945 if (typeof me.planet.miss_chance === 'number')
1946 { miss = me.planet.miss_chance; }
1947 }
1948 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
1949 app.pendingLobbyReturn = null;
1950 startPlay({ online: true, planet: planet, missChance: miss });
1951 if (typeof Online !== 'undefined')
1952 { Online.startPolling(onlinePayload); }
1953}
1954
1955function leaveOnlineMatch (goMenu)
1956{
1957 if (typeof Online !== 'undefined')
1958 {
1959 Online.stopPolling();
1960 Online.leaveLobby();
1961 Online.clearFlights();
1962 }
1963 teardownPlay();
1964 app.online = false;
1965 if (goMenu)
1966 {
1967 app.mode = 'menu';
1968 showEl('menu');
1969 }
1970 else
1971 {
1972 app.mode = 'online';
1973 openOnlinePanel();
1974 }
1975}
1976
1977function bindOnlineUi ()
1978{
1979 var onlineBtn = document.getElementById('btn-online');
1980 if (!onlineBtn)
1981 { return; }
1982 onlineBtn.addEventListener('click', function ()
1983 { openOnlinePanel(); });
1984
1985 var backs = document.querySelectorAll('[data-back-menu]');
1986 for (var i = 0; i < backs.length; i++)
1987 {
1988 backs[i].addEventListener('click', function ()
1989 {
1990 if (typeof Online !== 'undefined')
1991 { Online.stopPolling(); }
1992 hideEl('online-panel');
1993 app.mode = 'menu';
1994 app.online = false;
1995 showEl('menu');
1996 });
1997 }
1998
1999 document.getElementById('btn-create').addEventListener('click', function ()
2000 {
2001 Online.createLobby().then(function (data)
2002 {
2003 if (data && data.ok)
2004 {
2005 renderOnline();
2006 Online.startPolling(onlinePayload);
2007 }
2008 else
2009 { renderOnline(); }
2010 });
2011 });
2012
2013 document.getElementById('join-form').addEventListener('submit', function (e)
2014 {
2015 e.preventDefault();
2016 var code = (document.getElementById('join-code').value || '').trim();
2017 if (!code)
2018 { return; }
2019 Online.joinLobby(code).then(function ()
2020 {
2021 renderOnline();
2022 if (Online.lobby)
2023 { Online.startPolling(onlinePayload); }
2024 });
2025 });
2026
2027 document.getElementById('btn-ready').addEventListener('click', function ()
2028 {
2029 var me = Online.mePlayer();
2030 Online.setReady(!(me && me.ready)).then(renderOnline);
2031 });
2032
2033 document.getElementById('btn-start').addEventListener('click', function ()
2034 {
2035 Online.startGame().then(function (data)
2036 {
2037 if (data && data.ok)
2038 { startOnlineMatch(); }
2039 else
2040 { renderOnline(); }
2041 });
2042 });
2043
2044 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
2045 {
2046 Online.leaveLobby().then(function ()
2047 {
2048 Online.stopPolling();
2049 renderOnline();
2050 });
2051 });
2052
2053 document.getElementById('btn-copy-code').addEventListener('click', function ()
2054 {
2055 var code = document.getElementById('lobby-code').textContent;
2056 var btn = document.getElementById('btn-copy-code');
2057 var done = function ()
2058 {
2059 if (!btn)
2060 { return; }
2061 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied';
2062 setTimeout(function ()
2063 {
2064 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy';
2065 }, 1500);
2066 };
2067 if (navigator.clipboard && navigator.clipboard.writeText)
2068 { navigator.clipboard.writeText(code).then(done, done); }
2069 else
2070 { done(); }
2071 });
2072
2073 document.getElementById('btn-spectate').addEventListener('click', function ()
2074 {
2075 hideEl('spectator');
2076 app.spectating = true;
2077 });
2078
2079 document.getElementById('btn-leave-game').addEventListener('click', function ()
2080 { leaveOnlineMatch(false); });
2081
2082 if (typeof Online !== 'undefined')
2083 {
2084 Online.onChange = function ()
2085 { renderOnline(); };
2086 Online.onGameStart = function ()
2087 { startOnlineMatch(); };
2088 Online.onIncoming = function (incoming)
2089 {
2090 if (!app.core || app.core.state !== 'playing')
2091 { return; }
2092 for (var i = 0; i < incoming.length; i++)
2093 {
2094 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
2095 app.core.ingestGarbage(col);
2096 }
2097 };
2098 Online.onFinished = function (lobby)
2099 {
2100 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2101 {
2102 // Lifetime points in this same poll already include the
2103 // server's online award (maybeAwardOnlineLobby).
2104 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2105 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2106 {
2107 var pending = app.pendingLobbyReturn;
2108 app.pendingLobbyReturn = null;
2109 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2110 { Online.onLobbyReturn(pending || Online.lobby); }
2111 else
2112 { showPodium(Online.lobby); }
2113 });
2114 return;
2115 }
2116 showPodium(lobby);
2117 };
2118 Online.onLobbyReturn = function (lobby)
2119 {
2120 if (app.rewardActive)
2121 {
2122 app.pendingLobbyReturn = lobby;
2123 return;
2124 }
2125 teardownPlay();
2126 app.online = false;
2127 app.mode = 'online';
2128 hideEl('podium');
2129 showEl('online-panel');
2130 renderOnline();
2131 Online.startPolling(onlinePayload);
2132 };
2133 }
2134
2135 var params = new URLSearchParams(window.location.search);
2136 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
2137 {
2138 openOnlinePanel();
2139 // t1193: one-shot; a reload must not jump to online play again.
2140 try
2141 {
2142 params.delete('online');
2143 var rest = params.toString();
2144 window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash);
2145 }
2146 catch (e) { /* ignore */ }
2147 }
2148}
2149
2150function openOnlinePanel ()
2151{
2152 hideEl('menu');
2153 hideEl('game-over');
2154 hideEl('podium');
2155 hideEl('spectator');
2156 hideEl('planet-select');
2157 showEl('online-panel');
2158 app.mode = 'online';
2159 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…');
2160 if (typeof Online === 'undefined')
2161 {
2162 showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play solo.');
2163 showOnly('online-unconfigured');
2164 return;
2165 }
2166 Online.refresh().then(function (data)
2167 {
2168 if (!data || data.ok === false)
2169 {
2170 var msg = (data && data.error)
2171 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2172 : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.');
2173 showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play solo.'));
2174 if (data && data.configured === false)
2175 { showOnly('online-unconfigured'); }
2176 else
2177 { showOnly('online-login'); }
2178 document.getElementById('btn-login').style.display = 'none';
2179 return;
2180 }
2181 renderOnline();
2182 if (Online.lobby)
2183 { Online.startPolling(onlinePayload); }
2184 });
2185}
2186
2187function setOnlineStatus (text)
2188{
2189 var el = document.getElementById('online-status');
2190 if (el)
2191 { el.textContent = text; }
2192}
2193
2194function showOnlineError (text)
2195{
2196 var el = document.getElementById('online-error');
2197 if (!el)
2198 { return; }
2199 if (!text)
2200 {
2201 el.hidden = true;
2202 el.textContent = '';
2203 return;
2204 }
2205 el.hidden = false;
2206 el.textContent = text;
2207}
2208
2209function showOnly (id)
2210{
2211 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
2212 for (var i = 0; i < ids.length; i++)
2213 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
2214}
2215
2216function renderOnline ()
2217{
2218 if (typeof Online === 'undefined')
2219 { return; }
2220 if (app.mode === 'playing' && app.online)
2221 {
2222 Online.renderMinis(document.getElementById('minis'));
2223 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2224 { showPodium(Online.lobby); }
2225 return;
2226 }
2227 showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error);
2228 if (!Online.configured && !Online.me && !Online.local)
2229 {
2230 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.');
2231 showOnly('online-unconfigured');
2232 return;
2233 }
2234 if (!Online.me)
2235 {
2236 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.');
2237 showOnly('online-login');
2238 document.getElementById('btn-login').style.display = '';
2239 document.getElementById('btn-login').href = Online.loginUrl();
2240 document.getElementById('local-login').hidden = !Online.local;
2241 return;
2242 }
2243 if (Online.lobby)
2244 {
2245 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby');
2246 showOnly('online-lobby');
2247 document.getElementById('lobby-me-name').textContent = Online.me.name;
2248 document.getElementById('lobby-code').textContent = Online.lobby.code;
2249 var list = document.getElementById('lobby-players');
2250 list.innerHTML = '';
2251 var players = Online.lobby.players || [];
2252 for (var i = 0; i < players.length; i++)
2253 {
2254 var p = players[i];
2255 var li = document.createElement('li');
2256 if (p.is_me)
2257 { li.classList.add('you'); }
2258 var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
2259 var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you';
2260 var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : '');
2261 var state = p.ready ? 'Gereed' : 'Wacht…';
2262 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2263 li.innerHTML = '<span>' + escapeText(label)
2264 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2265 + '</span><span class="'
2266 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2267 list.appendChild(li);
2268 }
2269 renderPlanetGrid('lobby-planet-grid', true);
2270 var me = Online.mePlayer();
2271 document.getElementById('btn-ready').textContent = (me && me.ready)
2272 ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready')
2273 : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready');
2274 var start = document.getElementById('btn-start');
2275 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2276 start.disabled = !Online.lobby.can_start;
2277 var hint = document.getElementById('lobby-hint');
2278 if (Online.lobby.status === 'playing')
2279 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; }
2280 else if (players.length < 2)
2281 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; }
2282 else if (!Online.lobby.all_ready)
2283 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; }
2284 else if (Online.lobby.can_start)
2285 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; }
2286 else
2287 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; }
2288 return;
2289 }
2290 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.'));
2291 showOnly('online-home');
2292 document.getElementById('me-name').textContent = Online.me.name;
2293 document.getElementById('local-login').hidden = !Online.local;
2294}
2295
2296function escapeText (s)
2297{
2298 return String(s)
2299 .replace(/&/g, '&amp;')
2300 .replace(/</g, '&lt;')
2301 .replace(/>/g, '&gt;')
2302 .replace(/"/g, '&quot;');
2303}
2304
2305
2306function selectedPlanetId ()
2307{
2308 if (app.selectedPlanetId)
2309 { return app.selectedPlanetId; }
2310 return 'terra';
2311}
2312
2313/**
2314 * Pre-select the last chosen planet (t1196): logged in the profile value
2315 * (server), otherwise / as fallback localStorage, otherwise Terra. A
2316 * deleted custom planet falls back to the default (setSelectedPlanet).
2317 */
2318function restoreSelectedPlanet ()
2319{
2320 var id = null;
2321 if (typeof Online !== 'undefined' && Online.me && Online.lastPlanet)
2322 { id = Online.lastPlanet; }
2323 if (!id)
2324 {
2325 try
2326 { id = localStorage.getItem('meteors-planet'); }
2327 catch (e) {}
2328 }
2329 setSelectedPlanet(id || 'terra', true);
2330}
2331
2332function rememberPlanetChoice (id)
2333{
2334 if (typeof Online === 'undefined' || !Online.me || !Online.setLastPlanet)
2335 { return; }
2336 if (Online.lastPlanet === id)
2337 { return; }
2338 Promise.resolve(Online.setLastPlanet(id)).then(null, function () {});
2339}
2340
2341function setSelectedPlanet (id, silent)
2342{
2343 var all = Planet.allPlanets();
2344 var found = null;
2345 for (var i = 0; i < all.length; i++)
2346 {
2347 if (all[i].id === id)
2348 { found = all[i]; break; }
2349 }
2350 if (!found)
2351 { found = Planet.defaultPlanet(); }
2352 app.selectedPlanetId = found.id;
2353 try
2354 { localStorage.setItem('meteors-planet', found.id); }
2355 catch (e) {}
2356 if (!silent)
2357 {
2358 rememberPlanetChoice(found.id);
2359 var grid = document.getElementById('planet-grid');
2360 if (grid && !grid.hidden && grid.children.length)
2361 { renderPlanetGrid('planet-grid', false); }
2362 var lobby = document.getElementById('lobby-planet-grid');
2363 if (lobby && lobby.children.length)
2364 { renderPlanetGrid('lobby-planet-grid', true); }
2365 }
2366 return found;
2367}
2368
2369function openPlanetSelect (context)
2370{
2371 if (app.mode === 'playing')
2372 { return; }
2373 app.planetSelectContext = context || 'solo';
2374 app.mode = 'planet-select';
2375 hideEl('menu');
2376 hideEl('online-panel');
2377 hideEl('game-over');
2378 showEl('planet-select');
2379 renderPlanetGrid('planet-grid', false);
2380 var go = document.getElementById('btn-planet-go');
2381 if (go)
2382 { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; }
2383}
2384
2385function renderPlanetGrid (containerId, compact)
2386{
2387 var grid = document.getElementById(containerId);
2388 if (!grid)
2389 { return; }
2390 var current = selectedPlanetId();
2391 var all = Planet.allPlanets();
2392 grid.innerHTML = '';
2393 if (compact)
2394 { grid.classList.add('compact'); }
2395 for (var i = 0; i < all.length; i++)
2396 {
2397 var pl = all[i];
2398 var btn = document.createElement('button');
2399 btn.type = 'button';
2400 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2401 + (pl.custom ? ' custom' : '');
2402 btn.setAttribute('role', 'listitem');
2403 btn.dataset.planet = pl.id;
2404 var swatches = '';
2405 var colors = pl.colors || [];
2406 for (var c = 0; c < colors.length; c++)
2407 {
2408 var cname = colors[c].name;
2409 if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name)))
2410 { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); }
2411 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2412 + escapeText(cname) + '" title="' + escapeText(cname) + '">';
2413 }
2414 var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name;
2415 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people;
2416 var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours';
2417 btn.innerHTML = '<div class="planet-title">' + escapeText(title) + '</div>'
2418 + '<div class="planet-people">' + escapeText(people) + '</div>'
2419 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2420 + '<div class="planet-swatches">' + swatches + '</div>'
2421 + (pl.custom ? '<span class="custom-badge">' + escapeText(badge) + '</span>' : '');
2422 btn.addEventListener('click', (function (id, isCompact)
2423 {
2424 return function ()
2425 { onPlanetPicked(id, isCompact); };
2426 })(pl.id, !!compact));
2427 grid.appendChild(btn);
2428 }
2429}
2430
2431function onPlanetPicked (id, fromLobby)
2432{
2433 setSelectedPlanet(id);
2434 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2435 {
2436 Online.setPlanet(id).then(function ()
2437 { renderOnline(); });
2438 }
2439 else
2440 {
2441 renderPlanetGrid('planet-grid', false);
2442 }
2443}
2444
2445function confirmPlanetSelect ()
2446{
2447 var planet = setSelectedPlanet(selectedPlanetId());
2448 hideEl('planet-select');
2449 if (app.planetSelectContext === 'online')
2450 {
2451 openOnlinePanel();
2452 return;
2453 }
2454 if (app.planetSelectContext === 'offline')
2455 {
2456 startPlay({ planet: planet, offline: true });
2457 return;
2458 }
2459 startPlay({ planet: planet });
2460}
2461
2462function cancelPlanetSelect ()
2463{
2464 hideEl('planet-select');
2465 app.mode = 'menu';
2466 showEl('menu');
2467}
2468
2469function bindPlanetSelect ()
2470{
2471 var go = document.getElementById('btn-planet-go');
2472 var back = document.getElementById('btn-planet-back');
2473 if (go)
2474 {
2475 go.addEventListener('click', confirmPlanetSelect);
2476 }
2477 if (back)
2478 {
2479 back.addEventListener('click', cancelPlanetSelect);
2480 }
2481}
2482
2483
2484function refreshMenuAccount ()
2485{
2486 var guest = document.getElementById('menu-guest');
2487 var user = document.getElementById('menu-user');
2488 var designerBtn = document.getElementById('btn-designer');
2489 var localLogin = document.getElementById('menu-local-login');
2490 var me = (typeof Online !== 'undefined') ? Online.me : null;
2491 if (me)
2492 {
2493 if (guest)
2494 { guest.hidden = true; }
2495 if (user)
2496 { user.hidden = false; }
2497 var name = document.getElementById('menu-name');
2498 if (name)
2499 { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); }
2500 var pts = document.getElementById('menu-points');
2501 if (pts)
2502 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2503 if (designerBtn)
2504 { designerBtn.hidden = false; }
2505 }
2506 else
2507 {
2508 if (guest)
2509 { guest.hidden = false; }
2510 if (user)
2511 { user.hidden = true; }
2512 if (designerBtn)
2513 { designerBtn.hidden = true; }
2514 }
2515 if (localLogin)
2516 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2517}
2518
2519/* ---------- t1193 in-game menu (Spelen / Offline Strijd) ----------- */
2520
2521function setGameMenuButton (show)
2522{
2523 var btn = document.getElementById('btn-game-menu');
2524 if (btn)
2525 { btn.hidden = !show; }
2526}
2527
2528/** The menu can open during a running solo / offline field only. */
2529function canOpenGameMenu ()
2530{
2531 return app.mode === 'playing' && !!app.core && !app.online && !app.spectating
2532 && app.core.state === 'playing' && !app.rewardActive && !app.quitting
2533 && !(app.offline && app.battle && app.battle.state !== 'playing');
2534}
2535
2536function openGameMenu ()
2537{
2538 if (!canOpenGameMenu())
2539 { return false; }
2540 if (app.core.drag)
2541 { finishDrag({ noLaunch: true }); }
2542 app.paused = true;
2543 showEl('game-menu');
2544 var resume = document.getElementById('btn-game-resume');
2545 if (resume && resume.focus)
2546 { resume.focus(); }
2547 return true;
2548}
2549
2550function resumeFromGameMenu ()
2551{
2552 hideEl('game-menu');
2553 if (!app.quitting)
2554 { app.paused = false; }
2555}
2556
2557/**
2558 * "Back to main menu": ends the match now. Logged in, the points so far
2559 * go through the normal play_finish + reward screen first (the server
2560 * still applies its caps); logged out, straight to the menu. Offline
2561 * Strijd ends the whole battle (no next round).
2562 */
2563function quitToMainMenu ()
2564{
2565 if (!app.core || app.quitting)
2566 { return; }
2567 hideEl('game-menu');
2568 app.paused = true;
2569 app.quitting = true;
2570 app.gameOverShown = true;
2571 app.lastScore = app.core.score || 0;
2572 setGameMenuButton(false);
2573 var score = app.lastScore;
2574 var done = function ()
2575 {
2576 app.quitting = false;
2577 app.paused = false;
2578 returnToMenu();
2579 };
2580 if (rewardEnabled())
2581 {
2582 var title = (typeof I18n !== 'undefined') ? I18n.t('reward.ended') : 'Game ended';
2583 showReward(false, finishPlaySession(score), done, title);
2584 }
2585 else
2586 {
2587 finishPlaySession(score);
2588 done();
2589 }
2590}
2591
2592function bindGameMenu ()
2593{
2594 var btn = document.getElementById('btn-game-menu');
2595 if (btn)
2596 { btn.addEventListener('click', function () { openGameMenu(); }); }
2597 var resume = document.getElementById('btn-game-resume');
2598 if (resume)
2599 { resume.addEventListener('click', resumeFromGameMenu); }
2600 var quit = document.getElementById('btn-game-quit');
2601 if (quit)
2602 { quit.addEventListener('click', quitToMainMenu); }
2603 document.addEventListener('keydown', function (e)
2604 {
2605 if (e.key !== 'Escape')
2606 { return; }
2607 var menu = document.getElementById('game-menu');
2608 if (menu && !menu.hidden)
2609 { resumeFromGameMenu(); }
2610 else
2611 { openGameMenu(); }
2612 });
2613}
2614
2615function beginPlaySession (mode)
2616{
2617 if (app.playToken)
2618 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2619 app.playToken = null;
2620 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2621 { return; }
2622 Online.playBegin(mode || 'solo').then(function (data)
2623 {
2624 if (data && data.ok && data.token)
2625 { app.playToken = data.token; }
2626 });
2627}
2628
2629/**
2630 * Ends the solo/offline play session. Resolves to the server-confirmed
2631 * { before, after } profile totals (t1173), or null when there is no
2632 * logged-in user or the server did not confirm. Without a token (e.g.
2633 * play_begin failed) a logged-in player gets { before = after = current }.
2634 */
2635function finishPlaySession (score)
2636{
2637 var token = app.playToken;
2638 app.playToken = null;
2639 var hasOnline = typeof Online !== 'undefined';
2640 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2641 if (!token || !hasOnline || !Online.playFinish)
2642 {
2643 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2644 }
2645 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2646 {
2647 refreshMenuAccount();
2648 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2649 {
2650 var awarded = Math.max(0, Number(data.awarded) || 0);
2651 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2652 }
2653 return null;
2654 }, function ()
2655 { return null; });
2656}
2657
2658/* ---------- t1173 reward screen (logged in only) ------------------- */
2659
2660function rewardEnabled ()
2661{
2662 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2663}
2664
2665/**
2666 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2667 * next() — the same destination the mode used before (menu, next
2668 * offline round, offline result, or the online lobby/podium).
2669 */
2670function showReward (won, resultPromise, next, title)
2671{
2672 app.rewardActive = true;
2673 hideEl('game-over');
2674 hideEl('spectator');
2675 hideEl('podium');
2676 var handle = Reward.play({
2677 won: won,
2678 title: title || null,
2679 planet: app.planet,
2680 result: resultPromise,
2681 onDone: function ()
2682 {
2683 app.rewardActive = false;
2684 if (next)
2685 { next(); }
2686 }
2687 });
2688 if (!handle)
2689 {
2690 app.rewardActive = false;
2691 // No reward overlay (e.g. missing DOM): still continue (t1193).
2692 if (title && next)
2693 { next(); }
2694 }
2695}
2696
2697function myOnlinePlace (lobby)
2698{
2699 var me = typeof Online !== 'undefined' ? Online.me : null;
2700 var ranks = (lobby && lobby.rankings) || [];
2701 for (var i = 0; i < ranks.length; i++)
2702 {
2703 if (me && ranks[i].id === me.id)
2704 { return ranks[i].place; }
2705 }
2706 return null;
2707}
2708
2709
2710
2711function applyProfileLocale ()
2712{
2713 if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2714 { return; }
2715 if (Online.locale)
2716 { I18n.applyFromProfile(Online.locale); }
2717 else if (Online.me)
2718 { Online.setLocale(I18n.locale); }
2719}
2720
2721function refreshAllUi ()
2722{
2723 if (typeof I18n !== 'undefined')
2724 { I18n.apply(); }
2725 refreshMenuAccount();
2726 if (typeof renderPlanetGrid === 'function')
2727 {
2728 renderPlanetGrid('planet-grid', false);
2729 renderPlanetGrid('lobby-planet-grid', true);
2730 }
2731 if (app && app.mode === 'online' && typeof renderOnline === 'function')
2732 { renderOnline(); }
2733 if (typeof Designer !== 'undefined')
2734 {
2735 var des = document.getElementById('designer');
2736 var edit = document.getElementById('designer-edit');
2737 if (des && !des.hidden)
2738 { Designer.renderList(); }
2739 if (edit && !edit.hidden)
2740 {
2741 Designer.syncPreview();
2742 Designer.renderSlots();
2743 var modal = document.getElementById('des-modal');
2744 if (modal && !modal.hidden)
2745 { Designer.openModal(Designer.openSlot); }
2746 }
2747 }
2748 if (app && app.mode === 'playing')
2749 {
2750 if (typeof refreshHud === 'function')
2751 { refreshHud(); }
2752 if (typeof refreshOfflineHud === 'function')
2753 { refreshOfflineHud(); }
2754 }
2755}