-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgameStateManager.js
493 lines (391 loc) · 14.1 KB
/
gameStateManager.js
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
const ObjetivesGenerator = require('./objetives');
const { Rules, CardType } = require('./gameRules');
const EngineEvents = require('./engineEvents');
const { Subject } = require('rxjs');
const { pipe } = require('./utils');
const RegisterOperations = require('./registerOperations');
const uuidv1 = require('uuid/v1');
//create the event stream
const eventStream = new Subject();
const regOpsMap = {
[Symbol.for(4)]: RegisterOperations(4),
[Symbol.for(5)]: RegisterOperations(5),
[Symbol.for(6)]: RegisterOperations(6)
};
function operations(numBits) {
return regOpsMap[Symbol.for(numBits)];
}
//stop piping functions on null output and return {gameState :null} as fallback value
const pipeUntilNull = pipe.bind(undefined, (input) => input === null, () => { return { gameState: null }; });
// define the behavior of the operations piping stand alone functions
const joinPlayerPublicApi = pipeUntilNull(
checkGameWasStarted,
checkAlreadyJoined,
joinPlayer,
raiseGameStatusChanged
);
const leavePlayerPublicApi = pipeUntilNull(
checkNotJoined,
leavePlayer,
checkNoPlayersLeft,
raiseGameStatusChanged
);
const startGamePublicApi = pipeUntilNull(
checkNotJoined,
checkGameWasStarted,
startGame,
raiseGameStatusChanged
);
const endTurnPublicApi = pipeUntilNull(
checkNotJoined,
checkGameWasNotStarted,
checkIsNotPlayerTurn,
checkFixPending,
endTurn,
checkGameLost,
raiseGameStatusChanged
);
const executeBitOperationPublicApi = pipeUntilNull(
checkNotJoined,
checkGameWasNotStarted,
checkIsNotPlayerTurn,
checkFixPending,
obtainOperationCost,
checkNotEnoughEnergy,
checkOperationLocked,
checkRegisterLocked,
executeBitOperation,
decreasePlayerEnergy,
checkObjetiveAccomplished,
checkGameWon,
checkShouldEndTurn,
checkGameLost,
raiseGameStatusChanged
);
const fixErrorPublicApi = pipeUntilNull(
checkNoFixLeft,
checkAlreadyFixed,
fixError,
raiseGameStatusChanged
);
//expose the piped functions as the state manager public api
const gameStateManager = {
EventStream: eventStream,
CreateNewGameState: createGame,
JoinPlayer: joinPlayerPublicApi,
LeavePlayer: leavePlayerPublicApi,
StartGame: startGamePublicApi,
EndTurn: endTurnPublicApi,
ExecuteBitOperation: executeBitOperationPublicApi,
fixError: fixErrorPublicApi
};
/*
* stand alone functions with behavior. every one has a single responsibility for state checks and raise its related event
*/
function obtainOperationCost({ operation }) {
return { cost: Rules.OperationCost(operation) };
}
//notfy the game was started to not allow start again or join players
function checkGameWasStarted({ gameState, playerId }) {
if (gameState.started) {
eventStream.next({ eventType: EngineEvents.gameAlreadyStarted, gameState, playerId });
return null;
}
return { gameState };
}
//notyfy the game was not started to not allow endturn or bit operations
function checkGameWasNotStarted({ gameState, playerId }) {
if (!gameState.started) {
eventStream.next({ eventType: EngineEvents.gameNotStarted, gameState, playerId });
return null;
}
return { gameState };
}
//check the player is already joined to not allow join again
function checkAlreadyJoined({ gameState, playerId }) {
//provide context, clean and readable code by creating local functions with lambda expressions
const alreadyJoined = () => Rules.PlayerIsInGame(gameState, playerId);
//input parameters captured in the lambda expression
if (alreadyJoined()) {
eventStream.next({ eventType: EngineEvents.playerAlreadyJoined, gameState, playerId });
return null;
}
return { gameState };
}
//check player not joined to not allow ingame commands
function checkNotJoined({ gameState, playerId }) {
const alreadyJoined = () => Rules.PlayerIsInGame(gameState, playerId);
if (!alreadyJoined()) {
eventStream.next({ eventType: EngineEvents.playerNotJoined, gameState, playerId });
return null;
}
return { gameState };
}
//check if last player left the game; notyfy it to cancell the game
function checkNoPlayersLeft({ gameState, playerId }) {
const noPlayers = () => Rules.NoPlayersLeft(gameState);
if (noPlayers()) {
eventStream.next({ eventType: EngineEvents.noPlayersLeft, gameState, playerId });
return null;
}
return { gameState };
}
//check if its player turn to accept bit operations and end turn command
function checkIsNotPlayerTurn({ gameState, playerId }) {
const isCurrentPlayerTurn = () => Rules.IsPlayerTurn(gameState, playerId);
if (!isCurrentPlayerTurn()) {
eventStream.next({ eventType: EngineEvents.notPlayerTurn, gameState, playerId });
return null;
}
return { gameState };
}
//notyfy game was lost to cancel it
function checkGameLost({ gameState, playerId }) {
const loose = () => Rules.MaxUnresolvedReached(gameState);
if (loose()) {
eventStream.next({ eventType: EngineEvents.gameLost, gameState, playerId });
return null;
}
return { gameState };
}
//notify operation register is locked
function checkRegisterLocked({ gameState, playerId, cpu_reg1, cpu_reg2 }) {
const registerLocked = () => Rules.ElementLocked(gameState, cpu_reg1) || (cpu_reg2 ? Rules.ElementLocked(gameState, cpu_reg2) : false);
if (registerLocked()) {
eventStream.next({ eventType: EngineEvents.registerLocked, gameState, playerId });
return null;
}
return { gameState };
}
//notify operation is locked
function checkOperationLocked({ gameState, playerId, operation }) {
const operationLocked = () => Rules.ElementLocked(gameState, operation);
if (operationLocked()) {
eventStream.next({ eventType: EngineEvents.operationLocked, gameState, playerId });
return null;
}
return { gameState };
}
//chek if player has energy to perform the requested bit operation
function checkNotEnoughEnergy({ gameState, playerId, cost }) {
const enoughEnergy = () => Rules.CurrentPlayer(gameState).energy >= cost;
if (!enoughEnergy()) {
eventStream.next({ eventType: EngineEvents.notEnoughEnergy, gameState, playerId });
return null;
}
return { gameState };
}
const pipeAlways = pipe.bind(undefined, () => false, null); //pipe without stop condition
//objetive accomplisher decrease objetive; draws and apply game cards
const objetiveAccomplisher = pipeAlways(
decreaseObjetiveSlot,
obtainNextObjetive
);
//check if one objetive has benn accomplished and notify it
function checkObjetiveAccomplished({ gameState, playerId }) {
const objetiveAccomplished = () => Rules.ObjetiveIsInRegA(gameState);
if (objetiveAccomplished()) {
eventStream.next({ eventType: EngineEvents.objetiveAccomplished, gameState, playerId });
return objetiveAccomplisher({ gameState, playerId });
}
return { gameState };
}
//modify the game state for accomplish a objetive
function decreaseObjetiveSlot({ gameState }) {
const unresolvedObjetivesLeft = () => gameState.unresolved - 1;
gameState.unresolved = unresolvedObjetivesLeft();
return { gameState };
}
//draws game cards until a objetive card is found; apply event card on the course of looking for a objetive card
function obtainNextObjetive({ gameState, playerId }) {
let card = gameState.objetives.pop();
while (card && card.type !== CardType.Objetive) {
gameState = applyCardRules(gameState, card);
card = gameState.objetives.pop();
}
gameState.currentObjetive = card;
return { gameState };
}
//apply the card rules and raise related events
function applyCardRules(gameState, card, playerId) {
gameState = Rules.ApplyCardRule(gameState, card);
switch (card.type) {
case CardType.Bug:
eventStream.next({ eventType: EngineEvents.bugFound, gameState, playerId });
break;
case CardType.Event:
eventStream.next({ eventType: EngineEvents.gameEventFound, gameEvent: card, gameState, playerId });
break;
}
return gameState;
}
//notyfy game was won to cancel it
function checkGameWon({ gameState, playerId }) {
const win = () => Rules.NoObjetivesLeft(gameState);
if (win()) {
eventStream.next({ eventType: EngineEvents.gameWon, gameState, playerId });
return null;
}
return { gameState };
}
//notify a fix event is pending of confirmation
function checkFixPending({ gameState, playerId }) {
const fixRequested = () => gameState.fixPending !== 0;
if (fixRequested()) {
eventStream.next({ eventType: EngineEvents.fixOperationPending, gameState, playerId });
return null;
}
return { gameState };
}
//notify no more fix events left
function checkNoFixLeft({ gameState, playerId }) {
const noFixLeft = () => gameState.fixPending === 0;
if (noFixLeft()) {
eventStream.next({ eventType: EngineEvents.noFixLeft, gameState, playerId });
return null;
}
return { gameState };
}
function checkAlreadyFixed({ gameState, playerId, error }) {
const alreadyFixed = () => gameState.errors[error] === false;
if (alreadyFixed()) {
eventStream.next({ eventType: EngineEvents.alreadyFixed, gameState, playerId });
return null;
}
return { gameState };
}
//check if an automatic end turn should happend because player has 0 energy or there is no unresolved objetives in unresolved queue
function checkShouldEndTurn({ gameState, playerId }) {
const noUnresolvedLeft = Rules.NoUnresolvedLeft(gameState);
const shouldEndTurn = () => Rules.NoEnergyLeft(gameState) || noUnresolvedLeft;
if (shouldEndTurn()) {
return endTurn({ gameState, playerId });
}
return { gameState };
}
//notify the game state has changed
function raiseGameStatusChanged({ gameState, playerId }) {
eventStream.next({ eventType: EngineEvents.gameStatusChanged, gameState, playerId });
return { gameState };
}
/*
Core main functions. All previous and further checks are done piping the check functions.
*/
//game creation with inital state
function createGame({ gameId, playerId, numBits, numBugs, maxEnergy, useEvents }) {
const { registerValues, objetives, currentObjetive } = ObjetivesGenerator(numBits, Rules.KeepNumBugsInRange(numBugs), useEvents);
let gameState = {
...newGameState,
errors: {...errors },
id: gameId,
uuid: uuidv1(),
numBits: Rules.KeepNumBitsRange(numBits),
playerList: new Array(), //TODO: a linked list would be a better structure to manage players and turns
currentObjetive: currentObjetive,
objetives: objetives,
registers: {
...newRegisterState,
B: registerValues[0],
C: registerValues[1],
D: registerValues[2]
},
rules: {
maxEnergy: Rules.KeepMaxEnergyInRange(maxEnergy)
}
};
eventStream.next({ eventType: EngineEvents.gameCreated, gameState, playerId });
gameState = joinPlayer({ gameState, playerId }).gameState;
raiseGameStatusChanged({ gameState });
return { gameState };
}
function joinPlayer({ gameState, playerId }) {
const playerState = {
name: playerId,
energy: gameState.rules.maxEnergy
};
gameState.playerList.push(playerState);
eventStream.next({ eventType: EngineEvents.playerJoined, gameState, playerId });
return { gameState };
}
function leavePlayer({ gameState, playerId }) {
const playerIs = (currentName) => (player) => player.name === currentName;
const playerIsNot = (currentName) => (player) => player.name !== currentName;
const ofPlayerLeaving = playerIs(playerId);
const playerLeaving = playerIsNot(playerId);
const playerPosition = () => {
return gameState.playerList.findIndex(ofPlayerLeaving);
};
const nexPlayerTurn = () => (playerPosition() < gameState.playerTurn) ? gameState.playerTurn - 1 : gameState.playerTurn;
gameState.playerTurn = nexPlayerTurn();
gameState.playerList = gameState.playerList.filter(playerLeaving);
eventStream.next({ eventType: EngineEvents.playerLeft, gameState, playerId });
return { gameState };
}
function startGame({ gameState, playerId }) {
gameState.started = true;
eventStream.next({ eventType: EngineEvents.gameStarted, gameState, playerId });
return { gameState };
}
function endTurn({ gameState, playerId }) {
const endRound = () => Rules.LastPlayerPlaying(gameState);
const resetEnergy = () => gameState.playerList.map((playerState) => { playerState.energy = gameState.rules.maxEnergy; return playerState; });
const noUnresolvedLeft = () => Rules.NoUnresolvedLeft(gameState);
eventStream.next({ eventType: EngineEvents.turnEnded, gameState, playerId });
if (!endRound()) {
gameState.playerTurn += 1;
//if end turn was because unresolved = 0
//new cards was drawn so unresolved has to reset to 1 even if not endRound
if (noUnresolvedLeft()) { gameState.unresolved = 1; }
}
else {
gameState.playerTurn = 0;
gameState.unresolved += 1;
gameState.playerList = resetEnergy();
eventStream.next({ eventType: EngineEvents.roundFinished, gameState, playerId });
}
return { gameState };
}
function executeBitOperation({ gameState, playerId, operation, cpu_reg1, cpu_reg2 }) {
const cpu_reg_value = (reg) => reg ? gameState.registers[reg] : reg;
const reg1 = cpu_reg_value(cpu_reg1);
const reg2 = cpu_reg_value(cpu_reg2);
gameState.registers[cpu_reg1] = operations(gameState.numBits)[operation](reg1, reg2);
eventStream.next({ eventType: EngineEvents.operationApplied, gameState, playerId });
return { gameState };
}
function decreasePlayerEnergy({ gameState, cost }) {
const player = () => Rules.CurrentPlayer(gameState);
player().energy -= cost;
return { gameState };
}
/*Fix error core function. OK cards > 1 could been draw (fixPending > 1) but only 1 system error could be present;
fixPending should decrease by 1 or reset to 0 if no more system errors left*/
function fixError({ gameState, playerId, error }) {
gameState.errors[error] = false;
gameState.fixPending = Rules.SomeSystemError(gameState) ? gameState.fixPending - 1 : 0;
eventStream.next({ eventType: EngineEvents.fixOperationApplied, gameState, playerId, error });
return { gameState };
}
//default game state for new game
const newGameState = {
unresolved: 1,
started: false,
playerTurn: 0,
bugsFound: 0,
fixPending: 0
};
//default game state errors for new game
const errors = {
B: false,
C: false,
D: false,
ROL: false,
NOT: false,
XOR: false
};
//defauls register state for new game
const newRegisterState = {
A: 0
};
//expose just the public api
module.exports = gameStateManager;