BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 12.5 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lobby: null,
18 incoming: [],
19 shotResults: [],
20 error: '',
21 _timer: null,
22 _pendingShots: [],
23 _flights: [],
24 _lastStatus: null,
25 onChange: null,
26 onGameStart: null,
27 onIncoming: null,
28 onFinished: null,
29 onLobbyReturn: null
30};
31
32Online._headers = function (json)
33{
34 var h = { 'Accept': 'application/json' };
35 if (json)
36 { h['Content-Type'] = 'application/json'; }
37 if (this.csrf)
38 { h['X-CSRF-Token'] = this.csrf; }
39 return h;
40};
41
42Online._apply = function (data)
43{
44 if (!data)
45 { return; }
46 if (typeof data.configured === 'boolean')
47 { this.configured = data.configured; }
48 if (typeof data.local === 'boolean')
49 { this.local = data.local; }
50 if (data.csrf)
51 { this.csrf = data.csrf; }
52 if (data.me !== undefined)
53 { this.me = data.me; }
54 if (data.lobby !== undefined)
55 { this.lobby = data.lobby; }
56 if (data.incoming)
57 { this.incoming = data.incoming; }
58 if (data.shot_results)
59 { this.shotResults = data.shot_results; }
60 if (data.miss_chance_default != null)
61 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
62 if (data.flight_duration != null)
63 { this.FLIGHT_DURATION = data.flight_duration; }
64 if (data.error)
65 { this.error = data.error; }
66 else if (data.ok)
67 { this.error = ''; }
68};
69
70Online.request = function (action, body)
71{
72 var self = this;
73 var isGet = action === 'me' || action === '';
74 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
75 var opts = {
76 method: isGet && !body ? 'GET' : 'POST',
77 credentials: 'same-origin',
78 headers: this._headers(!!body || !isGet)
79 };
80 if (opts.method === 'POST')
81 {
82 var payload = body ? Object.assign({ action: action }, body) : { action: action };
83 opts.body = JSON.stringify(payload);
84 }
85 return fetch(url, opts).then(function (res)
86 {
87 return res.json().then(function (data)
88 {
89 data = data || {};
90 if (!res.ok && !data.error)
91 { data.error = 'De server gaf ' + res.status; data.ok = false; }
92 self._apply(data);
93 return data;
94 }, function ()
95 {
96 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
97 self.error = fail.error;
98 return fail;
99 });
100 }).catch(function (err)
101 {
102 var fail = { ok: false, error: 'Geen verbinding met de server.' };
103 self.error = fail.error;
104 return fail;
105 });
106};
107
108Online.refresh = function ()
109{
110 return this.request('me');
111};
112
113Online.testLogin = function (who)
114{
115 return this.request('test_login', { user: who });
116};
117
118Online.createLobby = function ()
119{
120 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
121};
122
123Online.joinLobby = function (code)
124{
125 return this.request('lobby_join', { code: code });
126};
127
128Online.leaveLobby = function ()
129{
130 return this.request('lobby_leave');
131};
132
133Online.setReady = function (ready)
134{
135 return this.request('lobby_ready', { ready: !!ready });
136};
137
138Online.startGame = function ()
139{
140 var self = this;
141 var prev = this.lobby && this.lobby.status;
142 return this.request('lobby_start').then(function (data)
143 {
144 self._handleTransitions(prev, data);
145 return data;
146 });
147};
148
149Online.queueShots = function (shots)
150{
151 for (var i = 0; i < shots.length; i++)
152 {
153 this._pendingShots.push({
154 client_id: String(shots[i].id),
155 color: shots[i].color,
156 col: shots[i].col,
157 y: shots[i].y
158 });
159 }
160};
161
162Online.poll = function (opts)
163{
164 opts = opts || {};
165 var body = {};
166 if (opts.snapshot)
167 { body.snapshot = opts.snapshot; }
168 if (opts.score != null)
169 { body.score = opts.score; }
170 if (opts.eliminated)
171 { body.eliminated = true; }
172 if (this._pendingShots.length)
173 {
174 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
175 }
176 var self = this;
177 var prevStatus = this.lobby && this.lobby.status;
178 return this.request('poll', body).then(function (data)
179 {
180 self._handleTransitions(prevStatus, data);
181 if (self.onChange)
182 { self.onChange(self); }
183 return data;
184 });
185};
186
187Online._handleTransitions = function (prevStatus, data)
188{
189 var lobby = this.lobby;
190 var status = lobby && lobby.status;
191 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
192 { this.onGameStart(lobby); }
193 if (data && data.incoming && data.incoming.length && this.onIncoming)
194 { this.onIncoming(data.incoming); }
195 if (data && data.shot_results && data.shot_results.length)
196 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
197 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
198 { this.onFinished(lobby); }
199 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
200 { this.onLobbyReturn(lobby); }
201};
202
203Online.startPolling = function (getPayload)
204{
205 this.stopPolling();
206 var self = this;
207 var tick = function ()
208 {
209 var payload = getPayload ? getPayload() : {};
210 self.poll(payload);
211 };
212 tick();
213 this._timer = setInterval(tick, this.POLL_MS);
214};
215
216Online.stopPolling = function ()
217{
218 if (this._timer)
219 {
220 clearInterval(this._timer);
221 this._timer = null;
222 }
223};
224
225Online.loginUrl = function ()
226{
227 return 'auth.php';
228};
229
230Online.logoutUrl = function ()
231{
232 return 'logout.php';
233};
234
235Online.opponents = function ()
236{
237 if (!this.lobby || !this.lobby.players)
238 { return []; }
239 return this.lobby.players.filter(function (p) { return !p.is_me; });
240};
241
242Online.aliveOpponents = function ()
243{
244 return this.opponents().filter(function (p) { return !p.eliminated; });
245};
246
247Online.mePlayer = function ()
248{
249 if (!this.lobby || !this.lobby.players)
250 { return null; }
251 for (var i = 0; i < this.lobby.players.length; i++)
252 {
253 if (this.lobby.players[i].is_me)
254 { return this.lobby.players[i]; }
255 }
256 return null;
257};
258
259/* ---------- miniatures --------------------------------------------- */
260
261Online.renderMinis = function (container)
262{
263 if (!container)
264 { return; }
265 var opponents = this.opponents();
266 var existing = {};
267 var kids = container.querySelectorAll('[data-player]');
268 for (var i = 0; i < kids.length; i++)
269 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
270
271 var seen = Object.create(null);
272 for (var i = 0; i < opponents.length; i++)
273 {
274 var p = opponents[i];
275 seen[p.id] = true;
276 var el = existing[p.id];
277 if (!el)
278 {
279 el = document.createElement('div');
280 el.className = 'mini';
281 el.setAttribute('data-player', p.id);
282 el.innerHTML = '<div class="mini-name"></div>'
283 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
284 + '<div class="mini-meta"></div>';
285 container.appendChild(el);
286 }
287 el.classList.toggle('eliminated', !!p.eliminated);
288 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
289 el.querySelector('.mini-meta').textContent = p.eliminated
290 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
291 : ('Punten ' + (p.score || 0));
292 this._drawMini(el.querySelector('canvas'), p.snapshot);
293 }
294 for (var id in existing)
295 {
296 if (!seen[id])
297 { existing[id].remove(); }
298 }
299};
300
301var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
302
303Online._drawMini = function (canvas, snapshot)
304{
305 if (!canvas)
306 { return; }
307 var ctx = canvas.getContext('2d');
308 var w = 10;
309 var h = 13;
310 var tw = canvas.width / w;
311 var th = canvas.height / h;
312 ctx.fillStyle = '#0c1020';
313 ctx.fillRect(0, 0, canvas.width, canvas.height);
314 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
315 ctx.lineWidth = 1;
316 for (var c = 0; c <= w; c++)
317 {
318 ctx.beginPath();
319 ctx.moveTo(c * tw + 0.5, 0);
320 ctx.lineTo(c * tw + 0.5, canvas.height);
321 ctx.stroke();
322 }
323 for (var r = 0; r <= h; r++)
324 {
325 ctx.beginPath();
326 ctx.moveTo(0, r * th + 0.5);
327 ctx.lineTo(canvas.width, r * th + 0.5);
328 ctx.stroke();
329 }
330 if (!snapshot || !snapshot.blocks)
331 { return; }
332 var blocks = snapshot.blocks;
333 for (var i = 0; i < blocks.length; i++)
334 {
335 var b = blocks[i];
336 var x = b.col * tw;
337 var y = canvas.height - (b.y + 1) * th;
338 if (b.state === 'locked')
339 { ctx.fillStyle = '#3a3d4a'; }
340 else if (b.color < 0)
341 { ctx.fillStyle = '#5a5d66'; }
342 else
343 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
344 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
345 }
346};
347
348Online.miniElement = function (playerId)
349{
350 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
351};
352
353/* ---------- flight tweens ------------------------------------------ */
354
355function colorSpriteUrl (color)
356{
357 if (color < 0)
358 { return 'images/block-gray.png'; }
359 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
360 return 'images/block-' + (names[color] || 'gray') + '.png';
361}
362
363/**
364 * Animate shot results. `locals` is a map of client_id → {col, y, color,
365 * startX, startY} in viewport pixels, filled by the view just after
366 * consumeOutgoingShots.
367 */
368Online.spawnFlights = function (results, locals)
369{
370 locals = locals || this._flightLocals || {};
371 var layer = document.getElementById('flights');
372 if (!layer)
373 { return; }
374 for (var i = 0; i < results.length; i++)
375 {
376 var r = results[i];
377 var meta = locals[r.client_id] || {};
378 var start = this._flightStart(meta.col);
379 var end;
380 var miss = !!r.miss;
381 if (miss)
382 { end = this._missEnd(start); }
383 else
384 { end = this._targetEnd(r.target_id, start); }
385 var el = document.createElement('img');
386 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
387 el.alt = '';
388 el.className = 'flight';
389 layer.appendChild(el);
390 var spin = (Math.random() * 2 - 1) * 720;
391 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
392 this._flights.push({
393 el: el,
394 start: start,
395 end: end,
396 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
397 t0: performance.now(),
398 duration: duration,
399 spin: spin,
400 miss: miss,
401 angle: Math.random() * 360
402 });
403 }
404 this._flightLocals = {};
405};
406
407Online.rememberFlightLocal = function (shot, startX, startY)
408{
409 if (!this._flightLocals)
410 { this._flightLocals = {}; }
411 this._flightLocals[String(shot.id)] = {
412 col: shot.col,
413 y: shot.y,
414 color: shot.color,
415 startX: startX,
416 startY: startY
417 };
418};
419
420Online._flightStart = function (col)
421{
422 var field = document.querySelector('canvas');
423 var appRef = typeof app !== 'undefined' ? app : null;
424 if (appRef && appRef.scene && appRef.scene.canvas)
425 {
426 var canvas = appRef.scene.canvas;
427 var rect = canvas.getBoundingClientRect();
428 var c = col == null ? 4.5 : col;
429 return {
430 x: rect.left + (c + 0.5) * (rect.width / 10),
431 y: rect.top + 4
432 };
433 }
434 if (field)
435 {
436 var rect = field.getBoundingClientRect();
437 return { x: rect.left + rect.width / 2, y: rect.top };
438 }
439 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
440};
441
442Online._targetEnd = function (targetId, start)
443{
444 var el = targetId && this.miniElement(targetId);
445 if (el)
446 {
447 var r = el.getBoundingClientRect();
448 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
449 }
450 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
451};
452
453Online._missEnd = function (start)
454{
455 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
456 return {
457 x: start.x + dx,
458 y: start.y - (120 + Math.random() * 220)
459 };
460};
461
462Online._missCtrl = function (start, end)
463{
464 return {
465 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
466 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
467 };
468};
469
470Online._hitCtrl = function (start, end)
471{
472 return {
473 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
474 y: (start.y + end.y) / 2 - 30
475 };
476};
477
478Online.tickFlights = function (now)
479{
480 now = now || performance.now();
481 var leftover = [];
482 for (var i = 0; i < this._flights.length; i++)
483 {
484 var f = this._flights[i];
485 var u = (now - f.t0) / f.duration;
486 if (u >= 1)
487 {
488 if (f.el && f.el.parentNode)
489 { f.el.parentNode.removeChild(f.el); }
490 continue;
491 }
492 // Quadratic bezier, ease-in so they feel like they recede.
493 var e = u * u;
494 var mt = 1 - e;
495 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
496 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
497 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
498 var angle = f.angle + f.spin * u;
499 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
500 + angle + 'deg) scale(' + scale + ')';
501 f.el.style.opacity = f.miss ? String(1 - e) : '1';
502 leftover.push(f);
503 }
504 this._flights = leftover;
505};
506
507Online.clearFlights = function ()
508{
509 for (var i = 0; i < this._flights.length; i++)
510 {
511 var el = this._flights[i].el;
512 if (el && el.parentNode)
513 { el.parentNode.removeChild(el); }
514 }
515 this._flights = [];
516 this._flightLocals = {};
517};
518
519if (typeof globalThis !== 'undefined')
520{ globalThis.Online = Online; }
521if (typeof module !== 'undefined' && module.exports)
522{ module.exports = Online; }