BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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