BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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