BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 68.2 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 // Draw the flight locally right away (t1181); the server
1410 // answer only retargets it.
1411 if (Online.startLocalShot)
1412 { Online.startLocalShot(s, start); }
1413 }
1414 Online.queueShots(shots);
1415 if (shots.length && Online.flushShotsSoon)
1416 { Online.flushShotsSoon(); }
1417 }
1418 Online.tickFlights();
1419 Online.renderMinis(document.getElementById('minis'));
1420 applyMinisLayout();
1421}
1422
1423
1424/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1425
1426function bindOfflineUi ()
1427{
1428 var btn = document.getElementById('btn-offline');
1429 if (btn)
1430 {
1431 btn.addEventListener('click', onOffline);
1432 btn.addEventListener('pointerup', function (e)
1433 {
1434 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1435 {
1436 e.preventDefault();
1437 onOffline();
1438 }
1439 });
1440 }
1441 var back = document.getElementById('btn-offline-menu');
1442 if (back)
1443 {
1444 back.addEventListener('click', function ()
1445 {
1446 teardownPlay();
1447 app.mode = 'menu';
1448 app.offline = false;
1449 app.battle = null;
1450 hideEl('offline-result');
1451 showEl('menu');
1452 });
1453 }
1454}
1455
1456function onOffline ()
1457{
1458 openPlanetSelect('offline');
1459}
1460
1461function tickOffline (dt)
1462{
1463 if (!app.battle || !app.core || typeof Offline === 'undefined')
1464 { return; }
1465
1466 if (app.battle.state === 'round_won')
1467 {
1468 if (!app.roundWonHandled)
1469 {
1470 app.roundWonHandled = true;
1471 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1472 if (rewardEnabled())
1473 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
1474 }
1475 if (app.rewardActive)
1476 {
1477 updateOfflineMinis(dt, true);
1478 return;
1479 }
1480 app.roundWonDelay -= dt;
1481 if (app.roundWonDelay <= 0)
1482 { startNextOfflineRound(); }
1483 updateOfflineMinis(dt, true);
1484 return;
1485 }
1486
1487 var result = app.battle.tick(dt, app.core);
1488 if (result && result.flights && result.flights.length
1489 && typeof Online !== 'undefined' && Online.spawnFlights)
1490 {
1491 var locals = Object.create(null);
1492 var list = result.locals || [];
1493 for (var i = 0; i < list.length; i++)
1494 {
1495 var s = list[i];
1496 var start;
1497 if (s.from_id === 'player')
1498 { start = fieldToViewport(s.col, s.y); }
1499 else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1500 { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1501 else
1502 { start = miniViewportCenter(s.from_id); }
1503 locals[s.client_id] = {
1504 col: s.col,
1505 y: s.y,
1506 color: s.color,
1507 startX: start.x,
1508 startY: start.y,
1509 from_id: s.from_id,
1510 land_col: s.land_col
1511 };
1512 }
1513 Online.spawnFlights(result.flights, locals);
1514 }
1515 if (typeof Online !== 'undefined' && Online.tickFlights)
1516 { Online.tickFlights(); }
1517 updateOfflineMinis(dt, false);
1518
1519 if (app.battle.state === 'lost' && !app.offlineResultShown)
1520 {
1521 if (rewardEnabled())
1522 {
1523 // Guard against starting the reward twice; showOfflineResult
1524 // sets the flag again when it runs afterwards.
1525 app.offlineResultShown = true;
1526 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
1527 }
1528 else
1529 { showOfflineResult(); }
1530 }
1531}
1532
1533function startNextOfflineRound ()
1534{
1535 if (!app.battle)
1536 { return; }
1537 app.battle.advanceRound();
1538 app.roundWonHandled = false;
1539 app.roundWonDelay = 0;
1540 app._keepBattleOnTeardown = true;
1541 // Tear down the current scene then start a fresh player field,
1542 // keeping the same battle (already advanced).
1543 var planet = app.battle.playerPlanet;
1544 var roundScore = app.core ? app.core.score : 0;
1545 finishPlaySession(roundScore);
1546 app._keepBattleOnTeardown = true;
1547 teardownPlay();
1548 app.offline = true;
1549 app.battle = app.battle; // kept
1550 startPlay({ planet: planet, offline: true, keepBattle: true });
1551}
1552
1553function showOfflineResult ()
1554{
1555 app.offlineResultShown = true;
1556 var battle = app.battle;
1557 var reached = document.getElementById('offline-reached');
1558 var sch = battle.schedule;
1559 var n = sch.opponents;
1560 var skill = Math.round(sch.skill * 100);
1561 var line = document.getElementById('offline-reached-line');
1562 if (line && typeof I18n !== 'undefined')
1563 { line.textContent = I18n.t('offline.reached', { n: battle.round }); }
1564 else if (reached)
1565 { reached.textContent = String(battle.round); }
1566 var detail = document.getElementById('offline-result-detail');
1567 if (detail)
1568 {
1569 if (typeof I18n !== 'undefined')
1570 {
1571 detail.textContent = I18n.t('offline.detail', {
1572 n: n,
1573 opponents: I18n.plural('hud.opponent', n),
1574 skill: skill
1575 });
1576 }
1577 else
1578 {
1579 var noun = n === 1 ? 'opponent' : 'opponents';
1580 detail.textContent = 'You played against ' + n + ' ' + noun
1581 + ' at skill ' + skill + '%.';
1582 }
1583 }
1584 hideEl('game-over');
1585 showEl('offline-result');
1586 finishPlaySession(app.core ? app.core.score : 0);
1587}
1588
1589function refreshOfflineHud ()
1590{
1591 var el = document.getElementById('offline-hud');
1592 if (!el)
1593 { return; }
1594 if (!(app.offline && app.battle && app.mode === 'playing'))
1595 {
1596 el.hidden = true;
1597 return;
1598 }
1599 el.hidden = false;
1600 var sch = app.battle.schedule;
1601 var n = sch.opponents;
1602 var r = document.getElementById('offline-round');
1603 var o = document.getElementById('offline-opponents');
1604 var s = document.getElementById('offline-skill');
1605 if (typeof I18n !== 'undefined')
1606 {
1607 if (r)
1608 { r.textContent = I18n.t('hud.round', { n: sch.round }); }
1609 if (o)
1610 {
1611 o.textContent = I18n.t('hud.opponentsLine', {
1612 n: n, word: I18n.plural('hud.opponent', n)
1613 });
1614 }
1615 if (s)
1616 { s.textContent = I18n.t('hud.skill', { n: Math.round(sch.skill * 100) }); }
1617 }
1618 else
1619 {
1620 var noun = n === 1 ? 'opponent' : 'opponents';
1621 if (r)
1622 { r.textContent = 'Round ' + sch.round; }
1623 if (o)
1624 { o.textContent = n + ' ' + noun; }
1625 if (s)
1626 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1627 }
1628}
1629
1630function hideOfflineHud ()
1631{
1632 var el = document.getElementById('offline-hud');
1633 if (el)
1634 { el.hidden = true; }
1635}
1636
1637function refreshChainIndicator ()
1638{
1639 var el = document.getElementById('chain-indicator');
1640 if (!el)
1641 { return; }
1642 var info = app.core && app.core.lastChainIndicator;
1643 var active = app.core && app.core.hasActiveLandingChain
1644 && app.core.hasActiveLandingChain();
1645 // Show only while a chained cluster is still in the air.
1646 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1647 {
1648 el.hidden = true;
1649 return;
1650 }
1651 el.hidden = false;
1652 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1653}
1654
1655function hideChainIndicator ()
1656{
1657 var el = document.getElementById('chain-indicator');
1658 if (el)
1659 { el.hidden = true; }
1660}
1661
1662function miniViewportCenter (botId)
1663{
1664 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1665 if (!el)
1666 { return { x: window.innerWidth / 2, y: 40 }; }
1667 var rect = el.getBoundingClientRect();
1668 var plan = app.miniLayout;
1669 if (plan && plan.mode === 'sides')
1670 {
1671 // Leave from the top of the mini, then the arc goes up and over (t1131).
1672 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1673 }
1674 return { x: rect.left + rect.width / 2, y: rect.bottom };
1675}
1676
1677function offlineMiniSize (n)
1678{
1679 return currentMiniSize();
1680}
1681
1682function updateOfflineMinis (dt, force)
1683{
1684 app.miniAcc = (app.miniAcc || 0) + dt;
1685 if (!force && app.miniAcc < 0.1)
1686 { return; }
1687 app.miniAcc = 0;
1688 renderOfflineMinis();
1689}
1690
1691function renderOfflineMinis ()
1692{
1693 var container = document.getElementById('minis');
1694 if (!container || !app.battle)
1695 { return; }
1696 var bots = app.battle.bots;
1697 var size = offlineMiniSize(bots.length);
1698 container.classList.toggle('crowded', bots.length > 5);
1699 var existing = {};
1700 var kids = container.querySelectorAll('[data-player]');
1701 for (var i = 0; i < kids.length; i++)
1702 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1703 var seen = Object.create(null);
1704 for (var i = 0; i < bots.length; i++)
1705 {
1706 var bot = bots[i];
1707 seen[bot.id] = true;
1708 var el = existing[bot.id];
1709 if (!el)
1710 {
1711 el = document.createElement('div');
1712 el.className = 'mini';
1713 el.setAttribute('data-player', bot.id);
1714 el.innerHTML = '<div class="mini-name"></div>'
1715 + '<canvas class="mini-canvas" width="' + size.w
1716 + '" height="' + size.h + '"></canvas>'
1717 + '<div class="mini-meta"></div>';
1718 container.appendChild(el);
1719 }
1720 var canvas = el.querySelector('canvas');
1721 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1722 {
1723 canvas.width = size.w;
1724 canvas.height = size.h;
1725 }
1726 el.classList.toggle('eliminated', !!bot.eliminated);
1727 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1728 var shownPlanet = planetName;
1729 if (bot.planet && typeof I18n !== 'undefined')
1730 { shownPlanet = I18n.planetName(bot.planet); }
1731 el.querySelector('.mini-name').textContent = bot.name
1732 + (shownPlanet ? ' · ' + shownPlanet : '');
1733 el.querySelector('.mini-meta').textContent = bot.eliminated
1734 ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out')
1735 : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (bot.score || 0)));
1736 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1737 if (typeof Online !== 'undefined' && Online._drawMini)
1738 { Online._drawMini(canvas, snap, bot.planet); }
1739 }
1740 for (var id in existing)
1741 {
1742 if (!seen[id])
1743 { existing[id].remove(); }
1744 }
1745 applyMinisLayout();
1746}
1747
1748function buildColumnWarn ()
1749{
1750 app.columnWarn = [];
1751 if (!app.scene)
1752 { return; }
1753 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1754 if (!img)
1755 { return; }
1756 for (var c = 0; c < 10; c++)
1757 {
1758 var obj = new GameObject(0, 0, img, 0);
1759 obj.renderer.alpha = 0;
1760 obj.renderer.visible = false;
1761 app.scene.addObject(obj);
1762 app.columnWarn.push(obj);
1763 }
1764 updateColumnWarn(0);
1765}
1766
1767function updateColumnWarn (dt)
1768{
1769 if (!app.columnWarn || !app.core)
1770 { return; }
1771 app.warnClock = (app.warnClock || 0) + (dt || 0);
1772 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1773 ? GameCore.columnWarnPulse(app.warnClock)
1774 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1775 var t = app.tile;
1776 for (var c = 0; c < app.columnWarn.length; c++)
1777 {
1778 var obj = app.columnWarn[c];
1779 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1780 obj.renderer.visible = !!on;
1781 obj.renderer.alpha = on ? pulse : 0;
1782 if (t)
1783 {
1784 obj.transform.position.x = c * t + t / 2;
1785 obj.transform.position.y = app.fieldH / 2;
1786 obj.transform.size = { x: t, y: app.fieldH };
1787 }
1788 }
1789}
1790
1791/**
1792 * A flight starts only when a block has actually left the field
1793 * (y ≥ height, the same threshold as cullOffTop). Rockets that
1794 * peak below the top and fall back must never get an arc (t1137).
1795 * Shared by the player's field, enemy minis, offline and online.
1796 */
1797function previewOutgoingFlights ()
1798{
1799 // Intentionally not called before core.tick: a block still on
1800 // the field (y < 13) is not a shot yet. Flights are spawned
1801 // from consumeOutgoingShots after cull, at the exit pose.
1802 if (typeof Online === 'undefined' || !Online.previewExit)
1803 { return; }
1804 if (app.core)
1805 { previewCoreExits(app.core, null); }
1806 if (app.offline && app.battle && app.battle.bots)
1807 {
1808 var bots = app.battle.bots;
1809 for (var i = 0; i < bots.length; i++)
1810 {
1811 var bot = bots[i];
1812 if (bot && bot.core && !bot.eliminated)
1813 { previewCoreExits(bot.core, bot.id); }
1814 }
1815 }
1816}
1817
1818function previewCoreExits (core, fromId)
1819{
1820 if (!core || !core.blocks)
1821 { return; }
1822 var height = core.height != null ? core.height : 13;
1823 var blocks = core.blocks;
1824 for (var i = 0; i < blocks.length; i++)
1825 {
1826 var b = blocks[i];
1827 if (b.state === 'manual')
1828 { continue; }
1829 if (typeof Online.hasLeftTheField === 'function'
1830 ? !Online.hasLeftTheField(b.y, height)
1831 : !(b.y >= height - 1e-9))
1832 { continue; }
1833 if (!(b.vy > 0))
1834 { continue; }
1835 var start = fromId
1836 ? (Online.miniCellViewport
1837 ? Online.miniCellViewport(fromId, b.col, b.y)
1838 : miniViewportCenter(fromId))
1839 : fieldToViewport(b.col, b.y);
1840 Online.previewExit({
1841 id: b.id,
1842 col: b.col,
1843 y: b.y,
1844 vy: b.vy,
1845 color: b.color,
1846 start: start,
1847 from_id: fromId || null
1848 });
1849 }
1850}
1851
1852function fieldToViewport (col, fieldY)
1853{
1854 var canvas = app.scene && app.scene.canvas;
1855 if (!canvas)
1856 { return { x: window.innerWidth / 2, y: 40 }; }
1857 var rect = canvas.getBoundingClientRect();
1858 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1859 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1860 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1861 return { x: x, y: y };
1862}
1863
1864function onlinePayload ()
1865{
1866 if (!app.online || !app.core)
1867 { return {}; }
1868 var snap = app.core.fieldSnapshot();
1869 // t1182: sender time (ms) so opponents can place the snapshot in
1870 // time and predict falling blocks smoothly. Visual only.
1871 snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
1872 return {
1873 snapshot: snap,
1874 score: app.core.score,
1875 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1876 };
1877}
1878
1879function onOnlineEliminated ()
1880{
1881 app.eliminatedReported = true;
1882 app.spectating = true;
1883 unbindPointer();
1884 hideEl('game-over');
1885 if (app.rewardActive)
1886 { return; }
1887 var lobby = typeof Online !== 'undefined' && Online.lobby;
1888 if (lobby && lobby.status === 'finished')
1889 {
1890 showPodium(lobby);
1891 return;
1892 }
1893 showEl('spectator');
1894}
1895
1896function showPodium (lobby)
1897{
1898 hideEl('spectator');
1899 hideEl('game-over');
1900 hideEl('online-panel');
1901 showEl('podium');
1902 var list = document.getElementById('podium-list');
1903 list.innerHTML = '';
1904 var ranks = (lobby && lobby.rankings) || [];
1905 for (var i = 0; i < ranks.length; i++)
1906 {
1907 var r = ranks[i];
1908 var li = document.createElement('li');
1909 var medal = (typeof I18n !== 'undefined') ? I18n.place(r.place)
1910 : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th')));
1911 li.textContent = (typeof I18n !== 'undefined')
1912 ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score })
1913 : (medal + ' ' + r.name + ' · ' + r.score + ' points');
1914 list.appendChild(li);
1915 }
1916 var hint = document.getElementById('podium-hint');
1917 var secs = (lobby && lobby.podium_seconds) || 5;
1918 if (hint)
1919 {
1920 hint.textContent = (typeof I18n !== 'undefined')
1921 ? I18n.t('podium.hint', { n: secs })
1922 : ('Returning to the lobby in ' + secs + ' seconds…');
1923 }
1924}
1925
1926function startOnlineMatch ()
1927{
1928 if (app.mode === 'playing' && app.online)
1929 { return; }
1930 var planet = Planet.planetById(selectedPlanetId());
1931 var miss = Planet.missChance(planet);
1932 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1933 if (me && me.planet)
1934 {
1935 if (typeof Planet.rememberPlanet === 'function')
1936 { planet = Planet.rememberPlanet(me.planet) || planet; }
1937 else if (me.planet.id)
1938 { planet = Planet.planetById(me.planet.id); }
1939 if (typeof me.planet.miss_chance === 'number')
1940 { miss = me.planet.miss_chance; }
1941 }
1942 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
1943 app.pendingLobbyReturn = null;
1944 startPlay({ online: true, planet: planet, missChance: miss });
1945 if (typeof Online !== 'undefined')
1946 { Online.startPolling(onlinePayload); }
1947}
1948
1949function leaveOnlineMatch (goMenu)
1950{
1951 if (typeof Online !== 'undefined')
1952 {
1953 Online.stopPolling();
1954 Online.leaveLobby();
1955 Online.clearFlights();
1956 }
1957 teardownPlay();
1958 app.online = false;
1959 if (goMenu)
1960 {
1961 app.mode = 'menu';
1962 showEl('menu');
1963 }
1964 else
1965 {
1966 app.mode = 'online';
1967 openOnlinePanel();
1968 }
1969}
1970
1971function bindOnlineUi ()
1972{
1973 var onlineBtn = document.getElementById('btn-online');
1974 if (!onlineBtn)
1975 { return; }
1976 onlineBtn.addEventListener('click', function ()
1977 { openOnlinePanel(); });
1978
1979 var backs = document.querySelectorAll('[data-back-menu]');
1980 for (var i = 0; i < backs.length; i++)
1981 {
1982 backs[i].addEventListener('click', function ()
1983 {
1984 if (typeof Online !== 'undefined')
1985 { Online.stopPolling(); }
1986 hideEl('online-panel');
1987 app.mode = 'menu';
1988 app.online = false;
1989 showEl('menu');
1990 });
1991 }
1992
1993 document.getElementById('btn-create').addEventListener('click', function ()
1994 {
1995 Online.createLobby().then(function (data)
1996 {
1997 if (data && data.ok)
1998 {
1999 renderOnline();
2000 Online.startPolling(onlinePayload);
2001 }
2002 else
2003 { renderOnline(); }
2004 });
2005 });
2006
2007 document.getElementById('join-form').addEventListener('submit', function (e)
2008 {
2009 e.preventDefault();
2010 var code = (document.getElementById('join-code').value || '').trim();
2011 if (!code)
2012 { return; }
2013 Online.joinLobby(code).then(function ()
2014 {
2015 renderOnline();
2016 if (Online.lobby)
2017 { Online.startPolling(onlinePayload); }
2018 });
2019 });
2020
2021 document.getElementById('btn-ready').addEventListener('click', function ()
2022 {
2023 var me = Online.mePlayer();
2024 Online.setReady(!(me && me.ready)).then(renderOnline);
2025 });
2026
2027 document.getElementById('btn-start').addEventListener('click', function ()
2028 {
2029 Online.startGame().then(function (data)
2030 {
2031 if (data && data.ok)
2032 { startOnlineMatch(); }
2033 else
2034 { renderOnline(); }
2035 });
2036 });
2037
2038 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
2039 {
2040 Online.leaveLobby().then(function ()
2041 {
2042 Online.stopPolling();
2043 renderOnline();
2044 });
2045 });
2046
2047 document.getElementById('btn-copy-code').addEventListener('click', function ()
2048 {
2049 var code = document.getElementById('lobby-code').textContent;
2050 var btn = document.getElementById('btn-copy-code');
2051 var done = function ()
2052 {
2053 if (!btn)
2054 { return; }
2055 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied';
2056 setTimeout(function ()
2057 {
2058 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy';
2059 }, 1500);
2060 };
2061 if (navigator.clipboard && navigator.clipboard.writeText)
2062 { navigator.clipboard.writeText(code).then(done, done); }
2063 else
2064 { done(); }
2065 });
2066
2067 document.getElementById('btn-spectate').addEventListener('click', function ()
2068 {
2069 hideEl('spectator');
2070 app.spectating = true;
2071 });
2072
2073 document.getElementById('btn-leave-game').addEventListener('click', function ()
2074 { leaveOnlineMatch(false); });
2075
2076 if (typeof Online !== 'undefined')
2077 {
2078 Online.onChange = function ()
2079 { renderOnline(); };
2080 Online.onGameStart = function ()
2081 { startOnlineMatch(); };
2082 Online.onIncoming = function (incoming)
2083 {
2084 if (!app.core || app.core.state !== 'playing')
2085 { return; }
2086 for (var i = 0; i < incoming.length; i++)
2087 {
2088 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
2089 app.core.ingestGarbage(col);
2090 }
2091 };
2092 Online.onFinished = function (lobby)
2093 {
2094 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2095 {
2096 // Lifetime points in this same poll already include the
2097 // server's online award (maybeAwardOnlineLobby).
2098 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2099 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2100 {
2101 var pending = app.pendingLobbyReturn;
2102 app.pendingLobbyReturn = null;
2103 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2104 { Online.onLobbyReturn(pending || Online.lobby); }
2105 else
2106 { showPodium(Online.lobby); }
2107 });
2108 return;
2109 }
2110 showPodium(lobby);
2111 };
2112 Online.onLobbyReturn = function (lobby)
2113 {
2114 if (app.rewardActive)
2115 {
2116 app.pendingLobbyReturn = lobby;
2117 return;
2118 }
2119 teardownPlay();
2120 app.online = false;
2121 app.mode = 'online';
2122 hideEl('podium');
2123 showEl('online-panel');
2124 renderOnline();
2125 Online.startPolling(onlinePayload);
2126 };
2127 }
2128
2129 var params = new URLSearchParams(window.location.search);
2130 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
2131 { openOnlinePanel(); }
2132}
2133
2134function openOnlinePanel ()
2135{
2136 hideEl('menu');
2137 hideEl('game-over');
2138 hideEl('podium');
2139 hideEl('spectator');
2140 hideEl('planet-select');
2141 showEl('online-panel');
2142 app.mode = 'online';
2143 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…');
2144 if (typeof Online === 'undefined')
2145 {
2146 showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play solo.');
2147 showOnly('online-unconfigured');
2148 return;
2149 }
2150 Online.refresh().then(function (data)
2151 {
2152 if (!data || data.ok === false)
2153 {
2154 var msg = (data && data.error)
2155 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2156 : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.');
2157 showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play solo.'));
2158 if (data && data.configured === false)
2159 { showOnly('online-unconfigured'); }
2160 else
2161 { showOnly('online-login'); }
2162 document.getElementById('btn-login').style.display = 'none';
2163 return;
2164 }
2165 renderOnline();
2166 if (Online.lobby)
2167 { Online.startPolling(onlinePayload); }
2168 });
2169}
2170
2171function setOnlineStatus (text)
2172{
2173 var el = document.getElementById('online-status');
2174 if (el)
2175 { el.textContent = text; }
2176}
2177
2178function showOnlineError (text)
2179{
2180 var el = document.getElementById('online-error');
2181 if (!el)
2182 { return; }
2183 if (!text)
2184 {
2185 el.hidden = true;
2186 el.textContent = '';
2187 return;
2188 }
2189 el.hidden = false;
2190 el.textContent = text;
2191}
2192
2193function showOnly (id)
2194{
2195 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
2196 for (var i = 0; i < ids.length; i++)
2197 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
2198}
2199
2200function renderOnline ()
2201{
2202 if (typeof Online === 'undefined')
2203 { return; }
2204 if (app.mode === 'playing' && app.online)
2205 {
2206 Online.renderMinis(document.getElementById('minis'));
2207 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2208 { showPodium(Online.lobby); }
2209 return;
2210 }
2211 showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error);
2212 if (!Online.configured && !Online.me && !Online.local)
2213 {
2214 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.');
2215 showOnly('online-unconfigured');
2216 return;
2217 }
2218 if (!Online.me)
2219 {
2220 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.');
2221 showOnly('online-login');
2222 document.getElementById('btn-login').style.display = '';
2223 document.getElementById('btn-login').href = Online.loginUrl();
2224 document.getElementById('local-login').hidden = !Online.local;
2225 return;
2226 }
2227 if (Online.lobby)
2228 {
2229 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby');
2230 showOnly('online-lobby');
2231 document.getElementById('lobby-me-name').textContent = Online.me.name;
2232 document.getElementById('lobby-code').textContent = Online.lobby.code;
2233 var list = document.getElementById('lobby-players');
2234 list.innerHTML = '';
2235 var players = Online.lobby.players || [];
2236 for (var i = 0; i < players.length; i++)
2237 {
2238 var p = players[i];
2239 var li = document.createElement('li');
2240 if (p.is_me)
2241 { li.classList.add('you'); }
2242 var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
2243 var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you';
2244 var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : '');
2245 var state = p.ready ? 'Gereed' : 'Wacht…';
2246 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2247 li.innerHTML = '<span>' + escapeText(label)
2248 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2249 + '</span><span class="'
2250 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2251 list.appendChild(li);
2252 }
2253 renderPlanetGrid('lobby-planet-grid', true);
2254 var me = Online.mePlayer();
2255 document.getElementById('btn-ready').textContent = (me && me.ready)
2256 ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready')
2257 : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready');
2258 var start = document.getElementById('btn-start');
2259 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2260 start.disabled = !Online.lobby.can_start;
2261 var hint = document.getElementById('lobby-hint');
2262 if (Online.lobby.status === 'playing')
2263 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; }
2264 else if (players.length < 2)
2265 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; }
2266 else if (!Online.lobby.all_ready)
2267 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; }
2268 else if (Online.lobby.can_start)
2269 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; }
2270 else
2271 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; }
2272 return;
2273 }
2274 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.'));
2275 showOnly('online-home');
2276 document.getElementById('me-name').textContent = Online.me.name;
2277 document.getElementById('local-login').hidden = !Online.local;
2278}
2279
2280function escapeText (s)
2281{
2282 return String(s)
2283 .replace(/&/g, '&amp;')
2284 .replace(/</g, '&lt;')
2285 .replace(/>/g, '&gt;')
2286 .replace(/"/g, '&quot;');
2287}
2288
2289
2290function selectedPlanetId ()
2291{
2292 if (app.selectedPlanetId)
2293 { return app.selectedPlanetId; }
2294 return 'terra';
2295}
2296
2297function restoreSelectedPlanet ()
2298{
2299 var id = 'terra';
2300 try
2301 { id = localStorage.getItem('meteors-planet') || 'terra'; }
2302 catch (e) {}
2303 setSelectedPlanet(id, true);
2304}
2305
2306function setSelectedPlanet (id, silent)
2307{
2308 var all = Planet.allPlanets();
2309 var found = null;
2310 for (var i = 0; i < all.length; i++)
2311 {
2312 if (all[i].id === id)
2313 { found = all[i]; break; }
2314 }
2315 if (!found)
2316 { found = Planet.defaultPlanet(); }
2317 app.selectedPlanetId = found.id;
2318 try
2319 { localStorage.setItem('meteors-planet', found.id); }
2320 catch (e) {}
2321 if (!silent)
2322 {
2323 var grid = document.getElementById('planet-grid');
2324 if (grid && !grid.hidden && grid.children.length)
2325 { renderPlanetGrid('planet-grid', false); }
2326 var lobby = document.getElementById('lobby-planet-grid');
2327 if (lobby && lobby.children.length)
2328 { renderPlanetGrid('lobby-planet-grid', true); }
2329 }
2330 return found;
2331}
2332
2333function openPlanetSelect (context)
2334{
2335 if (app.mode === 'playing')
2336 { return; }
2337 app.planetSelectContext = context || 'solo';
2338 app.mode = 'planet-select';
2339 hideEl('menu');
2340 hideEl('online-panel');
2341 hideEl('game-over');
2342 showEl('planet-select');
2343 renderPlanetGrid('planet-grid', false);
2344 var go = document.getElementById('btn-planet-go');
2345 if (go)
2346 { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; }
2347}
2348
2349function renderPlanetGrid (containerId, compact)
2350{
2351 var grid = document.getElementById(containerId);
2352 if (!grid)
2353 { return; }
2354 var current = selectedPlanetId();
2355 var all = Planet.allPlanets();
2356 grid.innerHTML = '';
2357 if (compact)
2358 { grid.classList.add('compact'); }
2359 for (var i = 0; i < all.length; i++)
2360 {
2361 var pl = all[i];
2362 var btn = document.createElement('button');
2363 btn.type = 'button';
2364 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2365 + (pl.custom ? ' custom' : '');
2366 btn.setAttribute('role', 'listitem');
2367 btn.dataset.planet = pl.id;
2368 var swatches = '';
2369 var colors = pl.colors || [];
2370 for (var c = 0; c < colors.length; c++)
2371 {
2372 var cname = colors[c].name;
2373 if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name)))
2374 { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); }
2375 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2376 + escapeText(cname) + '" title="' + escapeText(cname) + '">';
2377 }
2378 var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name;
2379 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people;
2380 var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours';
2381 btn.innerHTML = '<div class="planet-title">' + escapeText(title) + '</div>'
2382 + '<div class="planet-people">' + escapeText(people) + '</div>'
2383 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2384 + '<div class="planet-swatches">' + swatches + '</div>'
2385 + (pl.custom ? '<span class="custom-badge">' + escapeText(badge) + '</span>' : '');
2386 btn.addEventListener('click', (function (id, isCompact)
2387 {
2388 return function ()
2389 { onPlanetPicked(id, isCompact); };
2390 })(pl.id, !!compact));
2391 grid.appendChild(btn);
2392 }
2393}
2394
2395function onPlanetPicked (id, fromLobby)
2396{
2397 setSelectedPlanet(id);
2398 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2399 {
2400 Online.setPlanet(id).then(function ()
2401 { renderOnline(); });
2402 }
2403 else
2404 {
2405 renderPlanetGrid('planet-grid', false);
2406 }
2407}
2408
2409function confirmPlanetSelect ()
2410{
2411 var planet = setSelectedPlanet(selectedPlanetId());
2412 hideEl('planet-select');
2413 if (app.planetSelectContext === 'online')
2414 {
2415 openOnlinePanel();
2416 return;
2417 }
2418 if (app.planetSelectContext === 'offline')
2419 {
2420 startPlay({ planet: planet, offline: true });
2421 return;
2422 }
2423 startPlay({ planet: planet });
2424}
2425
2426function cancelPlanetSelect ()
2427{
2428 hideEl('planet-select');
2429 app.mode = 'menu';
2430 showEl('menu');
2431}
2432
2433function bindPlanetSelect ()
2434{
2435 var go = document.getElementById('btn-planet-go');
2436 var back = document.getElementById('btn-planet-back');
2437 if (go)
2438 {
2439 go.addEventListener('click', confirmPlanetSelect);
2440 }
2441 if (back)
2442 {
2443 back.addEventListener('click', cancelPlanetSelect);
2444 }
2445}
2446
2447
2448function refreshMenuAccount ()
2449{
2450 var guest = document.getElementById('menu-guest');
2451 var user = document.getElementById('menu-user');
2452 var designerBtn = document.getElementById('btn-designer');
2453 var localLogin = document.getElementById('menu-local-login');
2454 var me = (typeof Online !== 'undefined') ? Online.me : null;
2455 if (me)
2456 {
2457 if (guest)
2458 { guest.hidden = true; }
2459 if (user)
2460 { user.hidden = false; }
2461 var name = document.getElementById('menu-name');
2462 if (name)
2463 { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); }
2464 var pts = document.getElementById('menu-points');
2465 if (pts)
2466 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2467 if (designerBtn)
2468 { designerBtn.hidden = false; }
2469 }
2470 else
2471 {
2472 if (guest)
2473 { guest.hidden = false; }
2474 if (user)
2475 { user.hidden = true; }
2476 if (designerBtn)
2477 { designerBtn.hidden = true; }
2478 }
2479 if (localLogin)
2480 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2481}
2482
2483function beginPlaySession (mode)
2484{
2485 if (app.playToken)
2486 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2487 app.playToken = null;
2488 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2489 { return; }
2490 Online.playBegin(mode || 'solo').then(function (data)
2491 {
2492 if (data && data.ok && data.token)
2493 { app.playToken = data.token; }
2494 });
2495}
2496
2497/**
2498 * Ends the solo/offline play session. Resolves to the server-confirmed
2499 * { before, after } profile totals (t1173), or null when there is no
2500 * logged-in user or the server did not confirm. Without a token (e.g.
2501 * play_begin failed) a logged-in player gets { before = after = current }.
2502 */
2503function finishPlaySession (score)
2504{
2505 var token = app.playToken;
2506 app.playToken = null;
2507 var hasOnline = typeof Online !== 'undefined';
2508 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2509 if (!token || !hasOnline || !Online.playFinish)
2510 {
2511 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2512 }
2513 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2514 {
2515 refreshMenuAccount();
2516 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2517 {
2518 var awarded = Math.max(0, Number(data.awarded) || 0);
2519 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2520 }
2521 return null;
2522 }, function ()
2523 { return null; });
2524}
2525
2526/* ---------- t1173 reward screen (logged in only) ------------------- */
2527
2528function rewardEnabled ()
2529{
2530 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2531}
2532
2533/**
2534 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2535 * next() — the same destination the mode used before (menu, next
2536 * offline round, offline result, or the online lobby/podium).
2537 */
2538function showReward (won, resultPromise, next)
2539{
2540 app.rewardActive = true;
2541 hideEl('game-over');
2542 hideEl('spectator');
2543 hideEl('podium');
2544 var handle = Reward.play({
2545 won: won,
2546 planet: app.planet,
2547 result: resultPromise,
2548 onDone: function ()
2549 {
2550 app.rewardActive = false;
2551 if (next)
2552 { next(); }
2553 }
2554 });
2555 if (!handle)
2556 { app.rewardActive = false; }
2557}
2558
2559function myOnlinePlace (lobby)
2560{
2561 var me = typeof Online !== 'undefined' ? Online.me : null;
2562 var ranks = (lobby && lobby.rankings) || [];
2563 for (var i = 0; i < ranks.length; i++)
2564 {
2565 if (me && ranks[i].id === me.id)
2566 { return ranks[i].place; }
2567 }
2568 return null;
2569}
2570
2571
2572
2573function applyProfileLocale ()
2574{
2575 if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2576 { return; }
2577 if (Online.locale)
2578 { I18n.applyFromProfile(Online.locale); }
2579 else if (Online.me)
2580 { Online.setLocale(I18n.locale); }
2581}
2582
2583function refreshAllUi ()
2584{
2585 if (typeof I18n !== 'undefined')
2586 { I18n.apply(); }
2587 refreshMenuAccount();
2588 if (typeof renderPlanetGrid === 'function')
2589 {
2590 renderPlanetGrid('planet-grid', false);
2591 renderPlanetGrid('lobby-planet-grid', true);
2592 }
2593 if (app && app.mode === 'online' && typeof renderOnline === 'function')
2594 { renderOnline(); }
2595 if (typeof Designer !== 'undefined')
2596 {
2597 var des = document.getElementById('designer');
2598 var edit = document.getElementById('designer-edit');
2599 if (des && !des.hidden)
2600 { Designer.renderList(); }
2601 if (edit && !edit.hidden)
2602 {
2603 Designer.syncPreview();
2604 Designer.renderSlots();
2605 var modal = document.getElementById('des-modal');
2606 if (modal && !modal.hidden)
2607 { Designer.openModal(Designer.openSlot); }
2608 }
2609 }
2610 if (app && app.mode === 'playing')
2611 {
2612 if (typeof refreshHud === 'function')
2613 { refreshHud(); }
2614 if (typeof refreshOfflineHud === 'function')
2615 { refreshOfflineHud(); }
2616 }
2617}