-
Notifications
You must be signed in to change notification settings - Fork 11
/
game.rs
758 lines (679 loc) · 22.4 KB
/
game.rs
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use fnv::FnvHashMap;
use std::fmt;
use std::ops::Range;
pub type Player = u32;
pub type Color = char;
pub const NUM_COLORS: usize = 5;
pub const COLORS: [Color; NUM_COLORS] = ['r', 'y', 'g', 'b', 'w'];
pub type Value = u32;
// list of values, assumed to be small to large
pub const NUM_VALUES: usize = 5;
pub const VALUES: [Value; NUM_VALUES] = [1, 2, 3, 4, 5];
pub const FINAL_VALUE: Value = 5;
pub fn get_count_for_value(value: Value) -> u32 {
match value {
1 => 3,
2 | 3 | 4 => 2,
5 => 1,
_ => {
panic!("Unexpected value: {value}");
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct Card {
pub color: Color,
pub value: Value,
}
impl Card {
pub fn new(color: Color, value: Value) -> Card {
Card { color, value }
}
}
impl fmt::Display for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{}", self.color, self.value)
}
}
impl fmt::Debug for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{}", self.color, self.value)
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CardCounts {
counts: FnvHashMap<Card, u32>,
}
impl CardCounts {
pub fn new() -> CardCounts {
let mut counts = FnvHashMap::default();
for &color in COLORS.iter() {
for &value in VALUES.iter() {
counts.insert(Card::new(color, value), 0);
}
}
CardCounts { counts }
}
pub fn get_count(&self, card: &Card) -> u32 {
*self.counts.get(card).unwrap()
}
pub fn remaining(&self, card: &Card) -> u32 {
let count = self.get_count(card);
get_count_for_value(card.value) - count
}
pub fn increment(&mut self, card: &Card) {
let count = self.counts.get_mut(card).unwrap();
*count += 1;
}
}
impl fmt::Display for CardCounts {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &color in COLORS.iter() {
write!(f, "{color}: ")?;
for &value in VALUES.iter() {
let count = self.get_count(&Card::new(color, value));
let total = get_count_for_value(value);
write!(f, "{count}/{total} {value}s")?;
if value != FINAL_VALUE {
f.write_str(", ")?;
}
}
f.write_str("\n")?;
}
Ok(())
}
}
pub type Cards = Vec<Card>;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Discard {
pub cards: Cards,
counts: CardCounts,
}
impl Discard {
pub fn new() -> Discard {
Discard {
cards: Cards::new(),
counts: CardCounts::new(),
}
}
pub fn has_all(&self, card: &Card) -> bool {
self.counts.remaining(card) == 0
}
pub fn remaining(&self, card: &Card) -> u32 {
self.counts.remaining(card)
}
pub fn place(&mut self, card: Card) {
self.counts.increment(&card);
self.cards.push(card);
}
}
impl fmt::Display for Discard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!(f, "{}", self.cards)?;
write!(f, "{}", self.counts)
}
}
pub type Score = u32;
pub const PERFECT_SCORE: Score = (NUM_COLORS * NUM_VALUES) as u32;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Firework {
pub color: Color,
pub top: Value,
}
impl Firework {
pub fn new(color: Color) -> Firework {
Firework { color, top: 0 }
}
pub fn needed_value(&self) -> Option<Value> {
if self.complete() {
None
} else {
Some(self.top + 1)
}
}
pub fn score(&self) -> Score {
self.top
}
pub fn complete(&self) -> bool {
self.top == FINAL_VALUE
}
pub fn place(&mut self, card: &Card) {
assert!(
card.color == self.color,
"Attempted to place card on firework of wrong color!"
);
assert!(
Some(card.value) == self.needed_value(),
"Attempted to place card of wrong value on firework!"
);
self.top = card.value;
}
}
impl fmt::Display for Firework {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.complete() {
write!(f, "{} firework complete!", self.color)
} else {
write!(f, "{} firework at {}", self.color, self.top)
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum Hinted {
Color(Color),
Value(Value),
}
impl fmt::Display for Hinted {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Hinted::Color(color) => {
write!(f, "{color}")
}
Hinted::Value(value) => {
write!(f, "{value}")
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Hint {
pub player: Player,
pub hinted: Hinted,
}
// represents the choice a player made in a given turn
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TurnChoice {
Hint(Hint),
Discard(usize), // index of card to discard
Play(usize), // index of card to play
}
// represents what happened in a turn
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TurnResult {
Hint(Vec<bool>), // vector of whether each was in the hint
Discard(Card), // card discarded
Play(Card, bool), // card played, whether it succeeded
}
// represents a turn taken in the game
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct TurnRecord {
pub player: Player,
pub choice: TurnChoice,
pub result: TurnResult,
}
pub type TurnHistory = Vec<TurnRecord>;
// represents possible settings for the game
pub struct GameOptions {
pub num_players: u32,
pub hand_size: u32,
// when hits 0, you cannot hint
pub num_hints: u32,
// when hits 0, you lose
pub num_lives: u32,
// whether to allow hints that reveal no cards
pub allow_empty_hints: bool,
}
// State of everything except the player's hands
// Is all completely common knowledge
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BoardState {
pub deck_size: u32,
pub total_cards: u32,
pub discard: Discard,
pub fireworks: FnvHashMap<Color, Firework>,
pub num_players: u32,
// which turn is it?
pub turn: u32,
pub turn_history: TurnHistory,
// // whose turn is it?
pub player: Player,
pub hand_size: u32,
pub hints_total: u32,
pub hints_remaining: u32,
pub allow_empty_hints: bool,
pub lives_total: u32,
pub lives_remaining: u32,
// only relevant when deck runs out
pub deckless_turns_remaining: u32,
}
impl BoardState {
pub fn new(opts: &GameOptions, deck_size: u32) -> BoardState {
let fireworks = COLORS
.iter()
.map(|&color| (color, Firework::new(color)))
.collect::<FnvHashMap<_, _>>();
BoardState {
deck_size,
total_cards: deck_size,
fireworks,
discard: Discard::new(),
num_players: opts.num_players,
hand_size: opts.hand_size,
player: 0,
turn: 1,
allow_empty_hints: opts.allow_empty_hints,
hints_total: opts.num_hints,
hints_remaining: opts.num_hints,
lives_total: opts.num_lives,
lives_remaining: opts.num_lives,
turn_history: Vec::new(),
// number of turns to play with deck length ran out
deckless_turns_remaining: opts.num_players + 1,
}
}
fn try_add_hint(&mut self) {
if self.hints_remaining < self.hints_total {
self.hints_remaining += 1;
}
}
pub fn get_firework(&self, color: Color) -> &Firework {
self.fireworks.get(&color).unwrap()
}
fn get_firework_mut(&mut self, color: Color) -> &mut Firework {
self.fireworks.get_mut(&color).unwrap()
}
// returns whether a card would place on a firework
pub fn is_playable(&self, card: &Card) -> bool {
Some(card.value) == self.get_firework(card.color).needed_value()
}
// best possible value we can get for firework of that color,
// based on looking at discard + fireworks
fn highest_attainable(&self, color: Color) -> Value {
let firework = self.fireworks.get(&color).unwrap();
if firework.complete() {
return FINAL_VALUE;
}
let needed = firework.needed_value().unwrap();
for &value in VALUES.iter() {
if value < needed {
// already have these cards
continue;
}
let needed_card = Card::new(color, value);
if self.discard.has_all(&needed_card) {
// already discarded all of these
return value - 1;
}
}
FINAL_VALUE
}
// is never going to play, based on discard + fireworks
pub fn is_dead(&self, card: &Card) -> bool {
let firework = self.fireworks.get(&card.color).unwrap();
firework.complete()
|| card.value < firework.needed_value().unwrap()
|| card.value > self.highest_attainable(card.color)
}
// can be discarded without necessarily sacrificing score, based on discard + fireworks
pub fn is_dispensable(&self, card: &Card) -> bool {
self.is_dead(card) || self.discard.remaining(card) != 1
}
pub fn get_players(&self) -> Range<Player> {
0..self.num_players
}
pub fn score(&self) -> Score {
self.fireworks.values().map(Firework::score).sum()
}
pub fn discard_size(&self) -> u32 {
self.discard.cards.len() as u32
}
pub fn player_to_left(&self, player: &Player) -> Player {
(player + 1) % self.num_players
}
pub fn player_to_right(&self, player: &Player) -> Player {
(player + self.num_players - 1) % self.num_players
}
pub fn is_over(&self) -> bool {
(self.lives_remaining == 0)
|| (self.deckless_turns_remaining == 0)
|| (self.score() == PERFECT_SCORE)
}
}
impl fmt::Display for BoardState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_over() {
writeln!(f, "Turn {} (GAME ENDED):", self.turn)?;
} else {
writeln!(f, "Turn {} (Player {}'s turn):", self.turn, self.player)?;
}
writeln!(f, "{} cards remaining in deck", self.deck_size)?;
if self.deck_size == 0 {
writeln!(
f,
"Deck is empty. {} turns remaining in game",
self.deckless_turns_remaining
)?;
}
writeln!(
f,
"{}/{} hints remaining",
self.hints_remaining, self.hints_total
)?;
writeln!(
f,
"{}/{} lives remaining",
self.lives_remaining, self.lives_total
)?;
f.write_str("Fireworks:\n")?;
for &color in COLORS.iter() {
writeln!(f, " {}", self.get_firework(color))?;
}
f.write_str("Discard:\n")?;
writeln!(f, "{}\n", self.discard)?;
Ok(())
}
}
// complete game view of a given player
pub trait GameView {
fn me(&self) -> Player;
fn get_hand(&self, player: &Player) -> &Cards;
fn get_board(&self) -> &BoardState;
fn my_hand_size(&self) -> usize;
fn hand_size(&self, player: &Player) -> usize {
if self.me() == *player {
self.my_hand_size()
} else {
self.get_hand(player).len()
}
}
fn has_card(&self, player: &Player, card: &Card) -> bool {
self.get_hand(player)
.iter()
.any(|other_card| card == other_card)
}
fn get_other_players(&self) -> Vec<Player> {
self.get_board()
.get_players()
.filter(|&player| player != self.me())
.collect()
}
fn can_see(&self, card: &Card) -> bool {
self.get_other_players()
.iter()
.any(|player| self.has_card(player, card))
}
fn someone_else_can_play(&self) -> bool {
self.get_other_players().iter().any(|player| {
self.get_hand(player)
.iter()
.any(|card| self.get_board().is_playable(card))
})
}
}
// version of game view that is borrowed. used in simulator for efficiency,
#[derive(Debug)]
pub struct BorrowedGameView<'a> {
// the player whose view it is
pub player: Player,
pub hand_size: usize,
// the cards of the other players, as well as the information they have
pub other_hands: FnvHashMap<Player, &'a Cards>,
// board state
pub board: &'a BoardState,
}
impl<'a> GameView for BorrowedGameView<'a> {
fn me(&self) -> Player {
self.player
}
fn my_hand_size(&self) -> usize {
self.hand_size
}
fn get_hand(&self, player: &Player) -> &Cards {
assert!(self.me() != *player, "Cannot query about your own state!");
self.other_hands.get(player).unwrap()
}
fn get_board(&self) -> &BoardState {
self.board
}
}
// version of game view, may be useful to strategies
#[derive(Debug)]
pub struct OwnedGameView {
// the player whose view it is
pub player: Player,
pub hand_size: usize,
// the cards of the other players, as well as the information they have
pub other_hands: FnvHashMap<Player, Cards>,
// board state
pub board: BoardState,
}
impl OwnedGameView {
pub fn clone_from(borrowed_view: &BorrowedGameView) -> OwnedGameView {
let other_hands = borrowed_view
.other_hands
.iter()
.map(|(&other_player, &player_state)| (other_player, player_state.clone()))
.collect::<FnvHashMap<_, _>>();
OwnedGameView {
player: borrowed_view.player,
hand_size: borrowed_view.hand_size,
other_hands,
board: (*borrowed_view.board).clone(),
}
}
}
impl GameView for OwnedGameView {
fn me(&self) -> Player {
self.player
}
fn my_hand_size(&self) -> usize {
self.hand_size
}
fn get_hand(&self, player: &Player) -> &Cards {
assert!(self.me() != *player, "Cannot query about your own state!");
self.other_hands.get(player).unwrap()
}
fn get_board(&self) -> &BoardState {
&self.board
}
}
// Internally, every card is annotated with its index in the deck in order to
// generate easy-to-interpret JSON output. These annotations are stripped off
// when passing GameViews to strategies.
//
// TODO: Maybe we should give strategies access to the annotations as well?
// This could simplify code like in InformationPlayerStrategy::update_public_info_for_discard_or_play.
// Also, this would let a strategy publish "notes" on cards more easily.
pub type AnnotatedCard = (usize, Card);
pub type AnnotatedCards = Vec<AnnotatedCard>;
fn strip_annotations(cards: &AnnotatedCards) -> Cards {
cards.iter().map(|(_i, card)| card.clone()).collect()
}
// complete game state (known to nobody!)
#[derive(Debug)]
pub struct GameState {
pub hands: FnvHashMap<Player, AnnotatedCards>,
// used to construct BorrowedGameViews
pub unannotated_hands: FnvHashMap<Player, Cards>,
pub board: BoardState,
pub deck: AnnotatedCards,
}
impl fmt::Display for GameState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("\n")?;
f.write_str("======\n")?;
f.write_str("Hands:\n")?;
f.write_str("======\n")?;
for player in self.board.get_players() {
let hand = &self.hands.get(&player).unwrap();
write!(f, "player {player}:")?;
for (_i, card) in hand.iter() {
write!(f, " {card}")?;
}
f.write_str("\n")?;
}
f.write_str("======\n")?;
f.write_str("Board:\n")?;
f.write_str("======\n")?;
write!(f, "{}", self.board)?;
Ok(())
}
}
impl GameState {
pub fn new(opts: &GameOptions, deck: Cards) -> GameState {
// We enumerate the cards in reverse order since they'll be drawn from the back of the deck.
let mut deck: AnnotatedCards = deck.into_iter().rev().enumerate().rev().collect();
let mut board = BoardState::new(opts, deck.len() as u32);
let hands = (0..opts.num_players)
.map(|player| {
let hand = (0..opts.hand_size)
.map(|_| {
// we can assume the deck is big enough to draw initial hands
board.deck_size -= 1;
deck.pop().unwrap()
})
.collect::<Vec<_>>();
(player, hand)
})
.collect::<FnvHashMap<_, _>>();
let unannotated_hands = hands
.iter()
.map(|(player, hand)| (*player, strip_annotations(hand)))
.collect::<FnvHashMap<_, _>>();
GameState {
hands,
unannotated_hands,
board,
deck,
}
}
pub fn get_players(&self) -> Range<Player> {
self.board.get_players()
}
pub fn is_over(&self) -> bool {
self.board.is_over()
}
pub fn score(&self) -> Score {
self.board.score()
}
// get the game state view of a particular player
pub fn get_view(&self, player: Player) -> BorrowedGameView {
let mut other_hands = FnvHashMap::default();
for (&other_player, hand) in &self.unannotated_hands {
if player != other_player {
other_hands.insert(other_player, hand);
}
}
BorrowedGameView {
player,
hand_size: self.hands.get(&player).unwrap().len(),
other_hands,
board: &self.board,
}
}
fn update_player_hand(&mut self) {
let player = self.board.player;
self.unannotated_hands
.insert(player, strip_annotations(self.hands.get(&player).unwrap()));
}
// takes a card from the player's hand, and replaces it if possible
fn take_from_hand(&mut self, index: usize) -> Card {
let hand = &mut self.hands.get_mut(&self.board.player).unwrap();
let card = hand.remove(index).1;
self.update_player_hand();
card
}
fn replenish_hand(&mut self) {
let hand = &mut self.hands.get_mut(&self.board.player).unwrap();
if (hand.len() as u32) < self.board.hand_size {
if let Some(new_card) = self.deck.pop() {
self.board.deck_size -= 1;
debug!("Drew new card, {}", new_card.1);
hand.push(new_card);
}
}
self.update_player_hand();
}
pub fn process_choice(&mut self, choice: TurnChoice) -> TurnRecord {
let turn_result = {
match choice {
TurnChoice::Hint(ref hint) => {
assert!(
self.board.hints_remaining > 0,
"Tried to hint with no hints remaining"
);
self.board.hints_remaining -= 1;
debug!("Hint to player {}, about {}", hint.player, hint.hinted);
assert_ne!(
self.board.player, hint.player,
"Player {} gave a hint to himself",
hint.player
);
let hand = self.hands.get(&hint.player).unwrap();
let results = match hint.hinted {
Hinted::Color(color) => hand
.iter()
.map(|(_i, card)| card.color == color)
.collect::<Vec<_>>(),
Hinted::Value(value) => hand
.iter()
.map(|(_i, card)| card.value == value)
.collect::<Vec<_>>(),
};
if !self.board.allow_empty_hints {
assert!(
results.iter().any(|matched| *matched),
"Tried hinting an empty hint"
);
}
TurnResult::Hint(results)
}
TurnChoice::Discard(index) => {
assert!(
self.board.hints_remaining < self.board.hints_total,
"Tried to discard while at max hint count"
);
let card = self.take_from_hand(index);
debug!("Discard card in position {}, which is {}", index, card);
self.board.discard.place(card.clone());
self.board.try_add_hint();
TurnResult::Discard(card)
}
TurnChoice::Play(index) => {
let card = self.take_from_hand(index);
debug!("Playing card at position {}, which is {}", index, card);
let playable = self.board.is_playable(&card);
if playable {
{
let firework = self.board.get_firework_mut(card.color);
debug!("Successfully played {}!", card);
firework.place(&card);
}
if card.value == FINAL_VALUE {
debug!("Firework complete for {}!", card.color);
self.board.try_add_hint();
}
} else {
self.board.discard.place(card.clone());
self.board.lives_remaining -= 1;
debug!(
"Removing a life! Lives remaining: {}",
self.board.lives_remaining
);
}
TurnResult::Play(card, playable)
}
}
};
let turn_record = TurnRecord {
player: self.board.player,
result: turn_result,
choice,
};
self.board.turn_history.push(turn_record.clone());
self.replenish_hand();
if self.board.deck_size == 0 {
self.board.deckless_turns_remaining -= 1;
}
self.board.turn += 1;
self.board.player = {
let cur = self.board.player;
self.board.player_to_left(&cur)
};
assert_eq!(
(self.board.turn - 1) % self.board.num_players,
self.board.player
);
turn_record
}
}