'use strict'; /** * View and input for Meteors. The simulation lives in GameCore; this file * only draws it, scales it to the viewport, and translates pointer events * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired * through Online (src/online.js) and the same GameCore. */ var IMAGES = [ { name: 'ember', url: 'images/block-ember.png' }, { name: 'aqua', url: 'images/block-aqua.png' }, { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'sun', url: 'images/block-sun.png' }, { name: 'orchid', url: 'images/block-orchid.png' }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, { name: 'cell', url: 'images/cell.png' }, { name: 'pixel', url: 'images/pixel.png' } ]; var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; var GAME_OVER_DELAY = 2; var game = new Game(); var app = { mode: 'menu', core: null, scene: null, manager: null, planet: null, lastScore: 0, tile: 48, fieldX: 0, fieldY: 0, fieldW: 0, fieldH: 0, hudH: 56, sprites: Object.create(null), flames: Object.create(null), cells: [], pointerId: null, gameOverShown: false, selectTween: null, online: false, eliminatedReported: false, spectating: false, miniH: 0 }; window.onload = function () { var play = document.getElementById('btn-play'); play.addEventListener('click', onPlay); play.addEventListener('pointerup', function (e) { // A touch-friendly path: some mobile browsers swallow the click // after a slightly sloppy tap. Ignore the following click. if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onPlay(); } }); game.preloadImagesThenStart(IMAGES, function () { if (game.images.flame && game.images.flame.addAnimationCycle) { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); } }); bindOnlineUi(); }; function onPlay () { if (app.mode === 'playing') { return; } startPlay(); } function startPlay (opts) { opts = opts || {}; hideEl('menu'); hideEl('game-over'); hideEl('online-panel'); hideEl('spectator'); hideEl('podium'); showEl('hud'); app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet()); var miss = opts.missChance; if (typeof miss === 'number' && isFinite(miss)) { app.core = new GameCore(app.planet, Math.random, miss); } else { app.core = new GameCore(app.planet, Math.random); } app.mode = 'playing'; app.online = !!opts.online; app.gameOverShown = false; app.eliminatedReported = false; app.spectating = false; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.pointerId = null; app.selectTween = null; layout(); if (app.scene) { app.scene.destroy(); app.scene = null; } app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH); app.scene.backgroundColor = { r: 12, g: 16, b: 32 }; app.scene.renderBackground = true; game.loadScene(app.scene); buildCells(); app.manager = app.scene.addObject(makeManager()); if (!app.spectating) { bindPointer(app.scene.canvas); } refreshHud(); if (app.online) { showEl('minis'); } else { hideEl('minis'); } } function teardownPlay () { unbindPointer(); if (app.scene) { app.scene.destroy(); app.scene = null; } app.manager = null; app.core = null; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.selectTween = null; app.pointerId = null; app.gameOverShown = false; hideEl('hud'); hideEl('game-over'); hideEl('spectator'); hideEl('minis'); if (typeof Online !== 'undefined') { Online.clearFlights(); } } function returnToMenu () { if (app.online && typeof Online !== 'undefined') { // Online matches do not dump you back to the solo menu: // elimination becomes spectating; a finished match shows the podium. return; } teardownPlay(); app.mode = 'menu'; app.online = false; showEl('menu'); var last = document.getElementById('last-score'); if (app.lastScore > 0) { last.hidden = false; last.querySelector('strong').textContent = String(app.lastScore); } } function buildCells () { if (!app.scene) { return; } var img = game.images.cell; for (var row = 0; row < 13; row++) { for (var col = 0; col < 10; col++) { var obj = new GameObject(0, 0, img, 0); placeTile(obj, col, row); obj.renderer.alpha = 0.9; app.scene.addObject(obj); app.cells.push(obj); } } } function placeTile (obj, col, y) { var t = app.tile; obj.transform.position.x = col * t + t / 2; obj.transform.position.y = app.fieldH - (y + 0.5) * t; obj.transform.size = { x: t, y: t }; } function layout () { var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var safeTop = 0; try { // env(safe-area) is a CSS thing; keep a conservative HUD height. safeTop = 0; } catch (e) { /* ignore */ } app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop); app.miniH = 0; if (app.online) { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); } var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015)); var availW = Math.max(80, vw - margin * 2); var availH = Math.max(80, vh - app.hudH - app.miniH - margin); app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13))); app.fieldW = app.tile * 10; app.fieldH = app.tile * 13; app.fieldX = Math.floor((vw - app.fieldW) / 2); var topBand = app.hudH + app.miniH; app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2); if (app.fieldY < topBand) { app.fieldY = topBand; } var minis = document.getElementById('minis'); if (minis) { minis.style.top = app.hudH + 'px'; minis.style.maxHeight = app.miniH + 'px'; } if (app.scene) { app.scene.position.x = app.fieldX; app.scene.position.y = app.fieldY; app.scene.size.x = app.fieldW; app.scene.size.y = app.fieldH; } } function spriteFor (block) { if (block.state === 'locked') { return game.images.locked; } if (block.color < 0) { return game.images.gray; } return game.images[COLOR_SPRITES[block.color]] || game.images.gray; } function syncSprites () { if (!app.core || !app.scene) { return; } var seen = Object.create(null); var blocks = app.core.blocks; for (var i = 0; i < blocks.length; i++) { var block = blocks[i]; seen[block.id] = true; var obj = app.sprites[block.id]; if (!obj) { obj = new GameObject(0, 0, spriteFor(block), 2); app.scene.addObject(obj); app.sprites[block.id] = obj; } obj.renderer.sprite = spriteFor(block); placeTile(obj, block.col, block.y); applyBlockVisual(obj, block); obj.renderer.visible = true; obj.renderer.alpha = 1; if (block.flame) { var flame = app.flames[block.id]; if (!flame) { flame = new GameObject(0, 0, game.images.flame, 1); flame.renderer.setAnimation('burn', 0, 0.08); app.scene.addObject(flame); app.flames[block.id] = flame; } flame.renderer.visible = true; var t = app.tile; flame.transform.position.x = block.col * t + t / 2; flame.transform.position.y = app.fieldH - block.y * t + t * 0.15; flame.transform.size = { x: t * 0.85, y: t * 0.85 }; } else if (app.flames[block.id]) { app.flames[block.id].renderer.visible = false; } } var ids = Object.keys(app.sprites); for (var i = 0; i < ids.length; i++) { if (!seen[ids[i]]) { app.sprites[ids[i]].destroy(); delete app.sprites[ids[i]]; if (app.flames[ids[i]]) { app.flames[ids[i]].destroy(); delete app.flames[ids[i]]; } } } } function applyBlockVisual (obj, block) { var t = app.tile; var sx = 1; var sy = 1; var dy = 0; if (block.bouncing && app.planet && app.planet.bounceDuration > 0 && typeof Easing !== 'undefined' && Easing.bouncePose) { var u = block.bounceAge / app.planet.bounceDuration; var pose = Easing.bouncePose(u, app.planet.bounceSquash); sx = pose.sx; sy = pose.sy; dy = pose.dy; } var sel = 1; var tw = app.selectTween; if (tw && tw.blockId === block.id && tw.phase !== 'idle') { sel = tw.scale; } obj.transform.size = { x: t * sx * sel, y: t * sy * sel }; if (dy) { obj.transform.position.y -= dy * t; } } function clickTween () { return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null; } function startPressTween (blockId) { var c = clickTween(); if (!c) { return; } var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1; app.selectTween = { blockId: blockId, from: from, to: c.pressScale, t: 0, duration: c.pressDuration, ease: c.pressEase, scale: from, phase: 'press' }; } function startReleaseTween () { var c = clickTween(); var tw = app.selectTween; if (!c || !tw || tw.phase === 'idle') { return; } app.selectTween = { blockId: tw.blockId, from: tw.scale, to: c.releaseScale, t: 0, duration: c.releaseDuration, ease: c.releaseEase, scale: tw.scale, phase: 'release' }; } function updateSelectTween (dt) { var tw = app.selectTween; if (!tw || tw.phase === 'idle' || tw.phase === 'hold') { return; } tw.t += dt; var u = tw.duration > 0 ? tw.t / tw.duration : 1; if (u >= 1) { tw.scale = tw.to; tw.t = tw.duration; if (tw.phase === 'press') { tw.phase = 'hold'; } else { tw.phase = 'idle'; tw.scale = 1; tw.blockId = null; } return; } var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack); tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u; } function refreshHud () { if (!app.core) { return; } document.getElementById('score').textContent = String(app.core.score); var planet = app.planet; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; var d = Planet.displayValues(planet); document.getElementById('planet-stats').textContent = 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%'; } function makeManager () { var obj = new GameObject(0, 0, game.images.pixel, 0); obj.renderer.visible = false; var base = obj.update.bind(obj); obj.update = function (dt) { base(dt); tickView(dt); }; return obj; } function tickView (dt) { if (app.mode !== 'playing' || !app.core) { return; } layout(); for (var i = 0; i < app.cells.length; i++) { var col = i % 10; var row = Math.floor(i / 10); placeTile(app.cells[i], col, row); } app.core.tick(dt); updateSelectTween(dt); syncSprites(); refreshHud(); tickOnline(dt); if (app.core.state === 'gameover' && !app.gameOverShown) { app.gameOverShown = true; app.lastScore = app.core.score; document.getElementById('go-score').textContent = String(app.lastScore); if (app.online) { onOnlineEliminated(); } else { showEl('game-over'); } } if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) { returnToMenu(); } } /* ---------- pointer input (mouse + touch) --------------------------- */ /* * Both mouse and touch use Pointer Events. After pointerdown we listen * on window, so a drag that leaves the canvas (needed to launch a * block at the top of a full column) still reaches moveDrag. We do * not treat lostpointercapture as the end of a drag: on some touch * browsers that fires mid-gesture and would cancel a launch. */ var boundCanvas = null; var windowListening = false; function addWindowPointer () { if (windowListening) { return; } window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false }); window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false }); window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false }); windowListening = true; } function removeWindowPointer () { if (!windowListening) { return; } window.removeEventListener('pointermove', onPointerMove, { capture: true }); window.removeEventListener('pointerup', onPointerUp, { capture: true }); window.removeEventListener('pointercancel', onPointerUp, { capture: true }); windowListening = false; } function bindPointer (canvas) { unbindPointer(); boundCanvas = canvas; canvas.addEventListener('pointerdown', onPointerDown, { passive: false }); canvas.style.touchAction = 'none'; canvas.style.cursor = 'pointer'; canvas.style.webkitUserSelect = 'none'; canvas.style.userSelect = 'none'; } function unbindPointer () { removeWindowPointer(); if (boundCanvas) { boundCanvas.removeEventListener('pointerdown', onPointerDown); } boundCanvas = null; app.pointerId = null; } function fieldFromEvent (e) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return null; } var rect = canvas.getBoundingClientRect(); if (rect.width <= 0 || rect.height <= 0) { return null; } var x = (e.clientX - rect.left) * (canvas.width / rect.width); var y = (e.clientY - rect.top) * (canvas.height / rect.height); // Fractional column so beginDrag can snap across a nearby edge. var col = x / app.tile; var fieldY = (canvas.height - y) / app.tile; return { col: col, y: fieldY }; } function onPointerDown (e) { if (!app.core || app.core.state !== 'playing') { return; } if (app.pointerId != null) { return; } e.preventDefault(); app.pointerId = e.pointerId; try { boundCanvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } addWindowPointer(); var pos = fieldFromEvent(e); // Instant grab, no long-press or hold delay: the block is taken on // pointerdown and the click tween starts in the same moment. if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag) { startPressTween(app.core.drag.blockId); } } function onPointerMove (e) { if (app.pointerId == null || e.pointerId !== app.pointerId) { return; } if (!app.core || !app.core.drag) { return; } e.preventDefault(); var pos = fieldFromEvent(e); if (pos) { app.core.moveDrag(pos.y); } } function onPointerUp (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (e) { e.preventDefault(); } app.pointerId = null; removeWindowPointer(); if (boundCanvas) { try { boundCanvas.releasePointerCapture(e && e.pointerId); } catch (err) { /* ignore */ } } startReleaseTween(); if (app.core) { app.core.endDrag(); } } function hideEl (id) { document.getElementById(id).hidden = true; } function showEl (id) { document.getElementById(id).hidden = false; } window.addEventListener('resize', function () { if (app.mode === 'playing') { layout(); } }); window.addEventListener('orientationchange', function () { setTimeout(function () { if (app.mode === 'playing') { layout(); } }, 120); }); /* ---------- online play (stage 2) ---------------------------------- */ function tickOnline (dt) { if (!app.online || typeof Online === 'undefined') { return; } if (app.core) { var shots = app.core.consumeOutgoingShots(); for (var i = 0; i < shots.length; i++) { var s = shots[i]; var start = fieldToViewport(s.col, s.y + 1); Online.rememberFlightLocal(s, start.x, start.y); } Online.queueShots(shots); } Online.tickFlights(); Online.renderMinis(document.getElementById('minis')); } function fieldToViewport (col, fieldY) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return { x: window.innerWidth / 2, y: 40 }; } var rect = canvas.getBoundingClientRect(); var x = rect.left + ((col + 0.5) / 10) * rect.width; var y = rect.top + (1 - (fieldY / 13)) * rect.height; return { x: x, y: y }; } function onlinePayload () { if (!app.online || !app.core) { return {}; } return { snapshot: app.core.fieldSnapshot(), score: app.core.score, eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported }; } function onOnlineEliminated () { app.eliminatedReported = true; app.spectating = true; unbindPointer(); hideEl('game-over'); var lobby = typeof Online !== 'undefined' && Online.lobby; if (lobby && lobby.status === 'finished') { showPodium(lobby); return; } showEl('spectator'); } function showPodium (lobby) { hideEl('spectator'); hideEl('game-over'); hideEl('online-panel'); showEl('podium'); var list = document.getElementById('podium-list'); list.innerHTML = ''; var ranks = (lobby && lobby.rankings) || []; for (var i = 0; i < ranks.length; i++) { var r = ranks[i]; var li = document.createElement('li'); var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e')); li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten'; list.appendChild(li); } var hint = document.getElementById('podium-hint'); var secs = (lobby && lobby.podium_seconds) || 5; hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…'; } function startOnlineMatch () { if (app.mode === 'playing' && app.online) { return; } var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null) ? Online.lobby.miss_chance : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30); startPlay({ online: true, missChance: miss }); if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } } function leaveOnlineMatch (goMenu) { if (typeof Online !== 'undefined') { Online.stopPolling(); Online.leaveLobby(); Online.clearFlights(); } teardownPlay(); app.online = false; if (goMenu) { app.mode = 'menu'; showEl('menu'); } else { app.mode = 'online'; openOnlinePanel(); } } function bindOnlineUi () { var onlineBtn = document.getElementById('btn-online'); if (!onlineBtn) { return; } onlineBtn.addEventListener('click', function () { openOnlinePanel(); }); var backs = document.querySelectorAll('[data-back-menu]'); for (var i = 0; i < backs.length; i++) { backs[i].addEventListener('click', function () { if (typeof Online !== 'undefined') { Online.stopPolling(); } hideEl('online-panel'); app.mode = 'menu'; app.online = false; showEl('menu'); }); } document.getElementById('btn-create').addEventListener('click', function () { Online.createLobby().then(function (data) { if (data && data.ok) { renderOnline(); Online.startPolling(onlinePayload); } else { renderOnline(); } }); }); document.getElementById('join-form').addEventListener('submit', function (e) { e.preventDefault(); var code = (document.getElementById('join-code').value || '').trim(); if (!code) { return; } Online.joinLobby(code).then(function () { renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); }); document.getElementById('btn-ready').addEventListener('click', function () { var me = Online.mePlayer(); Online.setReady(!(me && me.ready)).then(renderOnline); }); document.getElementById('btn-start').addEventListener('click', function () { Online.startGame().then(function (data) { if (data && data.ok) { startOnlineMatch(); } else { renderOnline(); } }); }); document.getElementById('btn-leave-lobby').addEventListener('click', function () { Online.leaveLobby().then(function () { Online.stopPolling(); renderOnline(); }); }); document.getElementById('btn-copy-code').addEventListener('click', function () { var code = document.getElementById('lobby-code').textContent; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(code); } }); document.getElementById('btn-spectate').addEventListener('click', function () { hideEl('spectator'); app.spectating = true; }); document.getElementById('btn-leave-game').addEventListener('click', function () { leaveOnlineMatch(false); }); if (typeof Online !== 'undefined') { Online.onChange = function () { renderOnline(); }; Online.onGameStart = function () { startOnlineMatch(); }; Online.onIncoming = function (incoming) { if (!app.core || app.core.state !== 'playing') { return; } for (var i = 0; i < incoming.length; i++) { app.core.ingestGarbage(); } }; Online.onFinished = function (lobby) { showPodium(lobby); }; Online.onLobbyReturn = function (lobby) { teardownPlay(); app.online = false; app.mode = 'online'; hideEl('podium'); showEl('online-panel'); renderOnline(); Online.startPolling(onlinePayload); }; } var params = new URLSearchParams(window.location.search); if (params.get('online') === '1' || params.get('auth') === 'unconfigured') { openOnlinePanel(); } } function openOnlinePanel () { hideEl('menu'); hideEl('game-over'); hideEl('podium'); hideEl('spectator'); showEl('online-panel'); app.mode = 'online'; setOnlineStatus('Even kijken of online spelen beschikbaar is…'); if (typeof Online === 'undefined') { showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.'); showOnly('online-unconfigured'); return; } Online.refresh().then(function (data) { if (!data || data.ok === false) { var msg = (data && data.error) || 'Geen verbinding met de server.'; showOnlineError(msg + ' Je kunt wel alleen spelen.'); if (data && data.configured === false) { showOnly('online-unconfigured'); } else { showOnly('online-login'); } document.getElementById('btn-login').style.display = 'none'; return; } renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); } function setOnlineStatus (text) { var el = document.getElementById('online-status'); if (el) { el.textContent = text; } } function showOnlineError (text) { var el = document.getElementById('online-error'); if (!el) { return; } if (!text) { el.hidden = true; el.textContent = ''; return; } el.hidden = false; el.textContent = text; } function showOnly (id) { var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby']; for (var i = 0; i < ids.length; i++) { document.getElementById(ids[i]).hidden = (ids[i] !== id); } } function renderOnline () { if (typeof Online === 'undefined') { return; } if (app.mode === 'playing' && app.online) { Online.renderMinis(document.getElementById('minis')); if (Online.lobby && Online.lobby.status === 'finished') { showPodium(Online.lobby); } return; } showOnlineError(Online.error); if (!Online.configured && !Online.me && !Online.local) { setOnlineStatus('Online spelen is nog niet ingesteld.'); showOnly('online-unconfigured'); return; } if (!Online.me) { setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.'); showOnly('online-login'); document.getElementById('btn-login').style.display = ''; document.getElementById('btn-login').href = Online.loginUrl(); document.getElementById('local-login').hidden = !Online.local; return; } if (Online.lobby) { setOnlineStatus('Lobby'); showOnly('online-lobby'); document.getElementById('lobby-me-name').textContent = Online.me.name; document.getElementById('lobby-code').textContent = Online.lobby.code; var list = document.getElementById('lobby-players'); list.innerHTML = ''; var players = Online.lobby.players || []; for (var i = 0; i < players.length; i++) { var p = players[i]; var li = document.createElement('li'); if (p.is_me) { li.classList.add('you'); } var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var state = p.ready ? 'Gereed' : 'Wacht…'; li.innerHTML = '' + escapeText(label) + '' + state + ''; list.appendChild(li); } var me = Online.mePlayer(); document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; var start = document.getElementById('btn-start'); start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id); start.disabled = !Online.lobby.can_start; var hint = document.getElementById('lobby-hint'); if (Online.lobby.status === 'playing') { hint.textContent = 'Het spel start…'; } else if (players.length < 2) { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; } else if (!Online.lobby.all_ready) { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; } else if (Online.lobby.can_start) { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; } else { hint.textContent = 'Wachten tot de host start.'; } return; } setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.'); showOnly('online-home'); document.getElementById('me-name').textContent = Online.me.name; document.getElementById('local-login').hidden = !Online.local; } function escapeText (s) { return String(s) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); }