BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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