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