Duel arcade
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0a0d1f">
<title>Arcade</title>
<style>
:root {
--bg: #0a0d1f; --panel: #11152c; --edge: #232a52; --ink: #eef0ff; --dim: #8d94c2;
--p0: #d6ff3f; --p1: #ff4f9a; --cy: #56e8ff; --warn: #ffb347;
--chunk: "Arial Black", "Segoe UI Black", "Roboto Black", "Helvetica Neue", Roboto, system-ui, sans-serif;
--text: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body { margin: 0; background: var(--bg); color: var(--ink); }
body { font: 14px/1.35 var(--text); min-height: 100vh; overflow-x: hidden;
background:
radial-gradient(120% 60% at 50% 0%, rgba(86, 232, 255, .10), transparent 60%),
radial-gradient(90% 50% at 100% 100%, rgba(255, 79, 154, .10), transparent 65%),
radial-gradient(90% 50% at 0% 100%, rgba(214, 255, 63, .07), transparent 65%), var(--bg); }
#app { max-width: 480px; margin: 0 auto; display: flex; flex-direction: column; gap: 12px;
padding: calc(12px + env(safe-area-inset-top)) calc(16px + env(safe-area-inset-right)) calc(20px + env(safe-area-inset-bottom)) calc(16px + env(safe-area-inset-left)); }
/* ---- the title line ---- */
.top { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.logo { font: italic 900 23px/1 var(--chunk); letter-spacing: .5px; transform: skewX(-6deg); transform-origin: left;
background: linear-gradient(92deg, var(--p0) 0%, var(--cy) 55%, var(--p1) 100%); -webkit-background-clip: text; background-clip: text; color: transparent;
filter: drop-shadow(0 0 10px rgba(86, 232, 255, .35)); }
.where { font-size: 11px; color: var(--dim); letter-spacing: .6px; text-transform: uppercase; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.live { flex: none; display: flex; align-items: center; gap: 7px; font: 900 11px/1 var(--chunk); letter-spacing: 1.2px; padding: 8px 11px; border-radius: 999px;
border: 1.5px solid var(--edge); color: var(--dim); background: rgba(17, 21, 44, .7); }
.live i { width: 8px; height: 8px; border-radius: 50%; background: var(--dim); }
.live.on { color: var(--ink); border-color: rgba(255, 79, 154, .55); }
.live.on i { background: var(--p1); box-shadow: 0 0 10px var(--p1); animation: blink 1.1s steps(2, jump-none) infinite; }
@keyframes blink { 50% { opacity: .25; } }
/* ---- the score ---- */
.board { display: grid; grid-template-columns: 1fr auto auto auto 1fr; align-items: center; gap: 8px; padding: 12px 12px 11px; border-radius: 18px;
background: linear-gradient(180deg, rgba(27, 33, 68, .9), rgba(15, 18, 40, .9)); border: 1.5px solid var(--edge); position: relative; overflow: hidden; }
.board::before, .board::after { content: ""; position: absolute; top: 0; bottom: 0; width: 4px; }
.board::before { left: 0; background: var(--p0); box-shadow: 0 0 18px var(--p0); }
.board::after { right: 0; background: var(--p1); box-shadow: 0 0 18px var(--p1); }
.side { min-width: 0; padding-left: 6px; }
.side.s1 { text-align: right; padding: 0 6px 0 0; }
.side b { display: block; font: 900 18px/1.1 var(--chunk); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.side.s0 b { color: var(--p0); } .side.s1 b { color: var(--p1); }
.side span { display: block; font-size: 11.5px; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px; }
.side em { display: inline-block; font: normal 900 9px/1 var(--chunk); letter-spacing: 1px; margin-top: 6px; padding: 4px 6px; border-radius: 5px; color: var(--bg); background: var(--dim); white-space: nowrap; }
.side.s0 em.you { background: var(--p0); } .side.s1 em.you { background: var(--p1); }
.digit { display: block; height: 62px; width: auto; transform: skewX(-7deg); overflow: visible; }
.digit rect { fill: rgba(255, 255, 255, .055); transition: fill .12s; }
.digit.c0 rect.on { fill: var(--p0); } .digit.c1 rect.on { fill: var(--p1); }
.digit.c0 { filter: drop-shadow(0 0 9px rgba(214, 255, 63, .55)); } .digit.c1 { filter: drop-shadow(0 0 9px rgba(255, 79, 154, .6)); }
.digit.pop { animation: pop .55s cubic-bezier(.2, 1.6, .4, 1); }
@keyframes pop { 0% { transform: skewX(-7deg) scale(1.7) rotate(-6deg); } 100% { transform: skewX(-7deg) scale(1); } }
.mid { text-align: center; font: 900 10px/1.25 var(--chunk); letter-spacing: 1px; color: var(--dim); padding: 0 2px; }
.mid u { display: block; text-decoration: none; font-size: 20px; color: var(--ink); margin-bottom: 3px; }
/* ---- the playfield ---- */
.field { position: relative; width: 100%; aspect-ratio: 1; border-radius: 22px; overflow: hidden; border: 1.5px solid var(--edge);
background: radial-gradient(circle at 50% 50%, #10163a 0%, #080a1a 72%); }
.field canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.hud { position: absolute; top: 11px; font: 900 10.5px/1 var(--chunk); letter-spacing: 1.3px; color: var(--dim); pointer-events: none; }
.hud.l { left: 13px; } .hud.r { right: 13px; }
.hud b { color: var(--ink); font-weight: 900; }
.banner { position: absolute; left: 0; right: 0; top: 25%; text-align: center; pointer-events: none; opacity: 0; transform: translateY(-50%) scale(.6) skewX(-6deg);
transition: opacity .18s, transform .32s cubic-bezier(.2, 1.7, .4, 1); }
.banner.show { opacity: 1; transform: translateY(-50%) scale(1) skewX(-6deg); }
.banner b { display: block; font: italic 900 38px/1 var(--chunk); letter-spacing: 1px; color: var(--ink); padding: 0 14px; overflow-wrap: anywhere;
text-shadow: 0 0 22px currentColor, 0 3px 0 rgba(0, 0, 0, .55); }
.banner span { display: inline-block; margin-top: 9px; font: 900 11px/1 var(--chunk); letter-spacing: 1.6px; color: var(--ink); background: rgba(8, 10, 26, .78); padding: 7px 10px; border-radius: 7px; }
.banner.c0 b { color: var(--p0); } .banner.c1 b { color: var(--p1); } .banner.cc b { color: var(--cy); }
.call { position: absolute; left: 12px; right: 12px; bottom: 12px; padding: 11px 12px; border-radius: 12px; text-align: center; font: 900 13px/1.2 var(--chunk); letter-spacing: .8px;
color: var(--bg); background: var(--warn); box-shadow: 0 0 26px rgba(255, 179, 71, .7); opacity: 0; transform: translateY(16px); transition: opacity .2s, transform .25s; pointer-events: none; }
.call.show { opacity: 1; transform: none; animation: ring .5s steps(2, jump-none) 8; }
@keyframes ring { 50% { background: #fff3d6; } }
/* ---- the other cabinet and the connection ---- */
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.card { min-width: 0; border-radius: 16px; padding: 11px 12px 12px; background: rgba(17, 21, 44, .82); border: 1.5px solid var(--edge); }
.cap { font: 900 9.5px/1 var(--chunk); letter-spacing: 1.3px; color: var(--dim); text-transform: uppercase; margin-bottom: 9px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.rival { display: flex; align-items: center; gap: 9px; min-width: 0; }
.rival svg { flex: none; width: 30px; height: 30px; overflow: visible; filter: drop-shadow(0 0 6px currentColor); }
.rival div { min-width: 0; }
.rival b { display: block; font: 900 16px/1.1 var(--chunk); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.rival span { display: block; font-size: 11.5px; line-height: 1.3; color: var(--dim); overflow-wrap: anywhere; white-space: pre-line; }
.pill { display: inline-flex; align-items: center; gap: 6px; margin-top: 10px; font: 900 9.5px/1 var(--chunk); letter-spacing: 1px; padding: 5px 8px; border-radius: 6px; color: var(--dim); background: rgba(141, 148, 194, .14); max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pill i { flex: none; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.pill.good { color: var(--p0); background: rgba(214, 255, 63, .12); }
.pill.good i { box-shadow: 0 0 8px currentColor; }
.pill.warn { color: var(--warn); background: rgba(255, 179, 71, .13); }
.path { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.path b { font: italic 900 19px/1 var(--chunk); letter-spacing: .5px; color: var(--dim); white-space: nowrap; }
.path b.direct { color: var(--cy); text-shadow: 0 0 14px rgba(86, 232, 255, .6); }
.path b.relayed, .path b.local { color: var(--warn); }
.path span { font: 900 15px/1 var(--chunk); white-space: nowrap; }
.path span small { font: 900 9.5px/1 var(--chunk); color: var(--dim); letter-spacing: 1px; margin-left: 3px; }
.trace { display: block; width: 100%; height: 26px; margin-top: 8px; overflow: visible; }
.trace polyline { fill: none; stroke: var(--cy); stroke-width: 1.8; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; }
.trace line { stroke: var(--edge); stroke-width: 1; stroke-dasharray: 2 4; vector-effect: non-scaling-stroke; }
.note { font-size: 11px; color: var(--dim); margin-top: 6px; line-height: 1.3; }
/* ---- the challenge ---- */
.go { position: relative; display: block; width: 100%; border: 0; border-radius: 16px; padding: 17px 14px 16px; cursor: pointer; overflow: hidden;
font: italic 900 19px/1 var(--chunk); letter-spacing: 1px; color: #10130a; background: linear-gradient(180deg, #e9ff7a, var(--p0) 55%, #a8d61f);
box-shadow: 0 5px 0 #6f8f12, 0 10px 26px rgba(214, 255, 63, .28); transition: transform .08s, box-shadow .08s; white-space: nowrap; text-overflow: ellipsis; }
.go:active, .go.busy { transform: translateY(4px); box-shadow: 0 1px 0 #6f8f12, 0 4px 14px rgba(214, 255, 63, .25); }
.go::after { content: ""; position: absolute; top: 0; bottom: 0; width: 40%; left: -60%; background: linear-gradient(100deg, transparent, rgba(255, 255, 255, .65), transparent); animation: sweep 3.2s ease-in-out infinite; }
@keyframes sweep { 0%, 55% { left: -60%; } 100% { left: 130%; } }
.go.lit { color: #1c0a12; background: linear-gradient(180deg, #ffd0e4, var(--p1) 60%, #d92d78); box-shadow: 0 5px 0 #8e1c4e, 0 0 34px rgba(255, 79, 154, .7); animation: lit .45s steps(2, jump-none) 9; }
@keyframes lit { 50% { filter: brightness(1.35); } }
.said { min-height: 16px; text-align: center; font-size: 12px; color: var(--dim); margin-top: -4px; }
.said.bad { color: var(--warn); }
/* ---- the scoreboard of the two homes ---- */
.tally { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; }
.tally div { min-width: 0; }
.tally div:last-child { text-align: right; }
.tally b { display: block; font: 900 14px/1.15 var(--chunk); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tally span { font-size: 11.5px; color: var(--dim); }
.tally .nums { display: flex; align-items: center; gap: 7px; font: 900 16px/1 var(--chunk); color: var(--dim); }
.tally .nums .digits { display: flex; gap: 4px; }
.tally .digit { height: 34px; }
.split { display: flex; height: 8px; border-radius: 4px; overflow: hidden; margin: 12px 0 4px; background: var(--edge); gap: 3px; }
.split i { display: block; height: 100%; transition: flex-grow .6s cubic-bezier(.2, 1, .3, 1); min-width: 4px; }
.split i:first-child { background: var(--p0); box-shadow: 0 0 10px var(--p0); } .split i:last-child { background: var(--p1); box-shadow: 0 0 10px var(--p1); }
.games { list-style: none; margin: 8px 0 0; padding: 0; }
.games li { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 10px; padding: 9px 0; border-top: 1px solid rgba(35, 42, 82, .8); }
.games .res { font: 900 15px/1 var(--chunk); padding: 6px 8px; border-radius: 8px; white-space: nowrap; color: var(--bg); }
.games .w0 .res { background: var(--p0); } .games .w1 .res { background: var(--p1); }
.games .what { min-width: 0; }
.games .what b { display: block; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.games .what span, .games time { font-size: 11.5px; color: var(--dim); white-space: nowrap; }
.games .new { animation: slide .5s cubic-bezier(.2, 1.2, .4, 1); }
@keyframes slide { from { opacity: 0; transform: translateX(-18px); } }
.none { font-size: 12px; color: var(--dim); padding: 10px 0 0; }
@media (max-width: 359px) { .digit { height: 52px; } .side b { font-size: 16px; } .banner b { font-size: 31px; } .go { font-size: 17px; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; }
}
</style>
</head>
<body>
<div id="app">
<div class="top">
<div style="min-width:0">
<div class="logo" id="logo">RIMSHOCK</div>
<div class="where" id="where">Arcade cabinet</div>
</div>
<div class="live" id="live"><i></i><span id="liveText">CONNECTING</span></div>
</div>
<div class="board" aria-live="polite">
<div class="side s0"><b id="n0">Player one</b><span id="h0"> </span><em id="t0"> </em></div>
<svg class="digit c0" id="d0" viewBox="0 0 34 58" aria-hidden="true"></svg>
<div class="mid"><u>:</u>FIRST<br>TO <span id="target">5</span></div>
<svg class="digit c1" id="d1" viewBox="0 0 34 58" aria-hidden="true"></svg>
<div class="side s1"><b id="n1">Player two</b><span id="h1"> </span><em id="t1"> </em></div>
</div>
<div class="field">
<canvas id="cv" aria-label="The match as it is played"></canvas>
<div class="hud l">ROUND <b id="round">–</b></div>
<div class="hud r">PLATE <b id="rim">–</b></div>
<div class="banner" id="banner"><b id="bannerBig"></b><span id="bannerSmall"></span></div>
<div class="call" id="call"></div>
</div>
<div class="row">
<div class="card">
<div class="cap">Opponent</div>
<div class="rival" id="rival">
<svg viewBox="-16 -16 32 32" id="rivalMark" aria-hidden="true"></svg>
<div><b id="rivalName">–</b><span id="rivalWhere"> </span></div>
</div>
<div class="pill" id="rivalPill"><i></i><span>NOT CONNECTED</span></div>
<div class="note" id="rivalNote"> </div>
</div>
<div class="card">
<div class="cap">Cabinet link</div>
<div class="path"><b id="path">–</b><span><span id="rtt">–</span><small>MS</small></span></div>
<svg class="trace" viewBox="0 0 100 26" preserveAspectRatio="none" aria-hidden="true"><line x1="0" y1="25" x2="100" y2="25"/><polyline id="trace" points=""/></svg>
<div class="note" id="linkNote"> </div>
</div>
</div>
<button class="go" id="go" type="button">CHALLENGE</button>
<div class="said" id="said" role="status"> </div>
<div class="card">
<div class="cap">Matches won, home against home</div>
<div class="tally">
<div><b id="home0">Home one</b><span id="homeP0"> </span></div>
<div class="nums"><span class="digits" id="w0"></span>:<span class="digits" id="w1"></span></div>
<div><b id="home1">Home two</b><span id="homeP1"> </span></div>
</div>
<div class="split"><i id="split0" style="flex-grow:1"></i><i id="split1" style="flex-grow:1"></i></div>
<ul class="games" id="games"></ul>
<div class="none" id="none">No match has been played to the end yet.</div>
</div>
</div>
<script>
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
// The app's bridge (docs/device-ui): there in the Connectivitizer app, missing in a browser opened straight on the cabinet.
var bridge = window.connectivitizer && typeof window.connectivitizer.webSocket === 'function' ? window.connectivitizer : null;
var clamp = function (v, a, b) { return v < a ? a : v > b ? b : v; };
var COLOURS = ['#d6ff3f', '#ff4f9a'], CYAN = '#56e8ff';
var NS = 'http://www.w3.org/2000/svg';
/* ---------- what the cabinet said last ---------- */
var seat = 0; // which seat this cabinet has: 0 the host, 1 the guest
var players = [null, null];
var link = { connected: false, path: null, endToEndEncrypted: null, rttMs: null };
var snaps = []; // the last snapshots of the match, oldest first
var latest = null;
var clock = 0; // the game's time as this page follows it, seconds
var queued = []; // events waiting for the picture to reach their moment
var rtts = [];
var online = false;
/* ---------- chunky digits: a 3 by 5 grid of blocks ---------- */
var SHAPES = ['111101101101111', '010110010010111', '111001111100111', '111001111001111', '101101111001001',
'111100111001111', '111100111101111', '111001010010010', '111101111101111', '111101111001111'];
function buildDigit(svg) {
var cells = [];
for (var i = 0; i < 15; i++) {
var r = document.createElementNS(NS, 'rect');
r.setAttribute('x', (i % 3) * 12);
r.setAttribute('y', Math.floor(i / 3) * 12);
r.setAttribute('width', 10); r.setAttribute('height', 10); r.setAttribute('rx', 2.4);
svg.appendChild(r);
cells.push(r);
}
svg.czCells = cells;
svg.czValue = -1;
}
function setDigit(svg, value, pop) {
if (!svg.czCells) buildDigit(svg);
if (svg.czValue === value) return;
var changed = svg.czValue >= 0;
svg.czValue = value;
var shape = SHAPES[value] || SHAPES[0];
for (var i = 0; i < 15; i++) svg.czCells[i].setAttribute('class', shape.charAt(i) === '1' ? 'on' : '');
if (pop && changed && !reduced) {
svg.classList.remove('pop');
void svg.getBoundingClientRect();
svg.classList.add('pop');
}
}
function setNumber(holder, colour, value) {
var text = String(Math.max(0, Math.min(999, value | 0)));
while (holder.children.length < text.length) {
var svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', '0 0 34 58');
svg.setAttribute('class', 'digit c' + colour);
holder.appendChild(svg);
}
while (holder.children.length > text.length) holder.removeChild(holder.lastChild);
for (var i = 0; i < text.length; i++) setDigit(holder.children[i], Number(text.charAt(i)), true);
}
/* ---------- names, the other cabinet, the connection ---------- */
function nameOf(s) {
var p = players[s];
return (p && p.player) || (s === 0 ? 'Player one' : 'Player two');
}
function mark(svg, s) {
// The two skimmers: seat 0 is a dart, seat 1 a box.
svg.style.color = COLOURS[s];
svg.innerHTML = s === 0
? '<polygon points="13,0 -9,-10 -4,0 -9,10" fill="none" stroke="currentColor" stroke-width="3" stroke-linejoin="round"/>'
: '<rect x="-9" y="-9" width="18" height="18" rx="3" transform="rotate(45)" fill="none" stroke="currentColor" stroke-width="3"/><circle r="2.6" fill="currentColor"/>';
}
function showInfo() {
var other = 1 - seat, me = players[seat], them = players[other];
$('where').textContent = me && me.cabinet ? me.cabinet + (me.home ? ' · ' + me.home : '') : 'Arcade cabinet';
for (var s = 0; s < 2; s++) {
var p = players[s];
$('n' + s).textContent = nameOf(s);
$('h' + s).textContent = (p && p.home) || (p && p.cabinet) || ' ';
var tag = $('t' + s);
tag.textContent = s === seat ? 'HERE' : p && p.computer ? 'COMPUTER' : p && p.present ? 'REMOTE' : 'OFFLINE';
tag.className = s === seat ? 'you' : '';
}
mark($('rivalMark'), other);
$('rivalName').textContent = them && them.player ? them.player : 'Nobody yet';
$('rivalName').style.color = COLOURS[other];
$('rivalWhere').textContent = them && them.cabinet ? them.cabinet + (them.home ? '\n' + them.home : '') : them && them.computer ? 'fills the empty seat' : 'the cabinet is not connected';
var pill = $('rivalPill');
var present = !!(them && them.present);
pill.className = 'pill' + (present ? ' good' : '');
pill.lastChild.textContent = present ? (them.computer ? 'COMPUTER PLAYS' : 'CONNECTED') : 'NOT CONNECTED';
$('rivalNote').textContent = 'Plays the ' + (other === 0 ? 'lime dart.' : 'pink box.');
var path = link.connected ? link.path : null;
var label = $('path');
label.textContent = path === 'direct' ? 'DIRECT' : path === 'relayed' ? 'RELAYED' : path === 'local' ? 'LOCAL' : link.connected ? 'LINKED' : 'NO LINK';
label.className = path || '';
$('rtt').textContent = link.connected && typeof link.rttMs === 'number' ? (link.rttMs < 10 ? link.rttMs.toFixed(1) : Math.round(link.rttMs)) : '–';
var note = !link.connected ? 'The cabinets are not connected.'
: path === 'direct' ? 'Pi to Pi, peer to peer.'
: path === 'relayed' ? 'Pi to Pi, through the relay.'
: path === 'local' ? 'Both programs on one machine.' : 'Pi to Pi.';
// Encryption is named only when the cabinet reports it.
if (link.connected && link.endToEndEncrypted === true) note += ' End-to-end encrypted.';
if (link.connected && link.endToEndEncrypted === false) note += ' Not end-to-end encrypted.';
$('linkNote').textContent = note;
$('go').textContent = them && them.player && present ? 'CHALLENGE ' + them.player.toUpperCase() : 'CHALLENGE';
}
function showTrace() {
var top = 30;
for (var i = 0; i < rtts.length; i++) top = Math.max(top, rtts[i] * 1.25);
var points = [];
for (i = 0; i < rtts.length; i++) points.push((100 - (rtts.length - 1 - i) * (100 / 39)).toFixed(1) + ',' + (24 - (rtts[i] / top) * 22).toFixed(1));
$('trace').setAttribute('points', points.join(' '));
}
function setInfo(newPlayers, newLink) {
if (Array.isArray(newPlayers) && newPlayers.length === 2) players = newPlayers;
if (newLink && typeof newLink === 'object') {
link = newLink;
if (link.connected && typeof link.rttMs === 'number') {
rtts.push(link.rttMs);
if (rtts.length > 40) rtts.shift();
} else if (!link.connected) rtts = [];
showTrace();
}
showInfo();
showScores();
}
/* ---------- the scoreboard of the two homes ---------- */
var scores = { homes: [], history: [] };
var knownGames = null;
function ago(at) {
var seconds = Math.max(0, Date.now() / 1000 - at);
if (seconds < 90) return 'just now';
if (seconds < 3600) return Math.round(seconds / 60) + ' min ago';
if (seconds < 36 * 3600) return Math.round(seconds / 3600) + ' h ago';
return Math.round(seconds / 86400) + ' d ago';
}
function showScores() {
var total = 0, wins = [0, 0];
for (var s = 0; s < 2; s++) {
var home = scores.homes[s] || {};
wins[s] = home.wins | 0;
total += wins[s];
$('home' + s).textContent = home.home || (players[s] && players[s].home) || (s === 0 ? 'Home one' : 'Home two');
$('home' + s).style.color = COLOURS[s];
$('homeP' + s).textContent = home.player || nameOf(s);
setNumber($('w' + s), s, wins[s]);
}
$('split0').style.flexGrow = total ? Math.max(wins[0], 0.04 * total) : 1;
$('split1').style.flexGrow = total ? Math.max(wins[1], 0.04 * total) : 1;
var list = $('games'), games = (scores.history || []).slice(0, 6);
var first = games.length ? games[0].at : 0;
var fresh = knownGames !== null && first > knownGames;
knownGames = first;
list.textContent = '';
games.forEach(function (game, index) {
var winner = game.winner === 1 ? 1 : 0, score = game.score || [0, 0];
var li = document.createElement('li');
li.className = 'w' + winner + (fresh && index === 0 ? ' new' : '');
var res = document.createElement('span');
res.className = 'res';
res.textContent = score[0] + ' : ' + score[1];
var what = document.createElement('div');
what.className = 'what';
var who = document.createElement('b');
who.textContent = nameOf(winner) + ' won' + (game.computer ? ' (computer player)' : '');
var how = document.createElement('span');
var seconds = game.seconds | 0;
how.textContent = (game.rounds | 0) + ' rounds · ' + Math.floor(seconds / 60) + ':' + ('0' + (seconds % 60)).slice(-2) + ' of play';
what.appendChild(who); what.appendChild(how);
var when = document.createElement('time');
when.textContent = ago(game.at);
li.appendChild(res); li.appendChild(what); li.appendChild(when);
list.appendChild(li);
});
$('none').style.display = games.length ? 'none' : '';
}
function setScores(value) {
if (!value || !Array.isArray(value.homes) || !Array.isArray(value.history)) return;
scores = value;
showScores();
}
/* ---------- the match: snapshots in, a picture out ---------- */
var field = $('cv'), g = field.getContext('2d');
var size = 0, dpr = 1, centre = 0, unit = 0; // unit: pixels for one plate radius
var rings = [], bits = [], trails = [[], []], heading = [0, Math.PI], fellAt = [0, 0];
var shake = 0, flash = null, lastFrame = 0, hudAt = 0, bannerKey = '';
var stars = [];
for (var n = 0; n < 46; n++) stars.push([Math.random(), Math.random(), 0.4 + Math.random() * 1.1, Math.random() * 6.28]);
function resize() {
var box = field.getBoundingClientRect();
if (!box.width) return;
dpr = Math.min(window.devicePixelRatio || 1, 3);
size = box.width;
field.width = Math.round(size * dpr);
field.height = Math.round(size * dpr);
centre = size / 2;
unit = size * 0.44;
}
window.addEventListener('resize', resize);
function addSnap(snap) {
if (!snap || typeof snap.t !== 'number' || !Array.isArray(snap.p) || snap.p.length !== 2) return;
if (latest && snap.t <= latest.t) {
if (snap.t > latest.t - 0.5) return; // the same moment once more
snaps = []; // the cabinet's program started again
}
snaps.push(snap);
if (snaps.length > 16) snaps.shift();
latest = snap;
// The page's clock follows the game's: gently, or at once when it is far off.
if (Math.abs(snap.t - clock) > 0.6) clock = snap.t;
else clock += (snap.t - clock) * 0.12;
setDigit($('d0'), clamp(snap.score[0] | 0, 0, 9), true);
setDigit($('d1'), clamp(snap.score[1] | 0, 0, 9), true);
$('target').textContent = snap.target || 5;
}
// The match at time `at`: between two snapshots, or a little past the last one along the skimmers' speed.
function sample(at) {
var count = snaps.length;
if (!count) return null;
var a = snaps[0], b = snaps[count - 1];
for (var i = count - 1; i > 0; i--) if (snaps[i - 1].t <= at) { a = snaps[i - 1]; b = snaps[i]; break; }
if (at <= a.t || a === b) b = a;
var ahead = at > b.t, moving = b.phase === 'play' || b.phase === 'point';
var f = ahead || a === b ? 1 : (at - a.t) / (b.t - a.t);
var jump = a.round !== b.round || a.phase === 'ready' !== (b.phase === 'ready');
var over = ahead && moving ? Math.min(at - b.t, 0.15) : 0;
var view = { t: at, phase: b.phase, round: b.round, score: b.score, target: b.target, countdown: b.countdown, spark: b.spark, rim: jump ? b.rim : a.rim + (b.rim - a.rim) * f, p: [] };
for (var s = 0; s < 2; s++) {
var pa = jump ? b.p[s] : a.p[s], pb = b.p[s];
var still = pb.out ? 0 : over;
view.p.push({ x: pa.x + (pb.x - pa.x) * f + pb.vx * still, y: pa.y + (pb.y - pa.y) * f + pb.vy * still, vx: pb.vx, vy: pb.vy,
charge: pa.charge + (pb.charge - pa.charge) * (pb.charge < pa.charge ? 1 : f), boost: pb.boost, out: pb.out });
}
return view;
}
function burst(x, y, colour, count, speed, dirX, dirY) {
if (reduced) return;
for (var i = 0; i < count; i++) {
var angle = Math.random() * 6.283, v = speed * (0.35 + Math.random() * 0.9);
bits.push({ x: x, y: y, vx: Math.cos(angle) * v + (dirX || 0) * speed * 0.9, vy: Math.sin(angle) * v + (dirY || 0) * speed * 0.9,
life: 0.35 + Math.random() * 0.5, age: 0, colour: colour, size: 1.5 + Math.random() * 2.6 });
}
if (bits.length > 260) bits.splice(0, bits.length - 260);
}
function ring(x, y, to, colour, seconds, width) {
if (!reduced) rings.push({ x: x, y: y, to: to, colour: colour, seconds: seconds, width: width, age: 0 });
}
function play(event) {
var colour = COLOURS[event.seat === 1 ? 1 : 0];
switch (event.event) {
case 'shock':
ring(event.x, event.y, event.reach || 0.5, colour, 0.34, event.boost ? 9 : 6);
ring(event.x, event.y, (event.reach || 0.5) * 0.7, '#ffffff', 0.26, 2);
if (event.boost) ring(event.x, event.y, (event.reach || 0.5) * 1.12, CYAN, 0.46, 3);
break;
case 'hit':
var from = latest ? latest.p[event.by === 1 ? 1 : 0] : null;
var dx = from ? event.x - from.x : 0, dy = from ? event.y - from.y : 0, d = Math.sqrt(dx * dx + dy * dy) || 1;
burst(event.x, event.y, colour, 14, 0.9, dx / d, dy / d);
burst(event.x, event.y, '#ffffff', 5, 0.5, dx / d, dy / d);
shake = Math.max(shake, 3 + 2.2 * (event.strength || 1));
break;
case 'bump':
burst(event.x, event.y, '#ffffff', 7, 0.45);
ring(event.x, event.y, 0.13, '#ffffff', 0.2, 2);
shake = Math.max(shake, 2);
break;
case 'spark':
burst(event.x, event.y, CYAN, 16, 0.6);
ring(event.x, event.y, 0.2, CYAN, 0.35, 3);
break;
case 'fall':
fellAt[event.seat === 1 ? 1 : 0] = performance.now();
burst(event.x, event.y, colour, 46, 1.25, event.x, event.y);
burst(event.x, event.y, '#ffffff', 12, 0.8, event.x, event.y);
ring(event.x, event.y, 0.45, colour, 0.6, 8);
ring(event.x, event.y, 0.8, colour, 0.9, 3);
shake = 13;
flash = { colour: COLOURS[event.seat === 1 ? 0 : 1], age: 0 };
break;
case 'match':
for (var i = 0; i < 5; i++) burst((Math.random() - 0.5) * 1.2, (Math.random() - 0.5) * 1.2, COLOURS[event.winner === 1 ? 1 : 0], 22, 0.9);
break;
}
}
function showBanner(view) {
var big = '', small = '', tone = '';
if (!online) { big = 'NO SIGNAL'; small = 'THE CABINET DOES NOT ANSWER'; tone = 'cc'; }
else if (!view || view.phase === 'waiting') { big = 'WAITING'; small = 'FOR THE OTHER CABINET'; tone = 'cc'; }
else if (view.phase === 'ready') { big = 'ROUND ' + view.round; small = view.score[0] + ' : ' + view.score[1]; tone = 'cc'; }
else if (view.phase === 'point') {
if (view.p[0].out && view.p[1].out) { big = 'BOTH OUT'; small = 'NO POINT'; tone = 'cc'; }
else { var won = view.p[0].out ? 1 : 0; big = nameOf(won).toUpperCase(); small = 'TAKES THE ROUND'; tone = 'c' + won; }
} else if (view.phase === 'over') {
var winner = view.score[1] > view.score[0] ? 1 : 0;
big = nameOf(winner).toUpperCase() + ' WINS';
small = view.score[0] + ' : ' + view.score[1] + ' · NEXT MATCH IN ' + Math.ceil(view.countdown || 0);
tone = 'c' + winner;
}
var key = big + '|' + small + '|' + tone;
if (key === bannerKey) return;
bannerKey = key;
var banner = $('banner');
if (big) {
$('bannerBig').textContent = big;
$('bannerSmall').textContent = small;
banner.className = 'banner show ' + tone;
} else banner.className = 'banner ' + (banner.className.match(/c[01c]/) || [''])[0];
}
function px(v) { return centre + v * unit; }
function drawSkimmer(s, p, now, view) {
var x = px(p.x), y = px(p.y), colour = COLOURS[s], scale = 1, turn = 0, alpha = 1;
if (p.out) {
if (!fellAt[s]) fellAt[s] = now;
var k = (now - fellAt[s]) / 650;
if (k >= 1 || reduced) return;
var away = Math.sqrt(p.x * p.x + p.y * p.y) || 1;
x += (p.x / away) * k * 46; y += (p.y / away) * k * 46;
scale = 1 - k; turn = k * 9; alpha = 1 - k * k;
} else fellAt[s] = 0;
var speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy);
if (s === 0) { if (speed > 0.08) heading[0] = Math.atan2(p.vy, p.vx); }
else heading[1] = reduced ? Math.PI / 4 : (now / 900) % 6.283;
var r = 0.075 * unit;
g.save();
g.translate(x, y);
g.globalAlpha = alpha;
// The charge: an arc that closes into a ring when a shock is ready.
if (!p.out) {
var ready = p.charge >= 1, beat = ready && !reduced ? 0.5 + 0.5 * Math.sin(now / 90) : 0;
g.lineWidth = ready ? 2.6 : 2;
g.strokeStyle = colour;
g.globalAlpha = ready ? 0.75 + 0.25 * beat : 0.45;
g.beginPath();
g.arc(0, 0, r + 6 + beat * 1.5, -Math.PI / 2, -Math.PI / 2 + clamp(p.charge, 0.02, 1) * 6.2832);
g.stroke();
if (p.boost) { // holds a spark: a second, cyan ring with four teeth
g.strokeStyle = CYAN; g.lineWidth = 2; g.globalAlpha = 0.9;
g.shadowColor = CYAN; g.shadowBlur = 10;
var spin = reduced ? 0 : now / 300;
for (var t = 0; t < 4; t++) {
g.beginPath();
g.arc(0, 0, r + 11, spin + t * 1.5708, spin + t * 1.5708 + 0.9);
g.stroke();
}
}
g.globalAlpha = alpha;
}
g.rotate(heading[s] + turn);
g.scale(scale, scale);
g.shadowColor = colour; g.shadowBlur = 16;
g.lineJoin = 'round';
g.lineWidth = 3;
g.strokeStyle = colour;
g.fillStyle = s === 0 ? 'rgba(214,255,63,.22)' : 'rgba(255,79,154,.22)';
g.beginPath();
if (s === 0) {
g.moveTo(r * 1.25, 0); g.lineTo(-r * 0.95, -r * 1.0); g.lineTo(-r * 0.4, 0); g.lineTo(-r * 0.95, r * 1.0);
} else {
var h = r * 0.92;
g.moveTo(h, 0); g.lineTo(0, h); g.lineTo(-h, 0); g.lineTo(0, -h);
}
g.closePath();
g.fill(); g.stroke();
g.shadowBlur = 0;
g.fillStyle = '#ffffff';
g.beginPath();
g.arc(s === 0 ? r * 0.15 : 0, 0, r * 0.2, 0, 6.2832);
g.fill();
g.restore();
}
function draw(now) {
var dt = clamp((now - lastFrame) / 1000, 0, 0.1);
lastFrame = now;
if (latest && (latest.phase !== 'waiting')) clock += dt;
// The picture runs a little behind the cabinet, so that there are two snapshots to draw between.
var at = clock - (bridge ? 0.1 : 0.42);
while (queued.length && (queued[0].t <= at || queued[0].t > at + 3)) play(queued.shift());
var view = reduced ? latest : sample(at);
if (!size) resize();
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, size, size);
if (now - hudAt > 180) {
hudAt = now;
showBanner(view);
$('round').textContent = view && view.round ? view.round : '–';
$('rim').textContent = view ? Math.round(view.rim * 100) + '%' : '–';
var live = online && view && view.phase !== 'waiting';
$('live').className = 'live' + (live ? ' on' : '');
$('liveText').textContent = live ? 'LIVE' : online ? 'WAITING' : 'OFFLINE';
}
g.save();
if (shake > 0.2 && !reduced) {
g.translate((Math.random() - 0.5) * shake, (Math.random() - 0.5) * shake);
shake *= Math.pow(0.0015, dt);
} else shake = 0;
// Far lights that do not belong to the game.
for (var i = 0; i < stars.length; i++) {
var star = stars[i];
g.globalAlpha = reduced ? 0.3 : 0.18 + 0.22 * (0.5 + 0.5 * Math.sin(now / 700 + star[3]));
g.fillStyle = i % 5 === 0 ? CYAN : '#aab2ff';
g.fillRect(star[0] * size, star[1] * size, star[2], star[2]);
}
g.globalAlpha = 1;
if (view) {
var rim = Math.max(0, view.rim), R = rim * unit;
var danger = clamp((1 - rim) / 0.6, 0, 1);
var rimColour = rim < 0.4 ? '#ff7a3c' : 'hsl(' + Math.round(187 + 80 * danger) + ',100%,' + Math.round(67 + 5 * danger) + '%)';
// Where the plate was at the start of the round.
g.strokeStyle = 'rgba(141,148,194,.22)';
g.lineWidth = 1;
g.setLineDash([3, 7]);
g.beginPath(); g.arc(centre, centre, unit, 0, 6.2832); g.stroke();
g.setLineDash([]);
if (R > 1) {
// The plate, with a grid that stays where it is while the rim comes in.
var glow = g.createRadialGradient(centre, centre, 0, centre, centre, R);
glow.addColorStop(0, 'rgba(86,232,255,.13)');
glow.addColorStop(0.75, 'rgba(60,90,220,.10)');
glow.addColorStop(1, 'rgba(86,232,255,.20)');
g.fillStyle = glow;
g.beginPath(); g.arc(centre, centre, R, 0, 6.2832); g.fill();
g.save();
g.beginPath(); g.arc(centre, centre, R, 0, 6.2832); g.clip();
g.strokeStyle = 'rgba(170,190,255,.11)';
g.lineWidth = 1;
for (var c = 1; c <= 4; c++) { g.beginPath(); g.arc(centre, centre, c * 0.2 * unit, 0, 6.2832); g.stroke(); }
var twist = reduced ? 0 : now / 14000;
for (var k = 0; k < 12; k++) {
var a = twist + k * 0.5236;
g.beginPath();
g.moveTo(centre + Math.cos(a) * 0.2 * unit, centre + Math.sin(a) * 0.2 * unit);
g.lineTo(centre + Math.cos(a) * unit, centre + Math.sin(a) * unit);
g.stroke();
}
g.restore();
// The rim: cyan while the plate is wide, violet as it closes in, orange and restless once it collapses.
var throb = reduced ? 0 : (rim < 0.42 ? 0.5 + 0.5 * Math.sin(now / 70) : 0.5 + 0.5 * Math.sin(now / 420));
g.shadowColor = rimColour; g.shadowBlur = 14 + 10 * throb;
g.strokeStyle = rimColour;
g.lineWidth = 3.5;
g.beginPath(); g.arc(centre, centre, R, 0, 6.2832); g.stroke();
g.shadowBlur = 0;
g.strokeStyle = 'rgba(255,255,255,.75)';
g.lineWidth = 1;
g.beginPath(); g.arc(centre, centre, R, 0, 6.2832); g.stroke();
}
// The spark: a four-pointed star.
if (view.spark && view.phase === 'play') {
var sx = px(view.spark[0]), sy = px(view.spark[1]);
var pulse = reduced ? 1 : 0.8 + 0.25 * Math.sin(now / 120), long = 0.085 * unit * pulse, short = long * 0.28;
g.save();
g.translate(sx, sy);
g.rotate(reduced ? 0 : now / 600);
g.shadowColor = CYAN; g.shadowBlur = 18;
g.fillStyle = '#eaffff';
g.beginPath();
for (var q = 0; q < 8; q++) {
var reach = q % 2 ? short : long, angle = q * 0.7854;
g[q ? 'lineTo' : 'moveTo'](Math.cos(angle) * reach, Math.sin(angle) * reach);
}
g.closePath(); g.fill();
g.restore();
}
// Trails, then the skimmers.
g.lineCap = 'round';
for (var s = 0; s < 2; s++) {
var p = view.p[s], trail = trails[s], last = trail[trail.length - 1];
if (reduced || p.out || view.phase === 'ready' || (last && Math.abs(last[0] - p.x) + Math.abs(last[1] - p.y) > 0.3)) trail.length = 0;
if (!reduced && !p.out) {
trail.push([p.x, p.y]);
if (trail.length > 16) trail.shift();
g.globalCompositeOperation = 'lighter';
g.strokeStyle = COLOURS[s];
for (var j = 1; j < trail.length; j++) {
g.globalAlpha = 0.5 * (j / trail.length);
g.lineWidth = 0.11 * unit * (j / trail.length);
g.beginPath(); g.moveTo(px(trail[j - 1][0]), px(trail[j - 1][1])); g.lineTo(px(trail[j][0]), px(trail[j][1])); g.stroke();
}
g.globalAlpha = 1;
g.globalCompositeOperation = 'source-over';
}
}
drawSkimmer(0, view.p[0], now, view);
drawSkimmer(1, view.p[1], now, view);
}
// Shock rings and flying bits.
g.globalCompositeOperation = 'lighter';
for (i = rings.length - 1; i >= 0; i--) {
var ringNow = rings[i];
ringNow.age += dt;
var f = ringNow.age / ringNow.seconds;
if (f >= 1) { rings.splice(i, 1); continue; }
var ease = 1 - Math.pow(1 - f, 3);
g.globalAlpha = 1 - f * f;
g.strokeStyle = ringNow.colour;
g.shadowColor = ringNow.colour; g.shadowBlur = 12;
g.lineWidth = Math.max(0.6, ringNow.width * (1 - f));
g.beginPath(); g.arc(px(ringNow.x), px(ringNow.y), Math.max(1, ringNow.to * unit * ease), 0, 6.2832); g.stroke();
}
g.shadowBlur = 0;
for (i = bits.length - 1; i >= 0; i--) {
var bit = bits[i];
bit.age += dt;
if (bit.age >= bit.life) { bits.splice(i, 1); continue; }
bit.x += bit.vx * dt; bit.y += bit.vy * dt;
bit.vx *= Math.pow(0.08, dt); bit.vy *= Math.pow(0.08, dt);
g.globalAlpha = 1 - bit.age / bit.life;
g.strokeStyle = bit.colour;
g.lineWidth = bit.size;
g.beginPath(); g.moveTo(px(bit.x), px(bit.y)); g.lineTo(px(bit.x - bit.vx * 0.035), px(bit.y - bit.vy * 0.035)); g.stroke();
}
g.globalAlpha = 1;
g.globalCompositeOperation = 'source-over';
g.restore();
if (flash) {
flash.age += dt;
if (flash.age >= 0.35) flash = null;
else { g.globalAlpha = 0.32 * (1 - flash.age / 0.35); g.fillStyle = flash.colour; g.fillRect(0, 0, size, size); g.globalAlpha = 1; }
}
}
function frame(now) {
draw(now);
requestAnimationFrame(frame);
}
resize();
// With reduced motion the picture is a still that is replaced four times a second, without effects.
if (reduced) setInterval(function () { draw(performance.now()); }, 250);
else requestAnimationFrame(frame);
/* ---------- the challenge ---------- */
var goButton = $('go'), said = $('said'), sayTimer = 0, litTimer = 0, callTimer = 0;
function say(text, bad) {
said.textContent = text || ' ';
said.className = 'said' + (bad ? ' bad' : '');
clearTimeout(sayTimer);
if (text) sayTimer = setTimeout(function () { say(''); }, 6000);
}
goButton.addEventListener('click', function () {
if (goButton.classList.contains('busy')) return;
goButton.classList.add('busy');
say('Calling the other cabinet…');
fetch('/challenge', { method: 'POST' }).then(function (response) {
return response.json().catch(function () { return {}; }).then(function (body) {
if (!response.ok) throw new Error(body.error || 'The cabinet answered ' + response.status + '.');
say('Sent to ' + ((body.to && body.to.cabinet) || 'the other cabinet') + '.');
});
}).catch(function (error) {
say(error && error.message ? error.message : 'The challenge did not get through.', true);
}).then(function () {
goButton.classList.remove('busy');
});
});
function challengeEvent(event) {
var other = 1 - seat, them = players[other];
if (event.event === 'lit' && event.seat === other) {
// The other cabinet says its lights are on.
goButton.classList.add('lit');
say(((them && them.cabinet) || 'The other cabinet') + ' is lit up.');
clearTimeout(litTimer);
litTimer = setTimeout(function () { goButton.classList.remove('lit'); }, 4200);
} else if (event.event === 'challenge' && event.seat === other) {
var call = $('call');
call.textContent = String(event.player || 'The other cabinet').toUpperCase() + ' CHALLENGES THIS CABINET';
call.classList.add('show');
clearTimeout(callTimer);
callTimer = setTimeout(function () { call.classList.remove('show'); }, 5000);
}
}
/* ---------- talking to the cabinet ---------- */
function setState(state) {
if (!state || typeof state !== 'object') return;
seat = state.seat === 1 ? 1 : 0;
if (state.game) $('logo').textContent = String(state.game).toUpperCase();
setInfo(state.players, state.link);
addSnap(state.match);
}
function onMessage(message) {
if (!message || typeof message !== 'object') return;
if (message.type === 'state') addSnap(message);
else if (message.type === 'event') {
if (message.event === 'lit' || message.event === 'challenge') challengeEvent(message);
else if (typeof message.t === 'number') queued.push(message);
} else if (message.type === 'info') setInfo(message.players, message.link);
else if (message.type === 'scores') setScores(message);
else if (message.type === 'hello') { setState(message.state); setScores(message.scores); }
}
function openSocket() {
var socket;
try { socket = bridge.webSocket('/match'); } catch (error) { setTimeout(openSocket, 3000); return; }
socket.onopen = function () { online = true; };
socket.onmessage = function (event) {
if (typeof event.data !== 'string') return;
var message;
try { message = JSON.parse(event.data); } catch (error) { return; }
online = true;
onMessage(message);
};
socket.onclose = function () {
online = false;
setTimeout(openSocket, 2000);
};
}
// Without the bridge (a browser opened straight on the cabinet) the page asks instead of listening, and
// makes the effects up from what changed between two answers.
function poll() {
fetch('/state').then(function (response) { return response.json(); }).then(function (state) {
var before = latest;
online = true;
setState(state);
var now = state.match;
if (before && now && now.t > before.t && now.round === before.round) {
for (var s = 0; s < 2; s++) {
var was = before.p[s], is = now.p[s];
if (was.charge >= 0.6 && is.charge < was.charge - 0.3) queued.push({ type: 'event', event: 'shock', t: now.t, seat: s, x: is.x, y: is.y, reach: was.boost ? 0.64 : 0.5, boost: was.boost });
if (is.out && !was.out) queued.push({ type: 'event', event: 'fall', t: now.t, seat: s, x: is.x, y: is.y });
}
}
}).catch(function () { online = false; }).then(function () { setTimeout(poll, 250); });
}
function pollScores() {
fetch('/scores').then(function (response) { return response.json(); }).then(setScores).catch(function () {}).then(function () { setTimeout(pollScores, 5000); });
}
showInfo();
showScores();
setDigit($('d0'), 0); setDigit($('d1'), 0);
if (bridge) openSocket();
else { poll(); pollScores(); }
})();
</script>
</body>
</html>