cards/lib/src/game_master.rs
2024-08-02 02:35:31 -04:00

129 lines
3.5 KiB
Rust

use anyhow::Result;
use rand::prelude::IteratorRandom;
use rand::thread_rng;
use std::sync::{Arc, Mutex};
use crate::models::*;
impl Game {
/// Build game decks from input data for game start.
/// This should only run once and at startup.
fn _build_decks(&mut self, cards_json: Vec<CardSet>) -> Result<()> {
for pack in cards_json {
if let Some(white) = pack.white {
self.white.extend(white)
}
if let Some(black) = pack.black {
self.black.extend(black)
}
}
Ok(())
}
pub fn new(request: NewGameManifest) -> Result<Self> {
let mut game = Game {
..Default::default()
};
tracing::debug!(
"Creating game {} with {} as host",
&request.name,
request.host.lock().unwrap().name
);
game.name = request.name;
game.host = request.host.clone();
// game.build_decks(request.packs)?;
game.create_player(request.host)?;
game.deal_black()?;
Ok(game)
}
// pub fn join(request:GameJoinRequest)
/// Log counts of current drawable cards
/// For testing
pub fn deck_counts(&self) {
tracing::debug!(
"Deck Counts:\n {} White cards\n {} Black cards",
self.white.len(),
self.black.len()
);
}
/// Draw one white card at random from play deck.
fn draw_one_white(&mut self) -> Result<CardWhite> {
let deck = &mut self.white;
// this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index))
} else {
Ok(CardWhite {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pack: 0,
})
}
}
/// Draw one black card at random from play deck.
fn draw_one_black(&mut self) -> Result<CardBlack> {
let deck = &mut self.black;
// this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index))
} else {
Ok(CardBlack {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pick: 0,
pack: 0,
})
}
}
/// Deal a black card and use it for the current round
fn deal_black(&mut self) -> Result<()> {
self.current_black = Some(self.draw_one_black()?);
Ok(())
}
/// Create a new player and add them to the game.
pub fn create_player(&mut self, user: Arc<Mutex<User>>) -> Result<()> {
let mut new_player = Player {
user: user.clone(),
white: vec![],
black: vec![],
};
let new_player_name = user.lock().unwrap().name.clone();
tracing::debug!("Creating player for {}", &new_player_name);
let mut hand_buf = vec![];
for _ in 0..10 {
hand_buf.push(self.draw_one_white()?);
}
tracing::debug!("Dealing hand to {}", &new_player_name);
new_player.white.extend(hand_buf);
self.players.push(new_player);
Ok(())
}
pub fn game_start(&mut self) -> Result<()> {
self.game_active = true;
tracing::debug!("Game Active!");
if let Some(black) = &self.current_black {
tracing::debug!("{}", black.text);
} else {
tracing::debug!("YOU DONE FUCKED UP (no current black card)");
}
Ok(())
}
}