BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 38.3 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.
8 */
9
10function planetImages ()
11{
12 var list = [
13 { name: 'gray', url: 'images/block-gray.png' },
14 { name: 'locked', url: 'images/block-locked.png' },
15 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
16 { name: 'cell', url: 'images/cell.png' },
17 { name: 'pixel', url: 'images/pixel.png' },
18 // Keep the original Terra placeholders as aliases (Tim may still have them).
19 { name: 'ember', url: 'images/block-ember.png' },
20 { name: 'aqua', url: 'images/block-aqua.png' },
21 { name: 'leaf', url: 'images/block-leaf.png' },
22 { name: 'sun', url: 'images/block-sun.png' },
23 { name: 'orchid', url: 'images/block-orchid.png' }
24 ];
25 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
26 for (var i = 0; i < planets.length; i++)
27 {
28 var pl = planets[i];
29 for (var c = 0; c < pl.colors.length; c++)
30 {
31 list.push({
32 name: Planet.spriteKey(pl, c),
33 url: pl.colors[c].image
34 });
35 }
36 }
37 return list;
38}
39
40var IMAGES = planetImages();
41var GAME_OVER_DELAY = 2;
42
43var game = new Game();
44var app = {
45 mode: 'menu',
46 core: null,
47 scene: null,
48 manager: null,
49 planet: null,
50 lastScore: 0,
51 tile: 48,
52 fieldX: 0,
53 fieldY: 0,
54 fieldW: 0,
55 fieldH: 0,
56 hudH: 56,
57 sprites: Object.create(null),
58 flames: Object.create(null),
59 cells: [],
60 pointerId: null,
61 pointerType: null,
62 activeTouchId: null,
63 debugDrag: false,
64 debugPhysics: false,
65 gameOverShown: false,
66 selectTween: null,
67 online: false,
68 eliminatedReported: false,
69 spectating: false,
70 miniH: 0,
71 selectedPlanetId: 'terra',
72 planetSelectContext: 'solo'
73};
74
75window.onload = function ()
76{
77 app.debugDrag = isDragDebugEnabled();
78 app.debugPhysics = isPhysicsDebugEnabled();
79 var play = document.getElementById('btn-play');
80 play.addEventListener('click', onPlay);
81 play.addEventListener('pointerup', function (e)
82 {
83 // A touch-friendly path: some mobile browsers swallow the click
84 // after a slightly sloppy tap. Ignore the following click.
85 if (e.pointerType === 'touch' || e.pointerType === 'pen')
86 {
87 e.preventDefault();
88 onPlay();
89 }
90 });
91
92 game.preloadImagesThenStart(IMAGES, function ()
93 {
94 if (game.images.flame && game.images.flame.addAnimationCycle)
95 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
96 });
97
98 bindOnlineUi();
99 bindPlanetSelect();
100 restoreSelectedPlanet();
101};
102
103function onPlay ()
104{
105 if (app.mode === 'playing')
106 { return; }
107 openPlanetSelect('solo');
108}
109
110function startPlay (opts)
111{
112 opts = opts || {};
113 hideEl('menu');
114 hideEl('game-over');
115 hideEl('online-panel');
116 hideEl('spectator');
117 hideEl('podium');
118 hideEl('planet-select');
119 showEl('hud');
120
121 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
122 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
123 var miss = opts.missChance;
124 if (typeof miss !== 'number' || !isFinite(miss))
125 { miss = planetMod.missChance(app.planet); }
126 app.core = new GameCore(app.planet, Math.random, miss);
127 if (app.debugPhysics)
128 { app.core.debugInvariants = true; }
129 app.mode = 'playing';
130 app.online = !!opts.online;
131 app.gameOverShown = false;
132 app.eliminatedReported = false;
133 app.spectating = false;
134 app.sprites = Object.create(null);
135 app.flames = Object.create(null);
136 app.cells = [];
137 app.pointerId = null;
138 app.selectTween = null;
139
140 layout();
141 if (app.scene)
142 {
143 app.scene.destroy();
144 app.scene = null;
145 }
146 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
147 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
148 app.scene.renderBackground = true;
149 game.loadScene(app.scene);
150
151 buildCells();
152 app.manager = app.scene.addObject(makeManager());
153 if (!app.spectating)
154 { bindPointer(app.scene.canvas); }
155 refreshHud();
156 if (app.online)
157 { showEl('minis'); }
158 else
159 { hideEl('minis'); }
160}
161
162function teardownPlay ()
163{
164 unbindPointer();
165 if (app.scene)
166 {
167 app.scene.destroy();
168 app.scene = null;
169 }
170 app.manager = null;
171 app.core = null;
172 app.sprites = Object.create(null);
173 app.flames = Object.create(null);
174 app.cells = [];
175 app.selectTween = null;
176 app.pointerId = null;
177 app.gameOverShown = false;
178 hideEl('hud');
179 hideEl('game-over');
180 hideEl('spectator');
181 hideEl('minis');
182 if (typeof Online !== 'undefined')
183 { Online.clearFlights(); }
184}
185
186function returnToMenu ()
187{
188 if (app.online && typeof Online !== 'undefined')
189 {
190 // Online matches do not dump you back to the solo menu:
191 // elimination becomes spectating; a finished match shows the podium.
192 return;
193 }
194 teardownPlay();
195 app.mode = 'menu';
196 app.online = false;
197 hideEl('planet-select');
198 showEl('menu');
199 var last = document.getElementById('last-score');
200 if (app.lastScore > 0)
201 {
202 last.hidden = false;
203 last.querySelector('strong').textContent = String(app.lastScore);
204 }
205}
206
207function buildCells ()
208{
209 if (!app.scene)
210 { return; }
211 var img = game.images.cell;
212 for (var row = 0; row < 13; row++)
213 {
214 for (var col = 0; col < 10; col++)
215 {
216 var obj = new GameObject(0, 0, img, 0);
217 placeTile(obj, col, row);
218 obj.renderer.alpha = 0.9;
219 app.scene.addObject(obj);
220 app.cells.push(obj);
221 }
222 }
223}
224
225function placeTile (obj, col, y)
226{
227 var t = app.tile;
228 obj.transform.position.x = col * t + t / 2;
229 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
230 obj.transform.size = { x: t, y: t };
231}
232
233function layoutIfNeeded ()
234{
235 if (app.core && app.core.drag)
236 { return; }
237 var vw = window.innerWidth || 320;
238 var vh = window.innerHeight || 480;
239 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
240 { return; }
241 layout();
242}
243
244function layout ()
245{
246 if (app.core && app.core.drag)
247 { return; }
248 var vw = window.innerWidth || 320;
249 var vh = window.innerHeight || 480;
250 app._layoutVw = vw;
251 app._layoutVh = vh;
252 var safeTop = 0;
253 try
254 {
255 // env(safe-area) is a CSS thing; keep a conservative HUD height.
256 safeTop = 0;
257 }
258 catch (e) { /* ignore */ }
259 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
260 app.miniH = 0;
261 if (app.online)
262 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
263 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
264 var availW = Math.max(80, vw - margin * 2);
265 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
266 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
267 app.fieldW = app.tile * 10;
268 app.fieldH = app.tile * 13;
269 app.fieldX = Math.floor((vw - app.fieldW) / 2);
270 var topBand = app.hudH + app.miniH;
271 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
272 if (app.fieldY < topBand)
273 { app.fieldY = topBand; }
274 var minis = document.getElementById('minis');
275 if (minis)
276 {
277 minis.style.top = app.hudH + 'px';
278 minis.style.maxHeight = app.miniH + 'px';
279 }
280
281 if (app.scene)
282 {
283 app.scene.position.x = app.fieldX;
284 app.scene.position.y = app.fieldY;
285 app.scene.size.x = app.fieldW;
286 app.scene.size.y = app.fieldH;
287 }
288}
289
290function spriteFor (block)
291{
292 if (block.state === 'locked')
293 { return game.images.locked; }
294 if (block.color < 0)
295 { return game.images.gray; }
296 var key = Planet.spriteKey(app.planet, block.color);
297 return game.images[key] || game.images.gray;
298}
299
300function syncSprites ()
301{
302 if (!app.core || !app.scene)
303 { return; }
304 var seen = Object.create(null);
305 var blocks = app.core.blocks;
306 for (var i = 0; i < blocks.length; i++)
307 {
308 var block = blocks[i];
309 seen[block.id] = true;
310 var obj = app.sprites[block.id];
311 if (!obj)
312 {
313 obj = new GameObject(0, 0, spriteFor(block), 2);
314 app.scene.addObject(obj);
315 app.sprites[block.id] = obj;
316 }
317 obj.renderer.sprite = spriteFor(block);
318 placeTile(obj, block.col, block.y);
319 applyBlockVisual(obj, block);
320 obj.renderer.visible = true;
321 obj.renderer.alpha = 1;
322
323 if (block.flame)
324 {
325 var flame = app.flames[block.id];
326 if (!flame)
327 {
328 flame = new GameObject(0, 0, game.images.flame, 1);
329 flame.renderer.setAnimation('burn', 0, 0.08);
330 app.scene.addObject(flame);
331 app.flames[block.id] = flame;
332 }
333 flame.renderer.visible = true;
334 var t = app.tile;
335 // 3x as large (length and width, t1110). Keep the top of the
336 // flame at the same overlap into the block so the extra length
337 // extends downward under the rocket.
338 var flameW = t * 0.85 * 3;
339 var flameH = t * 0.85 * 3;
340 var origCenter = app.fieldH - block.y * t + t * 0.15;
341 var origTop = origCenter - (t * 0.85) / 2;
342 flame.transform.position.x = block.col * t + t / 2;
343 flame.transform.position.y = origTop + flameH / 2;
344 flame.transform.size = { x: flameW, y: flameH };
345 }
346 else if (app.flames[block.id])
347 { app.flames[block.id].renderer.visible = false; }
348 }
349
350 var ids = Object.keys(app.sprites);
351 for (var i = 0; i < ids.length; i++)
352 {
353 if (!seen[ids[i]])
354 {
355 app.sprites[ids[i]].destroy();
356 delete app.sprites[ids[i]];
357 if (app.flames[ids[i]])
358 {
359 app.flames[ids[i]].destroy();
360 delete app.flames[ids[i]];
361 }
362 }
363 }
364}
365
366function applyBlockVisual (obj, block)
367{
368 var t = app.tile;
369 var sx = 1;
370 var sy = 1;
371 var dy = 0;
372 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
373 && typeof Easing !== 'undefined' && Easing.bouncePose)
374 {
375 var u = block.bounceAge / app.planet.bounceDuration;
376 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
377 sx = pose.sx;
378 sy = pose.sy;
379 dy = pose.dy;
380 }
381 var sel = 1;
382 var tw = app.selectTween;
383 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
384 { sel = tw.scale; }
385 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
386 if (dy)
387 { obj.transform.position.y -= dy * t; }
388}
389
390function clickTween ()
391{
392 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
393}
394
395function startPressTween (blockId)
396{
397 var c = clickTween();
398 if (!c)
399 { return; }
400 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
401 app.selectTween = {
402 blockId: blockId,
403 from: from,
404 to: c.pressScale,
405 t: 0,
406 duration: c.pressDuration,
407 ease: c.pressEase,
408 scale: from,
409 phase: 'press'
410 };
411}
412
413function startReleaseTween ()
414{
415 var c = clickTween();
416 var tw = app.selectTween;
417 if (!c || !tw || tw.phase === 'idle')
418 { return; }
419 app.selectTween = {
420 blockId: tw.blockId,
421 from: tw.scale,
422 to: c.releaseScale,
423 t: 0,
424 duration: c.releaseDuration,
425 ease: c.releaseEase,
426 scale: tw.scale,
427 phase: 'release'
428 };
429}
430
431function updateSelectTween (dt)
432{
433 var tw = app.selectTween;
434 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
435 { return; }
436 tw.t += dt;
437 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
438 if (u >= 1)
439 {
440 tw.scale = tw.to;
441 tw.t = tw.duration;
442 if (tw.phase === 'press')
443 { tw.phase = 'hold'; }
444 else
445 {
446 tw.phase = 'idle';
447 tw.scale = 1;
448 tw.blockId = null;
449 }
450 return;
451 }
452 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
453 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
454}
455
456function refreshHud ()
457{
458 if (!app.core)
459 { return; }
460 document.getElementById('score').textContent = String(app.core.score);
461 var planet = app.planet;
462 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
463 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
464}
465
466function makeManager ()
467{
468 var obj = new GameObject(0, 0, game.images.pixel, 0);
469 obj.renderer.visible = false;
470 var base = obj.update.bind(obj);
471 obj.update = function (dt)
472 {
473 base(dt);
474 tickView(dt);
475 };
476 return obj;
477}
478
479function tickView (dt)
480{
481 if (app.mode !== 'playing' || !app.core)
482 { return; }
483
484 // Never resize the canvas mid-drag: a URL-bar hide would move the
485 // field under the finger and jump the target row. Also skip work
486 // when the viewport has not actually changed.
487 if (!(app.core && app.core.drag))
488 { layoutIfNeeded(); }
489 for (var i = 0; i < app.cells.length; i++)
490 {
491 var col = i % 10;
492 var row = Math.floor(i / 10);
493 placeTile(app.cells[i], col, row);
494 }
495
496 app.core.tick(dt);
497 updateSelectTween(dt);
498 syncSprites();
499 refreshHud();
500 tickOnline(dt);
501 if (app.debugPhysics)
502 { logPhysicsDebug(); }
503
504 if (app.core.state === 'gameover' && !app.gameOverShown)
505 {
506 app.gameOverShown = true;
507 app.lastScore = app.core.score;
508 document.getElementById('go-score').textContent = String(app.lastScore);
509 if (app.online)
510 { onOnlineEliminated(); }
511 else
512 { showEl('game-over'); }
513 }
514 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
515 { returnToMenu(); }
516}
517
518/* ---------- pointer input (mouse + touch) --------------------------- */
519/*
520 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
521 * on a real phone, pointer clientX/Y can disagree with the visual
522 * finger (zoomed visual viewport, gesture takeover, capture cancel)
523 * while changedTouches stays correct. When a touch is active, pointer
524 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
525 * walk the block to the top or bottom of the stack (t1106).
526 *
527 * After a down we also listen on the document, so a drag that leaves
528 * the canvas (needed to launch a block at the top of a full column)
529 * still reaches moveDrag. We do not call setPointerCapture: on mobile
530 * that is often cancelled when the browser takes the gesture, which
531 * would fire pointercancel mid-drag.
532 *
533 * A non-passive document touchstart/touchmove preventDefault during
534 * play stops scrolling, rubber-banding and the pointercancel that
535 * follows. pointercancel / touchcancel end the drag without launch.
536 *
537 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
538 */
539
540var boundCanvas = null;
541var windowListening = false;
542var touchListening = false;
543var lastDragDebug = null;
544
545function isDragDebugEnabled ()
546{
547 try
548 {
549 var q = window.location && window.location.search;
550 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
551 { return true; }
552 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
553 { return true; }
554 }
555 catch (err) { /* ignore */ }
556 return false;
557}
558
559/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
560function isPhysicsDebugEnabled ()
561{
562 try
563 {
564 var q = window.location && window.location.search;
565 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
566 { return true; }
567 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
568 || window.localStorage.getItem('meteors-debug-drag') === '1'))
569 { return true; }
570 }
571 catch (err) { /* ignore */ }
572 return false;
573}
574
575function eventClient (e)
576{
577 var t = null;
578 if (e.changedTouches && e.changedTouches.length)
579 { t = e.changedTouches[0]; }
580 else if (e.touches && e.touches.length)
581 { t = e.touches[0]; }
582 if (t)
583 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
584 if (e.clientX != null && e.clientY != null)
585 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
586 return null;
587}
588
589function addWindowPointer ()
590{
591 if (windowListening)
592 { return; }
593 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
594 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
595 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
596 windowListening = true;
597}
598
599function removeWindowPointer ()
600{
601 if (!windowListening)
602 { return; }
603 window.removeEventListener('pointermove', onPointerMove, { capture: true });
604 window.removeEventListener('pointerup', onPointerUp, { capture: true });
605 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
606 windowListening = false;
607}
608
609function addTouchListeners ()
610{
611 if (touchListening)
612 { return; }
613 var opts = { capture: true, passive: false };
614 document.addEventListener('touchstart', onTouchStart, opts);
615 document.addEventListener('touchmove', onTouchMove, opts);
616 document.addEventListener('touchend', onTouchEnd, opts);
617 document.addEventListener('touchcancel', onTouchCancel, opts);
618 touchListening = true;
619}
620
621function removeTouchListeners ()
622{
623 if (!touchListening)
624 { return; }
625 var opts = { capture: true };
626 document.removeEventListener('touchstart', onTouchStart, opts);
627 document.removeEventListener('touchmove', onTouchMove, opts);
628 document.removeEventListener('touchend', onTouchEnd, opts);
629 document.removeEventListener('touchcancel', onTouchCancel, opts);
630 touchListening = false;
631}
632
633function bindPointer (canvas)
634{
635 unbindPointer();
636 boundCanvas = canvas;
637 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
638 canvas.style.touchAction = 'none';
639 canvas.style.position = 'fixed';
640 canvas.style.cursor = 'pointer';
641 canvas.style.webkitUserSelect = 'none';
642 canvas.style.userSelect = 'none';
643 addTouchListeners();
644 if (app.debugDrag)
645 { ensureDragDebugOverlay(); }
646}
647
648function unbindPointer ()
649{
650 removeWindowPointer();
651 removeTouchListeners();
652 if (boundCanvas)
653 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
654 boundCanvas = null;
655 app.pointerId = null;
656 app.pointerType = null;
657 app.activeTouchId = null;
658}
659
660function fieldFromEvent (e)
661{
662 var canvas = app.scene && app.scene.canvas;
663 if (!canvas)
664 { return null; }
665 var rect = canvas.getBoundingClientRect();
666 if (rect.width <= 0 || rect.height <= 0)
667 { return null; }
668 var pt = eventClient(e);
669 if (!pt)
670 { return null; }
671 // Map through the CSS box only. Using canvas.width / app.tile would
672 // scale the pointer by the backing-store ratio whenever that differs
673 // from the layout size (high-DPR devices), so a short finger move
674 // would look like a long swipe.
675 var width = Planet.FIELD_WIDTH;
676 var height = Planet.FIELD_HEIGHT;
677 var col = ((pt.x - rect.left) / rect.width) * width;
678 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
679 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
680}
681
682function playingForDrag ()
683{
684 return app.core && app.core.state === 'playing';
685}
686
687function startDragFromEvent (e)
688{
689 var pos = fieldFromEvent(e);
690 if (!pos)
691 { return; }
692 if (app.core.drag)
693 {
694 app.core.moveDrag(pos.y);
695 logDragDebug(e, pos, 'move-already');
696 return;
697 }
698 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
699 { startPressTween(app.core.drag.blockId); }
700 logDragDebug(e, pos, 'down');
701}
702
703function moveDragFromEvent (e)
704{
705 if (!app.core || !app.core.drag)
706 { return; }
707 var pos = fieldFromEvent(e);
708 if (pos)
709 { app.core.moveDrag(pos.y); }
710 logDragDebug(e, pos, 'move');
711}
712
713function finishDrag (opts)
714{
715 opts = opts || {};
716 app.pointerId = null;
717 app.pointerType = null;
718 app.activeTouchId = null;
719 removeWindowPointer();
720 if (boundCanvas)
721 {
722 try
723 {
724 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
725 { boundCanvas.releasePointerCapture(opts.pointerId); }
726 }
727 catch (err) { /* ignore */ }
728 }
729 startReleaseTween();
730 if (app.core && app.core.drag)
731 {
732 if (opts.noLaunch)
733 { app.core.drag.launchIntent = false; }
734 app.core.endDrag();
735 }
736 else if (app.core)
737 { app.core.endDrag(); }
738 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
739}
740
741function onPointerDown (e)
742{
743 if (!playingForDrag())
744 { return; }
745 if (app.pointerId != null && e.pointerId !== app.pointerId)
746 { return; }
747 if (e.preventDefault)
748 { e.preventDefault(); }
749 app.pointerId = e.pointerId;
750 app.pointerType = e.pointerType || 'mouse';
751 addWindowPointer();
752 // If a touch is already in charge, do not reset the grab from pointerdown.
753 if (app.activeTouchId != null)
754 { return; }
755 startDragFromEvent(e);
756}
757
758function onPointerMove (e)
759{
760 if (app.pointerId == null || e.pointerId !== app.pointerId)
761 { return; }
762 if (!app.core || !app.core.drag)
763 { return; }
764 // Touch coordinates are the authority; ignore pointer moves for a
765 // live touch so a wrong clientY cannot walk the whole column.
766 // Only skip when touchstart has actually arrived — some environments
767 // deliver touch-pointer events without a TouchEvent stream.
768 if (app.activeTouchId != null)
769 {
770 if (e.preventDefault)
771 { e.preventDefault(); }
772 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
773 return;
774 }
775 if (e.preventDefault)
776 { e.preventDefault(); }
777 moveDragFromEvent(e);
778}
779
780function onPointerUp (e)
781{
782 if (app.pointerId == null)
783 { return; }
784 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
785 { return; }
786 if (app.activeTouchId != null)
787 {
788 // touchend will finish the drag.
789 if (e && e.preventDefault)
790 { e.preventDefault(); }
791 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
792 return;
793 }
794 if (e && e.preventDefault)
795 { e.preventDefault(); }
796 finishDrag({ pointerId: e && e.pointerId });
797}
798
799function onPointerCancel (e)
800{
801 if (app.pointerId == null)
802 { return; }
803 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
804 { return; }
805 if (app.activeTouchId != null)
806 {
807 if (e && e.preventDefault)
808 { e.preventDefault(); }
809 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
810 return;
811 }
812 if (e && e.preventDefault)
813 { e.preventDefault(); }
814 // A cancelled gesture is not a launch pull.
815 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
816}
817
818function touchById (list, id)
819{
820 if (!list)
821 { return null; }
822 for (var i = 0; i < list.length; i++)
823 {
824 if (list[i].identifier === id)
825 { return list[i]; }
826 }
827 return null;
828}
829
830function onTouchStart (e)
831{
832 if (!playingForDrag())
833 { return; }
834 if (app.activeTouchId != null)
835 {
836 if (e.preventDefault)
837 { e.preventDefault(); }
838 return;
839 }
840 var t = e.changedTouches && e.changedTouches[0];
841 if (!t)
842 { return; }
843 if (e.preventDefault)
844 { e.preventDefault(); }
845 app.activeTouchId = t.identifier;
846 addWindowPointer();
847 startDragFromEvent(e);
848}
849
850function onTouchMove (e)
851{
852 if (app.activeTouchId == null)
853 { return; }
854 if (!touchById(e.changedTouches, app.activeTouchId)
855 && !touchById(e.touches, app.activeTouchId))
856 { return; }
857 if (e.preventDefault)
858 { e.preventDefault(); }
859 moveDragFromEvent(e);
860}
861
862function onTouchEnd (e)
863{
864 if (app.activeTouchId == null)
865 { return; }
866 if (!touchById(e.changedTouches, app.activeTouchId))
867 { return; }
868 if (e.preventDefault)
869 { e.preventDefault(); }
870 finishDrag({});
871}
872
873function onTouchCancel (e)
874{
875 if (app.activeTouchId == null)
876 { return; }
877 if (!touchById(e.changedTouches, app.activeTouchId))
878 { return; }
879 if (e.preventDefault)
880 { e.preventDefault(); }
881 finishDrag({ noLaunch: true });
882}
883
884function logPhysicsDebug ()
885{
886 if (!app.debugPhysics || !app.core)
887 { return; }
888 ensureDragDebugOverlay();
889 var el = document.getElementById('drag-debug');
890 if (!el)
891 { return; }
892 var issues = app.core.lastInvariantViolations || [];
893 var flying = 0;
894 var manuals = 0;
895 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
896 for (var i = 0; i < app.core.blocks.length; i++)
897 {
898 if (app.core.blocks[i].state === 'flying')
899 { flying++; }
900 if (app.core.blocks[i].state === 'manual')
901 { manuals++; }
902 }
903 var status = issues.length
904 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
905 : ('physics ok blocks=' + app.core.blocks.length
906 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
907 // Keep any live drag line above the physics status.
908 var dragLine = '';
909 if (app.debugDrag && lastDragDebug)
910 {
911 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
912 ? el.textContent.split('\n')[0] + '\n'
913 : '';
914 }
915 el.textContent = dragLine + status;
916 el.hidden = false;
917 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
918}
919
920function ensureDragDebugOverlay ()
921{
922 if (document.getElementById('drag-debug'))
923 { return; }
924 var el = document.createElement('div');
925 el.id = 'drag-debug';
926 el.setAttribute('aria-live', 'polite');
927 document.body.appendChild(el);
928}
929
930function logDragDebug (e, pos, phase)
931{
932 if (!app.debugDrag)
933 { return; }
934 ensureDragDebugOverlay();
935 var el = document.getElementById('drag-debug');
936 if (!el)
937 { return; }
938 var block = null;
939 if (app.core && app.core.drag)
940 { block = app.core.blockById(app.core.drag.blockId); }
941 var pt = e ? eventClient(e) : null;
942 var evType = e ? e.type : phase;
943 var info = {
944 phase: phase,
945 ev: evType,
946 src: pos && pos.src,
947 fieldY: pos && Math.round(pos.y * 100) / 100,
948 col: pos && Math.round(pos.col * 100) / 100,
949 cy: pt && Math.round(pt.y * 10) / 10,
950 blockY: block && Math.round(block.y * 100) / 100,
951 target: block && Math.floor((pos && pos.y) + 1e-12),
952 launch: app.core && app.core.drag && app.core.drag.launchIntent,
953 touchId: app.activeTouchId,
954 pid: app.pointerId,
955 ptype: app.pointerType
956 };
957 lastDragDebug = info;
958 el.textContent = 'drag ' + phase
959 + ' ev=' + evType
960 + ' src=' + (info.src || '-')
961 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
962 + ' → ' + (info.target != null ? info.target : '-')
963 + ' block=' + (info.blockY != null ? info.blockY : '-')
964 + (info.launch ? ' LAUNCH' : '')
965 + ' tId=' + info.touchId
966 + ' pId=' + info.pid;
967 el.hidden = false;
968}
969
970
971function hideEl (id)
972{
973 document.getElementById(id).hidden = true;
974}
975
976function showEl (id)
977{
978 document.getElementById(id).hidden = false;
979}
980
981window.addEventListener('resize', function ()
982{
983 if (app.mode === 'playing')
984 { layout(); }
985});
986
987window.addEventListener('orientationchange', function ()
988{
989 setTimeout(function ()
990 {
991 if (app.mode === 'playing')
992 { layout(); }
993 }, 120);
994});
995
996/* ---------- online play (stage 2) ---------------------------------- */
997
998function tickOnline (dt)
999{
1000 if (!app.online || typeof Online === 'undefined')
1001 { return; }
1002 if (app.core)
1003 {
1004 var shots = app.core.consumeOutgoingShots();
1005 for (var i = 0; i < shots.length; i++)
1006 {
1007 var s = shots[i];
1008 var start = fieldToViewport(s.col, s.y + 1);
1009 Online.rememberFlightLocal(s, start.x, start.y);
1010 }
1011 Online.queueShots(shots);
1012 }
1013 Online.tickFlights();
1014 Online.renderMinis(document.getElementById('minis'));
1015}
1016
1017function fieldToViewport (col, fieldY)
1018{
1019 var canvas = app.scene && app.scene.canvas;
1020 if (!canvas)
1021 { return { x: window.innerWidth / 2, y: 40 }; }
1022 var rect = canvas.getBoundingClientRect();
1023 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1024 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
1025 return { x: x, y: y };
1026}
1027
1028function onlinePayload ()
1029{
1030 if (!app.online || !app.core)
1031 { return {}; }
1032 return {
1033 snapshot: app.core.fieldSnapshot(),
1034 score: app.core.score,
1035 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1036 };
1037}
1038
1039function onOnlineEliminated ()
1040{
1041 app.eliminatedReported = true;
1042 app.spectating = true;
1043 unbindPointer();
1044 hideEl('game-over');
1045 var lobby = typeof Online !== 'undefined' && Online.lobby;
1046 if (lobby && lobby.status === 'finished')
1047 {
1048 showPodium(lobby);
1049 return;
1050 }
1051 showEl('spectator');
1052}
1053
1054function showPodium (lobby)
1055{
1056 hideEl('spectator');
1057 hideEl('game-over');
1058 hideEl('online-panel');
1059 showEl('podium');
1060 var list = document.getElementById('podium-list');
1061 list.innerHTML = '';
1062 var ranks = (lobby && lobby.rankings) || [];
1063 for (var i = 0; i < ranks.length; i++)
1064 {
1065 var r = ranks[i];
1066 var li = document.createElement('li');
1067 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
1068 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
1069 list.appendChild(li);
1070 }
1071 var hint = document.getElementById('podium-hint');
1072 var secs = (lobby && lobby.podium_seconds) || 5;
1073 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
1074}
1075
1076function startOnlineMatch ()
1077{
1078 if (app.mode === 'playing' && app.online)
1079 { return; }
1080 var planet = Planet.planetById(selectedPlanetId());
1081 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1082 if (me && me.planet && me.planet.id)
1083 { planet = Planet.planetById(me.planet.id); }
1084 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1085 if (typeof Online !== 'undefined')
1086 { Online.startPolling(onlinePayload); }
1087}
1088
1089function leaveOnlineMatch (goMenu)
1090{
1091 if (typeof Online !== 'undefined')
1092 {
1093 Online.stopPolling();
1094 Online.leaveLobby();
1095 Online.clearFlights();
1096 }
1097 teardownPlay();
1098 app.online = false;
1099 if (goMenu)
1100 {
1101 app.mode = 'menu';
1102 showEl('menu');
1103 }
1104 else
1105 {
1106 app.mode = 'online';
1107 openOnlinePanel();
1108 }
1109}
1110
1111function bindOnlineUi ()
1112{
1113 var onlineBtn = document.getElementById('btn-online');
1114 if (!onlineBtn)
1115 { return; }
1116 onlineBtn.addEventListener('click', function ()
1117 { openOnlinePanel(); });
1118
1119 var backs = document.querySelectorAll('[data-back-menu]');
1120 for (var i = 0; i < backs.length; i++)
1121 {
1122 backs[i].addEventListener('click', function ()
1123 {
1124 if (typeof Online !== 'undefined')
1125 { Online.stopPolling(); }
1126 hideEl('online-panel');
1127 app.mode = 'menu';
1128 app.online = false;
1129 showEl('menu');
1130 });
1131 }
1132
1133 document.getElementById('btn-create').addEventListener('click', function ()
1134 {
1135 Online.createLobby().then(function (data)
1136 {
1137 if (data && data.ok)
1138 {
1139 renderOnline();
1140 Online.startPolling(onlinePayload);
1141 }
1142 else
1143 { renderOnline(); }
1144 });
1145 });
1146
1147 document.getElementById('join-form').addEventListener('submit', function (e)
1148 {
1149 e.preventDefault();
1150 var code = (document.getElementById('join-code').value || '').trim();
1151 if (!code)
1152 { return; }
1153 Online.joinLobby(code).then(function ()
1154 {
1155 renderOnline();
1156 if (Online.lobby)
1157 { Online.startPolling(onlinePayload); }
1158 });
1159 });
1160
1161 document.getElementById('btn-ready').addEventListener('click', function ()
1162 {
1163 var me = Online.mePlayer();
1164 Online.setReady(!(me && me.ready)).then(renderOnline);
1165 });
1166
1167 document.getElementById('btn-start').addEventListener('click', function ()
1168 {
1169 Online.startGame().then(function (data)
1170 {
1171 if (data && data.ok)
1172 { startOnlineMatch(); }
1173 else
1174 { renderOnline(); }
1175 });
1176 });
1177
1178 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
1179 {
1180 Online.leaveLobby().then(function ()
1181 {
1182 Online.stopPolling();
1183 renderOnline();
1184 });
1185 });
1186
1187 document.getElementById('btn-copy-code').addEventListener('click', function ()
1188 {
1189 var code = document.getElementById('lobby-code').textContent;
1190 if (navigator.clipboard && navigator.clipboard.writeText)
1191 { navigator.clipboard.writeText(code); }
1192 });
1193
1194 document.getElementById('btn-spectate').addEventListener('click', function ()
1195 {
1196 hideEl('spectator');
1197 app.spectating = true;
1198 });
1199
1200 document.getElementById('btn-leave-game').addEventListener('click', function ()
1201 { leaveOnlineMatch(false); });
1202
1203 if (typeof Online !== 'undefined')
1204 {
1205 Online.onChange = function ()
1206 { renderOnline(); };
1207 Online.onGameStart = function ()
1208 { startOnlineMatch(); };
1209 Online.onIncoming = function (incoming)
1210 {
1211 if (!app.core || app.core.state !== 'playing')
1212 { return; }
1213 for (var i = 0; i < incoming.length; i++)
1214 { app.core.ingestGarbage(); }
1215 };
1216 Online.onFinished = function (lobby)
1217 { showPodium(lobby); };
1218 Online.onLobbyReturn = function (lobby)
1219 {
1220 teardownPlay();
1221 app.online = false;
1222 app.mode = 'online';
1223 hideEl('podium');
1224 showEl('online-panel');
1225 renderOnline();
1226 Online.startPolling(onlinePayload);
1227 };
1228 }
1229
1230 var params = new URLSearchParams(window.location.search);
1231 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
1232 { openOnlinePanel(); }
1233}
1234
1235function openOnlinePanel ()
1236{
1237 hideEl('menu');
1238 hideEl('game-over');
1239 hideEl('podium');
1240 hideEl('spectator');
1241 hideEl('planet-select');
1242 showEl('online-panel');
1243 app.mode = 'online';
1244 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
1245 if (typeof Online === 'undefined')
1246 {
1247 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
1248 showOnly('online-unconfigured');
1249 return;
1250 }
1251 Online.refresh().then(function (data)
1252 {
1253 if (!data || data.ok === false)
1254 {
1255 var msg = (data && data.error) || 'Geen verbinding met de server.';
1256 showOnlineError(msg + ' Je kunt wel alleen spelen.');
1257 if (data && data.configured === false)
1258 { showOnly('online-unconfigured'); }
1259 else
1260 { showOnly('online-login'); }
1261 document.getElementById('btn-login').style.display = 'none';
1262 return;
1263 }
1264 renderOnline();
1265 if (Online.lobby)
1266 { Online.startPolling(onlinePayload); }
1267 });
1268}
1269
1270function setOnlineStatus (text)
1271{
1272 var el = document.getElementById('online-status');
1273 if (el)
1274 { el.textContent = text; }
1275}
1276
1277function showOnlineError (text)
1278{
1279 var el = document.getElementById('online-error');
1280 if (!el)
1281 { return; }
1282 if (!text)
1283 {
1284 el.hidden = true;
1285 el.textContent = '';
1286 return;
1287 }
1288 el.hidden = false;
1289 el.textContent = text;
1290}
1291
1292function showOnly (id)
1293{
1294 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
1295 for (var i = 0; i < ids.length; i++)
1296 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
1297}
1298
1299function renderOnline ()
1300{
1301 if (typeof Online === 'undefined')
1302 { return; }
1303 if (app.mode === 'playing' && app.online)
1304 {
1305 Online.renderMinis(document.getElementById('minis'));
1306 if (Online.lobby && Online.lobby.status === 'finished')
1307 { showPodium(Online.lobby); }
1308 return;
1309 }
1310 showOnlineError(Online.error);
1311 if (!Online.configured && !Online.me && !Online.local)
1312 {
1313 setOnlineStatus('Online spelen is nog niet ingesteld.');
1314 showOnly('online-unconfigured');
1315 return;
1316 }
1317 if (!Online.me)
1318 {
1319 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
1320 showOnly('online-login');
1321 document.getElementById('btn-login').style.display = '';
1322 document.getElementById('btn-login').href = Online.loginUrl();
1323 document.getElementById('local-login').hidden = !Online.local;
1324 return;
1325 }
1326 if (Online.lobby)
1327 {
1328 setOnlineStatus('Lobby');
1329 showOnly('online-lobby');
1330 document.getElementById('lobby-me-name').textContent = Online.me.name;
1331 document.getElementById('lobby-code').textContent = Online.lobby.code;
1332 var list = document.getElementById('lobby-players');
1333 list.innerHTML = '';
1334 var players = Online.lobby.players || [];
1335 for (var i = 0; i < players.length; i++)
1336 {
1337 var p = players[i];
1338 var li = document.createElement('li');
1339 if (p.is_me)
1340 { li.classList.add('you'); }
1341 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
1342 var state = p.ready ? 'Gereed' : 'Wacht…';
1343 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
1344 li.innerHTML = '<span>' + escapeText(label)
1345 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
1346 + '</span><span class="'
1347 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
1348 list.appendChild(li);
1349 }
1350 renderPlanetGrid('lobby-planet-grid', true);
1351 var me = Online.mePlayer();
1352 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
1353 var start = document.getElementById('btn-start');
1354 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
1355 start.disabled = !Online.lobby.can_start;
1356 var hint = document.getElementById('lobby-hint');
1357 if (Online.lobby.status === 'playing')
1358 { hint.textContent = 'Het spel start…'; }
1359 else if (players.length < 2)
1360 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
1361 else if (!Online.lobby.all_ready)
1362 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
1363 else if (Online.lobby.can_start)
1364 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
1365 else
1366 { hint.textContent = 'Wachten tot de host start.'; }
1367 return;
1368 }
1369 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
1370 showOnly('online-home');
1371 document.getElementById('me-name').textContent = Online.me.name;
1372 document.getElementById('local-login').hidden = !Online.local;
1373}
1374
1375function escapeText (s)
1376{
1377 return String(s)
1378 .replace(/&/g, '&amp;')
1379 .replace(/</g, '&lt;')
1380 .replace(/>/g, '&gt;')
1381 .replace(/"/g, '&quot;');
1382}
1383
1384
1385function selectedPlanetId ()
1386{
1387 if (app.selectedPlanetId)
1388 { return app.selectedPlanetId; }
1389 return 'terra';
1390}
1391
1392function restoreSelectedPlanet ()
1393{
1394 var id = 'terra';
1395 try
1396 { id = localStorage.getItem('meteors-planet') || 'terra'; }
1397 catch (e) {}
1398 setSelectedPlanet(id, true);
1399}
1400
1401function setSelectedPlanet (id, silent)
1402{
1403 var all = Planet.allPlanets();
1404 var found = null;
1405 for (var i = 0; i < all.length; i++)
1406 {
1407 if (all[i].id === id)
1408 { found = all[i]; break; }
1409 }
1410 if (!found)
1411 { found = Planet.defaultPlanet(); }
1412 app.selectedPlanetId = found.id;
1413 try
1414 { localStorage.setItem('meteors-planet', found.id); }
1415 catch (e) {}
1416 if (!silent)
1417 {
1418 var grid = document.getElementById('planet-grid');
1419 if (grid && !grid.hidden && grid.children.length)
1420 { renderPlanetGrid('planet-grid', false); }
1421 var lobby = document.getElementById('lobby-planet-grid');
1422 if (lobby && lobby.children.length)
1423 { renderPlanetGrid('lobby-planet-grid', true); }
1424 }
1425 return found;
1426}
1427
1428function openPlanetSelect (context)
1429{
1430 if (app.mode === 'playing')
1431 { return; }
1432 app.planetSelectContext = context || 'solo';
1433 app.mode = 'planet-select';
1434 hideEl('menu');
1435 hideEl('online-panel');
1436 hideEl('game-over');
1437 showEl('planet-select');
1438 renderPlanetGrid('planet-grid', false);
1439 var go = document.getElementById('btn-planet-go');
1440 if (go)
1441 { go.textContent = 'Spelen'; }
1442}
1443
1444function renderPlanetGrid (containerId, compact)
1445{
1446 var grid = document.getElementById(containerId);
1447 if (!grid)
1448 { return; }
1449 var current = selectedPlanetId();
1450 var all = Planet.allPlanets();
1451 grid.innerHTML = '';
1452 if (compact)
1453 { grid.classList.add('compact'); }
1454 for (var i = 0; i < all.length; i++)
1455 {
1456 var pl = all[i];
1457 var btn = document.createElement('button');
1458 btn.type = 'button';
1459 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
1460 btn.setAttribute('role', 'listitem');
1461 btn.dataset.planet = pl.id;
1462 var swatches = '';
1463 for (var c = 0; c < pl.colors.length; c++)
1464 {
1465 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
1466 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
1467 }
1468 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
1469 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
1470 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
1471 + '<div class="planet-swatches">' + swatches + '</div>';
1472 btn.addEventListener('click', (function (id, isCompact)
1473 {
1474 return function ()
1475 { onPlanetPicked(id, isCompact); };
1476 })(pl.id, !!compact));
1477 grid.appendChild(btn);
1478 }
1479}
1480
1481function onPlanetPicked (id, fromLobby)
1482{
1483 setSelectedPlanet(id);
1484 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
1485 {
1486 Online.setPlanet(id).then(function ()
1487 { renderOnline(); });
1488 }
1489 else
1490 {
1491 renderPlanetGrid('planet-grid', false);
1492 }
1493}
1494
1495function confirmPlanetSelect ()
1496{
1497 var planet = setSelectedPlanet(selectedPlanetId());
1498 hideEl('planet-select');
1499 if (app.planetSelectContext === 'online')
1500 {
1501 openOnlinePanel();
1502 return;
1503 }
1504 startPlay({ planet: planet });
1505}
1506
1507function cancelPlanetSelect ()
1508{
1509 hideEl('planet-select');
1510 app.mode = 'menu';
1511 showEl('menu');
1512}
1513
1514function bindPlanetSelect ()
1515{
1516 var go = document.getElementById('btn-planet-go');
1517 var back = document.getElementById('btn-planet-back');
1518 if (go)
1519 {
1520 go.addEventListener('click', confirmPlanetSelect);
1521 }
1522 if (back)
1523 {
1524 back.addEventListener('click', cancelPlanetSelect);
1525 }
1526}