@cordfuse/politik 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tournament.ts CHANGED
@@ -35,11 +35,18 @@ export interface Match {
35
35
  readonly a: string;
36
36
  readonly b: string | null;
37
37
  readonly winner: string | null;
38
+ /** Games needed to win: 1 for a single game, 3 for best-of-three, etc. */
39
+ readonly best_of: number;
40
+ /** Games won so far, per side — only ever above zero for a best-of-N match. */
41
+ readonly games: { readonly a: number; readonly b: number };
38
42
  }
39
43
 
40
44
  class TournamentError extends Error {}
41
45
  export { TournamentError };
42
46
 
47
+ /** Games one side must win to take a best-of-N match. */
48
+ export const gamesToWin = (bestOf: number): number => Math.floor(bestOf / 2) + 1;
49
+
43
50
  const pairKey = (a: string, b: string): string => [a, b].sort().join('|');
44
51
  const matchId = (round: number, a: string, b: string | null): string => `r${round}-${a}-${b ?? 'bye'}`;
45
52
 
@@ -49,8 +56,9 @@ const matchId = (round: number, a: string, b: string | null): string => `r${roun
49
56
 
50
57
  /** Every MATCH on the record, with its result if one has been reported. */
51
58
  export const matches = (hansard: string): readonly Match[] => {
52
- const created = new Map<string, { round: number; a: string; b: string | null }>();
59
+ const created = new Map<string, { round: number; a: string; b: string | null; bestOf: number }>();
53
60
  const winners = new Map<string, string>();
61
+ const gameWinners = new Map<string, string[]>();
54
62
 
55
63
  for (const entry of parseEntries(hansard)) {
56
64
  const id = entry.fields['Match'];
@@ -61,16 +69,25 @@ export const matches = (hansard: string): readonly Match[] => {
61
69
  round: Number(entry.fields['Round'] ?? '0'),
62
70
  a: entry.fields['A'] ?? '',
63
71
  b: b === undefined || b === 'bye' ? null : b,
72
+ bestOf: Math.max(1, Number(entry.fields['Best of'] ?? '1')),
64
73
  });
65
74
  } else if (entry.type === 'MATCH_DECIDED') {
66
75
  const w = entry.fields['Winner'];
67
76
  if (w !== undefined) winners.set(id, w);
77
+ } else if (entry.type === 'MATCH_GAME') {
78
+ const w = entry.fields['Winner'];
79
+ if (w !== undefined) gameWinners.set(id, [...(gameWinners.get(id) ?? []), w]);
68
80
  }
69
81
  }
70
82
 
71
- return [...created.entries()].map(([id, m]) => ({
72
- id, round: m.round, a: m.a, b: m.b, winner: winners.get(id) ?? null,
73
- }));
83
+ return [...created.entries()].map(([id, m]) => {
84
+ const gw = gameWinners.get(id) ?? [];
85
+ return {
86
+ id, round: m.round, a: m.a, b: m.b, best_of: m.bestOf,
87
+ games: { a: gw.filter((w) => w === m.a).length, b: gw.filter((w) => w === m.b).length },
88
+ winner: winners.get(id) ?? null,
89
+ };
90
+ });
74
91
  };
75
92
 
76
93
  /** Pairs already contested, so a format never rematches them. */
@@ -91,6 +108,13 @@ const playedPairs = (played: readonly Match[]): Set<string> => {
91
108
  * again. One left undefeated is the champion (returns no pairings).
92
109
  * - swiss: everyone, seeded by score, adjacent pairs, no rematches.
93
110
  * - round-robin: everyone, greedily paired with an opponent not yet played.
111
+ *
112
+ * `seed` is an optional strength order (strongest first). When given, the first
113
+ * round of a swiss or single-elim event pairs by the *fold* method — the top
114
+ * half against the bottom half (#1 vs the first of the lower half), so strong
115
+ * seeds meet late rather than by luck of the name sort — and in every later
116
+ * round the seed breaks ties within an equal-score group. A contestant absent
117
+ * from `seed` is treated as the weakest, ranked after every seeded one.
94
118
  */
95
119
  export const pairRound = (
96
120
  contestants: readonly string[],
@@ -98,19 +122,32 @@ export const pairRound = (
98
122
  format: PairingFormat,
99
123
  round: number,
100
124
  played: readonly Match[],
125
+ seed: readonly string[] = [],
101
126
  ): readonly Pairing[] => {
102
127
  const score = new Map(table.map((s) => [s.actor, s]));
103
128
  const losses = (a: string): number => score.get(a)?.losses ?? 0;
104
129
  const wins = (a: string): number => score.get(a)?.wins ?? 0;
130
+ const seedRank = new Map(seed.map((a, i) => [a, i] as const));
131
+ const bySeed = (a: string): number => seedRank.get(a) ?? Number.MAX_SAFE_INTEGER;
105
132
 
106
133
  let pool = [...contestants];
107
134
  if (format === 'single-elim') pool = pool.filter((a) => losses(a) === 0);
108
135
  if (pool.length < 2) return [];
109
136
 
110
- // Seed the order: by score for swiss/single-elim, by name for round-robin.
137
+ // Seed the order: by score for swiss/single-elim (seed, then name, break
138
+ // ties), by seed-or-name for round-robin.
111
139
  pool.sort((a, b) => format === 'round-robin'
112
- ? a.localeCompare(b)
113
- : (wins(b) - wins(a)) || (losses(a) - losses(b)) || a.localeCompare(b));
140
+ ? (bySeed(a) - bySeed(b)) || a.localeCompare(b)
141
+ : (wins(b) - wins(a)) || (losses(a) - losses(b)) || (bySeed(a) - bySeed(b)) || a.localeCompare(b));
142
+
143
+ // First round of a seeded bracket: fold the ordered field, top half against
144
+ // bottom half. An odd field gives the lowest top-half seed a bye.
145
+ if (seed.length > 0 && format !== 'round-robin' && played.length === 0) {
146
+ const mid = Math.ceil(pool.length / 2);
147
+ const top = pool.slice(0, mid);
148
+ const bottom = pool.slice(mid);
149
+ return top.map((a, i) => ({ a, b: bottom[i] ?? null }));
150
+ }
114
151
 
115
152
  const done = playedPairs(played);
116
153
  const used = new Set<string>();
@@ -135,8 +172,17 @@ export const pairRound = (
135
172
  return pairings;
136
173
  };
137
174
 
138
- /** Record a created MATCH. A bye is created already decided in the caller. */
139
- export const matchCreatedEntry = (pairing: Pairing, round: number, at: string): HansardEntry => ({
175
+ /**
176
+ * Record a created MATCH. A bye is created already decided in the caller.
177
+ * `bestOf` above 1 records a best-of-N match; the field is omitted for a plain
178
+ * single game so the common record is unchanged.
179
+ */
180
+ export const matchCreatedEntry = (
181
+ pairing: Pairing,
182
+ round: number,
183
+ at: string,
184
+ bestOf = 1,
185
+ ): HansardEntry => ({
140
186
  type: 'MATCH_CREATED',
141
187
  at,
142
188
  actor: 'RECORD',
@@ -146,6 +192,26 @@ export const matchCreatedEntry = (pairing: Pairing, round: number, at: string):
146
192
  Round: String(round),
147
193
  A: pairing.a,
148
194
  B: pairing.b ?? 'bye',
195
+ ...(bestOf > 1 ? { 'Best of': String(bestOf) } : {}),
196
+ },
197
+ });
198
+
199
+ /** Record one game of a best-of-N match. The match is decided separately. */
200
+ export const matchGameEntry = (
201
+ id: string,
202
+ round: number,
203
+ winner: string,
204
+ at: string,
205
+ by: string,
206
+ ): HansardEntry => ({
207
+ type: 'MATCH_GAME',
208
+ at,
209
+ actor: by,
210
+ role: 'AUTHORITY',
211
+ fields: {
212
+ Match: id,
213
+ Round: String(round),
214
+ Winner: winner,
149
215
  },
150
216
  });
151
217
 
@@ -170,9 +236,28 @@ export const matchDecidedEntry = (
170
236
  },
171
237
  });
172
238
 
239
+ export interface MatchReport {
240
+ /** The terminal entry appended — MATCH_DECIDED when the match is settled, the
241
+ * MATCH_GAME otherwise. Kept for callers that only need the last act. */
242
+ readonly entry: HansardEntry;
243
+ /** Every entry appended, in order (a game, optionally its deciding entry). */
244
+ readonly entries: readonly HansardEntry[];
245
+ readonly hansard: string;
246
+ /** True when this report settled the match. */
247
+ readonly decided: boolean;
248
+ readonly winner: string;
249
+ /** Game wins per side after this report — {a,b} both 0 for a settled best-of-1. */
250
+ readonly games: { readonly a: number; readonly b: number };
251
+ }
252
+
173
253
  /**
174
254
  * Report a result. Validates the match exists, is undecided, and the winner is
175
255
  * one of its contestants — a referee cannot crown a party that never played.
256
+ *
257
+ * A best-of-1 match settles on the single report (MATCH_DECIDED). A best-of-N
258
+ * match records the reported game (MATCH_GAME) and settles only once a side has
259
+ * won a majority — so `match report` is called per game and the caller sees the
260
+ * running tally until the deciding game lands.
176
261
  */
177
262
  export const reportMatch = (
178
263
  matchRef: string,
@@ -180,7 +265,7 @@ export const reportMatch = (
180
265
  at: string,
181
266
  referee: string,
182
267
  hansard: string,
183
- ): { readonly entry: HansardEntry; readonly hansard: string } => {
268
+ ): MatchReport => {
184
269
  const match = matches(hansard).find((m) => m.id === matchRef);
185
270
  if (match === undefined) throw new TournamentError(`no match ${matchRef} on the record`);
186
271
  if (match.winner !== null) throw new TournamentError(`match ${matchRef} is already decided — ${match.winner} won`);
@@ -188,8 +273,35 @@ export const reportMatch = (
188
273
  throw new TournamentError(`${winner} is not in match ${matchRef} (${match.a} vs ${match.b ?? 'bye'})`);
189
274
  }
190
275
  const loser = winner === match.a ? match.b : match.a;
191
- const entry = matchDecidedEntry(match.id, match.round, winner, loser, at, referee);
192
- return { entry, hansard: appendEntry(hansard, entry) };
276
+
277
+ // Best-of-1: one report decides it, exactly as before.
278
+ if (match.best_of <= 1) {
279
+ const decided = matchDecidedEntry(match.id, match.round, winner, loser, at, referee);
280
+ return {
281
+ entry: decided, entries: [decided], hansard: appendEntry(hansard, decided),
282
+ decided: true, winner, games: { a: 0, b: 0 },
283
+ };
284
+ }
285
+
286
+ // Best-of-N: this game counts toward the winner; the match settles on a majority.
287
+ const games = winner === match.a
288
+ ? { a: match.games.a + 1, b: match.games.b }
289
+ : { a: match.games.a, b: match.games.b + 1 };
290
+ const game = matchGameEntry(match.id, match.round, winner, at, referee);
291
+ const entries: HansardEntry[] = [game];
292
+ let doc = appendEntry(hansard, game);
293
+
294
+ const wonEnough = (winner === match.a ? games.a : games.b) >= gamesToWin(match.best_of);
295
+ if (wonEnough) {
296
+ const decided = matchDecidedEntry(match.id, match.round, winner, loser, at, referee);
297
+ entries.push(decided);
298
+ doc = appendEntry(doc, decided);
299
+ }
300
+
301
+ return {
302
+ entry: entries[entries.length - 1] as HansardEntry,
303
+ entries, hansard: doc, decided: wonEnough, winner, games,
304
+ };
193
305
  };
194
306
 
195
307
  /** The undefeated contestants — for single-elim, the ones still in the bracket. */