BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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