stuuuufff

This commit is contained in:
Adam 2024-08-17 21:55:15 -04:00
parent e6c55ba527
commit 3db4da669b
8 changed files with 148 additions and 17 deletions

View file

@ -67,6 +67,7 @@ pub fn Browser() -> impl IntoView {
<th class="border-b"></th>
</tr>
</thead>
<p>prevent joining an already joined game</p>
{move || {
game_browser_context()
.iter()

View file

@ -1,21 +1,25 @@
// use crate::components::websocket::WebSocketContext;
use crate::components::websocket::WebSocketContext;
use leptos::*;
use lib::*;
use serde_json::to_string;
#[component]
pub fn Game() -> impl IntoView {
// let websocket = expect_context::<WebSocketContext>();
let websocket = expect_context::<WebSocketContext>();
let game_meta = expect_context::<ReadSignal<Option<GameStateMeta>>>();
let (game_id, set_game_id) = create_signal("".to_string());
let (game_name, set_game_name) = create_signal("".to_string());
let (game_host, set_game_host) = create_signal("".to_string());
let (game_players, set_game_players) = create_signal(vec![]);
let (game_czar, set_game_czar) = create_signal("".to_string());
let (game_black, set_game_black) = create_signal(("".to_string(), 0u8));
let (game_white, set_game_white) = create_signal(vec![]);
let (selected_card, set_selected_card) = create_signal("".to_string());
create_effect(move |_| {
if let Some(game) = game_meta() {
set_game_id(game.uuid.clone());
set_game_name(game.name.clone());
set_game_host(game.host.clone());
set_game_players(game.players.clone());
@ -25,6 +29,17 @@ pub fn Game() -> impl IntoView {
}
});
create_effect(move |_| {
logging::log!("{:#?}", selected_card());
websocket.send(
&to_string(&PlayerMoveRequest {
game_id: game_id(),
card_id: selected_card(),
})
.unwrap(),
)
});
view! {
<div class="p-1">
<div class="relative">
@ -58,7 +73,15 @@ pub fn Game() -> impl IntoView {
.map(|card| {
view! {
<div class="relative m-2 w-40 h-60 text-black bg-white rounded-lg">
<p class="p-4">{card}</p>
<p class="p-4">{&card.text}</p>
<button
class="absolute w-full h-full opacity-10 left-0 top-0"
type="button"
value=card.uuid.clone()
on:click=move |e| {
set_selected_card(event_target_value(&e))
}
></button>
</div>
}
})

View file

@ -6,6 +6,20 @@ pub struct GameJoinRequest {
pub id: String,
}
/// Player Move Request
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PlayerMoveRequest {
pub game_id: String,
pub card_id: String,
}
/// White Card Meta
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WhiteCardMeta {
pub uuid: String,
pub text: String,
}
/// Game meta
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GameStateMeta {
@ -15,7 +29,7 @@ pub struct GameStateMeta {
pub players: Vec<String>,
pub czar: String,
pub black: (String, u8),
pub white: Vec<String>,
pub white: Vec<WhiteCardMeta>,
pub packs: Vec<u8>,
}

View file

@ -25,6 +25,11 @@ pub enum GameHandlerMessage {
addr: SocketAddr,
id: String,
},
MoveRequest {
card_id: String,
game_id: String,
addr: SocketAddr,
},
}
/// Handles game stuff
@ -42,11 +47,62 @@ impl GameHandler {
/// Handles incoming messages
pub async fn handle(&self, message: GameHandlerMessage) {
match message {
NewGame { addr, new_game } => self.new_game(addr, new_game).await,
NewGame { addr, new_game } => self.create_new_game(addr, new_game).await,
JoinGame { addr, id } => self.join_game(addr, id).await,
MoveRequest {
card_id,
game_id,
addr,
} => self.handle_player_move(card_id, game_id, addr).await,
}
}
/// Process player move request
async fn handle_player_move(&self, card_id: String, game_id: String, addr: SocketAddr) {
let this_player_id = self
.state
.online_users
.read()
.unwrap()
.get(&addr)
.unwrap()
.read()
.unwrap()
.uuid
.to_string();
let this_game = self
.state
.games
.read()
.unwrap()
.get(&game_id)
.unwrap()
.clone();
if this_game
.read()
.unwrap()
.czar
.read()
.unwrap()
.uuid
.to_string()
== this_player_id
{
tracing::error!("No! User id is same as current czar");
} else {
tracing::error!("Ok, but i have nothing to do");
}
tracing::debug!(
"Player move received:\nCard: {}\nGame: {}\nPlayer: {}",
card_id,
game_id,
this_player_id,
);
}
/// Puts a user in a game
async fn join_game(&self, addr: SocketAddr, id: String) {
// Get pointers
@ -82,7 +138,14 @@ impl GameHandler {
this_game.read().unwrap().current_black.text.clone(),
this_game.read().unwrap().current_black.pick,
),
white: player.white.iter().map(|card| card.text.clone()).collect(),
white: player
.white
.iter()
.map(|card| WhiteCardMeta {
uuid: card.uuid.to_string(),
text: card.text.clone(),
})
.collect(),
packs: this_game.read().unwrap().packs.clone(),
};
@ -106,7 +169,7 @@ impl GameHandler {
}
/// Creates a new game
async fn new_game(&self, addr: SocketAddr, new_game: NewGameRequest) {
async fn create_new_game(&self, addr: SocketAddr, new_game: NewGameRequest) {
if new_game.packs.is_empty() {
tracing::error!("New game cards are empty!");
return;
@ -148,7 +211,7 @@ impl GameHandler {
.iter()
.map(|player| {
self.state
.user_uuid
.users_by_id
.read()
.unwrap()
.get(player.0)
@ -170,7 +233,10 @@ impl GameHandler {
.unwrap()
.white
.iter()
.map(|card| card.text.clone())
.map(|card| WhiteCardMeta {
uuid: card.uuid.to_string(),
text: card.text.clone(),
})
.collect(),
packs: new_game_object.packs.clone(),
};
@ -301,6 +367,8 @@ pub struct Game {
pub host: Arc<RwLock<User>>,
/// White draw pile
pub white: Vec<Arc<CardWhiteWithID>>,
/// Current card czar
pub czar: Arc<RwLock<User>>,
/// Black draw pile
black: Vec<Arc<CardBlackWithID>>,
pub players: HashMap<Uuid, Player>,
@ -349,6 +417,7 @@ impl Game {
uuid: Uuid::now_v7(),
name: request.name,
host: request.host.clone(),
czar: request.host.clone(),
white,
black,
players: HashMap::new(),

View file

@ -67,7 +67,7 @@ pub struct AppState {
pub first_names: Vec<String>,
pub last_names: Vec<String>,
pub reserved_names: RwLock<HashSet<String>>,
pub user_uuid: RwLock<HashMap<Uuid, Arc<RwLock<User>>>>,
pub users_by_id: RwLock<HashMap<Uuid, Arc<RwLock<User>>>>,
pub online_users: RwLock<HashMap<SocketAddr, Arc<RwLock<User>>>>,
pub offline_users: RwLock<HashMap<String, Arc<RwLock<User>>>>,
pub packs: CardPacks,

View file

@ -35,7 +35,7 @@ async fn main() -> Result<()> {
let first_names = load_names("data/first.txt")?;
let last_names = load_names("data/last.txt")?;
let reserved_names = RwLock::new(HashSet::<String>::new());
let user_uuid = RwLock::new(HashMap::<Uuid, Arc<RwLock<User>>>::new());
let users_by_id = RwLock::new(HashMap::<Uuid, Arc<RwLock<User>>>::new());
let online_users = RwLock::new(HashMap::<SocketAddr, Arc<RwLock<User>>>::new());
let offline_users = RwLock::new(HashMap::<String, Arc<RwLock<User>>>::new());
let (packs, packs_meta) = load_cards_from_json("data/cah-cards-full.json")?;
@ -49,7 +49,7 @@ async fn main() -> Result<()> {
first_names,
last_names,
reserved_names,
user_uuid,
users_by_id,
online_users,
offline_users,
packs,

View file

@ -1,6 +1,7 @@
use crate::user_handler::*;
use crate::AppState;
use crate::GameHandlerMessage;
use crate::GameHandlerMessage::*;
use crate::UserHandlerMessage::*;
use axum::extract::ws::{CloseFrame, Message};
use lib::*;
use serde_json::{from_str, to_string};
@ -37,7 +38,7 @@ impl MessageHandler {
{
self.state
.users_tx
.send(UserHandlerMessage::UserLogIn {
.send(UserLogIn {
username: user_log_in.username,
addr,
})
@ -48,7 +49,7 @@ impl MessageHandler {
_new_game_request if let Ok(new_game) = from_str::<NewGameRequest>(&text) => {
self.state
.games_tx
.send(GameHandlerMessage::NewGame { addr, new_game })
.send(NewGame { addr, new_game })
.await
.unwrap();
}
@ -56,7 +57,7 @@ impl MessageHandler {
_join_game_request if let Ok(join_request) = from_str::<GameJoinRequest>(&text) => {
self.state
.games_tx
.send(GameHandlerMessage::JoinGame {
.send(JoinGame {
addr,
id: join_request.id,
})
@ -64,6 +65,29 @@ impl MessageHandler {
.unwrap();
}
_player_move_request
if let Ok(move_request) = from_str::<PlayerMoveRequest>(&text) =>
{
if move_request.card_id == "".to_string() {
tracing::error!("Move request card_id is empty! Ignoring...");
return;
}
if move_request.game_id == "".to_string() {
tracing::error!("Move request game_id is empty! Ignoring...");
return;
} else {
self.state
.games_tx
.send(MoveRequest {
card_id: move_request.card_id,
game_id: move_request.game_id,
addr,
})
.await
.unwrap();
}
}
_ => tracing::debug!("Unhandled text from {}", addr),
},

View file

@ -88,7 +88,7 @@ impl UserHandler {
// Register uuid
self.state
.user_uuid
.users_by_id
.write()
.unwrap()
.insert(new_user.read().unwrap().uuid.clone(), new_user.clone());