Skip to content

Rounds and timers

A five-minute round: a countdown on everyone's HUD, the richest player wins, and the next round starts after ten seconds. Timers are plain setInterval/setTimeout.

rounds.ts
import { Server, Color } from "@sagl/server";

export function rounds(server: Server, minutes = 5) {
  const clock = server.channel("clock");
  let endsAt = 0;

  function start() {
    endsAt = Date.now() + minutes * 60_000;
    for (const p of server.players) p.money = 0;
    server.broadcast(`New round: ${minutes} minutes. Get rich!`, Color.Yellow);
  }

  function end() {
    const winner = [...server.players].sort((a, b) => b.money - a.money)[0];
    server.broadcast(winner ? `${winner.name} wins with $${winner.money}!` : "Nobody played.", Color.Green);
    endsAt = 0;
    setTimeout(start, 10_000);
  }

  setInterval(() => {
    if (!endsAt) return;
    const left = Math.max(0, Math.round((endsAt - Date.now()) / 1000));
    clock.broadcast({ left });
    if (left === 60) server.broadcast("One minute left!", Color.Orange);
    if (left === 0) end();
  }, 1000);

  start();
}

The client side shows left as m:ss in a HUD:

sagl.on("clock", ({ left }) =>
  hud.setText("clock", `${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")}`));