BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 12.3 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 return this.request('lobby_start');
141};
142
143Online.queueShots = function (shots)
144{
145 for (var i = 0; i < shots.length; i++)
146 {
147 this._pendingShots.push({
148 client_id: String(shots[i].id),
149 color: shots[i].color,
150 col: shots[i].col,
151 y: shots[i].y
152 });
153 }
154};
155
156Online.poll = function (opts)
157{
158 opts = opts || {};
159 var body = {};
160 if (opts.snapshot)
161 { body.snapshot = opts.snapshot; }
162 if (opts.score != null)
163 { body.score = opts.score; }
164 if (opts.eliminated)
165 { body.eliminated = true; }
166 if (this._pendingShots.length)
167 {
168 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
169 }
170 var self = this;
171 var prevStatus = this.lobby && this.lobby.status;
172 return this.request('poll', body).then(function (data)
173 {
174 self._handleTransitions(prevStatus, data);
175 if (self.onChange)
176 { self.onChange(self); }
177 return data;
178 });
179};
180
181Online._handleTransitions = function (prevStatus, data)
182{
183 var lobby = this.lobby;
184 var status = lobby && lobby.status;
185 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
186 { this.onGameStart(lobby); }
187 if (data && data.incoming && data.incoming.length && this.onIncoming)
188 { this.onIncoming(data.incoming); }
189 if (data && data.shot_results && data.shot_results.length)
190 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
191 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
192 { this.onFinished(lobby); }
193 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
194 { this.onLobbyReturn(lobby); }
195};
196
197Online.startPolling = function (getPayload)
198{
199 this.stopPolling();
200 var self = this;
201 var tick = function ()
202 {
203 var payload = getPayload ? getPayload() : {};
204 self.poll(payload);
205 };
206 tick();
207 this._timer = setInterval(tick, this.POLL_MS);
208};
209
210Online.stopPolling = function ()
211{
212 if (this._timer)
213 {
214 clearInterval(this._timer);
215 this._timer = null;
216 }
217};
218
219Online.loginUrl = function ()
220{
221 return 'auth.php';
222};
223
224Online.logoutUrl = function ()
225{
226 return 'logout.php';
227};
228
229Online.opponents = function ()
230{
231 if (!this.lobby || !this.lobby.players)
232 { return []; }
233 return this.lobby.players.filter(function (p) { return !p.is_me; });
234};
235
236Online.aliveOpponents = function ()
237{
238 return this.opponents().filter(function (p) { return !p.eliminated; });
239};
240
241Online.mePlayer = function ()
242{
243 if (!this.lobby || !this.lobby.players)
244 { return null; }
245 for (var i = 0; i < this.lobby.players.length; i++)
246 {
247 if (this.lobby.players[i].is_me)
248 { return this.lobby.players[i]; }
249 }
250 return null;
251};
252
253/* ---------- miniatures --------------------------------------------- */
254
255Online.renderMinis = function (container)
256{
257 if (!container)
258 { return; }
259 var opponents = this.opponents();
260 var existing = {};
261 var kids = container.querySelectorAll('[data-player]');
262 for (var i = 0; i < kids.length; i++)
263 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
264
265 var seen = Object.create(null);
266 for (var i = 0; i < opponents.length; i++)
267 {
268 var p = opponents[i];
269 seen[p.id] = true;
270 var el = existing[p.id];
271 if (!el)
272 {
273 el = document.createElement('div');
274 el.className = 'mini';
275 el.setAttribute('data-player', p.id);
276 el.innerHTML = '<div class="mini-name"></div>'
277 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
278 + '<div class="mini-meta"></div>';
279 container.appendChild(el);
280 }
281 el.classList.toggle('eliminated', !!p.eliminated);
282 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
283 el.querySelector('.mini-meta').textContent = p.eliminated
284 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
285 : ('Punten ' + (p.score || 0));
286 this._drawMini(el.querySelector('canvas'), p.snapshot);
287 }
288 for (var id in existing)
289 {
290 if (!seen[id])
291 { existing[id].remove(); }
292 }
293};
294
295var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
296
297Online._drawMini = function (canvas, snapshot)
298{
299 if (!canvas)
300 { return; }
301 var ctx = canvas.getContext('2d');
302 var w = 10;
303 var h = 13;
304 var tw = canvas.width / w;
305 var th = canvas.height / h;
306 ctx.fillStyle = '#0c1020';
307 ctx.fillRect(0, 0, canvas.width, canvas.height);
308 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
309 ctx.lineWidth = 1;
310 for (var c = 0; c <= w; c++)
311 {
312 ctx.beginPath();
313 ctx.moveTo(c * tw + 0.5, 0);
314 ctx.lineTo(c * tw + 0.5, canvas.height);
315 ctx.stroke();
316 }
317 for (var r = 0; r <= h; r++)
318 {
319 ctx.beginPath();
320 ctx.moveTo(0, r * th + 0.5);
321 ctx.lineTo(canvas.width, r * th + 0.5);
322 ctx.stroke();
323 }
324 if (!snapshot || !snapshot.blocks)
325 { return; }
326 var blocks = snapshot.blocks;
327 for (var i = 0; i < blocks.length; i++)
328 {
329 var b = blocks[i];
330 var x = b.col * tw;
331 var y = canvas.height - (b.y + 1) * th;
332 if (b.state === 'locked')
333 { ctx.fillStyle = '#3a3d4a'; }
334 else if (b.color < 0)
335 { ctx.fillStyle = '#5a5d66'; }
336 else
337 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
338 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
339 }
340};
341
342Online.miniElement = function (playerId)
343{
344 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
345};
346
347/* ---------- flight tweens ------------------------------------------ */
348
349function colorSpriteUrl (color)
350{
351 if (color < 0)
352 { return 'images/block-gray.png'; }
353 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
354 return 'images/block-' + (names[color] || 'gray') + '.png';
355}
356
357/**
358 * Animate shot results. `locals` is a map of client_id → {col, y, color,
359 * startX, startY} in viewport pixels, filled by the view just after
360 * consumeOutgoingShots.
361 */
362Online.spawnFlights = function (results, locals)
363{
364 locals = locals || this._flightLocals || {};
365 var layer = document.getElementById('flights');
366 if (!layer)
367 { return; }
368 for (var i = 0; i < results.length; i++)
369 {
370 var r = results[i];
371 var meta = locals[r.client_id] || {};
372 var start = this._flightStart(meta.col);
373 var end;
374 var miss = !!r.miss;
375 if (miss)
376 { end = this._missEnd(start); }
377 else
378 { end = this._targetEnd(r.target_id, start); }
379 var el = document.createElement('img');
380 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
381 el.alt = '';
382 el.className = 'flight';
383 layer.appendChild(el);
384 var spin = (Math.random() * 2 - 1) * 720;
385 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
386 this._flights.push({
387 el: el,
388 start: start,
389 end: end,
390 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
391 t0: performance.now(),
392 duration: duration,
393 spin: spin,
394 miss: miss,
395 angle: Math.random() * 360
396 });
397 }
398 this._flightLocals = {};
399};
400
401Online.rememberFlightLocal = function (shot, startX, startY)
402{
403 if (!this._flightLocals)
404 { this._flightLocals = {}; }
405 this._flightLocals[String(shot.id)] = {
406 col: shot.col,
407 y: shot.y,
408 color: shot.color,
409 startX: startX,
410 startY: startY
411 };
412};
413
414Online._flightStart = function (col)
415{
416 var field = document.querySelector('canvas');
417 var appRef = typeof app !== 'undefined' ? app : null;
418 if (appRef && appRef.scene && appRef.scene.canvas)
419 {
420 var canvas = appRef.scene.canvas;
421 var rect = canvas.getBoundingClientRect();
422 var c = col == null ? 4.5 : col;
423 return {
424 x: rect.left + (c + 0.5) * (rect.width / 10),
425 y: rect.top + 4
426 };
427 }
428 if (field)
429 {
430 var rect = field.getBoundingClientRect();
431 return { x: rect.left + rect.width / 2, y: rect.top };
432 }
433 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
434};
435
436Online._targetEnd = function (targetId, start)
437{
438 var el = targetId && this.miniElement(targetId);
439 if (el)
440 {
441 var r = el.getBoundingClientRect();
442 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
443 }
444 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
445};
446
447Online._missEnd = function (start)
448{
449 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
450 return {
451 x: start.x + dx,
452 y: start.y - (120 + Math.random() * 220)
453 };
454};
455
456Online._missCtrl = function (start, end)
457{
458 return {
459 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
460 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
461 };
462};
463
464Online._hitCtrl = function (start, end)
465{
466 return {
467 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
468 y: (start.y + end.y) / 2 - 30
469 };
470};
471
472Online.tickFlights = function (now)
473{
474 now = now || performance.now();
475 var leftover = [];
476 for (var i = 0; i < this._flights.length; i++)
477 {
478 var f = this._flights[i];
479 var u = (now - f.t0) / f.duration;
480 if (u >= 1)
481 {
482 if (f.el && f.el.parentNode)
483 { f.el.parentNode.removeChild(f.el); }
484 continue;
485 }
486 // Quadratic bezier, ease-in so they feel like they recede.
487 var e = u * u;
488 var mt = 1 - e;
489 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
490 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
491 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
492 var angle = f.angle + f.spin * u;
493 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
494 + angle + 'deg) scale(' + scale + ')';
495 f.el.style.opacity = f.miss ? String(1 - e) : '1';
496 leftover.push(f);
497 }
498 this._flights = leftover;
499};
500
501Online.clearFlights = function ()
502{
503 for (var i = 0; i < this._flights.length; i++)
504 {
505 var el = this._flights[i].el;
506 if (el && el.parentNode)
507 { el.parentNode.removeChild(el); }
508 }
509 this._flights = [];
510 this._flightLocals = {};
511};
512
513if (typeof globalThis !== 'undefined')
514{ globalThis.Online = Online; }
515if (typeof module !== 'undefined' && module.exports)
516{ module.exports = Online; }