BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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