unocab 0.8.0

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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -0
  3. package/esm/_dnt.shims.d.ts +4 -0
  4. package/esm/_dnt.shims.js +62 -0
  5. package/esm/_dnt.test_shims.d.ts +7 -0
  6. package/esm/deps/deno.land/std@0.190.0/fmt/colors.d.ts +270 -0
  7. package/esm/deps/deno.land/std@0.190.0/testing/_diff.d.ts +26 -0
  8. package/esm/deps/deno.land/std@0.190.0/testing/_format.d.ts +1 -0
  9. package/esm/deps/deno.land/std@0.190.0/testing/asserts.d.ts +284 -0
  10. package/esm/deps/deno.land/x/zod@v3.21.4/ZodError.d.ts +163 -0
  11. package/esm/deps/deno.land/x/zod@v3.21.4/ZodError.js +148 -0
  12. package/esm/deps/deno.land/x/zod@v3.21.4/errors.d.ts +5 -0
  13. package/esm/deps/deno.land/x/zod@v3.21.4/errors.js +9 -0
  14. package/esm/deps/deno.land/x/zod@v3.21.4/external.d.ts +6 -0
  15. package/esm/deps/deno.land/x/zod@v3.21.4/external.js +6 -0
  16. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/enumUtil.d.ts +8 -0
  17. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/enumUtil.js +1 -0
  18. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/errorUtil.d.ts +9 -0
  19. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/errorUtil.js +5 -0
  20. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/parseUtil.d.ts +78 -0
  21. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/parseUtil.js +104 -0
  22. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/partialUtil.d.ts +8 -0
  23. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/partialUtil.js +1 -0
  24. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/typeAliases.d.ts +2 -0
  25. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/typeAliases.js +1 -0
  26. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/util.d.ts +68 -0
  27. package/esm/deps/deno.land/x/zod@v3.21.4/helpers/util.js +138 -0
  28. package/esm/deps/deno.land/x/zod@v3.21.4/index.d.ts +4 -0
  29. package/esm/deps/deno.land/x/zod@v3.21.4/index.js +4 -0
  30. package/esm/deps/deno.land/x/zod@v3.21.4/locales/en.d.ts +3 -0
  31. package/esm/deps/deno.land/x/zod@v3.21.4/locales/en.js +127 -0
  32. package/esm/deps/deno.land/x/zod@v3.21.4/mod.d.ts +1 -0
  33. package/esm/deps/deno.land/x/zod@v3.21.4/mod.js +1 -0
  34. package/esm/deps/deno.land/x/zod@v3.21.4/types.d.ts +965 -0
  35. package/esm/deps/deno.land/x/zod@v3.21.4/types.js +3689 -0
  36. package/esm/errors.d.ts +72 -0
  37. package/esm/errors.js +39 -0
  38. package/esm/game.d.ts +868 -0
  39. package/esm/game.js +868 -0
  40. package/esm/mod.d.ts +3 -0
  41. package/esm/mod.js +3 -0
  42. package/esm/package.json +3 -0
  43. package/esm/tests/basic-tests.d.ts +8 -0
  44. package/esm/tests/draw-tests.d.ts +8 -0
  45. package/esm/tests/non-specific-tests.test.d.ts +1 -0
  46. package/esm/tests/rule-violation-tests.d.ts +8 -0
  47. package/esm/tests/specific-tests.test.d.ts +1 -0
  48. package/esm/tests/test-utils.d.ts +91 -0
  49. package/esm/tests/turn-tests.d.ts +8 -0
  50. package/esm/types.d.ts +2280 -0
  51. package/esm/types.js +152 -0
  52. package/esm/utils.d.ts +19 -0
  53. package/esm/utils.js +44 -0
  54. package/package.json +32 -0
  55. package/script/_dnt.shims.d.ts +4 -0
  56. package/script/_dnt.shims.js +66 -0
  57. package/script/_dnt.test_shims.d.ts +7 -0
  58. package/script/deps/deno.land/std@0.190.0/fmt/colors.d.ts +270 -0
  59. package/script/deps/deno.land/std@0.190.0/testing/_diff.d.ts +26 -0
  60. package/script/deps/deno.land/std@0.190.0/testing/_format.d.ts +1 -0
  61. package/script/deps/deno.land/std@0.190.0/testing/asserts.d.ts +284 -0
  62. package/script/deps/deno.land/x/zod@v3.21.4/ZodError.d.ts +163 -0
  63. package/script/deps/deno.land/x/zod@v3.21.4/ZodError.js +152 -0
  64. package/script/deps/deno.land/x/zod@v3.21.4/errors.d.ts +5 -0
  65. package/script/deps/deno.land/x/zod@v3.21.4/errors.js +17 -0
  66. package/script/deps/deno.land/x/zod@v3.21.4/external.d.ts +6 -0
  67. package/script/deps/deno.land/x/zod@v3.21.4/external.js +22 -0
  68. package/script/deps/deno.land/x/zod@v3.21.4/helpers/enumUtil.d.ts +8 -0
  69. package/script/deps/deno.land/x/zod@v3.21.4/helpers/enumUtil.js +2 -0
  70. package/script/deps/deno.land/x/zod@v3.21.4/helpers/errorUtil.d.ts +9 -0
  71. package/script/deps/deno.land/x/zod@v3.21.4/helpers/errorUtil.js +8 -0
  72. package/script/deps/deno.land/x/zod@v3.21.4/helpers/parseUtil.d.ts +78 -0
  73. package/script/deps/deno.land/x/zod@v3.21.4/helpers/parseUtil.js +119 -0
  74. package/script/deps/deno.land/x/zod@v3.21.4/helpers/partialUtil.d.ts +8 -0
  75. package/script/deps/deno.land/x/zod@v3.21.4/helpers/partialUtil.js +2 -0
  76. package/script/deps/deno.land/x/zod@v3.21.4/helpers/typeAliases.d.ts +2 -0
  77. package/script/deps/deno.land/x/zod@v3.21.4/helpers/typeAliases.js +2 -0
  78. package/script/deps/deno.land/x/zod@v3.21.4/helpers/util.d.ts +68 -0
  79. package/script/deps/deno.land/x/zod@v3.21.4/helpers/util.js +142 -0
  80. package/script/deps/deno.land/x/zod@v3.21.4/index.d.ts +4 -0
  81. package/script/deps/deno.land/x/zod@v3.21.4/index.js +33 -0
  82. package/script/deps/deno.land/x/zod@v3.21.4/locales/en.d.ts +3 -0
  83. package/script/deps/deno.land/x/zod@v3.21.4/locales/en.js +129 -0
  84. package/script/deps/deno.land/x/zod@v3.21.4/mod.d.ts +1 -0
  85. package/script/deps/deno.land/x/zod@v3.21.4/mod.js +17 -0
  86. package/script/deps/deno.land/x/zod@v3.21.4/types.d.ts +965 -0
  87. package/script/deps/deno.land/x/zod@v3.21.4/types.js +3739 -0
  88. package/script/errors.d.ts +72 -0
  89. package/script/errors.js +43 -0
  90. package/script/game.d.ts +868 -0
  91. package/script/game.js +895 -0
  92. package/script/mod.d.ts +3 -0
  93. package/script/mod.js +19 -0
  94. package/script/package.json +3 -0
  95. package/script/tests/basic-tests.d.ts +8 -0
  96. package/script/tests/draw-tests.d.ts +8 -0
  97. package/script/tests/non-specific-tests.test.d.ts +1 -0
  98. package/script/tests/rule-violation-tests.d.ts +8 -0
  99. package/script/tests/specific-tests.test.d.ts +1 -0
  100. package/script/tests/test-utils.d.ts +91 -0
  101. package/script/tests/turn-tests.d.ts +8 -0
  102. package/script/types.d.ts +2280 -0
  103. package/script/types.js +155 -0
  104. package/script/utils.d.ts +19 -0
  105. package/script/utils.js +50 -0
