This commit is contained in:
Adam 2024-07-21 22:48:15 -04:00
parent 281c32f201
commit 6636920752
6 changed files with 59 additions and 57 deletions

View file

@ -5,7 +5,6 @@
[build] [build]
target = "client/index.html" target = "client/index.html"
dist = "dist" dist = "dist"
release = true
minify = "on_release" minify = "on_release"
[serve] [serve]

View file

@ -34,7 +34,7 @@ pub fn Websocket() -> impl IntoView {
let fake_new_game_request = NewGameRequest { let fake_new_game_request = NewGameRequest {
name: String::from("Ligma"), name: String::from("Ligma"),
host: CAHPlayer { host: Player {
name: String::from("Adam"), name: String::from("Adam"),
role: PlayerRole::Host, role: PlayerRole::Host,
white: vec![], white: vec![],
@ -50,26 +50,27 @@ pub fn Websocket() -> impl IntoView {
// Chat stuff // Chat stuff
let chat_history_ref = create_node_ref::<Textarea>(); let chat_history_ref = create_node_ref::<Textarea>();
let (chat_history, set_chat_history) = create_signal(vec![]); let (chat_history, set_chat_history) = create_signal::<Vec<String>>(vec![]);
fn update_chat_history(&history: &WriteSignal<Vec<String>>, message: String) { fn update_chat_history(&history: &WriteSignal<Vec<String>>, message: String) {
let _ = &history.update(|history: &mut Vec<_>| history.push(message)); let _ = &history.update(|history: &mut Vec<_>| history.push(message));
} }
// fn message_handler(message) {
//
// }
// handle incoming messages // handle incoming messages
create_effect(move |_| {
message.with(move |message| {
// Send all messages as strings into chat box
if let Some(m) = message {
update_chat_history(&set_chat_history, format!("{}\n", m));
// Scroll chat textarea to bottom create_effect(move |_| {
if let Some(hist) = chat_history_ref.get() { message.with(move |message_raw| {
hist.set_scroll_top(hist.scroll_height()); // Send all messages as strings into chat box
if let Some(message) = message_raw {
if let Ok(game) = serde_json::from_str::<Game>(message) {
logging::log!("{:#}", serde_json::json!(game));
} else {
update_chat_history(&set_chat_history, format!("{}\n", message));
// Scroll chat textarea to bottom
if let Some(hist) = chat_history_ref.get() {
hist.set_scroll_top(hist.scroll_height());
}
} }
} }
}) })

View file

@ -4,10 +4,10 @@ use rand::thread_rng;
use crate::models::*; use crate::models::*;
impl CAHGame { impl Game {
/// Build game decks from input data for game start. /// Build game decks from input data for game start.
/// This should only run once and at startup. /// This should only run once and at startup.
fn _build_decks(&mut self, cards_json: Vec<CAHCardSet>) -> Result<()> { fn _build_decks(&mut self, cards_json: Vec<CardSet>) -> Result<()> {
for pack in cards_json { for pack in cards_json {
if let Some(white) = pack.white { if let Some(white) = pack.white {
self.white.extend(white) self.white.extend(white)
@ -21,7 +21,7 @@ impl CAHGame {
} }
pub fn new(request: NewGameRequest) -> Result<Self> { pub fn new(request: NewGameRequest) -> Result<Self> {
let mut game = CAHGame { let mut game = Game {
..Default::default() ..Default::default()
}; };
tracing::debug!("Creating game {}", &request.name); tracing::debug!("Creating game {}", &request.name);
@ -47,14 +47,14 @@ impl CAHGame {
} }
/// Draw one white card at random from play deck. /// Draw one white card at random from play deck.
fn draw_one_white(&mut self) -> Result<CAHCardWhite> { fn draw_one_white(&mut self) -> Result<CardWhite> {
let deck = &mut self.white; let deck = &mut self.white;
// this feels sloppy // this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) { if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index)) Ok(deck.swap_remove(index))
} else { } else {
Ok(CAHCardWhite { Ok(CardWhite {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(), text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pack: 0, pack: 0,
}) })
@ -62,14 +62,14 @@ impl CAHGame {
} }
/// Draw one black card at random from play deck. /// Draw one black card at random from play deck.
fn draw_one_black(&mut self) -> Result<CAHCardBlack> { fn draw_one_black(&mut self) -> Result<CardBlack> {
let deck = &mut self.black; let deck = &mut self.black;
// this feels sloppy // this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) { if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index)) Ok(deck.swap_remove(index))
} else { } else {
Ok(CAHCardBlack { Ok(CardBlack {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(), text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pick: 0, pick: 0,
pack: 0, pack: 0,
@ -85,7 +85,7 @@ impl CAHGame {
} }
/// Create a new player and add them to the game. /// Create a new player and add them to the game.
pub fn create_player(&mut self, mut player: CAHPlayer) -> Result<()> { pub fn create_player(&mut self, mut player: Player) -> Result<()> {
tracing::debug!("Creating player {} as {:?}", &player.name, &player.role); tracing::debug!("Creating player {} as {:?}", &player.name, &player.role);
let mut hand_buf = vec![]; let mut hand_buf = vec![];

View file

@ -13,7 +13,7 @@ pub struct NewGameRequest {
/// Game name /// Game name
pub name: String, pub name: String,
/// Game host /// Game host
pub host: CAHPlayer, pub host: Player,
/// Chosen packs /// Chosen packs
pub packs: Vec<u8>, pub packs: Vec<u8>,
} }
@ -25,21 +25,21 @@ pub struct GameJoinRequest {
/// Game password /// Game password
pub password: Option<String>, pub password: Option<String>,
/// Player info /// Player info
pub player: CAHPlayer, pub player: Player,
} }
/// A CAH white card /// A white card
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardWhite { pub struct CardWhite {
/// Card text /// Card text
pub text: String, pub text: String,
/// ID of the pack it came from /// ID of the pack it came from
pub pack: u8, pub pack: u8,
} }
/// A CAH black card /// A black card
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardBlack { pub struct CardBlack {
/// Card text /// Card text
pub text: String, pub text: String,
/// Amount of cards to submit for judging /// Amount of cards to submit for judging
@ -48,9 +48,9 @@ pub struct CAHCardBlack {
pub pack: u8, pub pack: u8,
} }
/// A CAH pack /// A card set
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardSet { pub struct CardSet {
/// Name of the pack /// Name of the pack
name: String, name: String,
/// Pack Description /// Pack Description
@ -58,9 +58,9 @@ pub struct CAHCardSet {
/// Whether or not this is an official card pack /// Whether or not this is an official card pack
official: bool, official: bool,
/// White card data /// White card data
pub white: Option<Vec<CAHCardWhite>>, pub white: Option<Vec<CardWhite>>,
/// Black card data /// Black card data
pub black: Option<Vec<CAHCardBlack>>, pub black: Option<Vec<CardBlack>>,
} }
/// Player roles /// Player roles
@ -76,38 +76,38 @@ pub enum PlayerRole {
/// A struct that represents a player /// A struct that represents a player
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct CAHPlayer { pub struct Player {
/// Player's username /// Player's username
pub name: String, pub name: String,
/// This player's role /// This player's role
pub role: PlayerRole, pub role: PlayerRole,
/// The player's hand /// The player's hand
pub white: Vec<CAHCardWhite>, pub white: Vec<CardWhite>,
/// The player's wins /// The player's wins
pub black: Vec<CAHCardBlack>, pub black: Vec<CardBlack>,
} }
/// The game master /// The game master
#[derive(Default)] #[derive(Default, Debug, Serialize, Deserialize)]
pub struct CAHGame { pub struct Game {
/// The name of the game /// The name of the game
pub name: String, pub name: String,
/// White draw pile /// White draw pile
pub white: Vec<CAHCardWhite>, pub white: Vec<CardWhite>,
/// Black draw pile /// Black draw pile
pub black: Vec<CAHCardBlack>, pub black: Vec<CardBlack>,
/// White discard pile /// White discard pile
pub white_discard: Vec<CAHCardWhite>, pub white_discard: Vec<CardWhite>,
/// Black discard pile /// Black discard pile
pub black_discard: Vec<CAHCardBlack>, pub black_discard: Vec<CardBlack>,
/// Indicates game active/game over /// Indicates game active/game over
pub game_active: bool, pub game_active: bool,
/// List of current players /// List of current players
pub players: Vec<CAHPlayer>, pub players: Vec<Player>,
// /// Reference to current card czar // /// Reference to current card czar
// czar: &CAHPlayer, // czar: &Player,
/// Black card for the current round /// Black card for the current round
pub current_black: Option<CAHCardBlack>, pub current_black: Option<CardBlack>,
} }

View file

@ -9,10 +9,12 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User
match message { match message {
Message::Text(text) => { Message::Text(text) => {
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) { if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
tracing::debug!("{:#?}", &new_game); tracing::debug!("New game request received.");
// create game // create game
if let Ok(new_game_object) = CAHGame::new(new_game) { if let Ok(new_game_object) = Game::new(new_game) {
let _ = tx.send(format!("{:#?}", &new_game_object.players[0].white)); let game_json = serde_json::to_string(&new_game_object).unwrap();
tracing::debug!("Sent new game JSON.");
let _ = tx.send(game_json);
state.games.lock().unwrap().push(new_game_object); state.games.lock().unwrap().push(new_game_object);
let _update = tx.send(greeting(state)); let _update = tx.send(greeting(state));
} else { } else {

View file

@ -15,10 +15,10 @@ pub mod api;
use crate::api::*; use crate::api::*;
/// Parse json for card data /// Parse json for card data
fn load_json(path: &str) -> Result<Vec<CAHCardSet>> { fn load_json(path: &str) -> Result<Vec<CardSet>> {
let data: String = let data: String =
fs::read_to_string(path).with_context(|| format!("Invalid JSON path: \"{}\"", path))?; fs::read_to_string(path).with_context(|| format!("Invalid JSON path: \"{}\"", path))?;
let jayson: Vec<CAHCardSet> = let jayson: Vec<CardSet> =
serde_json::from_str(&data).with_context(|| format!("\"{path}\" is invalid json"))?; serde_json::from_str(&data).with_context(|| format!("\"{path}\" is invalid json"))?;
Ok(jayson) Ok(jayson)
@ -31,17 +31,17 @@ fn _test() -> Result<()> {
// TODO: this should be a master card database and pointers // TODO: this should be a master card database and pointers
// to the cards should be passed to the game instead of actual cards // to the cards should be passed to the game instead of actual cards
let chosen_packs: Vec<CAHCardSet> = load_json(cards_input_path)?; let chosen_packs: Vec<CardSet> = load_json(cards_input_path)?;
println!("{}", &chosen_packs.len()); println!("{}", &chosen_packs.len());
let test_player0 = CAHPlayer { let test_player0 = Player {
name: "Adam".to_string(), name: "Adam".to_string(),
role: PlayerRole::Host, role: PlayerRole::Host,
white: vec![], white: vec![],
black: vec![], black: vec![],
}; };
let test_player1 = CAHPlayer { let test_player1 = Player {
name: "Ferris".to_string(), name: "Ferris".to_string(),
role: PlayerRole::Player, role: PlayerRole::Player,
white: vec![], white: vec![],
@ -50,7 +50,7 @@ fn _test() -> Result<()> {
// make some games // make some games
// use hashmap? // use hashmap?
let mut games: Vec<CAHGame> = vec![]; let mut games: Vec<Game> = vec![];
// create game with/for player 0 // create game with/for player 0
let test_game0 = NewGameRequest { let test_game0 = NewGameRequest {
@ -60,7 +60,7 @@ fn _test() -> Result<()> {
packs: vec![0], packs: vec![0],
}; };
games.push(CAHGame::new(test_game0)?); games.push(Game::new(test_game0)?);
// a new game request struct but this player is a player // a new game request struct but this player is a player
games[0].create_player(test_player1)?; games[0].create_player(test_player1)?;
@ -82,9 +82,9 @@ pub struct AppState {
// Channel used to send messages to all connected clients. // Channel used to send messages to all connected clients.
tx: broadcast::Sender<String>, tx: broadcast::Sender<String>,
// Master card decks // Master card decks
all_cards: Mutex<Vec<CAHCardSet>>, all_cards: Mutex<Vec<CardSet>>,
// Games list // Games list
games: Mutex<Vec<CAHGame>>, games: Mutex<Vec<Game>>,
} }
// Include utf-8 files at **compile** time. // Include utf-8 files at **compile** time.