BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 24.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
10var IMAGES = [
11 { name: 'ember', url: 'images/block-ember.png' },
12 { name: 'aqua', url: 'images/block-aqua.png' },
13 { name: 'leaf', url: 'images/block-leaf.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
16 { name: 'gray', url: 'images/block-gray.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
19 { name: 'cell', url: 'images/cell.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
21];
22
23var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
24var GAME_OVER_DELAY = 2;
25
26var game = new Game();
27var app = {
28 mode: 'menu',
29 core: null,
30 scene: null,
31 manager: null,
32 planet: null,
33 lastScore: 0,
34 tile: 48,
35 fieldX: 0,
36 fieldY: 0,
37 fieldW: 0,
38 fieldH: 0,
39 hudH: 56,
40 sprites: Object.create(null),
41 flames: Object.create(null),
42 cells: [],
43 pointerId: null,
44 gameOverShown: false,
45 selectTween: null,
46 online: false,
47 eliminatedReported: false,
48 spectating: false,
49 miniH: 0
50};
51
52window.onload = function ()
53{
54 var play = document.getElementById('btn-play');
55 play.addEventListener('click', onPlay);
56 play.addEventListener('pointerup', function (e)
57 {
58 // A touch-friendly path: some mobile browsers swallow the click
59 // after a slightly sloppy tap. Ignore the following click.
60 if (e.pointerType === 'touch' || e.pointerType === 'pen')
61 {
62 e.preventDefault();
63 onPlay();
64 }
65 });
66
67 game.preloadImagesThenStart(IMAGES, function ()
68 {
69 if (game.images.flame && game.images.flame.addAnimationCycle)
70 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
71 });
72
73 bindOnlineUi();
74};
75
76function onPlay ()
77{
78 if (app.mode === 'playing')
79 { return; }
80 startPlay();
81}
82
83function startPlay (opts)
84{
85 opts = opts || {};
86 hideEl('menu');
87 hideEl('game-over');
88 hideEl('online-panel');
89 hideEl('spectator');
90 hideEl('podium');
91 showEl('hud');
92
93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
94 var miss = opts.missChance;
95 if (typeof miss === 'number' && isFinite(miss))
96 { app.core = new GameCore(app.planet, Math.random, miss); }
97 else
98 { app.core = new GameCore(app.planet, Math.random); }
99 app.mode = 'playing';
100 app.online = !!opts.online;
101 app.gameOverShown = false;
102 app.eliminatedReported = false;
103 app.spectating = false;
104 app.sprites = Object.create(null);
105 app.flames = Object.create(null);
106 app.cells = [];
107 app.pointerId = null;
108 app.selectTween = null;
109
110 layout();
111 if (app.scene)
112 {
113 app.scene.destroy();
114 app.scene = null;
115 }
116 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
117 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
118 app.scene.renderBackground = true;
119 game.loadScene(app.scene);
120
121 buildCells();
122 app.manager = app.scene.addObject(makeManager());
123 if (!app.spectating)
124 { bindPointer(app.scene.canvas); }
125 refreshHud();
126 if (app.online)
127 { showEl('minis'); }
128 else
129 { hideEl('minis'); }
130}
131
132function teardownPlay ()
133{
134 unbindPointer();
135 if (app.scene)
136 {
137 app.scene.destroy();
138 app.scene = null;
139 }
140 app.manager = null;
141 app.core = null;
142 app.sprites = Object.create(null);
143 app.flames = Object.create(null);
144 app.cells = [];
145 app.selectTween = null;
146 app.pointerId = null;
147 app.gameOverShown = false;
148 hideEl('hud');
149 hideEl('game-over');
150 hideEl('spectator');
151 hideEl('minis');
152 if (typeof Online !== 'undefined')
153 { Online.clearFlights(); }
154}
155
156function returnToMenu ()
157{
158 if (app.online && typeof Online !== 'undefined')
159 {
160 // Online matches do not dump you back to the solo menu:
161 // elimination becomes spectating; a finished match shows the podium.
162 return;
163 }
164 teardownPlay();
165 app.mode = 'menu';
166 app.online = false;
167 showEl('menu');
168 var last = document.getElementById('last-score');
169 if (app.lastScore > 0)
170 {
171 last.hidden = false;
172 last.querySelector('strong').textContent = String(app.lastScore);
173 }
174}
175
176function buildCells ()
177{
178 if (!app.scene)
179 { return; }
180 var img = game.images.cell;
181 for (var row = 0; row < 13; row++)
182 {
183 for (var col = 0; col < 10; col++)
184 {
185 var obj = new GameObject(0, 0, img, 0);
186 placeTile(obj, col, row);
187 obj.renderer.alpha = 0.9;
188 app.scene.addObject(obj);
189 app.cells.push(obj);
190 }
191 }
192}
193
194function placeTile (obj, col, y)
195{
196 var t = app.tile;
197 obj.transform.position.x = col * t + t / 2;
198 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
199 obj.transform.size = { x: t, y: t };
200}
201
202function layout ()
203{
204 var vw = window.innerWidth || 320;
205 var vh = window.innerHeight || 480;
206 var safeTop = 0;
207 try
208 {
209 // env(safe-area) is a CSS thing; keep a conservative HUD height.
210 safeTop = 0;
211 }
212 catch (e) { /* ignore */ }
213 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
214 app.miniH = 0;
215 if (app.online)
216 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
217 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
218 var availW = Math.max(80, vw - margin * 2);
219 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
220 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
221 app.fieldW = app.tile * 10;
222 app.fieldH = app.tile * 13;
223 app.fieldX = Math.floor((vw - app.fieldW) / 2);
224 var topBand = app.hudH + app.miniH;
225 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
226 if (app.fieldY < topBand)
227 { app.fieldY = topBand; }
228 var minis = document.getElementById('minis');
229 if (minis)
230 {
231 minis.style.top = app.hudH + 'px';
232 minis.style.maxHeight = app.miniH + 'px';
233 }
234
235 if (app.scene)
236 {
237 app.scene.position.x = app.fieldX;
238 app.scene.position.y = app.fieldY;
239 app.scene.size.x = app.fieldW;
240 app.scene.size.y = app.fieldH;
241 }
242}
243
244function spriteFor (block)
245{
246 if (block.state === 'locked')
247 { return game.images.locked; }
248 if (block.color < 0)
249 { return game.images.gray; }
250 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
251}
252
253function syncSprites ()
254{
255 if (!app.core || !app.scene)
256 { return; }
257 var seen = Object.create(null);
258 var blocks = app.core.blocks;
259 for (var i = 0; i < blocks.length; i++)
260 {
261 var block = blocks[i];
262 seen[block.id] = true;
263 var obj = app.sprites[block.id];
264 if (!obj)
265 {
266 obj = new GameObject(0, 0, spriteFor(block), 2);
267 app.scene.addObject(obj);
268 app.sprites[block.id] = obj;
269 }
270 obj.renderer.sprite = spriteFor(block);
271 placeTile(obj, block.col, block.y);
272 applyBlockVisual(obj, block);
273 obj.renderer.visible = true;
274 obj.renderer.alpha = 1;
275
276 if (block.flame)
277 {
278 var flame = app.flames[block.id];
279 if (!flame)
280 {
281 flame = new GameObject(0, 0, game.images.flame, 1);
282 flame.renderer.setAnimation('burn', 0, 0.08);
283 app.scene.addObject(flame);
284 app.flames[block.id] = flame;
285 }
286 flame.renderer.visible = true;
287 var t = app.tile;
288 flame.transform.position.x = block.col * t + t / 2;
289 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
290 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
291 }
292 else if (app.flames[block.id])
293 { app.flames[block.id].renderer.visible = false; }
294 }
295
296 var ids = Object.keys(app.sprites);
297 for (var i = 0; i < ids.length; i++)
298 {
299 if (!seen[ids[i]])
300 {
301 app.sprites[ids[i]].destroy();
302 delete app.sprites[ids[i]];
303 if (app.flames[ids[i]])
304 {
305 app.flames[ids[i]].destroy();
306 delete app.flames[ids[i]];
307 }
308 }
309 }
310}
311
312function applyBlockVisual (obj, block)
313{
314 var t = app.tile;
315 var sx = 1;
316 var sy = 1;
317 var dy = 0;
318 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
319 && typeof Easing !== 'undefined' && Easing.bouncePose)
320 {
321 var u = block.bounceAge / app.planet.bounceDuration;
322 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
323 sx = pose.sx;
324 sy = pose.sy;
325 dy = pose.dy;
326 }
327 var sel = 1;
328 var tw = app.selectTween;
329 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
330 { sel = tw.scale; }
331 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
332 if (dy)
333 { obj.transform.position.y -= dy * t; }
334}
335
336function clickTween ()
337{
338 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
339}
340
341function startPressTween (blockId)
342{
343 var c = clickTween();
344 if (!c)
345 { return; }
346 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
347 app.selectTween = {
348 blockId: blockId,
349 from: from,
350 to: c.pressScale,
351 t: 0,
352 duration: c.pressDuration,
353 ease: c.pressEase,
354 scale: from,
355 phase: 'press'
356 };
357}
358
359function startReleaseTween ()
360{
361 var c = clickTween();
362 var tw = app.selectTween;
363 if (!c || !tw || tw.phase === 'idle')
364 { return; }
365 app.selectTween = {
366 blockId: tw.blockId,
367 from: tw.scale,
368 to: c.releaseScale,
369 t: 0,
370 duration: c.releaseDuration,
371 ease: c.releaseEase,
372 scale: tw.scale,
373 phase: 'release'
374 };
375}
376
377function updateSelectTween (dt)
378{
379 var tw = app.selectTween;
380 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
381 { return; }
382 tw.t += dt;
383 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
384 if (u >= 1)
385 {
386 tw.scale = tw.to;
387 tw.t = tw.duration;
388 if (tw.phase === 'press')
389 { tw.phase = 'hold'; }
390 else
391 {
392 tw.phase = 'idle';
393 tw.scale = 1;
394 tw.blockId = null;
395 }
396 return;
397 }
398 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
399 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
400}
401
402function refreshHud ()
403{
404 if (!app.core)
405 { return; }
406 document.getElementById('score').textContent = String(app.core.score);
407 var planet = app.planet;
408 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
409 var d = Planet.displayValues(planet);
410 document.getElementById('planet-stats').textContent =
411 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
412 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
413}
414
415function makeManager ()
416{
417 var obj = new GameObject(0, 0, game.images.pixel, 0);
418 obj.renderer.visible = false;
419 var base = obj.update.bind(obj);
420 obj.update = function (dt)
421 {
422 base(dt);
423 tickView(dt);
424 };
425 return obj;
426}
427
428function tickView (dt)
429{
430 if (app.mode !== 'playing' || !app.core)
431 { return; }
432
433 layout();
434 for (var i = 0; i < app.cells.length; i++)
435 {
436 var col = i % 10;
437 var row = Math.floor(i / 10);
438 placeTile(app.cells[i], col, row);
439 }
440
441 app.core.tick(dt);
442 updateSelectTween(dt);
443 syncSprites();
444 refreshHud();
445 tickOnline(dt);
446
447 if (app.core.state === 'gameover' && !app.gameOverShown)
448 {
449 app.gameOverShown = true;
450 app.lastScore = app.core.score;
451 document.getElementById('go-score').textContent = String(app.lastScore);
452 if (app.online)
453 { onOnlineEliminated(); }
454 else
455 { showEl('game-over'); }
456 }
457 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
458 { returnToMenu(); }
459}
460
461/* ---------- pointer input (mouse + touch) --------------------------- */
462/*
463 * Both mouse and touch use Pointer Events. After pointerdown we listen
464 * on window, so a drag that leaves the canvas (needed to launch a
465 * block at the top of a full column) still reaches moveDrag. We do
466 * not treat lostpointercapture as the end of a drag: on some touch
467 * browsers that fires mid-gesture and would cancel a launch.
468 */
469
470var boundCanvas = null;
471var windowListening = false;
472
473function addWindowPointer ()
474{
475 if (windowListening)
476 { return; }
477 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
478 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
479 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
480 windowListening = true;
481}
482
483function removeWindowPointer ()
484{
485 if (!windowListening)
486 { return; }
487 window.removeEventListener('pointermove', onPointerMove, { capture: true });
488 window.removeEventListener('pointerup', onPointerUp, { capture: true });
489 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
490 windowListening = false;
491}
492
493function bindPointer (canvas)
494{
495 unbindPointer();
496 boundCanvas = canvas;
497 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
498 canvas.style.touchAction = 'none';
499 canvas.style.cursor = 'pointer';
500 canvas.style.webkitUserSelect = 'none';
501 canvas.style.userSelect = 'none';
502}
503
504function unbindPointer ()
505{
506 removeWindowPointer();
507 if (boundCanvas)
508 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
509 boundCanvas = null;
510 app.pointerId = null;
511}
512
513function fieldFromEvent (e)
514{
515 var canvas = app.scene && app.scene.canvas;
516 if (!canvas)
517 { return null; }
518 var rect = canvas.getBoundingClientRect();
519 if (rect.width <= 0 || rect.height <= 0)
520 { return null; }
521 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
522 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
523 // Fractional column so beginDrag can snap across a nearby edge.
524 var col = x / app.tile;
525 var fieldY = (canvas.height - y) / app.tile;
526 return { col: col, y: fieldY };
527}
528
529function onPointerDown (e)
530{
531 if (!app.core || app.core.state !== 'playing')
532 { return; }
533 if (app.pointerId != null)
534 { return; }
535 e.preventDefault();
536 app.pointerId = e.pointerId;
537 try
538 { boundCanvas.setPointerCapture(e.pointerId); }
539 catch (err) { /* ignore */ }
540 addWindowPointer();
541 var pos = fieldFromEvent(e);
542 // Instant grab, no long-press or hold delay: the block is taken on
543 // pointerdown and the click tween starts in the same moment.
544 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
545 { startPressTween(app.core.drag.blockId); }
546}
547
548function onPointerMove (e)
549{
550 if (app.pointerId == null || e.pointerId !== app.pointerId)
551 { return; }
552 if (!app.core || !app.core.drag)
553 { return; }
554 e.preventDefault();
555 var pos = fieldFromEvent(e);
556 if (pos)
557 { app.core.moveDrag(pos.y); }
558}
559
560function onPointerUp (e)
561{
562 if (app.pointerId == null)
563 { return; }
564 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
565 { return; }
566 if (e)
567 { e.preventDefault(); }
568 app.pointerId = null;
569 removeWindowPointer();
570 if (boundCanvas)
571 {
572 try
573 { boundCanvas.releasePointerCapture(e && e.pointerId); }
574 catch (err) { /* ignore */ }
575 }
576 startReleaseTween();
577 if (app.core)
578 { app.core.endDrag(); }
579}
580
581function hideEl (id)
582{
583 document.getElementById(id).hidden = true;
584}
585
586function showEl (id)
587{
588 document.getElementById(id).hidden = false;
589}
590
591window.addEventListener('resize', function ()
592{
593 if (app.mode === 'playing')
594 { layout(); }
595});
596
597window.addEventListener('orientationchange', function ()
598{
599 setTimeout(function ()
600 {
601 if (app.mode === 'playing')
602 { layout(); }
603 }, 120);
604});
605
606/* ---------- online play (stage 2) ---------------------------------- */
607
608function tickOnline (dt)
609{
610 if (!app.online || typeof Online === 'undefined')
611 { return; }
612 if (app.core)
613 {
614 var shots = app.core.consumeOutgoingShots();
615 for (var i = 0; i < shots.length; i++)
616 {
617 var s = shots[i];
618 var start = fieldToViewport(s.col, s.y + 1);
619 Online.rememberFlightLocal(s, start.x, start.y);
620 }
621 Online.queueShots(shots);
622 }
623 Online.tickFlights();
624 Online.renderMinis(document.getElementById('minis'));
625}
626
627function fieldToViewport (col, fieldY)
628{
629 var canvas = app.scene && app.scene.canvas;
630 if (!canvas)
631 { return { x: window.innerWidth / 2, y: 40 }; }
632 var rect = canvas.getBoundingClientRect();
633 var x = rect.left + ((col + 0.5) / 10) * rect.width;
634 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
635 return { x: x, y: y };
636}
637
638function onlinePayload ()
639{
640 if (!app.online || !app.core)
641 { return {}; }
642 return {
643 snapshot: app.core.fieldSnapshot(),
644 score: app.core.score,
645 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
646 };
647}
648
649function onOnlineEliminated ()
650{
651 app.eliminatedReported = true;
652 app.spectating = true;
653 unbindPointer();
654 hideEl('game-over');
655 var lobby = typeof Online !== 'undefined' && Online.lobby;
656 if (lobby && lobby.status === 'finished')
657 {
658 showPodium(lobby);
659 return;
660 }
661 showEl('spectator');
662}
663
664function showPodium (lobby)
665{
666 hideEl('spectator');
667 hideEl('game-over');
668 hideEl('online-panel');
669 showEl('podium');
670 var list = document.getElementById('podium-list');
671 list.innerHTML = '';
672 var ranks = (lobby && lobby.rankings) || [];
673 for (var i = 0; i < ranks.length; i++)
674 {
675 var r = ranks[i];
676 var li = document.createElement('li');
677 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
678 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
679 list.appendChild(li);
680 }
681 var hint = document.getElementById('podium-hint');
682 var secs = (lobby && lobby.podium_seconds) || 5;
683 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
684}
685
686function startOnlineMatch ()
687{
688 if (app.mode === 'playing' && app.online)
689 { return; }
690 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
691 ? Online.lobby.miss_chance
692 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
693 startPlay({ online: true, missChance: miss });
694 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
696}
697
698function leaveOnlineMatch (goMenu)
699{
700 if (typeof Online !== 'undefined')
701 {
702 Online.stopPolling();
703 Online.leaveLobby();
704 Online.clearFlights();
705 }
706 teardownPlay();
707 app.online = false;
708 if (goMenu)
709 {
710 app.mode = 'menu';
711 showEl('menu');
712 }
713 else
714 {
715 app.mode = 'online';
716 openOnlinePanel();
717 }
718}
719
720function bindOnlineUi ()
721{
722 var onlineBtn = document.getElementById('btn-online');
723 if (!onlineBtn)
724 { return; }
725 onlineBtn.addEventListener('click', function ()
726 { openOnlinePanel(); });
727
728 var backs = document.querySelectorAll('[data-back-menu]');
729 for (var i = 0; i < backs.length; i++)
730 {
731 backs[i].addEventListener('click', function ()
732 {
733 if (typeof Online !== 'undefined')
734 { Online.stopPolling(); }
735 hideEl('online-panel');
736 app.mode = 'menu';
737 app.online = false;
738 showEl('menu');
739 });
740 }
741
742 document.getElementById('btn-create').addEventListener('click', function ()
743 {
744 Online.createLobby().then(function (data)
745 {
746 if (data && data.ok)
747 {
748 renderOnline();
749 Online.startPolling(onlinePayload);
750 }
751 else
752 { renderOnline(); }
753 });
754 });
755
756 document.getElementById('join-form').addEventListener('submit', function (e)
757 {
758 e.preventDefault();
759 var code = (document.getElementById('join-code').value || '').trim();
760 if (!code)
761 { return; }
762 Online.joinLobby(code).then(function ()
763 {
764 renderOnline();
765 if (Online.lobby)
766 { Online.startPolling(onlinePayload); }
767 });
768 });
769
770 document.getElementById('btn-ready').addEventListener('click', function ()
771 {
772 var me = Online.mePlayer();
773 Online.setReady(!(me && me.ready)).then(renderOnline);
774 });
775
776 document.getElementById('btn-start').addEventListener('click', function ()
777 {
778 Online.startGame().then(function (data)
779 {
780 if (data && data.ok)
781 { startOnlineMatch(); }
782 else
783 { renderOnline(); }
784 });
785 });
786
787 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
788 {
789 Online.leaveLobby().then(function ()
790 {
791 Online.stopPolling();
792 renderOnline();
793 });
794 });
795
796 document.getElementById('btn-copy-code').addEventListener('click', function ()
797 {
798 var code = document.getElementById('lobby-code').textContent;
799 if (navigator.clipboard && navigator.clipboard.writeText)
800 { navigator.clipboard.writeText(code); }
801 });
802
803 document.getElementById('btn-spectate').addEventListener('click', function ()
804 {
805 hideEl('spectator');
806 app.spectating = true;
807 });
808
809 document.getElementById('btn-leave-game').addEventListener('click', function ()
810 { leaveOnlineMatch(false); });
811
812 if (typeof Online !== 'undefined')
813 {
814 Online.onChange = function ()
815 { renderOnline(); };
816 Online.onGameStart = function ()
817 { startOnlineMatch(); };
818 Online.onIncoming = function (incoming)
819 {
820 if (!app.core || app.core.state !== 'playing')
821 { return; }
822 for (var i = 0; i < incoming.length; i++)
823 { app.core.ingestGarbage(); }
824 };
825 Online.onFinished = function (lobby)
826 { showPodium(lobby); };
827 Online.onLobbyReturn = function (lobby)
828 {
829 teardownPlay();
830 app.online = false;
831 app.mode = 'online';
832 hideEl('podium');
833 showEl('online-panel');
834 renderOnline();
835 Online.startPolling(onlinePayload);
836 };
837 }
838
839 var params = new URLSearchParams(window.location.search);
840 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
841 { openOnlinePanel(); }
842}
843
844function openOnlinePanel ()
845{
846 hideEl('menu');
847 hideEl('game-over');
848 hideEl('podium');
849 hideEl('spectator');
850 showEl('online-panel');
851 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
853 if (typeof Online === 'undefined')
854 {
855 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
856 showOnly('online-unconfigured');
857 return;
858 }
859 Online.refresh().then(function (data)
860 {
861 if (!data || data.ok === false)
862 {
863 var msg = (data && data.error) || 'Geen verbinding met de server.';
864 showOnlineError(msg + ' Je kunt wel alleen spelen.');
865 if (data && data.configured === false)
866 { showOnly('online-unconfigured'); }
867 else
868 { showOnly('online-login'); }
869 document.getElementById('btn-login').style.display = 'none';
870 return;
871 }
872 renderOnline();
873 if (Online.lobby)
874 { Online.startPolling(onlinePayload); }
875 });
876}
877
878function setOnlineStatus (text)
879{
880 var el = document.getElementById('online-status');
881 if (el)
882 { el.textContent = text; }
883}
884
885function showOnlineError (text)
886{
887 var el = document.getElementById('online-error');
888 if (!el)
889 { return; }
890 if (!text)
891 {
892 el.hidden = true;
893 el.textContent = '';
894 return;
895 }
896 el.hidden = false;
897 el.textContent = text;
898}
899
900function showOnly (id)
901{
902 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
903 for (var i = 0; i < ids.length; i++)
904 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
905}
906
907function renderOnline ()
908{
909 if (typeof Online === 'undefined')
910 { return; }
911 if (app.mode === 'playing' && app.online)
912 {
913 Online.renderMinis(document.getElementById('minis'));
914 if (Online.lobby && Online.lobby.status === 'finished')
915 { showPodium(Online.lobby); }
916 return;
917 }
918 showOnlineError(Online.error);
919 if (!Online.configured && !Online.me && !Online.local)
920 {
921 setOnlineStatus('Online spelen is nog niet ingesteld.');
922 showOnly('online-unconfigured');
923 return;
924 }
925 if (!Online.me)
926 {
927 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
928 showOnly('online-login');
929 document.getElementById('btn-login').style.display = '';
930 document.getElementById('btn-login').href = Online.loginUrl();
931 document.getElementById('local-login').hidden = !Online.local;
932 return;
933 }
934 if (Online.lobby)
935 {
936 setOnlineStatus('Lobby');
937 showOnly('online-lobby');
938 document.getElementById('lobby-me-name').textContent = Online.me.name;
939 document.getElementById('lobby-code').textContent = Online.lobby.code;
940 var list = document.getElementById('lobby-players');
941 list.innerHTML = '';
942 var players = Online.lobby.players || [];
943 for (var i = 0; i < players.length; i++)
944 {
945 var p = players[i];
946 var li = document.createElement('li');
947 if (p.is_me)
948 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
954 }
955 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
958 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
959 start.disabled = !Online.lobby.can_start;
960 var hint = document.getElementById('lobby-hint');
961 if (Online.lobby.status === 'playing')
962 { hint.textContent = 'Het spel start…'; }
963 else if (players.length < 2)
964 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
965 else if (!Online.lobby.all_ready)
966 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
967 else if (Online.lobby.can_start)
968 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
969 else
970 { hint.textContent = 'Wachten tot de host start.'; }
971 return;
972 }
973 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
974 showOnly('online-home');
975 document.getElementById('me-name').textContent = Online.me.name;
976 document.getElementById('local-login').hidden = !Online.local;
977}
978
979function escapeText (s)
980{
981 return String(s)
982 .replace(/&/g, '&amp;')
983 .replace(/</g, '&lt;')
984 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
986}