package/esm/game.js ADDED
@@ -0,0 +1,868 @@
1
+ import * as dntShim from "./_dnt.shims.js";
2
+ import { UECode, UnocabError } from "./errors.js";
3
+ import { colorSwitchingScs, gameState, playerId, } from "./types.js";
4
+ import { DECK, ENGINE_ID, MAX_PLAYERS, MAX_SHORTHAND_EVENTS, MIN_PLAYERS, cyrb128, exhaustive, includes, } from "./utils.js";
5
+ export class Game {
6
+ get state() {
7
+ return structuredClone(this._state);
8
+ }
9
+ constructor(
10
+ // if a serialised state is provided, none of the
11
+ // customisation props are used, so don't allow
12
+ // passing them together with the serialised state.
13
+ props = {}) {
14
+ // FullGameState if Shorthand is false.
15
+ // ShorthandGameState if Shorthand is true.
16
+ // GameState (FullGameState | ShorthandGameState) if Shorthand is boolean.
17
+ Object.defineProperty(this, "_state", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: void 0
22
+ });
23
+ if ("serialisedState" in props && props.serialisedState) {
24
+ const state = JSON.parse(props.serialisedState);
25
+ gameState.parse(state);
26
+ this._state = state;
27
+ }
28
+ else {
29
+ const initialSeed = (() => {
30
+ if (props.initialSeed) {
31
+ return typeof props.initialSeed == "string"
32
+ ? cyrb128(props.initialSeed)
33
+ : props.initialSeed;
34
+ }
35
+ const randomValues = new Uint32Array(1);
36
+ dntShim.crypto.getRandomValues(randomValues);
37
+ return randomValues[0];
38
+ })();
39
+ const commonState = {
40
+ index: 0,
41
+ players: [],
42
+ initialSeed,
43
+ stackPlusTwos: props.stackPlusTwos ?? true,
44
+ cache: {
45
+ hands: {},
46
+ deck: [],
47
+ seed: initialSeed,
48
+ ended: false,
49
+ stackedPlusTwos: 0,
50
+ turnStep: 1,
51
+ pile: [],
52
+ last3CardPlayOrColorChanges: [],
53
+ },
54
+ };
55
+ if (props.shorthandMode) {
56
+ const shorthandGameState = {
57
+ shorthandMode: true,
58
+ events: [],
59
+ ...commonState,
60
+ };
61
+ // @ts-expect-error todo: figure out why we cannot narrow here
62
+ this._state = shorthandGameState;
63
+ }
64
+ else {
65
+ const fullGameState = {
66
+ shorthandMode: false,
67
+ events: [],
68
+ ...commonState,
69
+ };
70
+ // @ts-expect-error todo: figure out why we cannot narrow here
71
+ this._state = fullGameState;
72
+ }
73
+ if (!props.noInit) {
74
+ // assign everything that needs random(), since it
75
+ // cannot be used before _state is assigned.
76
+ this.init();
77
+ }
78
+ }
79
+ }
80
+ // mulberry32
81
+ random() {
82
+ let t = (this._state.cache.seed += 0x6d2b79f5);
83
+ t = Math.imul(t ^ (t >>> 15), t | 1);
84
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
85
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
86
+ }
87
+ shuffleDeck() {
88
+ const toShuffle = this._state.cache.deck;
89
+ for (let i = toShuffle.length - 1; i > 0; i--) {
90
+ const j = Math.floor(this.random() * (i + 1));
91
+ [toShuffle[i], toShuffle[j]] = [toShuffle[j], toShuffle[i]];
92
+ }
93
+ this.recordEvent({
94
+ type: "game_info",
95
+ info: {
96
+ type: "seed_changed",
97
+ newSeed: this._state.cache.seed,
98
+ },
99
+ });
100
+ }
101
+ nonInfoEvents() {
102
+ return this.state.events.filter((e) => e.type !== "game_info");
103
+ }
104
+ init(customDeckTopCard) {
105
+ this._state.cache.deck = structuredClone(DECK);
106
+ this.shuffleDeck();
107
+ // todo: return the deck top card here, and figure out what
108
+ // happens when it happens to be a color switching card.
109
+ const pileTopCard = (() => {
110
+ if (customDeckTopCard)
111
+ return customDeckTopCard;
112
+ const index = this._state.cache.deck.findIndex((card) => !includes(colorSwitchingScs.options, card.type));
113
+ const [ptc] = this._state.cache.deck.splice(index, 1);
114
+ return ptc;
115
+ })();
116
+ const firstCardPlayEvent = {
117
+ type: "card_played",
118
+ by: ENGINE_ID,
119
+ card: pileTopCard,
120
+ };
121
+ this._state.events = [firstCardPlayEvent];
122
+ this._state.cache.pile = [pileTopCard];
123
+ this._state.cache.last3CardPlayOrColorChanges = [pileTopCard];
124
+ }
125
+ recordEvent(event) {
126
+ if (this._state.shorthandMode) {
127
+ if (event.type == "game_info")
128
+ return;
129
+ // in shorthand mode, we keep at most MAX_SHORTHAND_EVENTS
130
+ if (this._state.events.length == MAX_SHORTHAND_EVENTS) {
131
+ this._state.events.shift();
132
+ }
133
+ this._state.events.push(event);
134
+ }
135
+ else
136
+ this._state.events.push(event);
137
+ }
138
+ deckTopCard() {
139
+ // if the deck is empty, shuffle the playing pile and make it the new deck
140
+ if (!this._state.cache.deck.length) {
141
+ const pile = this.getPile();
142
+ if (!pile.length) {
143
+ throw new UnocabError(UECode.DeckPileExhausted, undefined, "Both the deck and pile have been exhausted, cannot draw");
144
+ }
145
+ this._state.cache.deck = pile;
146
+ this.shuffleDeck();
147
+ this._state.cache.pile = [];
148
+ this.recordEvent({
149
+ type: "game_info",
150
+ info: { type: "pile_to_deck" },
151
+ });
152
+ }
153
+ return this._state.cache.deck.shift();
154
+ }
155
+ /**
156
+ * Returns the last two events that don't have the type "game_info".
157
+ * @param ignoredEvents - the number of non-info events to ignore from
158
+ * the end. This param is useful, say, when checking during a bluff call,
159
+ * where you might need to ignore the last 3 events.
160
+ */
161
+ lastTwoNonInfoEvents(ignoredEvents) {
162
+ // one game event is always guaranteed to be present, since at the
163
+ // start of the game, the engine always plays a card.
164
+ return this.nonInfoEvents()
165
+ .slice(-2 + (ignoredEvents ?? 0), ignoredEvents)
166
+ .reverse();
167
+ }
168
+ /**
169
+ * Returns the playing pile. This is where the first card is
170
+ * played, and where all the subsequent cards played by players
171
+ * are put. It is guaranteed to have one card at the start.
172
+ *
173
+ * ```typescript
174
+ * const game = new Game();
175
+ * game.play(p1, { type: "one", color: "red" });
176
+ * game.play(p2, { type: "one", color: "green" });
177
+ *
178
+ * assertEquals(game.getPile(), [
179
+ * { type: "six", color: "red" }, // randomly chosen by engine
180
+ * { type: "one", color: "red" },
181
+ * { type: "one", color: "green" },
182
+ * ]);
183
+ * ```
184
+ */
185
+ getPile() {
186
+ return structuredClone(this._state.cache.pile);
187
+ }
188
+ /**
189
+ * @param bluffSiteCheck - if set to true, the last 3 events will be ignored.
190
+ *
191
+ * Check whether the given event is valid at the current
192
+ * state of the game.
193
+ *
194
+ * ```typescript
195
+ * const game = new Game();
196
+ * game.draw(p1);
197
+ *
198
+ * // false, since you cannot call bluff after drawing
199
+ * game.checkEvent({ type: "bluff_called", by: p1 });
200
+ *
201
+ * // true, since you can pass after drawing
202
+ * game.checkEvent({ type: "pass", by: p1 }); // true
203
+ *
204
+ * game.pass(p1);
205
+ *
206
+ * // false, since you cannot pass without drawing
207
+ * game.checkEvent({ type: "draw", by: p2 }); // false
208
+ * ```
209
+ */
210
+ checkEvent(event, bluffSiteCheck = false) {
211
+ if (!bluffSiteCheck) {
212
+ // if a player leaves before another player calls bluff, this should still work
213
+ const playerCount = this._state.players.length;
214
+ if (playerCount < MIN_PLAYERS) {
215
+ return new UnocabError(UECode.TooFewPlayers, { playerCount }, "An active game must have at least two players");
216
+ }
217
+ // during a bluff site check, an actual move is not being checked for
218
+ if (event.by != this.activePlayer()) {
219
+ return new UnocabError(UECode.NotPlayersTurn, { playerId: event.by }, "It is not your turn");
220
+ }
221
+ }
222
+ const gameEnded = this.hasEnded();
223
+ if (gameEnded) {
224
+ return new UnocabError(UECode.GameEnded, { loser: gameEnded.loser }, "This game has ended");
225
+ }
226
+ // during a bluff site check, we need to not consider
227
+ // the last 3 events, since those would be the playing
228
+ // of +4, a color change, and a bluff call. By going
229
+ // back 3 steps, we reach a point where we check the
230
+ // event as if the player has not yet played a +4. This
231
+ // allows us to figure out if the player was bluffing.
232
+ const [lastEvent, secondLastEvent] = this.lastTwoNonInfoEvents(bluffSiteCheck ? -3 : undefined);
233
+ // if the last card was a color switching card, enforce color choose
234
+ if (lastEvent.type == "card_played" &&
235
+ includes(colorSwitchingScs.options, lastEvent.card.type) &&
236
+ event.type != "choose-color") {
237
+ return new UnocabError(UECode.MustPickColor, { performedEvent: event }, "Must pick color after playing a color switching card");
238
+ }
239
+ // if the last card was a +2, enforce draw or play of another +2
240
+ if (lastEvent.type == "card_played" &&
241
+ lastEvent.card.type == "plus-two" &&
242
+ event.type != "draw") {
243
+ const plusTwoPlayed = event.type == "card_played" && event.card.type == "plus-two";
244
+ if (!plusTwoPlayed) {
245
+ return new UnocabError(UECode.MustDrawOrPlusTwo, { performedEvent: event }, "Must draw or play another +2 on a +2");
246
+ }
247
+ }
248
+ if (secondLastEvent) {
249
+ // if the last card was a +4, enforce draw or call bluff
250
+ if (secondLastEvent.type == "card_played" &&
251
+ secondLastEvent.card.type == "plus-four" &&
252
+ event.type != "draw" &&
253
+ event.type != "bluff_called") {
254
+ return new UnocabError(UECode.MustDrawOrCallBluff, { performedEvent: event }, "Must either draw or call bluff after +4");
255
+ }
256
+ }
257
+ if (event.type == "card_played") {
258
+ const card = event.card;
259
+ if (includes(colorSwitchingScs.options, card.type) &&
260
+ this.handOf(event.by).length == 1) {
261
+ return new UnocabError(UECode.MustNotPlayLastCardColorChanging, { performedEvent: event }, `Cannot play one of ${colorSwitchingScs.options} as the last card`);
262
+ }
263
+ // if any of these are/have undefined, they become a non-condition.
264
+ const { expectedColor, expectedType } = this.expectedCard(bluffSiteCheck);
265
+ if (expectedType != card.type &&
266
+ (card.color ?? expectedColor) != expectedColor) {
267
+ let msg = "Must play ";
268
+ if (expectedType) {
269
+ msg += `card of type ${expectedType}`;
270
+ }
271
+ if (expectedColor) {
272
+ const ecErr = `color ${expectedColor}`;
273
+ msg += msg == "Must play " ? `card of ${ecErr}` : ` or ${ecErr}`;
274
+ }
275
+ const cardColor = card.color;
276
+ msg += `, found ${card.type}${cardColor ? ` of color ${cardColor}` : ""}`;
277
+ return new UnocabError(UECode.MustPlayExpectedCard, {
278
+ expected: { expectedType, expectedColor },
279
+ found: card,
280
+ }, msg);
281
+ }
282
+ }
283
+ else if (event.type == "draw") {
284
+ if (lastEvent.type == "draw" && lastEvent.by == event.by) {
285
+ return new UnocabError(UECode.MustNotDrawTwice, undefined, "Cannot draw twice in a row");
286
+ }
287
+ }
288
+ else if (event.type == "pass") {
289
+ const hasDrawn = lastEvent.type == "draw" && lastEvent.by == event.by;
290
+ if (!hasDrawn)
291
+ return new UnocabError(UECode.MustNotPassWithoutDraw, undefined, "Cannot pass without drawing");
292
+ }
293
+ else if (event.type == "bluff_called") {
294
+ const [, secondLastEvent] = this.lastTwoNonInfoEvents();
295
+ if (!secondLastEvent ||
296
+ secondLastEvent.type != "card_played" ||
297
+ secondLastEvent.card.type != "plus-four") {
298
+ return new UnocabError(UECode.CannotCallBluff, undefined, "You cannot call bluff when the last card is not a +4 or a color has not yet been chosen");
299
+ }
300
+ }
301
+ else if (event.type == "choose-color") {
302
+ if (lastEvent.type != "card_played" ||
303
+ !includes(colorSwitchingScs.options, lastEvent.card.type) ||
304
+ event.by != lastEvent.by) {
305
+ return new UnocabError(UECode.CannotSwitchColors, undefined, `You can only switch colors if you played one of [${colorSwitchingScs.options}] in the last turn`);
306
+ }
307
+ }
308
+ }
309
+ // ─── Event Processing Method ─────────────────────────────────────────
310
+ /**
311
+ * This function can be used as an alternative to the user-friendly
312
+ * methods like {@link Game.draw} or {@link Game.pass}, where you are
313
+ * allowed to directly pass in a {@link GameEvent}.
314
+ *
315
+ * ```typescript
316
+ * const game = new Game();
317
+ *
318
+ * // regular way
319
+ * game.draw(p1);
320
+ *
321
+ * // processNewEvent way
322
+ * game.processNewEvent({ type: "draw", by: p1 });
323
+ * ```
324
+ */
325
+ processNewEvent(event) {
326
+ if (!playerId.safeParse(event.by).success) {
327
+ throw new UnocabError(UECode.InvalidId, { id: event.by }, "Invalid player ID");
328
+ }
329
+ const hand = this.handOf(event.by);
330
+ const err = this.checkEvent(event);
331
+ if (err)
332
+ throw err;
333
+ // ─── Card Played Event ───────────────────────────────
334
+ if (event.type == "card_played") {
335
+ const currentCard = event.card;
336
+ const cardIndex = hand.findIndex((c) => c.type == event.card.type && c.color == event.card.color);
337
+ if (cardIndex < 0) {
338
+ throw new UnocabError(UECode.PlayerDoesntHaveCard, { playerId: event.by, card: event.card }, "You do not have this card");
339
+ }
340
+ // remove the card from the players deck
341
+ hand.splice(cardIndex, 1);
342
+ // add this event to the game events
343
+ this.recordEvent(event);
344
+ if (this._state.cache.last3CardPlayOrColorChanges.length == 3)
345
+ this._state.cache.last3CardPlayOrColorChanges.shift();
346
+ this._state.cache.last3CardPlayOrColorChanges.push(currentCard);
347
+ this._state.cache.pile.push(currentCard);
348
+ if (currentCard.type == "plus-two") {
349
+ this._state.cache.stackedPlusTwos++;
350
+ }
351
+ if (currentCard.type == "reverse") {
352
+ this._state.cache.turnStep *= -1;
353
+ }
354
+ if (!includes(colorSwitchingScs.options, currentCard.type)) {
355
+ const turnStepMultiplier = (() => {
356
+ if (currentCard.type == "skip") {
357
+ return 2;
358
+ }
359
+ else if (currentCard.type == "reverse") {
360
+ return this._state.players.length == 2 ? 2 : 1;
361
+ }
362
+ return 1;
363
+ })();
364
+ this._state.index += this._state.cache.turnStep * turnStepMultiplier;
365
+ }
366
+ if (!this.handOf(event.by).length) {
367
+ // add 'player_won' event if the player's deck is now empty
368
+ this.recordEvent({
369
+ type: "game_info",
370
+ info: {
371
+ type: "player_won",
372
+ id: event.by,
373
+ },
374
+ });
375
+ // if there's only one person left with cards, end the game
376
+ const playersWithCards = Object.entries(this._state.cache.hands)
377
+ .filter(([, v]) => v.length)
378
+ .map(([k]) => k);
379
+ if (playersWithCards.length == 1) {
380
+ this.recordEvent({
381
+ type: "game_info",
382
+ info: {
383
+ type: "game_ended",
384
+ loser: playersWithCards[0],
385
+ },
386
+ });
387
+ this._state.cache.ended = true;
388
+ return {
389
+ type: "player_win_game_end",
390
+ won: event.by,
391
+ lost: playersWithCards[0],
392
+ formatted: `Player ${event.by} won! Game ended.`,
393
+ };
394
+ }
395
+ return {
396
+ type: "player_win",
397
+ won: event.by,
398
+ formatted: `Player ${event.by} won!`,
399
+ };
400
+ }
401
+ return {
402
+ type: "card_played",
403
+ card: event.card,
404
+ formatted: `Played a ${event.card.color ? `${event.card.color} ` : ""}${event.card.type}`,
405
+ };
406
+ }
407
+ // ─── Draw Event ──────────────────────────────────────────────
408
+ else if (event.type == "draw") {
409
+ const [lastEvent, secondLastEvent] = this.lastTwoNonInfoEvents();
410
+ const toDraw = (() => {
411
+ if (lastEvent.type == "card_played" &&
412
+ lastEvent.card.type == "plus-two") {
413
+ const stackedPlusTwos = this._state.stackPlusTwos
414
+ ? this._state.cache.stackedPlusTwos
415
+ : 1;
416
+ return stackedPlusTwos * 2;
417
+ }
418
+ if (secondLastEvent &&
419
+ secondLastEvent.type == "card_played" &&
420
+ secondLastEvent.card.type == "plus-four") {
421
+ return 4;
422
+ }
423
+ return 1;
424
+ })();
425
+ const drawCards = Array(toDraw)
426
+ .fill(null)
427
+ .map(() => this.deckTopCard());
428
+ this.handOf(event.by).push(...drawCards);
429
+ // forfeit the turn after drawing 2/4 cards
430
+ if (toDraw != 1) {
431
+ this._state.index += this._state.cache.turnStep;
432
+ }
433
+ // add this event to the game events
434
+ this.recordEvent(event);
435
+ this._state.cache.stackedPlusTwos = 0;
436
+ return {
437
+ type: "drawing_cards",
438
+ cards: drawCards,
439
+ count: drawCards.length,
440
+ formatted: `Drawing ${drawCards.length} card(s)`,
441
+ };
442
+ }
443
+ // ─── Pass Event ──────────────────────────────────────────────
444
+ else if (event.type == "pass") {
445
+ // add this event to the game events and increase the turn
446
+ this.recordEvent(event);
447
+ this._state.index += this._state.cache.turnStep;
448
+ return {
449
+ type: "turn_passed",
450
+ formatted: "Turn passed",
451
+ };
452
+ }
453
+ // ─── Bluff Called Event ──────────────────────────────────────
454
+ else if (event.type == "bluff_called") {
455
+ // this cast is safe, because it has already been checked for
456
+ // in the checkEvent() function above.
457
+ const [, secondLastEvent] = this.lastTwoNonInfoEvents();
458
+ const lastPlayerId = secondLastEvent.by;
459
+ const lastPlayerHand = this.handOf(lastPlayerId);
460
+ // add this event to the game events and increase the step
461
+ this.recordEvent(event);
462
+ this._state.index += this._state.cache.turnStep;
463
+ if (lastPlayerHand
464
+ .filter((c) => !includes(colorSwitchingScs.options, c.type))
465
+ .some((c) =>
466
+ // if the return value is not an error, it's a valid play
467
+ !this.checkEvent({
468
+ type: "card_played",
469
+ card: c,
470
+ by: ENGINE_ID,
471
+ }, true))) {
472
+ // bluff call succeeded, give 4 cards to last player
473
+ lastPlayerHand.push(...Array(4)
474
+ .fill(null)
475
+ .map(() => this.deckTopCard()));
476
+ const info = {
477
+ type: "bluff_call_succeeded",
478
+ by: event.by,
479
+ of: lastPlayerId,
480
+ };
481
+ this.recordEvent({
482
+ type: "game_info",
483
+ info,
484
+ });
485
+ return {
486
+ ...info,
487
+ formatted: "Bluff called! giving 4 cards to the previous player.",
488
+ };
489
+ }
490
+ else {
491
+ // bluff call failed, give 6 cards to current player
492
+ this.handOf(event.by).push(...Array(6)
493
+ .fill(null)
494
+ .map(() => this.deckTopCard()));
495
+ const info = {
496
+ type: "bluff_call_failed",
497
+ by: event.by,
498
+ of: lastPlayerId,
499
+ };
500
+ this.recordEvent({
501
+ type: "game_info",
502
+ info,
503
+ });
504
+ return {
505
+ ...info,
506
+ formatted: "Bluff call failed! Giving 6 cards to current player",
507
+ };
508
+ }
509
+ }
510
+ // ─── Choose Color Event ──────────────────────────────
511
+ else if (event.type == "choose-color") {
512
+ if (this._state.cache.last3CardPlayOrColorChanges.length == 3)
513
+ this._state.cache.last3CardPlayOrColorChanges.shift();
514
+ this._state.cache.last3CardPlayOrColorChanges.push(event.color);
515
+ // add this event to the game events and increase the turn
516
+ this.recordEvent(event);
517
+ this._state.index += this._state.cache.turnStep;
518
+ return {
519
+ type: "color_changed",
520
+ to: event.color,
521
+ formatted: `Color changed to ${event.color}`,
522
+ };
523
+ }
524
+ else
525
+ exhaustive(event);
526
+ throw "unreachable";
527
+ }
528
+ // ─── Gameplay Functions ──────────────────────────────────────────────
529
+ /**
530
+ * Have player(s) denoted by an ID join the game.
531
+ *
532
+ * ```typescript
533
+ * const game = new Game();
534
+ * const p1 = uuidv4();
535
+ * const p2 = uuidv4();
536
+ * game.join(p1, p2);
537
+ * ```
538
+ */
539
+ join(...playerIds) {
540
+ const playerCount = this._state.players.length;
541
+ if (playerCount == MAX_PLAYERS) {
542
+ throw new UnocabError(UECode.TooManyPlayers, { playerCount }, "At most 10 players can join a game");
543
+ }
544
+ playerIds.forEach((id) => {
545
+ if (id == ENGINE_ID || !playerId.safeParse(id).success) {
546
+ throw new UnocabError(UECode.InvalidId, { id }, `${id} is an invalid id`);
547
+ }
548
+ });
549
+ playerIds.forEach((playerId) => {
550
+ const hand = Array(7)
551
+ .fill(null)
552
+ .map(() => this.deckTopCard());
553
+ this._state.players.push(playerId);
554
+ this._state.cache.hands[playerId] = hand;
555
+ this.recordEvent({
556
+ type: "game_info",
557
+ info: {
558
+ type: "player_joined",
559
+ id: playerId,
560
+ },
561
+ });
562
+ });
563
+ }
564
+ /**
565
+ * Have player(s) denoted by an ID join the game.
566
+ *
567
+ * ```typescript
568
+ * const game = new Game();
569
+ * const p1 = uuidv4();
570
+ * const p2 = uuidv4();
571
+ * game.join(p1, p2);
572
+ *
573
+ * game.leave(p1, p2);
574
+ * ```
575
+ */
576
+ leave(...playerIds) {
577
+ playerIds.forEach((playerId) => {
578
+ if (!this._state.players.find((id) => id == playerId)) {
579
+ throw new UnocabError(UECode.PlayerNotInGame, { playerId }, "This player is not in the game");
580
+ }
581
+ this._state.players = this._state.players.filter((id) => id != playerId);
582
+ this.recordEvent({
583
+ type: "game_info",
584
+ info: {
585
+ type: "player_left",
586
+ id: playerId,
587
+ },
588
+ });
589
+ });
590
+ }
591
+ /**
592
+ * Have a player denoted by an ID play a card. Throws
593
+ * an {@link UnocabError} in case the player does not
594
+ * have the given card, or if playing it is an invalid move.
595
+ *
596
+ * ```typescript
597
+ * const game = new Game();
598
+ * game.play(p1, { type: "one", color: "red" });
599
+ * ```
600
+ */
601
+ play(by, card) {
602
+ return this.processNewEvent({
603
+ type: "card_played",
604
+ by,
605
+ card,
606
+ });
607
+ }
608
+ /**
609
+ * Have a player denoted by an ID draw a card. Throws
610
+ * an {@link UnocabError} in case it's invalid to draw.
611
+ *
612
+ * ```typescript
613
+ * const game = new Game();
614
+ * game.draw(p1);
615
+ * ```
616
+ */
617
+ draw(by) {
618
+ return this.processNewEvent({
619
+ type: "draw",
620
+ by,
621
+ });
622
+ }
623
+ /**
624
+ * Have a player denoted by an ID draw a card. Throws
625
+ * an {@link UnocabError} in case it's invalid to pass.
626
+ *
627
+ * ```typescript
628
+ * const game = new Game();
629
+ * game.draw(p1);
630
+ * game.pass(p1);
631
+ * ```
632
+ */
633
+ pass(by) {
634
+ return this.processNewEvent({
635
+ type: "pass",
636
+ by,
637
+ });
638
+ }
639
+ /**
640
+ * Have a player denoted by an ID call bluff. Throws
641
+ * an {@link UnocabError} in case a +4 was not played
642
+ * as the previous event, or if it is an invalid move.
643
+ *
644
+ * ```typescript
645
+ * const game = new Game();
646
+ * game.play(p1, { type: "plus-four" });
647
+ * game.switchColor(p1, "red");
648
+ * game.callBluff(p2);
649
+ * ```
650
+ */
651
+ callBluff(by) {
652
+ return this.processNewEvent({
653
+ type: "bluff_called",
654
+ by,
655
+ });
656
+ }
657
+ /**
658
+ * Have a player denoted by an ID switch color. Throws
659
+ * an {@link UnocabError} in case a color switching card
660
+ * was not played as the previous event, or if it is an invalid move.
661
+ *
662
+ * ```typescript
663
+ * const game = new Game();
664
+ * game.play(p1, { type: "plus-four" });
665
+ * game.switchColor(p1, "red");
666
+ * ```
667
+ */
668
+ chooseColor(by, color) {
669
+ return this.processNewEvent({
670
+ type: "choose-color",
671
+ by,
672
+ color,
673
+ });
674
+ }
675
+ /**
676
+ * Fetches the hand of a player denoted by an ID.
677
+ * Throws an {@link UnocabError} if the player is
678
+ * not present in the game.
679
+ */
680
+ handOf(playerId) {
681
+ const hand = this._state.cache.hands[playerId];
682
+ if (!hand)
683
+ throw new UnocabError(UECode.PlayerNotInGame, { playerId }, "This player is not in the game");
684
+ return hand;
685
+ }
686
+ // ─── Util Functions ──────────────────────────────────────────────────
687
+ /**
688
+ * Serialises the game state into a JSON. This can then
689
+ * be passed to the constructor when creating a new game
690
+ * in order to recreate the game.
691
+ *
692
+ * ```typescript
693
+ * const game = new Game({ shorthandMode: true });
694
+ *
695
+ * const json = game.serialise();
696
+ *
697
+ * const recreatedGame = new Game<true>({ serialisedState: json });
698
+ * ```
699
+ */
700
+ serialise() {
701
+ return JSON.stringify(this._state);
702
+ }
703
+ /**
704
+ * Clones this game to create another game with the exact
705
+ * same state and set of players.
706
+ */
707
+ clone() {
708
+ return new Game({ serialisedState: this.serialise() });
709
+ }
710
+ /**
711
+ * Fetches events of the given type from the game.
712
+ *
713
+ * ```typescript
714
+ * const game = new Game();
715
+ * game.draw(p1);
716
+ * game.pass(p1);
717
+ * game.draw(p2);
718
+ *
719
+ * assertEquals(game.eventsOfType("draw"), [
720
+ * { type: "draw", by: p1 },
721
+ * { type: "draw", by: p2 }
722
+ * ]);
723
+ * ```
724
+ */
725
+ eventsOfType(type) {
726
+ return this._state.events.filter((event) => event.type == type);
727
+ }
728
+ /**
729
+ * Get the player ID of the active player who is expected to play.
730
+ *
731
+ * ```typescript
732
+ * const game = new Game();
733
+ *
734
+ * assertEquals(game.activePlayer(), p1);
735
+ *
736
+ * game.draw(p1);
737
+ * game.pass(p1);
738
+ *
739
+ * assertEquals(game.activePlayer(), p2);
740
+ * ```
741
+ */
742
+ activePlayer() {
743
+ const validPlayers = Object.entries(this._state.cache.hands)
744
+ .filter(([, v]) => v)
745
+ .map(([k]) => k);
746
+ const index = Math.abs(this._state.index % validPlayers.length);
747
+ return validPlayers[index];
748
+ }
749
+ /**
750
+ * Checks whether this game has ended. If it has, returns an
751
+ * object containing the player ID of the losing player.
752
+ */
753
+ hasEnded() {
754
+ if (this._state.cache.ended) {
755
+ const loser = Object.entries(this._state.cache.hands).find(([, v]) => v.length)[0];
756
+ return { loser };
757
+ }
758
+ return false;
759
+ }
760
+ /**
761
+ * @param bluffSiteCheck - if set to true, the last 3 events will be ignored.
762
+ *
763
+ * Gets the expected card type and color that, if playing a card is
764
+ * possible in the current state, would be valid. Please note that this
765
+ * does not mean actually playing that card is okay. It just denotes the
766
+ * current "pile status", so to speak. To check if playing a card is valid
767
+ * in the current situation, use {@link Game.checkEvent}. Also, in case any
768
+ * of `expectedType` or `expectedColor` is undefined, it becomes a non
769
+ * condition. This means any type/color is allowed.
770
+ */
771
+ expectedCard(bluffSiteCheck = false) {
772
+ const expectedType = (() => {
773
+ const lastPileCard = this._state.cache.pile.at(-1);
774
+ if (lastPileCard &&
775
+ !includes(colorSwitchingScs.options, lastPileCard.type)) {
776
+ return lastPileCard.type;
777
+ }
778
+ })();
779
+ const expectedColor = (() => {
780
+ const lcc = this._state.cache.last3CardPlayOrColorChanges.at(bluffSiteCheck ? -3 : -1);
781
+ if (lcc) {
782
+ return typeof lcc == "string" ? lcc : lcc.color;
783
+ }
784
+ return undefined;
785
+ })();
786
+ return {
787
+ expectedType,
788
+ expectedColor,
789
+ };
790
+ }
791
+ /**
792
+ * Resets the game to a previous index of the events array.
793
+ * This can be used to replay a game from the start, or to
794
+ * undo a previous move. Cannot be used in shorthand mode.
795
+ * Returns the events that will be "removed".
796
+ *
797
+ * ```typescript
798
+ * const game = new Game();
799
+ *
800
+ * game.play(p1, { type: "seven", color: "blue" });
801
+ *
802
+ * // jump to the second last index, where the above
803
+ * // move does not exist, effectively undo-ing it.
804
+ * game.jumpToEventIndex(-2);
805
+ *
806
+ * game.play(p1, { type: "six", color: "blue" });
807
+ * ```
808
+ */
809
+ jumpToEventIndex(index) {
810
+ if (this._state.shorthandMode)
811
+ throw new Error("Cannot jump to index in shorthand mode");
812
+ const length = this._state.events.length;
813
+ if (index < -length || index >= length)
814
+ throw new Error("Invalid event index");
815
+ if (index < 0) {
816
+ index = this._state.events.length + index;
817
+ }
818
+ const remainingEvents = this._state.events.splice(index + 1);
819
+ const cg = new Game({ initialSeed: this._state.initialSeed });
820
+ for (const event of this.state.events) {
821
+ if (event.type == "game_info") {
822
+ const info = event.info;
823
+ if (info.type == "game_ended")
824
+ break;
825
+ if (info.type == "player_joined")
826
+ cg.join(info.id);
827
+ if (info.type == "player_left")
828
+ cg.leave(info.id);
829
+ continue;
830
+ }
831
+ if (event.by == ENGINE_ID)
832
+ continue;
833
+ cg.processNewEvent(event);
834
+ }
835
+ this._state = cg.state;
836
+ return remainingEvents;
837
+ }
838
+ /**
839
+ * Get a set of {@link GameEvent} that are valid in the current state of
840
+ * the game. For example, after a draw, only a pass is a valid move, so
841
+ * this function will return that. The returned events can also be directly
842
+ * passed to {@link Game.processNewEvent}.
843
+ *
844
+ * ```typescript
845
+ * const game = new Game();
846
+ * game.draw(p1);
847
+ * assertEquals(game.validEvents(), [
848
+ * { type: "pass", by: p1 }
849
+ * ]);
850
+ * ```
851
+ */
852
+ validEvents(playerId) {
853
+ const allEvents = [
854
+ { type: "draw", by: playerId },
855
+ { type: "bluff_called", by: playerId },
856
+ { type: "pass", by: playerId },
857
+ // here red itself has no purpose -- if red can be
858
+ // chosen, any color can be.
859
+ { type: "choose-color", by: playerId, color: "red" },
860
+ ...this.handOf(playerId).map((card) => ({
861
+ type: "card_played",
862
+ by: playerId,
863
+ card,
864
+ })),
865
+ ];
866
+ return allEvents.filter((e) => !this.checkEvent(e));
867
+ }
868
+ }