Build your room

Pick system

Queue, captains who pick by number, the winner stays and teams are always the same size. Explained line by line.

The "pick" is the heart of a football room: it decides who plays, on which team and who waits. On this page you learn the rules and the code of pick.ts from the example project, and at the end you get ideas to customize it.

The rules

  1. Whoever joins goes to the queue (spectating).
  2. The 1st in the queue becomes blue captain; the 2nd, red captain.
  3. To fill the teams, the captain of the smaller team (tie: blue) types the number of the player they want. With no answer within 30 s, the first on the list goes. If only one candidate is left, they join without a pick.
  4. Teams always equal. With 3 players and teams of 2, it plays 1v1 and one waits. A match never starts 2v1.
  5. The winner stays blue. The whole losing team goes to the back of the queue and the 1st in the queue becomes the new red captain.
  6. Someone left or went AFK mid-match? The match stops and the teams are rebuilt.

An example with teams of 2 and Eva waiting:

text
blue: Ana, Carla     red: Bruno, Diego     queue: Eva
> red wins
blue: Bruno, Diego   red: Eva (captain)    queue: Ana, Carla
> Eva types: 2   (Carla)
blue: Bruno, Diego   red: Eva, Carla       queue: Ana

The state: four lists and a phase

Everything the pick needs to remember fits in a few variables (fila = queue, azul = blue, vermelho = red, fase = phase):

ts
private fila: number[] = [];          // spectator ids, in order of arrival
private readonly afk = new Set<number>();
private azul: number[] = [];          // the first one of each team is the captain
private vermelho: number[] = [];
private fase: 'lobby' | 'escolhendo' | 'jogando' = 'lobby';   // lobby | picking | playing

Players are stored by id (a number bonk.io gives each one in the room), never by name: two guests can have the same name.

The heart: atualizar()

Every time something changes (someone joined, left, a pick was made, the match ended), the pick calls atualizar() ("update"). It does three steps:

ts
private atualizar(): void {
  if (this.fase !== 'lobby') return;
  // 1) captains
  if (!this.azul.length && this.fila.length) this.azul.push(this.fila.shift()!);
  if (!this.vermelho.length && this.fila.length) this.vermelho.push(this.fila.shift()!);
  // 2) fill the teams: the smaller team's captain picks
  while (this.azul.length && this.vermelho.length && this.fila.length) {
    const time = this.azul.length <= this.vermelho.length ? TEAM_BLUE : TEAM_RED;
    if (this.lista(time).length >= this.n) break;          // both teams are full
    if (this.fila.length === 1) { this.lista(time).push(this.fila.shift()!); continue; }
    this.pedirEscolha(time);                              // pauses until the captain picks
    return;
  }
  // 3) the golden rule: teams of the same size
  const m = Math.min(this.azul.length, this.vermelho.length);
  if (m >= 1) for (const time of [this.azul, this.vermelho]) while (time.length > m) this.fila.unshift(time.pop()!);
  this.sincronizar();
  if (m >= 1) void this.comecar();
}

