'use strict'; /** * Online play: talks to api.php (cookie session), polls lobby and game * state, and draws opponent miniatures plus flying-block tweens. * Real-time sync is not required; a 0.75 s poll is enough. */ var Online = { POLL_MS: 750, DEFAULT_MISS_CHANCE: 0.30, FLIGHT_DURATION: 1.2, configured: false, local: false, csrf: '', me: null, lobby: null, incoming: [], shotResults: [], error: '', _timer: null, _pendingShots: [], _flights: [], _lastStatus: null, onChange: null, onGameStart: null, onIncoming: null, onFinished: null, onLobbyReturn: null }; Online._headers = function (json) { var h = { 'Accept': 'application/json' }; if (json) { h['Content-Type'] = 'application/json'; } if (this.csrf) { h['X-CSRF-Token'] = this.csrf; } return h; }; Online._apply = function (data) { if (!data) { return; } if (typeof data.configured === 'boolean') { this.configured = data.configured; } if (typeof data.local === 'boolean') { this.local = data.local; } if (data.csrf) { this.csrf = data.csrf; } if (data.me !== undefined) { this.me = data.me; } if (data.lobby !== undefined) { this.lobby = data.lobby; } if (data.incoming) { this.incoming = data.incoming; } if (data.shot_results) { this.shotResults = data.shot_results; } if (data.miss_chance_default != null) { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; } if (data.flight_duration != null) { this.FLIGHT_DURATION = data.flight_duration; } if (data.error) { this.error = data.error; } else if (data.ok) { this.error = ''; } }; Online.request = function (action, body) { var self = this; var isGet = action === 'me' || action === ''; var url = 'api.php?action=' + encodeURIComponent(action || 'me'); var opts = { method: isGet && !body ? 'GET' : 'POST', credentials: 'same-origin', headers: this._headers(!!body || !isGet) }; if (opts.method === 'POST') { var payload = body ? Object.assign({ action: action }, body) : { action: action }; opts.body = JSON.stringify(payload); } return fetch(url, opts).then(function (res) { return res.json().then(function (data) { data = data || {}; if (!res.ok && !data.error) { data.error = 'De server gaf ' + res.status; data.ok = false; } self._apply(data); return data; }, function () { var fail = { ok: false, error: 'Geen geldig antwoord van de server.' }; self.error = fail.error; return fail; }); }).catch(function (err) { var fail = { ok: false, error: 'Geen verbinding met de server.' }; self.error = fail.error; return fail; }); }; Online.refresh = function () { return this.request('me'); }; Online.testLogin = function (who) { return this.request('test_login', { user: who }); }; Online.createLobby = function () { return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE }); }; Online.joinLobby = function (code) { return this.request('lobby_join', { code: code }); }; Online.leaveLobby = function () { return this.request('lobby_leave'); }; Online.setReady = function (ready) { return this.request('lobby_ready', { ready: !!ready }); }; Online.startGame = function () { var self = this; var prev = this.lobby && this.lobby.status; return this.request('lobby_start').then(function (data) { self._handleTransitions(prev, data); return data; }); }; Online.queueShots = function (shots) { for (var i = 0; i < shots.length; i++) { this._pendingShots.push({ client_id: String(shots[i].id), color: shots[i].color, col: shots[i].col, y: shots[i].y }); } }; Online.poll = function (opts) { opts = opts || {}; var body = {}; if (opts.snapshot) { body.snapshot = opts.snapshot; } if (opts.score != null) { body.score = opts.score; } if (opts.eliminated) { body.eliminated = true; } if (this._pendingShots.length) { body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length); } var self = this; var prevStatus = this.lobby && this.lobby.status; return this.request('poll', body).then(function (data) { self._handleTransitions(prevStatus, data); if (self.onChange) { self.onChange(self); } return data; }); }; Online._handleTransitions = function (prevStatus, data) { var lobby = this.lobby; var status = lobby && lobby.status; if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart) { this.onGameStart(lobby); } if (data && data.incoming && data.incoming.length && this.onIncoming) { this.onIncoming(data.incoming); } if (data && data.shot_results && data.shot_results.length) { this.spawnFlights(data.shot_results, this._lastQueuedMeta); } if (status === 'finished' && prevStatus !== 'finished' && this.onFinished) { this.onFinished(lobby); } if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn) { this.onLobbyReturn(lobby); } }; Online.startPolling = function (getPayload) { this.stopPolling(); var self = this; var tick = function () { var payload = getPayload ? getPayload() : {}; self.poll(payload); }; tick(); this._timer = setInterval(tick, this.POLL_MS); }; Online.stopPolling = function () { if (this._timer) { clearInterval(this._timer); this._timer = null; } }; Online.loginUrl = function () { return 'auth.php'; }; Online.logoutUrl = function () { return 'logout.php'; }; Online.opponents = function () { if (!this.lobby || !this.lobby.players) { return []; } return this.lobby.players.filter(function (p) { return !p.is_me; }); }; Online.aliveOpponents = function () { return this.opponents().filter(function (p) { return !p.eliminated; }); }; Online.mePlayer = function () { if (!this.lobby || !this.lobby.players) { return null; } for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i]; } } return null; }; /* ---------- miniatures --------------------------------------------- */ Online.renderMinis = function (container) { if (!container) { return; } var opponents = this.opponents(); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < opponents.length; i++) { var p = opponents[i]; seen[p.id] = true; var el = existing[p.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', p.id); el.innerHTML = '
' + '' + '
'; container.appendChild(el); } el.classList.toggle('eliminated', !!p.eliminated); el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : ''); el.querySelector('.mini-meta').textContent = p.eliminated ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) : ('Punten ' + (p.score || 0)); this._drawMini(el.querySelector('canvas'), p.snapshot); } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } }; var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4']; Online._drawMini = function (canvas, snapshot) { if (!canvas) { return; } var ctx = canvas.getContext('2d'); var w = 10; var h = 13; var tw = canvas.width / w; var th = canvas.height / h; ctx.fillStyle = '#0c1020'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.lineWidth = 1; for (var c = 0; c <= w; c++) { ctx.beginPath(); ctx.moveTo(c * tw + 0.5, 0); ctx.lineTo(c * tw + 0.5, canvas.height); ctx.stroke(); } for (var r = 0; r <= h; r++) { ctx.beginPath(); ctx.moveTo(0, r * th + 0.5); ctx.lineTo(canvas.width, r * th + 0.5); ctx.stroke(); } if (!snapshot || !snapshot.blocks) { return; } var blocks = snapshot.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; var x = b.col * tw; var y = canvas.height - (b.y + 1) * th; if (b.state === 'locked') { ctx.fillStyle = '#3a3d4a'; } else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } else { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }; Online.miniElement = function (playerId) { return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]'); }; /* ---------- flight tweens ------------------------------------------ */ function colorSpriteUrl (color) { if (color < 0) { return 'images/block-gray.png'; } var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; return 'images/block-' + (names[color] || 'gray') + '.png'; } /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY} in viewport pixels, filled by the view just after * consumeOutgoingShots. */ Online.spawnFlights = function (results, locals) { locals = locals || this._flightLocals || {}; var layer = document.getElementById('flights'); if (!layer) { return; } for (var i = 0; i < results.length; i++) { var r = results[i]; var meta = locals[r.client_id] || {}; var start = this._flightStart(meta.col); var end; var miss = !!r.miss; if (miss) { end = this._missEnd(start); } else { end = this._targetEnd(r.target_id, start); } var el = document.createElement('img'); el.src = colorSpriteUrl(r.color != null ? r.color : meta.color); el.alt = ''; el.className = 'flight'; layer.appendChild(el); var spin = (Math.random() * 2 - 1) * 720; var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000; this._flights.push({ el: el, start: start, end: end, ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end), t0: performance.now(), duration: duration, spin: spin, miss: miss, angle: Math.random() * 360 }); } this._flightLocals = {}; }; Online.rememberFlightLocal = function (shot, startX, startY) { if (!this._flightLocals) { this._flightLocals = {}; } this._flightLocals[String(shot.id)] = { col: shot.col, y: shot.y, color: shot.color, startX: startX, startY: startY }; }; Online._flightStart = function (col) { var field = document.querySelector('canvas'); var appRef = typeof app !== 'undefined' ? app : null; if (appRef && appRef.scene && appRef.scene.canvas) { var canvas = appRef.scene.canvas; var rect = canvas.getBoundingClientRect(); var c = col == null ? 4.5 : col; return { x: rect.left + (c + 0.5) * (rect.width / 10), y: rect.top + 4 }; } if (field) { var rect = field.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top }; } return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 }; }; Online._targetEnd = function (targetId, start) { var el = targetId && this.miniElement(targetId); if (el) { var r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; } return { x: start.x + (Math.random() - 0.5) * 80, y: 40 }; }; Online._missEnd = function (start) { var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35; return { x: start.x + dx, y: start.y - (120 + Math.random() * 220) }; }; Online._missCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160, y: Math.min(start.y, end.y) - 40 - Math.random() * 80 }; }; Online._hitCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40, y: (start.y + end.y) / 2 - 30 }; }; Online.tickFlights = function (now) { now = now || performance.now(); var leftover = []; for (var i = 0; i < this._flights.length; i++) { var f = this._flights[i]; var u = (now - f.t0) / f.duration; if (u >= 1) { if (f.el && f.el.parentNode) { f.el.parentNode.removeChild(f.el); } continue; } // Quadratic bezier, ease-in so they feel like they recede. var e = u * u; var mt = 1 - e; var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x; var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y; var scale = f.miss ? (1 - e) : (1 - 0.85 * e); var angle = f.angle + f.spin * u; f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate(' + angle + 'deg) scale(' + scale + ')'; f.el.style.opacity = f.miss ? String(1 - e) : '1'; leftover.push(f); } this._flights = leftover; }; Online.clearFlights = function () { for (var i = 0; i < this._flights.length; i++) { var el = this._flights[i].el; if (el && el.parentNode) { el.parentNode.removeChild(el); } } this._flights = []; this._flightLocals = {}; }; if (typeof globalThis !== 'undefined') { globalThis.Online = Online; } if (typeof module !== 'undefined' && module.exports) { module.exports = Online; }