Duel arcade
demo-kit/ es lo que simula el dispositivo para la demostración en la página de inicio. El dispositivo en sí no lo necesita.
demo-kit/ es lo que simula el dispositivo para la demostración en la página de inicio. El dispositivo en sí no lo necesita.
// The pretend cabinet for the demo of the arcade example (../../demo-kit/README.md): the same answers and
// messages the host cabinet's program gives (../pi/arcade.py), with the game (../pi/game.py) once more in
// JavaScript and two computer players at the sticks. The demo opens in the middle of a match. The players,
// the homes, the scoreboard and the round-trip time are invented.
(function () {
var ctx = czDemo.context;
// --- The game: the same rules and numbers as ../pi/game.py. ---
var DT = 1 / 60;
var SKIMMER_RADIUS = 0.075, THRUST = 2.7, DRAG = 1.8, BOUNCE = 0.9, START_X = 0.45;
var SHOCK_RADIUS = 0.5, SHOCK_PUSH = 2.0, SHOCK_FALLOFF = 0.55, SHOCK_RECOIL = 0.3;
var BOOST_RADIUS = 0.64, BOOST_PUSH = 2.8, RECHARGE_SECONDS = 2.2;
var SPARK_RADIUS = 0.05, SPARK_DELAY = 2.5;
var SHRINK_SECONDS = 14, SMALL_RIM = 0.4, COLLAPSE_SECONDS = 6;
var READY_SECONDS = 1.2, POINT_SECONDS = 2.2, OVER_SECONDS = 6, TARGET = 5;
function hypot(x, y) {
return Math.sqrt(x * x + y * y);
}
function round(value, digits) {
var factor = Math.pow(10, digits);
return Math.round(value * factor) / factor;
}
function rimAt(clock) {
if (clock <= SHRINK_SECONDS) return 1 - (1 - SMALL_RIM) * (clock / SHRINK_SECONDS);
return SMALL_RIM * Math.max(0, 1 - (clock - SHRINK_SECONDS) / COLLAPSE_SECONDS);
}
function skimmer() {
return { x: 0, y: 0, vx: 0, vy: 0, charge: 0, boost: false, out: false, button: false };
}
var game = { t: 0, s: [skimmer(), skimmer()], score: [0, 0], round: 0, phase: 'waiting', clock: 0, rim: 1, spark: null, sparkIn: 0, left: 0, seconds: 0 };
var events = [];
function emit(event, details) {
var message = { type: 'event', event: event, t: round(game.t, 3) };
for (var key in details) message[key] = details[key];
events.push(message);
}
function place(s, x) {
s.x = x; s.y = 0; s.vx = 0; s.vy = 0; s.charge = 0.5; s.boost = false; s.out = false;
}
function startRound() {
game.round += 1;
game.phase = 'ready';
game.left = READY_SECONDS;
game.clock = 0;
game.rim = 1;
game.spark = null;
game.sparkIn = SPARK_DELAY;
place(game.s[0], -START_X);
place(game.s[1], START_X);
emit('round', { round: game.round, score: game.score.slice() });
}
function newMatch() {
game.score = [0, 0];
game.round = 0;
game.seconds = 0;
startRound();
}
function move(s, x, y) {
var length = hypot(x, y);
if (length > 1) { x /= length; y /= length; }
s.vx += x * THRUST * DT;
s.vy += y * THRUST * DT;
var keep = Math.exp(-DRAG * DT);
s.vx *= keep;
s.vy *= keep;
s.x += s.vx * DT;
s.y += s.vy * DT;
}
function play(inputs) {
var one = game.s[0], two = game.s[1], seat, s;
game.clock += DT;
game.seconds += DT;
game.rim = rimAt(game.clock);
for (seat = 0; seat < 2; seat++) {
move(game.s[seat], inputs[seat][0], inputs[seat][1]);
game.s[seat].charge = Math.min(1, game.s[seat].charge + DT / RECHARGE_SECONDS);
}
// Two skimmers that touch bounce off each other like two equal balls.
var dx = two.x - one.x, dy = two.y - one.y, distance = hypot(dx, dy);
if (distance > 0 && distance < 2 * SKIMMER_RADIUS) {
var nx = dx / distance, ny = dy / distance, overlap = 2 * SKIMMER_RADIUS - distance;
one.x -= nx * overlap / 2; one.y -= ny * overlap / 2;
two.x += nx * overlap / 2; two.y += ny * overlap / 2;
var closing = (one.vx - two.vx) * nx + (one.vy - two.vy) * ny;
if (closing > 0) {
var change = closing * (1 + BOUNCE) / 2;
one.vx -= nx * change; one.vy -= ny * change;
two.vx += nx * change; two.vy += ny * change;
if (closing > 0.25) emit('bump', { x: round((one.x + two.x) / 2, 3), y: round((one.y + two.y) / 2, 3), speed: round(closing, 2) });
}
}
// The button sends a shock when it is pressed with a full charge.
for (seat = 0; seat < 2; seat++) {
s = game.s[seat];
var pressed = inputs[seat][2] && !s.button;
s.button = inputs[seat][2];
if (!pressed || s.charge < 1) continue;
var reach = s.boost ? BOOST_RADIUS : SHOCK_RADIUS, push = s.boost ? BOOST_PUSH : SHOCK_PUSH;
emit('shock', { seat: seat, x: round(s.x, 3), y: round(s.y, 3), reach: reach, boost: s.boost });
s.charge = 0;
s.boost = false;
var other = game.s[1 - seat], ox = other.x - s.x, oy = other.y - s.y, away = hypot(ox, oy);
if (away > 0 && away < reach) {
var strength = push * (1 - SHOCK_FALLOFF * away / reach);
other.vx += ox / away * strength; other.vy += oy / away * strength;
s.vx -= ox / away * strength * SHOCK_RECOIL; s.vy -= oy / away * strength * SHOCK_RECOIL;
emit('hit', { seat: 1 - seat, by: seat, x: round(other.x, 3), y: round(other.y, 3), strength: round(strength, 2) });
}
}
// One spark at a time lies on the plate; touching it fills the charge and makes the next shock stronger.
if (!game.spark) {
game.sparkIn -= DT;
if (game.sparkIn <= 0 && game.rim > 0.3) {
var angle = ctx.rand() * 2 * Math.PI, radius = Math.sqrt(ctx.rand()) * game.rim * 0.7;
game.spark = [radius * Math.cos(angle), radius * Math.sin(angle)];
}
} else if (hypot(game.spark[0], game.spark[1]) > game.rim - SPARK_RADIUS) {
game.spark = null;
game.sparkIn = 0.6;
} else {
for (seat = 0; seat < 2; seat++) {
s = game.s[seat];
if (hypot(s.x - game.spark[0], s.y - game.spark[1]) < SKIMMER_RADIUS + SPARK_RADIUS) {
s.charge = 1;
s.boost = true;
emit('spark', { seat: seat, x: round(game.spark[0], 3), y: round(game.spark[1], 3) });
game.spark = null;
game.sparkIn = SPARK_DELAY;
break;
}
}
}
// Whoever is past the rim has left the plate. Both in the same tick: nobody scores.
one.out = hypot(one.x, one.y) > game.rim;
two.out = hypot(two.x, two.y) > game.rim;
if (!one.out && !two.out) return;
game.phase = 'point';
game.left = POINT_SECONDS;
if (one.out && two.out) {
emit('draw', { round: game.round });
return;
}
var loser = one.out ? 0 : 1, winner = 1 - loser;
game.score[winner] += 1;
emit('fall', { seat: loser, x: round(game.s[loser].x, 3), y: round(game.s[loser].y, 3), score: game.score.slice(), round: game.round });
if (game.score[winner] >= TARGET) {
game.phase = 'over';
game.left = OVER_SECONDS;
emit('match', { winner: winner, score: game.score.slice(), rounds: game.round, seconds: Math.round(game.seconds) });
}
}
function step(inputs) {
game.t += DT;
if (game.phase === 'waiting') return;
if (game.phase === 'play') return play(inputs);
if (game.phase === 'point') {
for (var seat = 0; seat < 2; seat++) if (!game.s[seat].out) move(game.s[seat], inputs[seat][0], inputs[seat][1]);
}
game.left -= DT;
if (game.left <= 0) {
if (game.phase === 'ready') {
game.phase = 'play';
emit('go', { round: game.round });
} else if (game.phase === 'point') startRound();
else newMatch();
}
}
function snapshot() {
return {
t: round(game.t, 3), phase: game.phase, round: game.round, clock: round(game.clock, 2), countdown: round(Math.max(0, game.left), 2),
rim: round(game.rim, 4), score: game.score.slice(), target: TARGET,
p: game.s.map(function (s) {
return { x: round(s.x, 4), y: round(s.y, 4), vx: round(s.vx, 3), vy: round(s.vy, 3), charge: round(s.charge, 2), boost: s.boost, out: s.out };
}),
spark: game.spark ? [round(game.spark[0], 4), round(game.spark[1], 4)] : null,
};
}
// --- The computer player: the same as ComputerPlayer in ../pi/game.py. ---
function computerPlayer(seat) {
var wobble = ctx.rand() * 6.28, aimSince = null, react = 0.2, held = false;
return function (view) {
if (view.phase !== 'play' && view.phase !== 'point') { held = false; return [0, 0, false]; }
var me = view.p[seat], foe = view.p[1 - seat], rim = view.rim;
var myRadius = hypot(me.x, me.y), foeRadius = hypot(foe.x, foe.y), gap = hypot(foe.x - me.x, foe.y - me.y);
var tx, ty;
if (view.phase === 'point' || foe.out) { tx = 0; ty = 0; }
else if (view.spark && !me.boost && hypot(view.spark[0] - me.x, view.spark[1] - me.y) < hypot(view.spark[0] - foe.x, view.spark[1] - foe.y) + 0.2) { tx = view.spark[0]; ty = view.spark[1]; }
else if (foeRadius > 0.12) { var inside = Math.max(0, foeRadius - 0.2) / foeRadius; tx = foe.x * inside; ty = foe.y * inside; }
else { tx = foe.x; ty = foe.y; }
var sx = (tx - me.x) * 3 - me.vx * 0.9, sy = (ty - me.y) * 3 - me.vy * 0.9;
var margin = rim - myRadius;
if (margin < 0.24 && myRadius > 0) {
var pull = (0.24 - margin) / 0.24 * 4;
sx -= me.x / myRadius * pull + me.vx * 0.8;
sy -= me.y / myRadius * pull + me.vy * 0.8;
}
wobble += 0.05;
sx += Math.sin(wobble * 1.3) * 0.35;
sy += Math.cos(wobble) * 0.35;
var length = hypot(sx, sy);
if (length > 1) { sx /= length; sy /= length; }
var reach = (me.boost ? BOOST_RADIUS : SHOCK_RADIUS) * 0.72;
var outward = (foe.x - me.x) * foe.x + (foe.y - me.y) * foe.y;
var aimed = view.phase === 'play' && me.charge >= 1 && gap < reach && (outward > 0 || foeRadius < 0.1);
var press = false;
if (aimed) {
if (aimSince === null) { aimSince = view.t; react = 0.08 + ctx.rand() * 0.3; }
press = view.t - aimSince >= react && !held;
} else aimSince = null;
held = press;
return [sx, sy, press];
};
}
// --- The pretend cabinet: cabinet one, the host, with the other cabinet connected directly. ---
var players = [
{ cabinet: 'cabinet-one', home: 'The Loft', player: 'Mika', present: true, computer: false },
{ cabinet: 'cabinet-two', home: 'The Shed', player: 'Robin', present: true, computer: false },
];
var link = { connected: true, path: 'direct', endToEndEncrypted: true, rttMs: 14.2 };
var wins = [7, 5];
var history = [];
(function inventHistory() {
var past = [[0, 5, 3, 8, 82, 0.4], [1, 2, 5, 7, 66, 0.5], [0, 5, 4, 9, 97, 21], [0, 5, 1, 6, 55, 22], [1, 3, 5, 8, 79, 46], [1, 4, 5, 9, 104, 47.5]];
var now = Math.round(Date.now() / 1000);
past.forEach(function (m) {
history.push({ at: now - Math.round(m[5] * 3600), winner: m[0], score: [m[1], m[2]], rounds: m[3], seconds: m[4], computer: false });
});
})();
var sockets = [];
var brains = [computerPlayer(0), computerPlayer(1)];
function scores() {
return {
homes: players.map(function (player, seat) { return { home: player.home, player: player.player, wins: wins[seat] }; }),
history: history,
};
}
function state() {
return { game: 'Rimshock', role: 'host', seat: 0, players: players, link: link, match: snapshot() };
}
function broadcast(message) {
sockets.forEach(function (socket) { socket.send(message); });
}
// The demo opens in the fourth round of a match that stands 2 : 1, a few seconds in.
newMatch();
game.score = [2, 1];
game.round = 4;
game.seconds = 31;
game.phase = 'play';
events = [];
(function warmUp() {
for (var i = 0; i < 4.5 * 60 && game.phase === 'play' && game.rim - Math.max(hypot(game.s[0].x, game.s[0].y), hypot(game.s[1].x, game.s[1].y)) > 0.15; i++) {
var view = snapshot();
step([brains[0](view), brains[1](view)]);
}
events = [];
})();
var lastReal = Date.now(), owed = 0, ticks = 0, lastInfo = 0;
setInterval(function () {
var now = Date.now();
// Not more than a tenth of a second at once: when the demo was paused off screen, the match does not jump.
owed += Math.min(0.1, (now - lastReal) / 1000);
lastReal = now;
while (owed >= DT) {
owed -= DT;
ticks += 1;
var view = snapshot();
step([brains[0](view), brains[1](view)]);
var happened = events;
events = [];
happened.forEach(function (event) {
broadcast(event);
if (event.event !== 'match') return;
wins[event.winner] += 1;
history.unshift({ at: Math.round(Date.now() / 1000), winner: event.winner, score: event.score, rounds: event.rounds, seconds: event.seconds, computer: false });
history.length = Math.min(history.length, 20);
var board = scores();
broadcast({ type: 'scores', homes: board.homes, history: board.history });
});
if (ticks % 3 === 0 && sockets.length) {
var message = snapshot();
message.type = 'state';
broadcast(message);
}
}
if (now - lastInfo >= 1000) {
lastInfo = now;
link.rttMs = round(Math.max(9, Math.min(24, link.rttMs + (ctx.rand() - 0.5) * 3 + (14.5 - link.rttMs) * 0.15)), 1);
broadcast({ type: 'info', players: players, link: link });
}
}, 1000 / 60);
czDemo.define({
device: { name: 'cabinet-one', title: 'Arcade' },
routes: {
'GET /state': function () {
return state();
},
'GET /scores': function () {
return scores();
},
'POST /challenge': function () {
// The pretend other cabinet lights up a moment later and says so, as a real one does.
setTimeout(function () {
broadcast({ type: 'event', event: 'lit', t: round(game.t, 3), seat: 1 });
}, 700);
return { ok: true, to: { cabinet: players[1].cabinet, player: players[1].player } };
},
},
sockets: {
'/match': function (socket) {
sockets.push(socket);
socket.send({ type: 'hello', state: state(), scores: scores() });
socket.onclose = function () {
sockets.splice(sockets.indexOf(socket), 1);
};
},
},
});
})();