1 use rand::seq::SliceRandom;
4 pub const NUM_RANKS: usize = 13;
5 pub const NUM_SUITS: usize = 4;
6 pub const NUM_JOKERS: usize = 2;
7 pub const NUM_CARDS: usize = NUM_RANKS * NUM_SUITS + NUM_JOKERS;
9 pub const STARTING_CARDS: u8 = 3;
10 pub const STARTING_MAD_SCIENCE_TOKENS: i8 = 15;
11 pub const STARTING_PROGRESS: i8 = -10;
13 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
17 pub fn value(&self) -> u8 {
21 pub fn is_face(&self) -> bool {
25 pub fn random() -> Self {
28 .gen_range(0..NUM_RANKS)
30 .expect("Too many ranks?"),
35 #[derive(Clone, Copy, Eq, PartialEq)]
38 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
42 pub fn is_joker(&self) -> bool {
43 usize::from(self.0) >= NUM_RANKS * NUM_SUITS
46 pub fn rank(&self) -> Option<Rank> {
47 (!self.is_joker()).then_some(Rank(self.0 >> 2))
50 pub fn suit(&self) -> Option<Suit> {
51 (!self.is_joker()).then_some(Suit(self.0 & 3))
55 #[derive(Clone, Copy)]
56 pub enum WithOrWithoutJokers {
62 pub fn deck(j: WithOrWithoutJokers) -> Vec<Card> {
63 let limit = u8::try_from(match j {
64 WithOrWithoutJokers::WithJokers => NUM_CARDS,
65 WithOrWithoutJokers::WithoutJokers => NUM_SUITS * NUM_RANKS,
67 .expect("Too many cards?");
68 (0..limit).map(Card).collect()
71 fn shuffle(cards: &mut Vec<Card>) {
72 cards.shuffle(&mut rand::thread_rng());
75 fn shuffled(mut cards: Vec<Card>) -> Vec<Card> {
80 #[derive(Clone, Copy, Debug)]
81 pub struct PathLength(Rank);
84 pub fn random() -> Self {
89 #[derive(Clone, Copy, Default)]
90 pub struct PathLengthInfo(u16);
93 pub fn is_showing(&self, i: Rank) -> bool {
94 (self.0 >> i.0) & 1 == 1
96 fn reveal(&mut self, i: Rank) {
99 pub fn reveal_random(&mut self, true_length: PathLength) -> Option<Rank> {
100 let showing = usize::try_from(self.0.count_ones()).expect("There aren't that many bits");
101 let not_showing = NUM_RANKS - showing;
102 if not_showing <= 1 {
106 let mut show = rand::thread_rng().gen_range(0..not_showing - 1);
107 for i in 0..NUM_RANKS {
108 let r = Rank(u8::try_from(i).expect("Too many cards?"));
109 if !self.is_showing(r) && r != true_length.0 {
126 pub fn discard(&mut self, card: Card) {
127 self.cards.push(card);
130 pub fn top(&self) -> Option<&Card> {
133 fn len(&self) -> usize {
143 pub fn new(cards: Vec<Card>) -> Self {
146 pub fn draw(&mut self, discard: &mut Discard) -> Option<Card> {
147 if self.cards.is_empty() {
148 if let Some(top_discard) = discard.cards.pop() {
149 std::mem::swap(&mut self.cards, &mut discard.cards);
150 discard.discard(top_discard);
151 shuffle(&mut self.cards);
156 fn len(&self) -> usize {
161 #[derive(Debug, Default)]
166 fn add(&mut self, card: Card) {
167 self.cards.push(card);
169 fn remove(&mut self, card: Card) -> Result<(), &'static str> {
173 .position(|&e| e == card)
174 .ok_or("That card is not in your hand")?;
175 self.cards.swap_remove(i);
178 fn len(&self) -> usize {
181 fn random(&self) -> Option<&Card> {
182 self.cards.choose(&mut rand::thread_rng())
184 /// Make a new Hand that contains only cards of the requested suit
185 fn filter_by_suit(&self, suit: Suit) -> Self {
190 .filter(|c| c.suit().expect("I shouldn't have jokers in my hand") == suit)
197 #[derive(Copy, Clone)]
198 pub struct PlayerIndex(usize);
200 fn next(self, num_players: usize) -> Self {
201 Self((self.0 + 1) % num_players)
205 #[derive(Copy, Clone, Debug)]
211 #[derive(Eq, PartialEq)]
218 pub enum GameOutcome {
223 pub enum PlayOutcome {
229 mad_science_tokens: i8,
230 progress: [i8; NUM_SUITS],
231 path_lengths: [PathLength; NUM_SUITS],
232 path_length_info: [PathLengthInfo; NUM_SUITS],
240 pub fn add_player(&mut self) {
241 self.hands.push(Hand::default());
242 for _ in 0..STARTING_CARDS {
243 self.draw_for_player(PlayerIndex(self.hands.len() - 1));
248 /// Will return `Err` on invalid plays, like trying to draw during Play phase,
249 /// or trying to play a card that's not in your hand.
250 pub fn play(&mut self, play: Play) -> Result<PlayOutcome, &'static str> {
252 Play::Play(card) => self.play_card(card),
253 Play::Draw => self.draw_for_momentum(),
258 pub fn current_player_hand(&self) -> &Hand {
259 &self.hands[self.turn.0]
261 fn player_hand_mut(&mut self, pi: PlayerIndex) -> &mut Hand {
262 &mut self.hands[pi.0]
264 fn current_player_hand_mut(&mut self) -> &mut Hand {
265 self.player_hand_mut(self.turn)
268 fn play_card(&mut self, card: Card) -> Result<PlayOutcome, &'static str> {
269 let momentum = self.apply_card(card)?;
270 if self.phase == Phase::Play && momentum {
271 self.phase = Phase::Momentum;
272 Ok(PlayOutcome::Continue)
274 Ok(self.end_of_turn())
277 fn draw_for_momentum(&mut self) -> Result<PlayOutcome, &'static str> {
278 if self.phase != Phase::Momentum {
279 return Err("You don't have momentum");
281 self.draw_for_player(self.turn);
282 Ok(self.end_of_turn())
285 fn draw_for_player(&mut self, pi: PlayerIndex) {
287 if let Some(card) = self.library.draw(&mut self.discard) {
289 self.remove_mad_science_token();
290 self.discard.discard(card);
292 self.player_hand_mut(pi).add(card);
296 println!("Library ran out of cards");
300 fn remove_mad_science_token(&mut self) {
302 self.mad_science_tokens -= 1;
303 if self.mad_science_tokens != 0 {
308 fn make_progress(&mut self, card: Card) {
309 let rank = card.rank().expect("Can't play jokers").0;
311 let roll = rand::thread_rng().gen_range(1..=6);
313 self.remove_mad_science_token();
316 self.progress[usize::from(card.suit().expect("Can't play jokers").0)] += 1;
318 fn forecast(&mut self, card: Card) {
319 let suit = usize::from(card.suit().expect("Can't play jokers").0);
320 self.path_length_info[suit].reveal_random(self.path_lengths[suit]);
322 // Returns whether or not this play grants momentum
323 fn apply_card(&mut self, card: Card) -> Result<bool, &'static str> {
324 self.current_player_hand_mut().remove(card)?;
325 if card.rank().expect("Can't play jokers").is_face() {
328 self.make_progress(card);
330 let suits_match = self
333 .map_or(false, |dis| dis.suit() == card.suit());
334 self.discard.discard(card);
337 fn valid(&self) -> bool {
338 108 == (self.library.len()
340 + self.hands.iter().map(Hand::len).sum::<usize>())
342 fn roll_mad_science(&mut self) -> PlayOutcome {
343 let mut tokens = std::iter::from_fn(|| Some(rand::thread_rng().gen_bool(0.5)))
344 .take(usize::try_from(self.mad_science_tokens.abs()).expect("wat?"));
345 let keep_going = if self.mad_science_tokens > 0 {
351 PlayOutcome::Continue
353 PlayOutcome::End(self.final_score())
356 fn final_score(&self) -> GameOutcome {
360 .zip(self.path_lengths.iter())
361 .any(|(&prog, len)| prog >= len.0.value().try_into().expect("wat?"))
368 fn end_of_turn(&mut self) -> PlayOutcome {
369 assert!(self.valid());
370 self.phase = Phase::Play;
371 self.turn = self.turn.next(self.hands.len());
372 if self.turn.0 == 0 {
373 if let PlayOutcome::End(game_outcome) = self.roll_mad_science() {
374 return PlayOutcome::End(game_outcome);
377 self.draw_for_player(self.turn);
378 assert!(self.valid());
379 PlayOutcome::Continue
382 impl Default for Game {
383 fn default() -> Self {
385 mad_science_tokens: STARTING_MAD_SCIENCE_TOKENS,
386 progress: [STARTING_PROGRESS; NUM_SUITS],
387 path_lengths: std::iter::from_fn(|| Some(PathLength::random()))
392 path_length_info: [PathLengthInfo::default(); NUM_SUITS],
393 library: Library::new(shuffled(
395 deck(WithOrWithoutJokers::WithJokers),
396 deck(WithOrWithoutJokers::WithJokers),
400 discard: Discard::default(),
402 turn: PlayerIndex(0),
408 pub struct Player(Box<dyn FnMut(&Game) -> Play>);
411 pub fn new<T>(f: T) -> Self
413 T: FnMut(&Game) -> Play + 'static,
420 pub fn random_player(draw_chance: f64) -> Player {
421 Player(Box::new(move |game: &Game| -> Play {
423 Phase::Play => Play::Play(
425 .current_player_hand()
427 .expect("I always have a card to play because I just drew one"),
430 if rand::thread_rng().gen_bool(draw_chance) {
433 match game.current_player_hand().random() {
434 Some(card) => Play::Play(*card),
443 /// When available, make plays that grant momentum.
445 pub fn momentum_player(mut fallback: Player) -> Player {
446 Player(Box::new(move |game: &Game| -> Play {
447 match (&game.phase, game.discard.top().and_then(Card::suit)) {
448 (Phase::Play, Some(suit)) => {
449 match game.current_player_hand().filter_by_suit(suit).random() {
450 Some(card) => Play::Play(*card),
451 _ => fallback.0(game),
454 _ => fallback.0(game),
461 /// Will return `Err` on invalid plays, like trying to draw during Play phase,
462 /// or trying to play a card that's not in your hand.
463 pub fn play(mut game: Game, mut players: Vec<Player>) -> Result<GameOutcome, &'static str> {
464 game.draw_for_player(game.turn);
466 if let PlayOutcome::End(game_outcome) = game.play(players[game.turn.0].0(&game))? {
467 return Ok(game_outcome);
477 fn path_length_info_random_reveal() {
478 let length = PathLength(Rank(7));
479 let mut pli = PathLengthInfo::default();
481 let old_pli = PathLengthInfo::clone(&pli);
482 match pli.reveal_random(length) {
483 None => panic!("Nothing revealed?"),
485 assert!(!old_pli.is_showing(r));
486 assert!(pli.is_showing(r));
489 assert_eq!(pli.0.count_ones(), 1 + old_pli.0.count_ones());
491 assert!(pli.reveal_random(length).is_none());
496 use WithOrWithoutJokers::*;
497 let d = deck(WithoutJokers);
498 let rank_sum: u32 = d
502 .map(|r| u32::from(r.value()))
504 assert_eq!(rank_sum, 364);
505 let _dj = deck(WithJokers);
510 let mut lib = Library::new(vec![Card(7)]);
511 let mut dis = Discard::default();
512 dis.discard(Card(8));
513 dis.discard(Card(9));
514 assert_eq!(lib.draw(&mut dis), Some(Card(7)));
515 assert_eq!(lib.draw(&mut dis), Some(Card(8)));
516 assert_eq!(lib.draw(&mut dis), None);
521 let mut h = Hand::default();
522 assert!(h.remove(Card(4)).is_err());
524 assert!(h.remove(Card(3)).is_err());
525 assert!(h.remove(Card(4)).is_ok());
526 assert!(h.remove(Card(4)).is_err());
531 for num_players in 1..10 {
532 let players: Vec<_> = std::iter::from_fn(|| Some(random_player(0.5)))
535 let mut game = Game::default();
536 for _ in 0..num_players {
539 assert!(play(game, players).is_ok());