BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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