diff -r 3d9dba5b16e0 -r a2f0cb2b5c13 src/table.rs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/table.rs Tue Jan 31 23:25:50 2023 +0100 @@ -0,0 +1,99 @@ +/*** Table ****/ + +use std::collections::VecDeque; + +use crate::card::Card; +use crate::row::Row; +use crate::player::PlayerCard; + +#[derive(Debug)] +pub(crate) struct Table { + rows: Vec, + player_cards: VecDeque, // owned by a player +} + +impl Table { + pub(crate) fn new(row_cards: VecDeque) -> Self { + let mut rows = Vec::with_capacity(5); + for card in row_cards { + // create a new row then put a card into it + let mut row = Row::new(); + if let Some(_c) = row.push_or_collect(card) { + panic!("Freshly created row overflowed"); + } + rows.push( row ); + } + + Table { + rows, + player_cards: VecDeque::new(), + } + } + + pub(crate) fn lay_player_card( &mut self, card: Card, player_id: i32 ) { + self.player_cards.push_back( PlayerCard { player_id, card } ); + } + + pub(crate) fn sort_cards( &mut self ) { + self.player_cards.make_contiguous().sort_by( |a,b| b.card.cmp(&a.card) ); + } + + pub(crate) fn has_player_cards( &self ) -> bool { + self.player_cards.len() > 0 + } + + pub(crate) fn get_smallest_player_card( &mut self ) -> PlayerCard { + // FIXME: check! + self.player_cards.pop_back().expect("out of player cards on table") + } + + pub(crate) fn get_closest_row( &self, pcard: &PlayerCard ) -> Option { + // get the row id with last card closest smaller to players' + let row_heads = self.get_row_heads(); + let mut closest_val = None; + let mut diff = 127; + for i in 0..row_heads.len() { + if row_heads[i] < pcard.card.value && pcard.card.value - row_heads[i] < diff { + closest_val = Some(i); + diff = pcard.card.value - row_heads[i]; + // println!("DEBUG: pcard {}, row {}, head {}, diff {}, closest {:?}", pcard.card.value, i, row_heads[i], diff, closest_val); + } + } + + closest_val + } + + pub(crate) fn put_card_into_row( &mut self, pcard: PlayerCard, row_id: usize ) -> Option> { + self.rows[row_id as usize].push_or_collect(pcard.card) + } + + pub(crate) fn get_row_heads( &self ) -> Vec { + let mut heads: Vec = Vec::new(); + for i in 0..self.rows.len() { + heads.push( self.rows[i].last_card_value() ); + } + heads + } + + // take a whole row and hand it over + pub(crate) fn take_row( &mut self, row_id: usize ) -> VecDeque { + self.rows[row_id].take_row() + } + + // collect remaining cards in the rows at the end of round + pub(crate) fn collect_rows( &mut self ) -> VecDeque { + let mut cards = VecDeque::new(); + for row in 0..self.rows.len() { + self.rows[row] + .take_row() + .into_iter() + .for_each(|card| cards.push_back(card)); + } + cards + } + + pub fn peek_rows(&self) -> &Vec { + &self.rows + } +} +