-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
466 lines (419 loc) · 13.9 KB
/
game.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
"use strict";
var ActionTypes = require('./ActionTypes');
var EventType = require('./EventType');
var invariant_violation = require('./invariant_violation');
var invariant = require('./invariant');
var _ = require('underscore');
var Colors = require('./Colors');
var GameData = require('./GameData');
var RequestTypes = require('./RequestTypes');
var Player = require('./Player');
var Card = require('./Card');
var Deck = require('./Deck');
var CARDS_PER_LEVEL = 4;
var MAX_CHIPS = 10;
var GAME_ENDING_SCORE = 15;
function Game(players) {
this.id_ = _.uniqueId('game_');
this.players_ = _.shuffle(players);
this.lastCardID_ = 100;
this.cardsByID_ = {};
this.decks_ = _.times(3, function(n) {
return new Deck();
});
this.boards_ = _.times(3, function(n) {
return [];
});
this.nobles_ = [];
this.chipSupply_ = {};
this.turn_ = 0;
this.logItems_ = [];
this.messages_ = [];
this.sequenceID_ = 0;
return this;
}
Game.prototype.getID = function() {
return this.id_;
};
Game.prototype.getSequenceID = function() {
return this.sequenceID_;
};
Game.prototype.getPlayers = function() {
return this.players_;
};
Game.prototype.getPlayerByID = function(userID) {
return _.find(this.players_, function(player) {
return player.getID() === userID;
});
};
Game.prototype.spawnCard = function(card_def) {
var card = new Card(this.lastCardID_, card_def.level, card_def.color, card_def.cost, card_def.points);
this.lastCardID_ += 1;
this.cardsByID_[card.id] = card;
return card;
};
Game.prototype.bumpSequenceID = function() {
this.sequenceID_ += 1;
};
Game.prototype.setUpGame = function() {
this.gameStartTimestamp_ = Date.now();
_.each(this.players_, function(player) {
_.each(Colors, function(color) {
player.chips[color] = 0;
});
});
_.each(GameData.Cards, function(card_def) {
var i = card_def.level - 1;
invariant(i >= 0 && i < 3, 'invalid card level');
this.decks_[i].addCardsToTop([this.spawnCard(card_def)]);
}, this);
_.each(this.decks_, function(deck, n) {
deck.shuffle();
this.boards_[n] = deck.drawN(CARDS_PER_LEVEL);
}, this);
this.nobles_ = _.sample(GameData.Nobles, this.players_.length + 1);
var playerCountToChipCount = {
2: 4,
3: 5,
4: 7,
};
_.each(Colors, function(color) {
this.chipSupply_[color] = color === Colors.JOKER ?
5 : (playerCountToChipCount[this.players_.length] || 7);
}, this);
this.currentPlayerIndex_ = this.players_.length - 1;
this.currentRequest_ = RequestTypes.ACTION;
this.winningPlayerIndex_ = -1;
this.nextTurn();
};
Game.prototype.addEventHelper_ = function(userID, type, payload) {
this.logItems_.push({
userId: userID,
type: type,
payload: payload,
});
};
var FULL_HAND_OF_JOKERS = {
white: 0,
blue : 0,
red : 0,
green : 0,
black : 0,
joker : 9
};
Game.prototype.nextTurn = function() {
var player = this.players_[this.currentPlayerIndex_];
var total_chips = player.getChipCount();
//player.chips = FULL_HAND_OF_JOKERS; // uncomment to be able to buy pretty much anything
// check for chip overflow
if (total_chips > MAX_CHIPS) {
this.currentRequest_ = RequestTypes.DISCARD_CHIPS;
return;
}
// check for noble visit
var current_discount = player.getDiscountMap();
var selectable_nobles = Game.selectableNobles(current_discount, this.nobles_);
if (this.currentRequest_ != RequestTypes.SELECT_NOBLE) {
if (selectable_nobles.length == 1) {
var noble = selectable_nobles[0];
player.nobles = player.nobles.concat(noble);
this.nobles_ = _.without(this.nobles_, noble);
this.addEventHelper_(player.getID(), EventType.RECEIVE_NOBLE, {noble: noble});
} else if (selectable_nobles.length > 1) {
this.currentRequest_ = RequestTypes.SELECT_NOBLE;
return;
}
}
this.currentPlayerIndex_ = (this.currentPlayerIndex_ + 1) % this.players_.length;
this.currentRequest_ = RequestTypes.ACTION;
var next_player = this.players_[this.currentPlayerIndex_]
this.addEventHelper_(next_player.getID(), EventType.START_TURN, {turn: this.turn_});
if (this.currentPlayerIndex_ === 0) {
this.turn_ += 1;
// check for win condition
var player_scores = _.map(this.players_, function(player) {
return player.getScore();
});
var is_game_over = _.some(player_scores, function(score) {
return score >= GAME_ENDING_SCORE;
});
if (is_game_over) {
var winning_index = -1;
var winning_score = -1;
_.each(player_scores, function(score, index) {
if (score > winning_score) {
winning_score = score;
winning_index = index;
}
});
this.winningPlayerIndex_ = winning_index;
this.currentPlayerIndex_ = -1;
this.currentRequest_ = null;
}
}
};
var isValidChipSelection = function(color_counts, supply) {
if (_.some(color_counts, function(count, color) {
return !_.contains(_.values(Colors), color);
})) {
return false;
}
if (color_counts[Colors.JOKER] > 0) {
return false;
}
var filtered_colors = {};
_.each(color_counts, function(count, color) {
if (count > 0) {
filtered_colors[color] = count;
}
});
var num_colors = _.size(filtered_colors);
if (num_colors <= 0 || num_colors > 3) {
return false;
}
// handle double chip draft
var first_count = _.head(_.values(filtered_colors));
if (num_colors == 1 && first_count == 2) {
return supply[_.keys(filtered_colors)[0]] >= 4;
}
// must be single chip draft and have enough resources
return _.all(filtered_colors, function(count, color) {
return count == 1 && supply[color] >= count;
});
};
// returns the cost of a card given some supply of chips to pay with and some discount
Game.costForCard = function(card, supply, discount) {
var cost = {};
_.each(card.cost, function(count, color) {
var discounted_count = Math.max(count - (discount[color] || 0), 0);
var supply_count = supply[color];
cost[color] = Math.min(discounted_count, supply_count);
if (supply_count < discounted_count) {
cost[Colors.JOKER] = (cost[Colors.JOKER] || 0) + (discounted_count - supply_count);
}
});
return cost;
};
Game.canPayCost = function(cost, supply) {
return _.all(cost, function(count, key) {
return supply[key] >= count;
});
};
var supplyAfterPayingCost = function(supply, cost) {
var new_supply = _.clone(supply);
_.each(cost, function(count, key) {
new_supply[key] -= count;
});
return new_supply;
};
var supplyAfterGainingCost = function(supply, cost) {
var new_supply = _.clone(supply);
_.each(cost, function(count, key) {
new_supply[key] += count;
});
return new_supply;
};
var RequestTypeByActionType = {};
RequestTypeByActionType[ActionTypes.BUILD_HAND_CARD] = RequestTypes.ACTION;
RequestTypeByActionType[ActionTypes.BUILD_TABLE_CARD] = RequestTypes.ACTION;
RequestTypeByActionType[ActionTypes.DRAFT_CHIPS] = RequestTypes.ACTION;
RequestTypeByActionType[ActionTypes.RESERVE_CARD] = RequestTypes.ACTION;
RequestTypeByActionType[ActionTypes.SELECT_NOBLE] = RequestTypes.SELECT_NOBLE;
RequestTypeByActionType[ActionTypes.DISCARD_CHIPS] = RequestTypes.DISCARD_CHIPS;
Game.prototype.addAction = function(userID, action) {
var player = this.getPlayerByID(userID);
if (!player) {
console.log('could not find player', userID);
return;
}
var player_index = this.players_.indexOf(player);
if (player_index != this.currentPlayerIndex_) {
throw new Error('not your turn');
}
var request_type = RequestTypeByActionType[action.type];
if (request_type != this.currentRequest_) {
throw new Error('invalid action for request');
}
switch (action.type) {
case ActionTypes.DRAFT_CHIPS: {
var chips = action.payload.color_counts;
var valid_draft = isValidChipSelection(chips, this.chipSupply_);
if (!valid_draft) {
throw new Error('invalid chip selection');
}
var double_draft = false;
_.each(chips, function(count, color) {
player.chips[color] += count;
this.chipSupply_[color] -= count;
if (count == 2) {
double_draft = true;
}
}, this);
if (double_draft) {
this.addEventHelper_(userID, EventType.DRAFT_TWO_CHIP, {chips: chips});
} else {
this.addEventHelper_(userID, EventType.DRAFT_MULTI_CHIP, {chips: chips});
}
break;
}
case ActionTypes.RESERVE_CARD: {
var level = action.payload.level;
var cardID = action.payload.cardID;
if (!_.contains([1, 2, 3], level)) {
throw new Error('invalid level');
}
if (player.hand.length >= 3) {
throw new Error('not enough hand space');
}
var deck = this.decks_[level - 1];
var drafted_card = null;
var draftedFromDeck = false;
if (!cardID) {
if (!deck.count()) {
throw new Error('not enough cards to draft from deck');
}
drafted_card = deck.drawOne();
draftedFromDeck = true;
} else {
var card = _.find(this.boards_[level - 1], function(card, i) {
return card.id === cardID;
});
if (!card) {
throw new Error('card not found');
}
drafted_card = card;
var index = _.indexOf(this.boards_[level - 1], card);
this.boards_[level - 1][index] = deck.drawOne();
}
player.hand.push(drafted_card);
var gotJoker = false;
if (this.chipSupply_[Colors.JOKER] > 0) {
player.chips[Colors.JOKER] += 1;
this.chipSupply_[Colors.JOKER] -= 1;
gotJoker = true;
}
if (draftedFromDeck) {
this.addEventHelper_(userID, EventType.RESERVE_CARD_DECK, {card_level: level, recieved_joker: gotJoker});
} else {
this.addEventHelper_(userID, EventType.RESERVE_CARD_TABLE, {cardID: cardID, card_level: level, recieved_joker: gotJoker});
}
break;
}
case ActionTypes.BUILD_TABLE_CARD: {
var board = this.boards_[action.payload.level - 1];
if (!board) {
throw new Error('bad level param');
}
var index = -1;
var card = _.find(board, function(card, i) {
index = i;
return card.id === action.payload.cardID;
});
if (!card) {
throw new Error('bad card id');
}
var cost = Game.costForCard(card, player.chips, player.getDiscountMap());
if (!Game.canPayCost(cost, player.chips)) {
throw new Error('cannot afford card');
}
player.chips = supplyAfterPayingCost(player.chips, cost);
this.chipSupply_ = supplyAfterGainingCost(this.chipSupply_, cost);
player.board = player.board.concat(card);
var deck = this.decks_[action.payload.level - 1];
invariant(index < board.length, 'invalid card index');
board[index] = deck.drawOne();
this.addEventHelper_(userID, EventType.BUILD_TABLE_CARD, {cardID: card.id});
break;
}
case ActionTypes.BUILD_HAND_CARD: {
var card = _.find(player.hand, function(card, i) {
return card.id === action.payload.cardID;
});
if (!card) {
throw new Error('bad card id');
}
var cost = Game.costForCard(card, player.chips, player.getDiscountMap());
if (!Game.canPayCost(cost, player.chips)) {
throw new Error('cannot afford card');
}
player.chips = supplyAfterPayingCost(player.chips, cost);
this.chipSupply_ = supplyAfterGainingCost(this.chipSupply_, cost);
player.board = player.board.concat(card);
player.hand = _.without(player.hand, card);
this.addEventHelper_(userID, EventType.BUILD_HAND_CARD, {cardID: card.id});
break;
}
case ActionTypes.SELECT_NOBLE: {
var noble_index = action.payload.index;
if (noble_index >= this.nobles_.length || noble_index < 0) {
throw new Error('invalid noble index', noble_index);
}
var noble = this.nobles_[noble_index];
if (!player.canSelectNoble(noble)) {
throw new Error('cannot select noble');
}
player.nobles = player.nobles.concat(noble);
this.nobles_ = _.without(this.nobles_, noble);
this.addEventHelper_(userID, EventType.RECEIVE_NOBLE, {noble: noble});
break;
}
case ActionTypes.DISCARD_CHIPS: {
var discarded_chips = action.payload.chips;
if (!_.isObject(discarded_chips)) {
throw new Error('invalid chips dictionary');
}
var has_chips = _.every(discarded_chips, function(count, color) {
return player.chips[color] >= count;
});
if (!has_chips) {
throw new Error('invalid chip selection');
}
var new_chips = {};
var new_chips_count = 0;
_.each(player.chips, function(count, color) {
var discarded_count = (discarded_chips[color] || 0);
var new_count = count - discarded_count;
new_chips[color] = new_count;
new_chips_count += new_count;
this.chipSupply_[color] += discarded_count;
}, this);
if (new_chips_count > MAX_CHIPS) {
throw new Error('still too many chips');
}
player.chips = new_chips;
this.addEventHelper_(userID, EventType.DISCARD_CHIPS, {chips: discarded_chips});
break;
}
default:
throw new Error('unknown action type ', action.type);
}
this.nextTurn();
this.bumpSequenceID();
};
Game.selectableNobles = function(discountMap, noblesList) {
return _.filter(noblesList, function(noble) {
return _.every(noble.cost, function(count, color) {
return discountMap[color] >= count;
});
});
};
Game.prototype.toJSON = function() {
return {
id: this.id_,
sequenceID: this.sequenceID_,
turn: this.turn_,
decks: _.invoke(this.decks_, 'toJSON'),
boards: this.boards_,
nobles: this.nobles_,
chipSupply: this.chipSupply_,
players: _.invoke(this.players_, 'toJSON'),
currentPlayerIndex: this.currentPlayerIndex_,
currentRequest: this.currentRequest_,
winningPlayerIndex: this.winningPlayerIndex_,
lastCardID: this.lastCardID_,
cardsByID: this.cardsByID_,
logItems: this.logItems_,
messages: this.messages_,
};
};
module.exports = Game;