aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/lib/matches.ts
blob: d889a0d9cb32cb68108d356fd5e057e9df449195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { Match as ApiMatch, MatchPlayer as ApiMatchPlayer, Map } from "./api_types";

// match from the perspective of a bot
export type BotMatch = {
  id: number;
  opponent: BotMatchOpponent;
  outcome: BotMatchOutcome;
  timestamp: string;
  map: Map;
  hadErrors?: boolean;
};

export type BotMatchOutcome = "win" | "loss" | "tie";

export type BotMatchOpponent = {
  bot_id: number;
  bot_name: string;
  owner_id?: number;
};

export function apiMatchtoBotMatch(bot_name: string, apiMatch: ApiMatch): BotMatch {
  let player: ApiMatchPlayer;
  let playerIndex: number;
  let opponent: ApiMatchPlayer;
  apiMatch.players.forEach((matchPlayer, index) => {
    if (matchPlayer.bot_name === bot_name) {
      player = matchPlayer;
      playerIndex = index;
    } else {
      opponent = matchPlayer;
    }
  });

  if (player === undefined || opponent === undefined || playerIndex === undefined) {
    throw "could not assign player and opponent";
  }

  let outcome: BotMatchOutcome;
  if (apiMatch.winner === playerIndex) {
    outcome = "win";
  } else if (apiMatch.winner) {
    outcome = "loss";
  } else {
    outcome = "tie";
  }

  return {
    id: apiMatch.id,
    opponent,
    outcome,
    timestamp: apiMatch.timestamp,
    map: apiMatch.map,
    hadErrors: player.had_errors,
  };
}