BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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