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.
This commit is contained in:
ducklet 2021-03-06 20:57:29 +01:00
parent 81ee2200fb
commit 8fad6d64df

View file

@ -4,7 +4,16 @@
const location = document.location const location = document.location
const performance = window.performance 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 let conn
@ -126,8 +135,9 @@ function highlight(client_id, until_ns) {
function setup_ws() { function setup_ws() {
let clients = {}, let clients = {},
me, me,
monitored = [], monitored = [], // list of client IDs
sounds = {} sounds = {}, // mapping of client ID to Audio instance
buzzes = {} // mapping of client ID to buzz time
const sid = session_id() const sid = session_id()
const overlay = q("#text-overlay") const overlay = q("#text-overlay")
conn = new Connection() conn = new Connection()
@ -138,12 +148,24 @@ function setup_ws() {
me = value me = value
}) })
conn.on("buzz", ({ 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 { time: buzztime_ns, client: client_id } = value
const duration_ns = 12 * s_ns if (!(client_id in buzzes)) {
const until_ns = buzztime_ns + duration_ns buzzes[client_id] = buzztime_ns
const is_new_buzz = highlight(client_id, until_ns)
if (is_new_buzz && sounds[client_id]) {
sounds[client_id].play()
} }
}) })
conn.on("clients", ({ value }) => { conn.on("clients", ({ value }) => {