From 8fad6d64df67206cb53798d77b21f97e21bf5774 Mon Sep 17 00:00:00 2001 From: ducklet Date: Sat, 6 Mar 2021 20:57:29 +0100 Subject: [PATCH] use actual client buzzing time to determine winner By waiting and collecting buzzes over a short period of time we can try to compensate for network latency. This opens up a way to cheat for the player by forging timestamps, but normally it should makes things more fair. --- public/monitor.js | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/public/monitor.js b/public/monitor.js index 186ef39..57b4cbe 100644 --- a/public/monitor.js +++ b/public/monitor.js @@ -4,7 +4,16 @@ const location = document.location const performance = window.performance -import { Connection, ms_ns, node, q, s_ns, session_id, session_url } from "./shared.js" +import { + Connection, + isEmpty, + ms_ns, + node, + q, + s_ns, + session_id, + session_url, +} from "./shared.js" let conn @@ -126,8 +135,9 @@ function highlight(client_id, until_ns) { function setup_ws() { let clients = {}, me, - monitored = [], - sounds = {} + monitored = [], // list of client IDs + sounds = {}, // mapping of client ID to Audio instance + buzzes = {} // mapping of client ID to buzz time const sid = session_id() const overlay = q("#text-overlay") conn = new Connection() @@ -138,12 +148,24 @@ function setup_ws() { me = value }) conn.on("buzz", ({ value }) => { + const collect_duration_ms = 500 + const highlight_duration_ns = 12 * s_ns + // Collect buzzes to find the true winner. + if (isEmpty(buzzes)) { + setTimeout(() => { + // Show winner in UI. + const winner_id = Object.entries(buzzes).sort(([x, a], [y, b]) => a - b)[0][0] + buzzes = {} + const until_ns = buzztime_ns + highlight_duration_ns + const is_new_buzz = highlight(winner_id, until_ns) + if (is_new_buzz && sounds[winner_id]) { + sounds[winner_id].play() + } + }, collect_duration_ms) + } const { time: buzztime_ns, client: client_id } = value - const duration_ns = 12 * s_ns - const until_ns = buzztime_ns + duration_ns - const is_new_buzz = highlight(client_id, until_ns) - if (is_new_buzz && sounds[client_id]) { - sounds[client_id].play() + if (!(client_id in buzzes)) { + buzzes[client_id] = buzztime_ns } }) conn.on("clients", ({ value }) => {