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]
target = "client/index.html"
dist = "dist"
release = true
minify = "on_release"
[serve]

View file

@ -34,7 +34,7 @@ pub fn Websocket() -> impl IntoView {
let fake_new_game_request = NewGameRequest {
name: String::from("Ligma"),
host: CAHPlayer {
host: Player {
name: String::from("Adam"),
role: PlayerRole::Host,
white: vec![],
@ -50,26 +50,27 @@ pub fn Websocket() -> impl IntoView {
// Chat stuff
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) {
let _ = &history.update(|history: &mut Vec<_>| history.push(message));
}
// fn message_handler(message) {
//
// }
// 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
if let Some(hist) = chat_history_ref.get() {
hist.set_scroll_top(hist.scroll_height());
create_effect(move |_| {
message.with(move |message_raw| {
// 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::*;
impl CAHGame {
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<CAHCardSet>) -> Result<()> {
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)
@ -21,7 +21,7 @@ impl CAHGame {
}
pub fn new(request: NewGameRequest) -> Result<Self> {
let mut game = CAHGame {
let mut game = Game {
..Default::default()
};
tracing::debug!("Creating game {}", &request.name);
@ -47,14 +47,14 @@ impl CAHGame {
}
/// 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;
// this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index))
} else {
Ok(CAHCardWhite {
Ok(CardWhite {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pack: 0,
})
@ -62,14 +62,14 @@ impl CAHGame {
}
/// 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;
// this feels sloppy
if let Some(index) = (0..deck.len()).choose(&mut thread_rng()) {
Ok(deck.swap_remove(index))
} else {
Ok(CAHCardBlack {
Ok(CardBlack {
text: "Error.\n\nbtw if you see this tell me I'm lazy :)".to_string(),
pick: 0,
pack: 0,
@ -85,7 +85,7 @@ impl CAHGame {
}
/// 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);
let mut hand_buf = vec![];

View file

@ -13,7 +13,7 @@ pub struct NewGameRequest {
/// Game name
pub name: String,
/// Game host
pub host: CAHPlayer,
pub host: Player,
/// Chosen packs
pub packs: Vec<u8>,
}
@ -25,21 +25,21 @@ pub struct GameJoinRequest {
/// Game password
pub password: Option<String>,
/// Player info
pub player: CAHPlayer,
pub player: Player,
}
/// A CAH white card
/// A white card
#[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardWhite {
pub struct CardWhite {
/// Card text
pub text: String,
/// ID of the pack it came from
pub pack: u8,
}
/// A CAH black card
/// A black card
#[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardBlack {
pub struct CardBlack {
/// Card text
pub text: String,
/// Amount of cards to submit for judging
@ -48,9 +48,9 @@ pub struct CAHCardBlack {
pub pack: u8,
}
/// A CAH pack
/// A card set
#[derive(Debug, Serialize, Deserialize)]
pub struct CAHCardSet {
pub struct CardSet {
/// Name of the pack
name: String,
/// Pack Description
@ -58,9 +58,9 @@ pub struct CAHCardSet {
/// Whether or not this is an official card pack
official: bool,
/// White card data
pub white: Option<Vec<CAHCardWhite>>,
pub white: Option<Vec<CardWhite>>,
/// Black card data
pub black: Option<Vec<CAHCardBlack>>,
pub black: Option<Vec<CardBlack>>,
}
/// Player roles
@ -76,38 +76,38 @@ pub enum PlayerRole {
/// A struct that represents a player
#[derive(Debug, Serialize, Deserialize)]
pub struct CAHPlayer {
pub struct Player {
/// Player's username
pub name: String,
/// This player's role
pub role: PlayerRole,
/// The player's hand
pub white: Vec<CAHCardWhite>,
pub white: Vec<CardWhite>,
/// The player's wins
pub black: Vec<CAHCardBlack>,
pub black: Vec<CardBlack>,
}
/// The game master
#[derive(Default)]
pub struct CAHGame {
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Game {
/// The name of the game
pub name: String,
/// White draw pile
pub white: Vec<CAHCardWhite>,
pub white: Vec<CardWhite>,
/// Black draw pile
pub black: Vec<CAHCardBlack>,
pub black: Vec<CardBlack>,
/// White discard pile
pub white_discard: Vec<CAHCardWhite>,
pub white_discard: Vec<CardWhite>,
/// Black discard pile
pub black_discard: Vec<CAHCardBlack>,
pub black_discard: Vec<CardBlack>,
/// Indicates game active/game over
pub game_active: bool,
/// List of current players
pub players: Vec<CAHPlayer>,
pub players: Vec<Player>,
// /// Reference to current card czar
// czar: &CAHPlayer,
// czar: &Player,
/// 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 {
Message::Text(text) => {
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
tracing::debug!("{:#?}", &new_game);
tracing::debug!("New game request received.");
// create game
if let Ok(new_game_object) = CAHGame::new(new_game) {
let _ = tx.send(format!("{:#?}", &new_game_object.players[0].white));
if let Ok(new_game_object) = Game::new(new_game) {
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);
let _update = tx.send(greeting(state));
} else {

View file

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