From 644e6c7a89b96a5542bf3a647cf23bfaf6765a94 Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Sun, 16 Jul 2023 22:27:58 -0700 Subject: [PATCH] Library, drawing, & recycling discard pile --- src/lib.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index b0387bc..4496f80 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,7 @@ impl Rank { #[derive(Clone, Copy, Eq, PartialEq)] pub struct Suit(u8); -#[derive(Clone, Copy, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Card(u8); impl Card { #[must_use] @@ -85,6 +85,36 @@ impl PathLengthInfo { } } +#[derive(Default)] +pub struct Discard { + cards: Vec, +} +impl Discard { + pub fn discard(&mut self, card: Card) { + self.cards.push(card); + } +} + +pub struct Library { + cards: Vec, +} +impl Library { + #[must_use] + pub fn new(cards: Vec) -> Self { + Self { cards } + } + pub fn draw(&mut self, discard: &mut Discard) -> Option { + if self.cards.is_empty() { + if let Some(top_discard) = discard.cards.pop() { + std::mem::swap(&mut self.cards, &mut discard.cards); + discard.discard(top_discard); + // TODO: Shuffle + } + } + self.cards.pop() + } +} + #[cfg(test)] mod tests { use super::*; @@ -120,4 +150,15 @@ mod tests { assert_eq!(rank_sum, 364); let _dj = deck(WithJokers); } + + #[test] + fn test_library() { + let mut lib = Library::new(vec![Card(7)]); + let mut dis = Discard::default(); + dis.discard(Card(8)); + dis.discard(Card(9)); + assert_eq!(lib.draw(&mut dis), Some(Card(7))); + assert_eq!(lib.draw(&mut dis), Some(Card(8))); + assert_eq!(lib.draw(&mut dis), None); + } } -- 2.44.1