Split main into module files.
// #[allow(dead_code, unused)]
// vigyazz6! autplayer
//
use core::panic;
use std::{collections::VecDeque, time::Instant, cmp::Reverse};
use crate::{deck::Deck, player::Player, table::Table};
// use rand::Rng;
// use std::mem;
mod deck;
mod table;
mod player;
mod card;
mod row;
extern crate pretty_env_logger;
#[macro_use] extern crate log;
const GAME_ROUNDS: i32 = 100_000;
fn main() {
// RUST_LOG=debug cargo run
pretty_env_logger::init();
info!("Program starting.");
game();
info!("End of run.");
}
// Card
// Deck
// Player
// Row
/*** Game ****/
struct GameStat {
game_count: i64,
shuffle_count: i64,
start_time: Instant, // use start_time.elapsed().as_nanos() or .as_secs()
}
fn game() {
let mut stats = GameStat { game_count:0, shuffle_count: 0, start_time: Instant::now() };
let mut deck = Deck::new();
let player_names = vec![ "grin", "moni", "icbalint", "orsi", "topi", "kgb", "zsu", "csilla" ];
let mut players: Vec<Player> = player_names.iter().map( |n| Player::new(n.to_string()) ).collect();
let player_count = players.len(); // pc - 1
for cnt_game in 1..=GAME_ROUNDS {
debug!("Game round {} starts", cnt_game);
deck.shuffle();
stats.shuffle_count += 1;
stats.game_count += 1;
// dealing
debug!("Dealing.");
for _i in 1..=10 {
for player in 0 .. player_count {
players[player].get_card( deck.pop().expect("Deck is empty while dealing to players") );
}
}
// we need 5 crds from deck
debug!("Building the rows.");
let mut cards = VecDeque::new();
(1..=5).for_each(|_| {
cards.push_back( deck.pop().expect("deck empty before starting the game") );
});
// println!("We push 5 cards to rows: {:?}\n", cards);
let mut table = Table::new(cards);
// DEBUG
/* println!("Table: {:?}\n", table);
println!("PLayers: {:?}\n", players);
println!("Deck: {:?}\n", deck);
*/
debug!("We have the table ready: {:?}", table);
// playing
debug!("Players start taking turns");
for turn in 1..=10 {
debug!("Turn {}!", turn);
trace!("The table: {:?}", table);
// everyone puts a card face down
for player in 0 .. player_count {
let player_id: i32 = player.try_into().unwrap();
// get a card from the player
let topcard = players[player].throw_card();
// put it on the table ("turned face down")
table.lay_player_card( topcard, player_id );
}
// process cards
debug!("The Table process the throws.");
table.sort_cards();
while table.has_player_cards() {
let smallest = table.get_smallest_player_card();
trace!("Take smallest card {:?}", &smallest);
let closest_row = table.get_closest_row(&smallest);
trace!("Choose closest row: {:?}", closest_row);
match closest_row {
Some(rowid) => {
debug!("Putting down card into row {}", rowid);
let player_id: usize = smallest.player_id.try_into().unwrap();
let overflow = table.put_card_into_row(smallest, rowid);
if let Some(cards) = overflow {
// row is full, got pile
debug!("Row is busted, {} collects", players[player_id].get_name());
// player gets pile, card gets into row head
players[ player_id ].give_pile( cards );
}
},
None => {
// card too small, need to pick row!
let player_id: usize = smallest.player_id.try_into().unwrap();
debug!("Too small from {}, picking row", players[player_id].get_name());
// pick any row to take
// let rowid = players[ player_id ].pick_row_for_small_card(&table.rows, &smallest.card);
let rowid = players[ player_id ].pick_row_for_small_card(table.peek_rows(), &smallest.card);
trace!("Picked row {}", rowid);
// take the row cards
let cards = table.take_row(rowid);
trace!("Took cards: {:?}", cards);
players[ player_id ].give_pile( cards );
// put new card in the row
let overflow = table.put_card_into_row(smallest, rowid);
if let Some(_) = overflow {
panic!("Player took whole row and it's already full");
}
}
}
}
}
// end of round
info!("Round finished, len is {} ??sec", stats.start_time.elapsed().as_micros());
debug!("End of round, counting and collecting back piles");
let mut winners: Vec<usize> = Vec::new();
let mut winscore: i32 = i32::MAX-1;
for i in 0..player_count {
info!("Player {} has {} points", players[i].get_name(), players[i].get_points());
if players[i].get_points() < winscore {
trace!("New winner {} with score {}", players[i].get_name(), players[i].get_points());
winners.clear();
winners.push(i);
winscore = players[i].get_points();
} else if players[i].get_points() == winscore {
trace!("New co-winner {} with score {}", players[i].get_name(), players[i].get_points());
winners.push(i);
}
trace!("The list of winners is {:?}", winners);
// get pile from player
let cards = players[i].get_pile();
// and give it back to the deck
deck.push_cards(cards);
// close player round and update stats
players[i].close_round();
}
// collect cards from table
deck.push_cards( table.collect_rows() );
trace!("Shall have full deck now, len {}", deck.len());
let mut finals = Vec::new();
for i in winners.iter() {
players[*i].inc_wins();
}
for i in winners {
finals.push( players[i].get_name() );
}
info!("The winner(s): {:?}", &finals);
/* players.iter().for_each(|player| {
println!("Player {} has {} points", player.name, player.game_point);
let cards = player.get_pile();
deck.push_cards(cards);
player.close_round();
});
*/
}
// do the type conversions _very_ visibly
let elapsed_micro: f64 = stats.start_time.elapsed().as_micros() as f64;
let game_rounds: f64 = GAME_ROUNDS.into();
// which is same as the slightly uglier
let _res: f64 = stats.start_time.elapsed().as_micros() as f64 / <i32 as Into<f64>>::into(GAME_ROUNDS);
println!("Totals (game time {} ??s, or {} s; {} ??s/game), {} games played ({} shuffles):",
stats.start_time.elapsed().as_micros(),
stats.start_time.elapsed().as_secs(),
elapsed_micro / game_rounds,
stats.game_count,
stats.shuffle_count,
);
// players.sort_by( |a, b| a.total_point.partial_cmp(&b.total_point).unwrap() ); // ASC points
// players.sort_by( |a, b| b.wins.partial_cmp(&a.wins).unwrap() ); // DESC wins
players.sort_by_cached_key( |x| Reverse(x.get_wins()) ); // DESC wins (caching is just for the show)
for i in 0..players.len() {
let p = &players[i];
println!("Player {} has wins {}, score {} (busted {} times)",
p.get_name(),
p.get_wins(),
p.get_total_points(),
p.get_rows_busted());
}
}
#[cfg(test)]
mod tests {
use std::collections::VecDeque;
use rand::Rng;
use crate::{card::Card, player::{Player, PlayerCard}, row::Row, table::Table};
#[test]
fn card_values() {
let card_values = vec![1,2,5,10,33,55,77];
let card_points = vec![1,1,2,3, 5, 7, 5];
for i in 1 .. card_values.len() {
let c = Card::new( card_values[i] );
let p = c.points;
assert!(p == card_points[i], "card={} card points={} i={} expected point={}", card_values[i], p, i, card_points[i]);
}
}
#[test]
fn player_take_pile() {
// create a player
let mut p = Player::new("bob".to_string());
// create a pile
let mut pile = VecDeque::new();
let mut refpile = VecDeque::new();
for i in 5..10 {
let c = Card::new(i);
pile.push_back(c);
let c = Card::new(i);
refpile.push_back(c);
}
// give the pile to player
p.give_pile(pile);
assert!( p.get_rows_busted() == 1 );
// get back the pile from player
// p = p.gimme_pile();
let pile = p.get_pile();
// the pile we got shall be same as the pile we gave
// this check is O(n^2), doesn't matter for less than 100 items
assert_eq!( pile, refpile );
assert!( pile.iter().all( |item| refpile.contains(item)) );
let mut pile = VecDeque::new();
for i in 4..=9 {
let c = Card::new(i);
pile.push_back(c);
}
p.give_pile(pile);
assert!( p.get_rows_busted() == 2 );
}
#[test]
fn row_push() {
let mut row = Row::new();
let mut refcard = VecDeque::new(); // reference vec to check
for i in 1..=7 {
let cval = i+5;
let card = Card::new(cval);
// push a card into the row
if let Some(cards) = row.push_or_collect(card) {
// got the overflow
println!("Got overflow row at {}!", i);
assert!( i == 6, "Overflow at wrong position: {} != 6", i );
// we need to get the proper vec
assert!( cards.iter().all( |item| refcard.contains(item) ), "Got cards {:?}", cards );
} else {
println!("push success {}", i);
}
// remember the correct vec for checking
let card = Card::new(cval);
refcard.push_back(card);
// check card value
assert!( row.last_card_value() == cval, "Last card value mismatch: got {} vs expected {}", row.last_card_value(), cval );
}
assert!( row.len() == 2, "Row contains wrong amount of cards: {}", row.len() );
}
#[test]
fn sort_cards() {
let mut cards: VecDeque<Card> = VecDeque::new();
let mut rng = rand::thread_rng();
for _ in 1..50 {
let n = rng.gen_range(1..104);
cards.push_back( Card::new(n) );
}
cards.make_contiguous().sort();
for i in 1..cards.len() {
assert!( cards[i-1].value <= cards[i].value, "Bad ordering: {} > {}", cards[i-1].value,cards[i].value );
}
}
#[test]
fn check_closest_row() {
let table = generate_table();
let pcard = PlayerCard{ player_id: 42, card: Card::new(42) };
let closest = table.get_closest_row(&pcard);
assert_eq!( closest, Some(3) ); // index from 0
}
#[test]
fn check_smallest_player_card() {
let mut table = generate_table();
let mut player_id = 1;
vec![103, 8, 71, 93, 6].into_iter().for_each(|c| {
table.lay_player_card( Card::new(c), player_id);
player_id += 1;
});
let smallest = table.get_smallest_player_card();
assert_eq!( smallest, PlayerCard{ player_id: 5, card: Card::new(6) } );
}
fn generate_table() -> Table {
let mut row_cards = VecDeque::new();
vec![5,7,10,33,70].into_iter().for_each(|c| row_cards.push_back( Card::new(c) ));
let table = Table::new(row_cards);
table
}
}
/*
- 1-104 lap,
- *5 - 2
- *0 - 3
- NN - 5
- 55 - 7
- deck
- jatekosok; kezben tartott lapok; elvitt lapok; pontszamok; counter: elvitt sorok, okrok, total pont
-- keveres (keveresek szama)
-- osztas: mindenki 10 lap
-- start sorok: 5 kartya
- jatek (jatekok szama)
-- mindenki a felso lapot kiteszi
-- szamsorrendben felkerulnek, aki viszi, viszi
--- ha kisebb, akkor dontes
---- ha van legkevesebb, viszi
---- ha tobb min van, random valaszt
- osszesites
-- okrok, elvitt sorok
-- keveresek szama, jatekok szama, eltelt ido
- deck osszegyujtes
*/