BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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