cards/server/src/game_handler.rs

358 lines
9.6 KiB
Rust
Raw Normal View History

2024-08-08 05:29:32 -04:00
use crate::user_handler::*;
use crate::AppState;
2024-08-09 01:21:04 -04:00
use crate::User;
2024-08-12 15:10:48 -04:00
use anyhow::Result;
2024-08-09 02:57:27 -04:00
use lib::*;
2024-08-12 15:10:48 -04:00
use rand::prelude::IteratorRandom;
use rand::thread_rng;
use serde::Deserialize;
use std::{
collections::HashMap,
net::SocketAddr,
sync::{Arc, RwLock},
};
use uuid::Uuid;
2024-08-08 05:29:32 -04:00
2024-08-10 19:50:26 -04:00
// This file is disgusting, don't look at it
2024-08-08 05:29:32 -04:00
2024-08-12 15:10:48 -04:00
/// Card Set
#[derive(Debug)]
pub struct CardSet {
pub white: Option<Vec<CardWhite>>,
pub black: Option<Vec<CardBlack>>,
}
/// Card Packs
#[derive(Debug)]
pub struct CardPacks {
pub official: HashMap<u8, CardSet>,
pub unofficial: HashMap<u8, CardSet>,
}
/// A white card
#[derive(Debug, Deserialize)]
pub struct CardWhite {
/// Card text
pub text: String,
/// ID of the pack it came from
pub pack: u8,
}
/// A black card
#[derive(Debug, Deserialize)]
pub struct CardBlack {
/// Card text
pub text: String,
/// Amount of cards to submit for judging
pub pick: u8,
/// ID of the pack it came from
pub pack: u8,
}
/// A card pack
#[derive(Debug, Deserialize)]
pub struct CardPack {
/// Name of the pack
pub name: String,
/// Whether or not this is an official card pack
pub official: bool,
/// White card data
pub white: Option<Vec<CardWhite>>,
/// Black card data
pub black: Option<Vec<CardBlack>>,
}
/// New game request structure
#[derive(Debug)]
pub struct NewGameManifest {
/// Game name
pub name: String,
/// Game host
pub host: Arc<RwLock<User>>,
/// Selected game packs
pub packs: Vec<u8>,
}
/// A struct that represents a player
#[derive(Debug)]
pub struct Player {
/// Player's user's uuid
pub user_uuid: Uuid,
/// The player's hand
pub white: Vec<CardWhite>,
/// The player's wins
pub black: Vec<CardBlack>,
}
/// The game master
#[derive(Debug)]
pub struct Game {
/// The name of the game
pub name: String,
/// The host user of the game
pub host: Arc<RwLock<User>>,
/// White draw pile
pub white: Vec<CardWhite>,
/// Black draw pile
pub black: Vec<CardBlack>,
/// White discard pile
pub white_discard: Vec<CardWhite>,
/// Black discard pile
pub black_discard: Vec<CardBlack>,
/// List of current players
pub players: HashMap<Uuid, Player>,
// /// Reference to current card czar
// czar: &Player,
/// Black card for the current round
pub current_black: Option<CardBlack>,
}
impl Game {
/// Build game decks from input data for game start.
/// This should only run once and at startup.
fn build_decks(&mut self, selected_packs: Vec<u8>) -> Result<()> {
// for pack in selected_packs {
// for pack in card_packs {
// 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 {
name: request.host.read().unwrap().name.clone(),
host: request.host.clone(),
white: vec![],
black: vec![],
white_discard: vec![],
black_discard: vec![],
players: HashMap::new(),
current_black: Option::None,
};
tracing::debug!(
"Creating game {} with {} as host",
&request.name,
request.host.read().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<RwLock<User>>) -> Result<()> {
let mut new_player = Player {
user_uuid: user.read().unwrap().uuid.clone(),
white: vec![],
black: vec![],
};
let new_player_name = user.read().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
.insert(user.read().unwrap().uuid.clone(), new_player);
Ok(())
}
pub fn game_start(&mut self) -> Result<()> {
if let Some(black) = &self.current_black {
tracing::debug!("{}", black.text);
} else {
tracing::debug!("YOU DONE FUCKED UP (no current black card)");
}
Ok(())
}
}
2024-08-09 01:21:04 -04:00
pub enum GameHandlerMessage {
NewGame {
addr: SocketAddr,
new_game: NewGameRequest,
},
JoinGame {
user: Arc<User>,
game_name: String,
},
}
2024-08-08 05:29:32 -04:00
pub struct GameHandler {
state: Arc<AppState>,
}
impl GameHandler {
pub fn new(state: Arc<AppState>) -> Self {
GameHandler { state }
}
2024-08-09 01:21:04 -04:00
pub async fn handle(&self, message: GameHandlerMessage) {
match message {
GameHandlerMessage::NewGame { addr, new_game } => self.new_game(addr, new_game).await,
_ => {
tracing::debug!("Unhandled at game handler");
}
}
}
async fn new_game(&self, addr: SocketAddr, new_game: NewGameRequest) {
if new_game.packs.is_empty() {
tracing::debug!("Cards are empty");
return;
} else if new_game.name.is_empty() {
tracing::debug!("Name are empty");
return;
}
2024-08-08 05:29:32 -04:00
let manifest = NewGameManifest {
2024-08-09 01:21:04 -04:00
name: new_game.name,
2024-08-08 05:29:32 -04:00
host: self
.state
.online_users
.read()
.unwrap()
2024-08-09 01:21:04 -04:00
.get(&addr)
2024-08-08 05:29:32 -04:00
.unwrap()
.clone(),
2024-08-12 15:10:48 -04:00
packs: new_game.packs,
2024-08-08 05:29:32 -04:00
};
// create game
if let Ok(new_game_object) = Game::new(manifest) {
2024-08-09 02:57:27 -04:00
let tx = self
.state
.online_users
.read()
.unwrap()
.get(&addr)
.unwrap()
.read()
.unwrap()
.tx
.clone();
2024-08-10 19:50:26 -04:00
let mut black_text = "Error".to_string();
if let Some(ref current_black) = new_game_object.current_black {
black_text = current_black.text.to_owned()
}
let meta = GameMeta {
name: new_game_object.name.clone(),
host: new_game_object.host.read().unwrap().name.clone(),
players: new_game_object
.players
.iter()
2024-08-11 19:51:30 -04:00
.map(|player| {
self.state
.user_uuid
.read()
.unwrap()
.get(&player.0)
.unwrap()
.read()
.unwrap()
.name
.clone()
})
2024-08-10 19:50:26 -04:00
.collect(),
czar: new_game_object.host.read().unwrap().name.clone(),
black: black_text,
white: new_game_object
2024-08-11 19:51:30 -04:00
.players
.get(&new_game_object.host.read().unwrap().uuid)
.unwrap()
2024-08-10 19:50:26 -04:00
.white
.iter()
.map(|card| card.text.clone())
.collect(),
};
tx.send(serde_json::to_string(&meta).unwrap())
.await
.unwrap();
2024-08-09 01:21:04 -04:00
self.state.games.write().unwrap().insert(
new_game_object.name.clone(),
Arc::new(RwLock::new(new_game_object)),
);
2024-08-08 05:29:32 -04:00
self.state
.broadcast_tx
.send(meta_games_browser_update(&self.state))
.unwrap();
self.state
.broadcast_tx
.send(meta_server_summary_update(&self.state))
.unwrap();
}
}
}