Step 3 is what guarantees "no 2v1": if a team got bigger, whoever is left over goes back to the front of the queue (they don't lose their turn).

Picking by number

pedirEscolha() ("ask for a pick") announces the list and waits. When the captain whose turn it is types in the chat, sala.ts passes the message to pick.mensagem() before any command:

ts
mensagem(id: number, texto: string): boolean {
  if (this.fase !== 'escolhendo' || this.vez === null || this.lista(this.vez)[0] !== id) return false;
  const n = Number(texto.trim().replace(/^!pick\s+/i, ''));   // accepts "2" and "!pick 2"
  const escolhido = Number.isInteger(n) ? this.fila[n - 1] : undefined;
  if (escolhido === undefined) return false;
  this.escolher(escolhido);
  return true;
}

If the captain leaves or someone on the list goes AFK during the pick, the list has changed and the pick restarts (recomecarEscolha()). Without that, the number they typed could point to another person.

Starting the match with the right state

bonk.io needs an initial state (the "IS blob") with one disc per player. The ScoreTracker builds that state with the game's own physics, for any number of players:

ts
this.pick = new Pick(room, config.tamanhoTime, async (escalacao) => {
  const is = await this.tracker.buildInitialState(escalacao);
  if (!is) return false;          // the pick tries again in 3 s
  room.startGame({ is });
  return true;
});

The escalacao ("lineup") is a list indexed by id: [ , {id:1,team:3}, {id:2,team:2}]. More details in Matches, IS blob and spectators.

End of match

The ScoreTracker emits match-winner. sala.ts waits 4 seconds (the game's victory screen) and calls pick.fimDePartida(team) ("end of match"):

ts
fimDePartida(vencedor: number): void {
  const perdedores = vencedor === TEAM_BLUE ? this.vermelho : this.azul;
  this.fila.push(...perdedores);                                   // back of the queue
  this.azul = vencedor === TEAM_BLUE ? this.azul : this.vermelho;  // the winner stays blue
  this.vermelho = [];                                              // 1st in the queue becomes captain
  this.pararPartida();
  this.atualizar();
}

AFK

  • !afk toggles it on and off. Whoever is playing cannot go AFK (it would be an easy way to escape a losing match).
  • The library's anti-AFK (room.enableAntiAfk()) emits player-afk when someone spends 12 s without moving or chatting during the match. The pick stops the match, moves the person to AFK and rebuilds the teams. See Anti-AFK.

The full code

ts
// pick.ts
import { TEAM_BLUE, TEAM_RED, TEAM_SPEC, type BonkRoom } from 'bonktools';
import { falar } from './chat.js';

type Fase = 'lobby' | 'escolhendo' | 'jogando';
/** Who plays the next match: index = player id (the format the ScoreTracker expects). */
export type Escalacao = Array<{ id: number; team: number } | null>;

const TEMPO_ESCOLHA_MS = 30_000;

/**
 * Pick system: waiting queue, captains who pick by number, the winner stays blue
 * and no match starts with uneven teams (no 2v1).
 */
export class Pick {
  private fila: number[] = []; // spectators, in order of arrival
  private readonly afk = new Set<number>();
  private azul: number[] = []; // the first one of each team is the captain
  private vermelho: number[] = [];
  private fase: Fase = 'lobby';
  private vez: number | null = null; // team of the captain who is picking
  private timer: NodeJS.Timeout | null = null;

  constructor(
    private readonly room: BonkRoom,
    /** Players per team (1 = 1v1, 2 = 2v2...). */
    private readonly n: number,
    /** Who actually starts the match (builds the initial state and calls room.startGame). */
    private readonly iniciar: (escalacao: Escalacao) => Promise<boolean>,
  ) {}

  get jogando(): boolean {
    return this.fase === 'jogando';
  }

  entrou(id: number): void {
    this.fila.push(id);
    this.atualizar();
  }

  saiu(id: number): void {
    const jogava = this.fase === 'jogando' && this.emCampo(id);
    this.remover(id);
    this.afk.delete(id);
    if (jogava) {
      falar(this.room, 'um jogador saiu: match ended, refazendo os times');
      this.pararPartida();
    }
    this.recomecarEscolha();
  }

  /** The captain whose turn it is typed something in chat. Returns true if it was a pick. */
  mensagem(id: number, texto: string): boolean {
    if (this.fase !== 'escolhendo' || this.vez === null || this.lista(this.vez)[0] !== id) return false;
    const n = Number(texto.trim().replace(/^!pick\s+/i, ''));
    const escolhido = Number.isInteger(n) ? this.fila[n - 1] : undefined;
    if (escolhido === undefined) return false;
    this.escolher(escolhido);
    return true;
  }

  /** !afk: toggles. Returns the reply for the chat. */
  alternarAfk(id: number): string {
    if (this.afk.delete(id)) {
      this.fila.push(id);
      this.atualizar();
      return `${this.nome(id)} saiu do AFK`;
    }
    if (this.fase === 'jogando' && this.emCampo(id)) return 'quem está jogando não pode ficar AFK agora';
    this.remover(id);
    this.afk.add(id);
    this.recomecarEscolha();
    return `${this.nome(id)} agora está AFK`;
  }

  /** The anti-AFK caught someone idle mid-match. */
  parado(id: number): void {
    if (!(this.fase === 'jogando' && this.emCampo(id))) return;
    falar(this.room, `${this.nome(id)} ficou parado e foi para o AFK`);
    this.remover(id);
    this.afk.add(id);
    this.pararPartida();
    this.atualizar();
  }

  /** End of match: call it after the victory screen. The loser goes to the back of the queue and the winner stays blue. */
  fimDePartida(vencedor: number): void {
    if (this.fase !== 'jogando') return;
    const perdedores = vencedor === TEAM_BLUE ? this.vermelho : this.azul;
    this.fila.push(...perdedores);
    this.azul = vencedor === TEAM_BLUE ? this.azul : this.vermelho;
    this.vermelho = [];
    this.pararPartida();
    this.atualizar();
  }

  // ── the heart: builds the teams and starts when possible ──────────────────────

  private atualizar(): void {
    if (this.fase !== 'lobby') return;
    // 1) captains: the first in the queue goes blue, the second goes red
    if (!this.azul.length && this.fila.length) this.azul.push(this.fila.shift()!);
    if (!this.vermelho.length && this.fila.length) this.vermelho.push(this.fila.shift()!);
    // 2) fills the teams: the captain of the smaller team picks (tie: blue)
    while (this.azul.length && this.vermelho.length && this.fila.length) {
      const time = this.azul.length <= this.vermelho.length ? TEAM_BLUE : TEAM_RED;
      if (this.lista(time).length >= this.n) break; // both teams are full
      if (this.fila.length === 1) {
        this.lista(time).push(this.fila.shift()!); // only one candidate: joins without a pick
        continue;
      }
      this.pedirEscolha(time);
      return;
    }
    // 3) the golden rule: both teams the SAME size (whoever is left over goes back to the front of the queue)
    const m = Math.min(this.azul.length, this.vermelho.length);
    if (m >= 1) for (const time of [this.azul, this.vermelho]) while (time.length > m) this.fila.unshift(time.pop()!);
    this.sincronizar();
    if (m >= 1) void this.comecar();
  }

  private pedirEscolha(time: number): void {
    this.fase = 'escolhendo';
    this.vez = time;
    this.sincronizar();
    const capitao = this.nome(this.lista(time)[0]!);
    falar(this.room, `${capitao}, digite o número de quem você quer no time:`);
    falar(this.room, this.fila.map((id, i) => `${i + 1} - ${this.nome(id)}`).join(', '));
    this.timer = setTimeout(() => this.escolher(this.fila[0]!), TEMPO_ESCOLHA_MS);
  }

  private escolher(id: number): void {
    if (this.vez === null || !this.fila.includes(id)) return;
    this.limparTimer();
    this.fila = this.fila.filter((x) => x !== id);
    this.lista(this.vez).push(id);
    falar(this.room, `${this.nome(this.lista(this.vez)[0]!)} escolheu ${this.nome(id)}`);
    this.fase = 'lobby';
    this.vez = null;
    this.atualizar();
  }

  private async comecar(): Promise<void> {
    this.fase = 'jogando';
    const escalacao: Escalacao = [];
    for (const id of this.azul) escalacao[id] = { id, team: TEAM_BLUE };
    for (const id of this.vermelho) escalacao[id] = { id, team: TEAM_RED };
    this.room.lockTeams(); // only the bot moves players
    const ok = await this.iniciar(escalacao).catch(() => false);
    if (!ok && this.fase === 'jogando') {
      this.fase = 'lobby';
      setTimeout(() => this.atualizar(), 3_000); // tries again shortly
    }
  }

  private pararPartida(): void {
    this.fase = 'lobby';
    this.room.stopGame();
    // The server doesn't send GAME_END to whoever stopped the match: we notify our own listeners.
    this.room.emit('game-end', { type: 'GAME_END' });
  }

  /** Someone left or went AFK during the pick: the list changed, so the pick restarts. */
  private recomecarEscolha(): void {
    if (this.fase === 'escolhendo') {
      this.limparTimer();
      this.fase = 'lobby';
      this.vez = null;
    }
    this.atualizar();
  }

  /** Puts each player on the team the pick decided (only sends what changed). */
  private sincronizar(): void {
    const quer = new Map<number, number>();
    for (const id of this.azul) quer.set(id, TEAM_BLUE);
    for (const id of this.vermelho) quer.set(id, TEAM_RED);
    for (const [id, p] of this.room.state.players) {
      if (id === this.room.state.myId) continue;
      const time = quer.get(id) ?? TEAM_SPEC;
      if (p.team !== time) this.room.setTeam(id, time);
    }
  }

  private lista(time: number): number[] {
    return time === TEAM_BLUE ? this.azul : this.vermelho;
  }

  private emCampo(id: number): boolean {
    return this.azul.includes(id) || this.vermelho.includes(id);
  }

  private remover(id: number): void {
    this.fila = this.fila.filter((x) => x !== id);
    this.azul = this.azul.filter((x) => x !== id);
    this.vermelho = this.vermelho.filter((x) => x !== id);
  }

  private nome(id: number): string {
    return this.room.state.players.get(id)?.userName ?? `#${id}`;
  }

  private limparTimer(): void {
    if (this.timer) clearTimeout(this.timer);
    this.timer = null;
  }

  destroy(): void {
    this.limparTimer();
  }
}

Ideas to customize

IdeaWhere to change
King of the court: whoever wins 3 in a row steps out to give others a turnCount wins in fimDePartida() and send the team to the queue
Queue skipping for VIPs (!furarfila)A command that moves the id to the front of fila
Random teams instead of picksIn pedirEscolha(), draw instead of waiting for the number
Stop the match when enough people arrive to turn a 1v1 into a 2v2In entrou(), if jogando and the teams are below n with enough queue, call pararPartida()
Shorter pick timeTEMPO_ESCOLHA_MS