BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 81.9 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 = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
2003 app.pendingLobbyReturn = null;
2004 startPlay({ online: true, planet: planet, missChance: miss });
2005 if (typeof Online !== 'undefined')
2006 { Online.startPolling(onlinePayload); }
2007}
2008
2009function leaveOnlineMatch (goMenu)
2010{
2011 if (typeof Online !== 'undefined')
2012 {
2013 Online.stopPolling();
2014 Online.leaveLobby();
2015 Online.clearFlights();
2016 }
2017 teardownPlay();
2018 app.online = false;
2019 if (goMenu)
2020 {
2021 app.mode = 'menu';
2022 showEl('menu');
2023 }
2024 else
2025 {
2026 app.mode = 'online';
2027 openOnlinePanel();
2028 }
2029}
2030
2031function bindOnlineUi ()
2032{
2033 var onlineBtn = document.getElementById('btn-online');
2034 if (!onlineBtn)
2035 { return; }
2036 onlineBtn.addEventListener('click', function ()
2037 { openOnlinePanel(); });
2038
2039 var backs = document.querySelectorAll('[data-back-menu]');
2040 for (var i = 0; i < backs.length; i++)
2041 {
2042 backs[i].addEventListener('click', function ()
2043 {
2044 if (typeof Online !== 'undefined')
2045 { Online.stopPolling(); }
2046 hideEl('online-panel');
2047 app.mode = 'menu';
2048 app.online = false;
2049 showEl('menu');
2050 });
2051 }
2052
2053 document.getElementById('btn-create').addEventListener('click', function ()
2054 {
2055 Online.createLobby().then(function (data)
2056 {
2057 if (data && data.ok)
2058 {
2059 renderOnline();
2060 Online.startPolling(onlinePayload);
2061 }
2062 else
2063 { renderOnline(); }
2064 });
2065 });
2066
2067 document.getElementById('join-form').addEventListener('submit', function (e)
2068 {
2069 e.preventDefault();
2070 var code = (document.getElementById('join-code').value || '').trim();
2071 if (!code)
2072 { return; }
2073 Online.joinLobby(code).then(function ()
2074 {
2075 renderOnline();
2076 if (Online.lobby)
2077 { Online.startPolling(onlinePayload); }
2078 });
2079 });
2080
2081 document.getElementById('btn-ready').addEventListener('click', function ()
2082 {
2083 var me = Online.mePlayer();
2084 Online.setReady(!(me && me.ready)).then(renderOnline);
2085 });
2086
2087 document.getElementById('btn-start').addEventListener('click', function ()
2088 {
2089 Online.startGame().then(function (data)
2090 {
2091 if (data && data.ok)
2092 { startOnlineMatch(); }
2093 else
2094 { renderOnline(); }
2095 });
2096 });
2097
2098 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
2099 {
2100 Online.leaveLobby().then(function ()
2101 {
2102 Online.stopPolling();
2103 renderOnline();
2104 });
2105 });
2106
2107 document.getElementById('btn-copy-code').addEventListener('click', function ()
2108 {
2109 var code = document.getElementById('lobby-code').textContent;
2110 var btn = document.getElementById('btn-copy-code');
2111 var done = function ()
2112 {
2113 if (!btn)
2114 { return; }
2115 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied';
2116 setTimeout(function ()
2117 {
2118 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy';
2119 }, 1500);
2120 };
2121 if (navigator.clipboard && navigator.clipboard.writeText)
2122 { navigator.clipboard.writeText(code).then(done, done); }
2123 else
2124 { done(); }
2125 });
2126
2127 document.getElementById('btn-spectate').addEventListener('click', function ()
2128 {
2129 hideEl('spectator');
2130 app.spectating = true;
2131 });
2132
2133 document.getElementById('btn-leave-game').addEventListener('click', function ()
2134 { leaveOnlineMatch(false); });
2135
2136 if (typeof Online !== 'undefined')
2137 {
2138 Online.onChange = function ()
2139 { renderOnline(); };
2140 Online.onGameStart = function ()
2141 { startOnlineMatch(); };
2142 Online.onIncoming = function (incoming)
2143 {
2144 if (!app.core || app.core.state !== 'playing')
2145 { return; }
2146 for (var i = 0; i < incoming.length; i++)
2147 {
2148 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
2149 app.core.ingestGarbage(col);
2150 }
2151 };
2152 Online.onFinished = function (lobby)
2153 {
2154 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2155 {
2156 // Lifetime points in this same poll already include the
2157 // server's online award (maybeAwardOnlineLobby).
2158 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2159 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2160 {
2161 var pending = app.pendingLobbyReturn;
2162 app.pendingLobbyReturn = null;
2163 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2164 { Online.onLobbyReturn(pending || Online.lobby); }
2165 else
2166 { showPodium(Online.lobby); }
2167 });
2168 return;
2169 }
2170 showPodium(lobby);
2171 };
2172 Online.onLobbyReturn = function (lobby)
2173 {
2174 if (app.rewardActive)
2175 {
2176 app.pendingLobbyReturn = lobby;
2177 return;
2178 }
2179 teardownPlay();
2180 app.online = false;
2181 app.mode = 'online';
2182 hideEl('podium');
2183 showEl('online-panel');
2184 renderOnline();
2185 Online.startPolling(onlinePayload);
2186 };
2187 }
2188
2189 var params = new URLSearchParams(window.location.search);
2190 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
2191 {
2192 openOnlinePanel();
2193 // t1193: one-shot; a reload must not jump to online play again.
2194 try
2195 {
2196 params.delete('online');
2197 var rest = params.toString();
2198 window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash);
2199 }
2200 catch (e) { /* ignore */ }
2201 }
2202}
2203
2204function openOnlinePanel ()
2205{
2206 hideEl('menu');
2207 hideEl('game-over');
2208 hideEl('podium');
2209 hideEl('spectator');
2210 hideEl('planet-select');
2211 showEl('online-panel');
2212 app.mode = 'online';
2213 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…');
2214 if (typeof Online === 'undefined')
2215 {
2216 showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play offline.');
2217 showOnly('online-unconfigured');
2218 return;
2219 }
2220 Online.refresh().then(function (data)
2221 {
2222 if (!data || data.ok === false)
2223 {
2224 var msg = (data && data.error)
2225 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2226 : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.');
2227 showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play offline.'));
2228 if (data && data.configured === false)
2229 { showOnly('online-unconfigured'); }
2230 else
2231 { showOnly('online-login'); }
2232 document.getElementById('btn-login').style.display = 'none';
2233 return;
2234 }
2235 renderOnline();
2236 if (Online.lobby)
2237 { Online.startPolling(onlinePayload); }
2238 });
2239}
2240
2241function setOnlineStatus (text)
2242{
2243 var el = document.getElementById('online-status');
2244 if (el)
2245 { el.textContent = text; }
2246}
2247
2248function showOnlineError (text)
2249{
2250 var el = document.getElementById('online-error');
2251 if (!el)
2252 { return; }
2253 if (!text)
2254 {
2255 el.hidden = true;
2256 el.textContent = '';
2257 return;
2258 }
2259 el.hidden = false;
2260 el.textContent = text;
2261}
2262
2263function showOnly (id)
2264{
2265 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
2266 for (var i = 0; i < ids.length; i++)
2267 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
2268}
2269
2270function renderOnline ()
2271{
2272 if (typeof Online === 'undefined')
2273 { return; }
2274 if (app.mode === 'playing' && app.online)
2275 {
2276 Online.renderMinis(document.getElementById('minis'));
2277 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2278 { showPodium(Online.lobby); }
2279 return;
2280 }
2281 showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error);
2282 if (!Online.configured && !Online.me && !Online.local)
2283 {
2284 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.');
2285 showOnly('online-unconfigured');
2286 return;
2287 }
2288 if (!Online.me)
2289 {
2290 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.');
2291 showOnly('online-login');
2292 document.getElementById('btn-login').style.display = '';
2293 document.getElementById('btn-login').href = Online.loginUrl();
2294 document.getElementById('local-login').hidden = !Online.local;
2295 return;
2296 }
2297 if (Online.lobby)
2298 {
2299 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby');
2300 showOnly('online-lobby');
2301 document.getElementById('lobby-me-name').textContent = Online.me.name;
2302 document.getElementById('lobby-code').textContent = Online.lobby.code;
2303 var list = document.getElementById('lobby-players');
2304 list.innerHTML = '';
2305 var players = Online.lobby.players || [];
2306 for (var i = 0; i < players.length; i++)
2307 {
2308 var p = players[i];
2309 var li = document.createElement('li');
2310 if (p.is_me)
2311 { li.classList.add('you'); }
2312 var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
2313 var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you';
2314 var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : '');
2315 var state = p.ready ? 'Gereed' : 'Wacht…';
2316 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2317 li.innerHTML = '<span>' + escapeText(label)
2318 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2319 + '</span><span class="'
2320 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2321 list.appendChild(li);
2322 }
2323 renderPlanetGrid('lobby-planet-grid', true);
2324 var me = Online.mePlayer();
2325 document.getElementById('btn-ready').textContent = (me && me.ready)
2326 ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready')
2327 : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready');
2328 var start = document.getElementById('btn-start');
2329 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2330 start.disabled = !Online.lobby.can_start;
2331 var hint = document.getElementById('lobby-hint');
2332 if (Online.lobby.status === 'playing')
2333 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; }
2334 else if (players.length < 2)
2335 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; }
2336 else if (!Online.lobby.all_ready)
2337 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; }
2338 else if (Online.lobby.can_start)
2339 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; }
2340 else
2341 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; }
2342 return;
2343 }
2344 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.'));
2345 showOnly('online-home');
2346 document.getElementById('me-name').textContent = Online.me.name;
2347 document.getElementById('local-login').hidden = !Online.local;
2348}
2349
2350function escapeText (s)
2351{
2352 return String(s)
2353 .replace(/&/g, '&amp;')
2354 .replace(/</g, '&lt;')
2355 .replace(/>/g, '&gt;')
2356 .replace(/"/g, '&quot;');
2357}
2358
2359
2360function selectedPlanetId ()
2361{
2362 if (app.selectedPlanetId)
2363 { return app.selectedPlanetId; }
2364 return 'terra';
2365}
2366
2367/**
2368 * Pre-select the last chosen planet (t1196): logged in the profile value
2369 * (server), otherwise / as fallback localStorage, otherwise Terra. A
2370 * deleted custom planet falls back to the default (setSelectedPlanet).
2371 */
2372function restoreSelectedPlanet ()
2373{
2374 var id = null;
2375 if (typeof Online !== 'undefined' && Online.me && Online.lastPlanet)
2376 { id = Online.lastPlanet; }
2377 if (!id)
2378 {
2379 try
2380 { id = localStorage.getItem('meteors-planet'); }
2381 catch (e) {}
2382 }
2383 setSelectedPlanet(id || 'terra', true);
2384}
2385
2386function rememberPlanetChoice (id)
2387{
2388 if (typeof Online === 'undefined' || !Online.me || !Online.setLastPlanet)
2389 { return; }
2390 if (Online.lastPlanet === id)
2391 { return; }
2392 Promise.resolve(Online.setLastPlanet(id)).then(null, function () {});
2393}
2394
2395function setSelectedPlanet (id, silent)
2396{
2397 var all = Planet.allPlanets();
2398 var found = null;
2399 for (var i = 0; i < all.length; i++)
2400 {
2401 if (all[i].id === id)
2402 { found = all[i]; break; }
2403 }
2404 if (!found)
2405 { found = Planet.defaultPlanet(); }
2406 app.selectedPlanetId = found.id;
2407 try
2408 { localStorage.setItem('meteors-planet', found.id); }
2409 catch (e) {}
2410 if (!silent)
2411 {
2412 rememberPlanetChoice(found.id);
2413 var grid = document.getElementById('planet-grid');
2414 if (grid && !grid.hidden && grid.children.length)
2415 { renderPlanetGrid('planet-grid', false); }
2416 var lobby = document.getElementById('lobby-planet-grid');
2417 if (lobby && lobby.children.length)
2418 { renderPlanetGrid('lobby-planet-grid', true); }
2419 }
2420 return found;
2421}
2422
2423function openPlanetSelect (context)
2424{
2425 if (app.mode === 'playing')
2426 { return; }
2427 app.planetSelectContext = context || 'solo';
2428 app.mode = 'planet-select';
2429 hideEl('menu');
2430 hideEl('online-panel');
2431 hideEl('game-over');
2432 showEl('planet-select');
2433 renderPlanetGrid('planet-grid', false);
2434 var go = document.getElementById('btn-planet-go');
2435 if (go)
2436 { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; }
2437 // t1201: show which mode this planet choice is for.
2438 var modeEl = document.getElementById('planet-mode');
2439 if (modeEl)
2440 { modeEl.textContent = modeLabel(app.planetSelectContext); }
2441}
2442
2443function renderPlanetGrid (containerId, compact)
2444{
2445 var grid = document.getElementById(containerId);
2446 if (!grid)
2447 { return; }
2448 var current = selectedPlanetId();
2449 var all = Planet.allPlanets();
2450 grid.innerHTML = '';
2451 if (compact)
2452 { grid.classList.add('compact'); }
2453 for (var i = 0; i < all.length; i++)
2454 {
2455 var pl = all[i];
2456 var btn = document.createElement('button');
2457 btn.type = 'button';
2458 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2459 + (pl.custom ? ' custom' : '');
2460 btn.setAttribute('role', 'listitem');
2461 btn.dataset.planet = pl.id;
2462 var swatches = '';
2463 var colors = pl.colors || [];
2464 for (var c = 0; c < colors.length; c++)
2465 {
2466 var cname = colors[c].name;
2467 if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name)))
2468 { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); }
2469 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2470 + escapeText(cname) + '" title="' + escapeText(cname) + '">';
2471 }
2472 var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name;
2473 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people;
2474 var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours';
2475 btn.innerHTML = '<div class="planet-title">' + escapeText(title) + '</div>'
2476 + '<div class="planet-people">' + escapeText(people) + '</div>'
2477 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2478 + '<div class="planet-swatches">' + swatches + '</div>'
2479 + (pl.custom ? '<span class="custom-badge">' + escapeText(badge) + '</span>' : '');
2480 btn.addEventListener('click', (function (id, isCompact)
2481 {
2482 return function ()
2483 { onPlanetPicked(id, isCompact); };
2484 })(pl.id, !!compact));
2485 grid.appendChild(btn);
2486 }
2487}
2488
2489function onPlanetPicked (id, fromLobby)
2490{
2491 setSelectedPlanet(id);
2492 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2493 {
2494 Online.setPlanet(id).then(function ()
2495 { renderOnline(); });
2496 }
2497 else
2498 {
2499 renderPlanetGrid('planet-grid', false);
2500 }
2501}
2502
2503function confirmPlanetSelect ()
2504{
2505 var planet = setSelectedPlanet(selectedPlanetId());
2506 hideEl('planet-select');
2507 if (app.planetSelectContext === 'online')
2508 {
2509 openOnlinePanel();
2510 return;
2511 }
2512 if (app.planetSelectContext === 'offline')
2513 {
2514 startPlay({ planet: planet, offline: true });
2515 return;
2516 }
2517 startPlay({ planet: planet });
2518}
2519
2520function cancelPlanetSelect ()
2521{
2522 hideEl('planet-select');
2523 app.mode = 'menu';
2524 showEl('menu');
2525}
2526
2527function bindPlanetSelect ()
2528{
2529 var go = document.getElementById('btn-planet-go');
2530 var back = document.getElementById('btn-planet-back');
2531 if (go)
2532 {
2533 go.addEventListener('click', confirmPlanetSelect);
2534 }
2535 if (back)
2536 {
2537 back.addEventListener('click', cancelPlanetSelect);
2538 }
2539}
2540
2541
2542/** t1246: ask a logged-out player to log in, or continue as guest. */
2543function bindLoginPrompt ()
2544{
2545 if (typeof LoginPrompt !== 'undefined' && LoginPrompt.isAuthReturn)
2546 {
2547 var search = (window.location && window.location.search) || '';
2548 var referrer = (typeof document !== 'undefined' && document.referrer) || '';
2549 if (LoginPrompt.isAuthReturn(search, referrer))
2550 { LoginPrompt.remember(); }
2551 }
2552 var guest = document.getElementById('btn-play-guest');
2553 if (guest)
2554 { guest.addEventListener('click', playAsGuest); }
2555 var login = document.getElementById('btn-login-prompt');
2556 if (login)
2557 {
2558 login.addEventListener('click', function ()
2559 {
2560 if (typeof LoginPrompt !== 'undefined')
2561 { LoginPrompt.remember(); }
2562 });
2563 }
2564 var local = document.getElementById('login-prompt-local');
2565 if (local)
2566 {
2567 local.addEventListener('click', function (e)
2568 {
2569 var a = e.target && e.target.closest ? e.target.closest('a') : null;
2570 if (a && typeof LoginPrompt !== 'undefined')
2571 { LoginPrompt.remember(); }
2572 });
2573 }
2574}
2575
2576function maybeShowLoginPrompt ()
2577{
2578 var me = (typeof Online !== 'undefined') ? Online.me : null;
2579 var remembered = (typeof LoginPrompt !== 'undefined') && LoginPrompt.remembered();
2580 var fromAuth = (typeof LoginPrompt !== 'undefined') && LoginPrompt.isAuthReturn(
2581 (window.location && window.location.search) || '',
2582 (typeof document !== 'undefined' && document.referrer) || ''
2583 );
2584 var show = (typeof LoginPrompt === 'undefined')
2585 ? (!me && !remembered && !fromAuth)
2586 : LoginPrompt.shouldShow({ me: me, remembered: remembered, fromAuthReturn: fromAuth });
2587 if (show)
2588 { showLoginPrompt(); }
2589 else
2590 { hideLoginPrompt(); }
2591 app.loginPromptReady = true;
2592}
2593
2594function showLoginPrompt ()
2595{
2596 var el = document.getElementById('login-prompt');
2597 if (!el)
2598 { return; }
2599 el.hidden = false;
2600 var login = document.getElementById('btn-login-prompt');
2601 if (login && login.focus)
2602 { login.focus(); }
2603}
2604
2605function hideLoginPrompt ()
2606{
2607 var el = document.getElementById('login-prompt');
2608 if (el)
2609 { el.hidden = true; }
2610}
2611
2612function playAsGuest ()
2613{
2614 if (typeof LoginPrompt !== 'undefined')
2615 { LoginPrompt.remember(); }
2616 hideLoginPrompt();
2617}
2618
2619function refreshMenuAccount ()
2620{
2621 var guest = document.getElementById('menu-guest');
2622 var user = document.getElementById('menu-user');
2623 var designerBtn = document.getElementById('btn-designer');
2624 var localLogin = document.getElementById('menu-local-login');
2625 var me = (typeof Online !== 'undefined') ? Online.me : null;
2626 if (me)
2627 {
2628 if (guest)
2629 { guest.hidden = true; }
2630 if (user)
2631 { user.hidden = false; }
2632 var name = document.getElementById('menu-name');
2633 if (name)
2634 { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); }
2635 var pts = document.getElementById('menu-points');
2636 if (pts)
2637 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2638 if (designerBtn)
2639 { designerBtn.hidden = false; }
2640 }
2641 else
2642 {
2643 if (guest)
2644 { guest.hidden = false; }
2645 if (user)
2646 { user.hidden = true; }
2647 if (designerBtn)
2648 { designerBtn.hidden = true; }
2649 }
2650 if (localLogin)
2651 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2652 var promptLocal = document.getElementById('login-prompt-local');
2653 if (promptLocal)
2654 { promptLocal.hidden = !(typeof Online !== 'undefined' && Online.local); }
2655}
2656
2657/* ---------- t1193 in-game menu (Spelen / Offline Strijd) ----------- */
2658
2659function setGameMenuButton (show)
2660{
2661 var btn = document.getElementById('btn-game-menu');
2662 if (btn)
2663 { btn.hidden = !show; }
2664}
2665
2666/** The menu can open during a running solo / offline field only. */
2667function canOpenGameMenu ()
2668{
2669 return app.mode === 'playing' && !!app.core && !app.online && !app.spectating
2670 && app.core.state === 'playing' && !app.rewardActive && !app.quitting
2671 && !(app.offline && app.battle && app.battle.state !== 'playing');
2672}
2673
2674function openGameMenu ()
2675{
2676 if (!canOpenGameMenu())
2677 { return false; }
2678 if (app.core.drag)
2679 { finishDrag({ noLaunch: true }); }
2680 app.paused = true;
2681 // t1201: name the running mode ("Play" = rounds vs bots, "Survival" = endless).
2682 var modeEl = document.getElementById('game-menu-mode');
2683 if (modeEl)
2684 { modeEl.textContent = modeLabel(app.offline ? 'offline' : 'solo'); }
2685 showEl('game-menu');
2686 var resume = document.getElementById('btn-game-resume');
2687 if (resume && resume.focus)
2688 { resume.focus(); }
2689 return true;
2690}
2691
2692function resumeFromGameMenu ()
2693{
2694 hideEl('game-menu');
2695 if (!app.quitting)
2696 { app.paused = false; }
2697}
2698
2699/**
2700 * "Back to main menu": ends the match now. Logged in, the points so far
2701 * go through the normal play_finish + reward screen first (the server
2702 * still applies its caps); logged out, straight to the menu. Offline
2703 * Strijd ends the whole battle (no next round).
2704 */
2705function quitToMainMenu ()
2706{
2707 if (!app.core || app.quitting)
2708 { return; }
2709 hideEl('game-menu');
2710 app.paused = true;
2711 app.quitting = true;
2712 app.gameOverShown = true;
2713 app.lastScore = app.core.score || 0;
2714 setGameMenuButton(false);
2715 var score = app.lastScore;
2716 var done = function ()
2717 {
2718 app.quitting = false;
2719 app.paused = false;
2720 returnToMenu();
2721 };
2722 if (rewardEnabled())
2723 {
2724 var title = (typeof I18n !== 'undefined') ? I18n.t('reward.ended') : 'Game ended';
2725 showReward(false, finishPlaySession(score), done, title);
2726 }
2727 else
2728 {
2729 finishPlaySession(score);
2730 done();
2731 }
2732}
2733
2734function bindGameMenu ()
2735{
2736 var btn = document.getElementById('btn-game-menu');
2737 if (btn)
2738 { btn.addEventListener('click', function () { openGameMenu(); }); }
2739 var resume = document.getElementById('btn-game-resume');
2740 if (resume)
2741 { resume.addEventListener('click', resumeFromGameMenu); }
2742 var quit = document.getElementById('btn-game-quit');
2743 if (quit)
2744 { quit.addEventListener('click', quitToMainMenu); }
2745 document.addEventListener('keydown', function (e)
2746 {
2747 if (e.key !== 'Escape')
2748 { return; }
2749 var menu = document.getElementById('game-menu');
2750 if (menu && !menu.hidden)
2751 { resumeFromGameMenu(); }
2752 else
2753 { openGameMenu(); }
2754 });
2755}
2756
2757function beginPlaySession (mode)
2758{
2759 if (app.playToken)
2760 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2761 app.playToken = null;
2762 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2763 { return; }
2764 Online.playBegin(mode || 'solo').then(function (data)
2765 {
2766 if (data && data.ok && data.token)
2767 { app.playToken = data.token; }
2768 });
2769}
2770
2771/**
2772 * Ends the solo/offline play session. Resolves to the server-confirmed
2773 * { before, after } profile totals (t1173), or null when there is no
2774 * logged-in user or the server did not confirm. Without a token (e.g.
2775 * play_begin failed) a logged-in player gets { before = after = current }.
2776 */
2777function finishPlaySession (score)
2778{
2779 var token = app.playToken;
2780 app.playToken = null;
2781 var hasOnline = typeof Online !== 'undefined';
2782 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2783 if (!token || !hasOnline || !Online.playFinish)
2784 {
2785 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2786 }
2787 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2788 {
2789 refreshMenuAccount();
2790 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2791 {
2792 var awarded = Math.max(0, Number(data.awarded) || 0);
2793 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2794 }
2795 return null;
2796 }, function ()
2797 { return null; });
2798}
2799
2800/* ---------- t1173 reward screen (logged in only) ------------------- */
2801
2802function rewardEnabled ()
2803{
2804 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2805}
2806
2807/**
2808 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2809 * next() — the same destination the mode used before (menu, next
2810 * offline round, offline result, or the online lobby/podium).
2811 */
2812function showReward (won, resultPromise, next, title)
2813{
2814 app.rewardActive = true;
2815 hideEl('game-over');
2816 hideEl('spectator');
2817 hideEl('podium');
2818 var handle = Reward.play({
2819 won: won,
2820 title: title || null,
2821 planet: app.planet,
2822 result: resultPromise,
2823 onDone: function ()
2824 {
2825 app.rewardActive = false;
2826 if (next)
2827 { next(); }
2828 }
2829 });
2830 if (!handle)
2831 {
2832 app.rewardActive = false;
2833 // No reward overlay (e.g. missing DOM): still continue (t1193).
2834 if (title && next)
2835 { next(); }
2836 }
2837}
2838
2839function myOnlinePlace (lobby)
2840{
2841 var me = typeof Online !== 'undefined' ? Online.me : null;
2842 var ranks = (lobby && lobby.rankings) || [];
2843 for (var i = 0; i < ranks.length; i++)
2844 {
2845 if (me && ranks[i].id === me.id)
2846 { return ranks[i].place; }
2847 }
2848 return null;
2849}
2850
2851
2852
2853function applyProfileLocale ()
2854{
2855 if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2856 { return; }
2857 if (!Online.me)
2858 { return; }
2859 I18n.applyPreferred({
2860 explicit: !!(Online.localeExplicit && Online.locale),
2861 locale: Online.locale,
2862 authLocale: Online.authLocale,
2863 syncExplicit: true
2864 });
2865}
2866
2867/* ---------- t1247 leaderboard -------------------------------------- */
2868
2869function bindLeaderboard ()
2870{
2871 var btn = document.getElementById('btn-leaderboard');
2872 if (btn)
2873 {
2874 var open = function () { openLeaderboard(); };
2875 btn.addEventListener('click', open);
2876 // Same mobile path as Play / Survival: some browsers swallow click
2877 // after a slightly sloppy tap.
2878 btn.addEventListener('pointerup', function (e)
2879 {
2880 if (e.pointerType === 'touch' || e.pointerType === 'pen')
2881 {
2882 e.preventDefault();
2883 open();
2884 }
2885 });
2886 }
2887 var back = document.getElementById('btn-lb-back');
2888 if (back)
2889 { back.addEventListener('click', closeLeaderboard); }
2890 var globalTab = document.getElementById('lb-tab-global');
2891 var friendsTab = document.getElementById('lb-tab-friends');
2892 if (globalTab)
2893 { globalTab.addEventListener('click', function () { setLeaderboardTab('global'); }); }
2894 if (friendsTab)
2895 { friendsTab.addEventListener('click', function () { setLeaderboardTab('friends'); }); }
2896}
2897
2898function openLeaderboard (tab)
2899{
2900 if (app.mode === 'leaderboard')
2901 { return; }
2902 hideEl('menu');
2903 hideEl('online-panel');
2904 hideEl('planet-select');
2905 hideEl('login-prompt');
2906 app.mode = 'leaderboard';
2907 app.leaderboardTab = tab || app.leaderboardTab || 'global';
2908 showEl('leaderboard');
2909 setLeaderboardTab(app.leaderboardTab);
2910}
2911
2912function closeLeaderboard ()
2913{
2914 hideEl('leaderboard');
2915 app.mode = 'menu';
2916 showEl('menu');
2917}
2918
2919function setLeaderboardTab (tab)
2920{
2921 tab = tab === 'friends' ? 'friends' : 'global';
2922 app.leaderboardTab = tab;
2923 var globalTab = document.getElementById('lb-tab-global');
2924 var friendsTab = document.getElementById('lb-tab-friends');
2925 if (globalTab)
2926 { globalTab.setAttribute('aria-selected', tab === 'global' ? 'true' : 'false'); }
2927 if (friendsTab)
2928 { friendsTab.setAttribute('aria-selected', tab === 'friends' ? 'true' : 'false'); }
2929 loadLeaderboard(tab);
2930}
2931
2932function loadLeaderboard (tab)
2933{
2934 tab = tab || app.leaderboardTab || 'global';
2935 var login = document.getElementById('lb-login');
2936 var list = document.getElementById('lb-list');
2937 var empty = document.getElementById('lb-empty');
2938 var err = document.getElementById('lb-error');
2939 if (err)
2940 { err.hidden = true; err.textContent = ''; }
2941 if (empty)
2942 { empty.hidden = true; }
2943 if (list)
2944 { list.innerHTML = ''; }
2945 var loggedIn = typeof Online !== 'undefined' && !!Online.me;
2946 if (tab === 'friends' && !loggedIn)
2947 {
2948 if (login)
2949 { login.hidden = false; }
2950 return;
2951 }
2952 if (login)
2953 { login.hidden = true; }
2954 if (typeof Online === 'undefined' || !Online.leaderboard)
2955 {
2956 showLeaderboardError((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.');
2957 return;
2958 }
2959 Online.leaderboard(tab).then(function (data)
2960 {
2961 if (app.mode !== 'leaderboard' || app.leaderboardTab !== tab)
2962 { return; }
2963 if (!data || data.ok === false)
2964 {
2965 var msg = (data && data.error)
2966 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2967 : ((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.');
2968 showLeaderboardError(msg);
2969 return;
2970 }
2971 if (tab === 'friends' && data.login_required)
2972 {
2973 if (login)
2974 { login.hidden = false; }
2975 return;
2976 }
2977 renderLeaderboard(data.players || [], tab);
2978 });
2979}
2980
2981function showLeaderboardError (text)
2982{
2983 var err = document.getElementById('lb-error');
2984 if (!err)
2985 { return; }
2986 err.hidden = !text;
2987 err.textContent = text || '';
2988}
2989
2990function renderLeaderboard (players, tab)
2991{
2992 var list = document.getElementById('lb-list');
2993 var empty = document.getElementById('lb-empty');
2994 var login = document.getElementById('lb-login');
2995 if (login)
2996 { login.hidden = true; }
2997 if (!list)
2998 { return; }
2999 list.innerHTML = '';
3000 if (!players || !players.length)
3001 {
3002 if (empty)
3003 { empty.hidden = false; }
3004 return;
3005 }
3006 if (empty)
3007 { empty.hidden = true; }
3008 var meId = (typeof Online !== 'undefined' && Online.me) ? Online.me.id : null;
3009 for (var i = 0; i < players.length; i++)
3010 {
3011 var p = players[i];
3012 var li = document.createElement('li');
3013 var you = !!(p.you || (meId && p.id === meId));
3014 li.className = 'lb-row' + (you ? ' you' : '');
3015 var rank = document.createElement('span');
3016 rank.className = 'lb-rank';
3017 rank.textContent = String(p.rank || (i + 1));
3018 li.appendChild(rank);
3019 if (typeof Avatar !== 'undefined' && Avatar.piece)
3020 { li.appendChild(Avatar.piece({ id: p.id, name: p.name, avatar: p.avatar }, { size: 40 })); }
3021 var name = document.createElement('span');
3022 name.className = 'lb-name';
3023 name.textContent = p.name || '';
3024 li.appendChild(name);
3025 var pts = document.createElement('span');
3026 pts.className = 'lb-points';
3027 var n = p.points || 0;
3028 pts.textContent = (typeof I18n !== 'undefined')
3029 ? I18n.t('leaderboard.points', { n: n }, n + ' points')
3030 : (n + ' points');
3031 li.appendChild(pts);
3032 list.appendChild(li);
3033 }
3034}
3035
3036function refreshAllUi ()
3037{
3038 if (typeof I18n !== 'undefined')
3039 { I18n.apply(); }
3040 refreshMenuAccount();
3041 if (typeof renderPlanetGrid === 'function')
3042 {
3043 renderPlanetGrid('planet-grid', false);
3044 renderPlanetGrid('lobby-planet-grid', true);
3045 }
3046 if (app && app.mode === 'online' && typeof renderOnline === 'function')
3047 { renderOnline(); }
3048 if (typeof Designer !== 'undefined')
3049 {
3050 var des = document.getElementById('designer');
3051 var edit = document.getElementById('designer-edit');
3052 if (des && !des.hidden)
3053 { Designer.renderList(); }
3054 if (edit && !edit.hidden)
3055 {
3056 Designer.syncPreview();
3057 Designer.renderSlots();
3058 var modal = document.getElementById('des-modal');
3059 if (modal && !modal.hidden)
3060 { Designer.openModal(Designer.openSlot); }
3061 }
3062 }
3063 if (app && app.mode === 'playing')
3064 {
3065 if (typeof refreshHud === 'function')
3066 { refreshHud(); }
3067 if (typeof refreshOfflineHud === 'function')
3068 { refreshOfflineHud(); }
3069 }
3070 if (app && app.mode === 'leaderboard' && typeof loadLeaderboard === 'function')
3071 { loadLeaderboard(app.leaderboardTab); }
3072}