-
Notifications
You must be signed in to change notification settings - Fork 742
/
Copy pathturn-order.ts
441 lines (398 loc) · 11.2 KB
/
turn-order.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
import * as logging from './logger';
import * as plugin from '../plugins/main';
import type {
Ctx,
StageArg,
ActivePlayersArg,
PlayerID,
State,
TurnConfig,
} from '../types';
/**
* Event to change the active players (and their stages) in the current turn.
*/
export function SetActivePlayersEvent(
state: State,
_playerID: PlayerID,
arg: ActivePlayersArg | PlayerID[]
) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
export function SetActivePlayers(ctx: Ctx, arg: ActivePlayersArg | PlayerID[]) {
let { _prevActivePlayers } = ctx;
let activePlayers = {};
let _nextActivePlayers: ActivePlayersArg | null = null;
let _activePlayersMoveLimit = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
} else {
// process active players argument object
if (arg.next) {
_nextActivePlayers = arg.next;
}
_prevActivePlayers = arg.revert
? _prevActivePlayers.concat({
activePlayers: ctx.activePlayers,
_activePlayersMoveLimit: ctx._activePlayersMoveLimit,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
})
: [];
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(
activePlayers,
_activePlayersMoveLimit,
ctx.currentPlayer,
arg.currentPlayer
);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(
activePlayers,
_activePlayersMoveLimit,
id,
arg.others
);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(
activePlayers,
_activePlayersMoveLimit,
id,
arg.all
);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(
activePlayers,
_activePlayersMoveLimit,
id,
arg.value[id]
);
}
}
if (arg.moveLimit) {
for (const id in activePlayers) {
if (_activePlayersMoveLimit[id] === undefined) {
_activePlayersMoveLimit[id] = arg.moveLimit;
}
}
}
}
if (Object.keys(activePlayers).length == 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMoveLimit).length == 0) {
_activePlayersMoveLimit = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
export function UpdateActivePlayersOnceEmpty(ctx: Ctx) {
let {
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx;
if (activePlayers && Object.keys(activePlayers).length == 0) {
if (ctx._nextActivePlayers) {
ctx = SetActivePlayers(ctx, ctx._nextActivePlayers);
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx);
} else if (_prevActivePlayers.length > 0) {
const lastIndex = _prevActivePlayers.length - 1;
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
} = _prevActivePlayers[lastIndex]);
_prevActivePlayers = _prevActivePlayers.slice(0, lastIndex);
} else {
activePlayers = null;
_activePlayersMoveLimit = null;
}
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
};
}
/**
* Apply an active player argument to the given player ID
* @param {Object} activePlayers
* @param {Object} _activePlayersMoveLimit
* @param {String} playerID The player to apply the parameter to
* @param {(String|Object)} arg An active player argument
*/
function ApplyActivePlayerArgument(
activePlayers: Ctx['activePlayers'],
_activePlayersMoveLimit: Ctx['_activePlayersMoveLimit'],
playerID: PlayerID,
arg: StageArg
) {
if (typeof arg !== 'object' || arg === Stage.NULL) {
arg = { stage: arg as string | null };
}
if (arg.stage !== undefined) {
activePlayers[playerID] = arg.stage;
if (arg.moveLimit) _activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
/**
* Converts a playOrderPos index into its value in playOrder.
* @param {Array} playOrder - An array of player ID's.
* @param {number} playOrderPos - An index into the above.
*/
function getCurrentPlayer(
playOrder: Ctx['playOrder'],
playOrderPos: Ctx['playOrderPos']
) {
// convert to string in case playOrder is set to number[]
return playOrder[playOrderPos] + '';
}
/**
* Called at the start of a turn to initialize turn order state.
*
* TODO: This is called inside StartTurn, which is called from
* both UpdateTurn and StartPhase (so it's called at the beginning
* of a new phase as well as between turns). We should probably
* split it into two.
*/
export function InitTurnOrderState(state: State, turn: TurnConfig) {
let { G, ctx } = state;
const ctxWithAPI = plugin.EnhanceCtx(state);
const order = turn.order;
let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
logging.error(
`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`
);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
export function UpdateTurnOrderState(
state: State,
currentPlayer: PlayerID,
turn: TurnConfig,
endTurnArg?: true | { remove?: any; next?: string }
) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
logging.error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
logging.error(`invalid argument to endTurn: ${arg}`);
}
});
} else {
const ctxWithAPI = plugin.EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
logging.error(
`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`
);
}
if (t === undefined) {
endPhase = true;
} else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
export const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G: any, ctx: Ctx) =>
ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G: any, ctx: Ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G: any, ctx: Ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G: any, ctx: Ctx) => ctx.playOrderPos,
next: (G: any, ctx: Ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G: any, ctx: Ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder: string[]) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G: any, ctx: Ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField: string) => ({
playOrder: (G: any) => G[playOrderField],
first: () => 0,
next: (G: any, ctx: Ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
export const Stage = {
NULL: null,
};
export const ActivePlayers = {
/**
* ALL
*
* The turn stays with one player, but any player can play (in any order)
* until the phase ends.
*/
ALL: { all: Stage.NULL },
/**
* ALL_ONCE
*
* The turn stays with one player, but any player can play (once, and in any order).
* This is typically used in a phase where you want to elicit a response
* from every player in the game.
*/
ALL_ONCE: { all: Stage.NULL, moveLimit: 1 },
/**
* OTHERS
*
* The turn stays with one player, and every *other* player can play (in any order)
* until the phase ends.
*/
OTHERS: { others: Stage.NULL },
/**
* OTHERS_ONCE
*
* The turn stays with one player, and every *other* player can play (once, and in any order).
* This is typically used in a phase where you want to elicit a response
* from every *other* player in the game.
*/
OTHERS_ONCE: { others: Stage.NULL, moveLimit: 1 },
};