src/row.rs
changeset 4 a2f0cb2b5c13
child 5 0dd7f2c9fd81
equal deleted inserted replaced
3:3d9dba5b16e0 4:a2f0cb2b5c13
       
     1 /*** Row ****/
       
     2 // a row of cards on the table (max 5)
       
     3 
       
     4 use std::{collections::VecDeque, mem};
       
     5 
       
     6 use crate::card::Card;
       
     7 
       
     8 #[derive(Debug)]
       
     9 pub(crate) struct Row {
       
    10     cards: VecDeque<Card>,
       
    11 }
       
    12 
       
    13 impl Row {
       
    14     const MAX_LEN: usize = 5;
       
    15 
       
    16     pub(crate) fn new() -> Self {
       
    17         Row {
       
    18             cards: VecDeque::with_capacity(5),
       
    19         }
       
    20     }
       
    21 
       
    22     pub(crate) fn push_or_collect( &mut self, card: Card ) -> Option<VecDeque<Card>> {
       
    23         trace!("Called push_or_collect on row {:?}", &self);
       
    24         if self.cards.len() < Self::MAX_LEN {
       
    25             trace!("Less than {} cards, putting at the end", Self::MAX_LEN);
       
    26             self.cards.push_back(card);
       
    27             None
       
    28 
       
    29         } else {
       
    30             trace!("Row is full, len {}, maxlen {}", self.cards.len(), Self::MAX_LEN);
       
    31             // row overflow
       
    32             let row_cards = mem::take( &mut self.cards );
       
    33             self.cards.push_back(card);
       
    34             if self.cards.len() != 1 {
       
    35                 panic!("New row must have one card, not {}", self.cards.len());
       
    36             }
       
    37             Some(row_cards)
       
    38         }
       
    39     }
       
    40 
       
    41     pub(crate) fn take_row( &mut self ) -> VecDeque<Card> {
       
    42         // take cards and empty the row
       
    43         mem::take( &mut self.cards )
       
    44     }
       
    45 
       
    46     pub(crate) fn last_card_value(&self) -> i8 {
       
    47         // println!("last_card_value: cards {:?}, len {}", self.cards, self.cards.len());
       
    48         self.cards.get( self.cards.len()-1 ).unwrap().value
       
    49     }
       
    50 
       
    51     // sum of row card points
       
    52     pub(crate) fn sum(&self) -> i32 {
       
    53         let mut sum: i32 = 0;
       
    54         self.cards.iter().for_each(|card| {
       
    55             sum += card.points as i32;
       
    56         });
       
    57         sum
       
    58     }
       
    59 
       
    60     pub fn len(&self) -> usize {
       
    61         self.cards.len()
       
    62     }
       
    63 }