Skip to content

Commit

Permalink
Upgrade game joining
Browse files Browse the repository at this point in the history
  • Loading branch information
Indy2222 committed Aug 9, 2023
1 parent 0a75005 commit ed5ea53
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 32 deletions.
25 changes: 18 additions & 7 deletions crates/lobby_client/src/endpoints.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::borrow::Cow;

use de_lobby_model::{Game, GameListing, GameSetup, Token, UserWithPassword, UsernameAndPassword};
use de_lobby_model::{
Game, GameListing, GamePlayerInfo, GameSetup, Token, UserWithPassword, UsernameAndPassword,
};
use reqwest::{header::HeaderValue, Method, Request};
use serde::Serialize;
use url::Url;
Expand Down Expand Up @@ -117,11 +119,14 @@ impl LobbyRequestCreator for GetGameRequest {
}
}

pub struct JoinGameRequest(String);
pub struct JoinGameRequest {
game: String,
player: GamePlayerInfo,
}

impl JoinGameRequest {
pub fn new(name: String) -> Self {
Self(name)
pub fn new(game: String, player: GamePlayerInfo) -> Self {
Self { game, player }
}
}

Expand All @@ -131,11 +136,13 @@ impl LobbyRequest for JoinGameRequest {

impl LobbyRequestCreator for JoinGameRequest {
fn path(&self) -> Cow<str> {
encode(&["a", "games", self.0.as_str(), "join"])
encode(&["a", "games", self.game.as_str(), "join"])
}

fn create(&self, url: Url) -> Request {
Request::new(Method::PUT, url)
let mut request = Request::new(Method::PUT, url);
json(&mut request, &self.player);
request
}
}

Expand Down Expand Up @@ -255,8 +262,12 @@ mod tests {

#[test]
fn test_join() {
let request = JoinGameRequest::new("Cool Game".to_owned());
let request = JoinGameRequest::new("Cool Game".to_owned(), GamePlayerInfo::new(2));
assert_eq!(request.path().as_ref(), "/a/games/Cool%20Game/join");

let request = request.create(Url::parse("http://example.com/a/games/123/join").unwrap());
let body = String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap();
assert_eq!(body, r#"{"ordinal":2}"#);
}

#[test]
Expand Down
47 changes: 24 additions & 23 deletions crates/menu/src/multiplayer/joining.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::net::SocketAddr;

use bevy::prelude::*;
use de_gui::ToastEvent;
use de_lobby_client::{GetGameRequest, JoinGameRequest};
use de_lobby_model::GamePlayerInfo;
use de_multiplayer::{
ConnectionType, GameJoinedEvent, NetGameConf, ShutdownMultiplayerEvent, StartMultiplayerEvent,
};
Expand Down Expand Up @@ -32,8 +31,8 @@ impl Plugin for JoiningGamePlugin {
Update,
(
handle_get_response,
handle_join_response.run_if(resource_exists::<GameSocketAddrRes>()),
handle_joined_event.run_if(on_event::<GameJoinedEvent>()),
handle_join_response,
)
.run_if(in_state(MultiplayerState::GameJoining)),
);
Expand All @@ -56,9 +55,6 @@ impl JoinGameEvent {
#[derive(Resource)]
pub(crate) struct GameNameRes(String);

#[derive(Resource)]
pub(crate) struct GameSocketAddrRes(SocketAddr);

fn handle_join_event(
mut commands: Commands,
mut next_state: ResMut<NextState<MultiplayerState>>,
Expand All @@ -78,7 +74,6 @@ fn cleanup(
mut shutdown: EventWriter<ShutdownMultiplayerEvent>,
) {
commands.remove_resource::<GameNameRes>();
commands.remove_resource::<GameSocketAddrRes>();

if state.as_ref() != &MultiplayerState::GameJoined {
shutdown.send(ShutdownMultiplayerEvent);
Expand All @@ -90,19 +85,19 @@ fn get_game(game_name: Res<GameNameRes>, mut sender: Sender<GetGameRequest>) {
}

fn handle_get_response(
mut commands: Commands,
mut next_state: ResMut<NextState<MultiplayerState>>,
mut receiver: Receiver<GetGameRequest>,
mut sender: Sender<JoinGameRequest>,
mut multiplayer: EventWriter<StartMultiplayerEvent>,
mut toasts: EventWriter<ToastEvent>,
) {
while let Some(result) = receiver.receive() {
match result {
Ok(game) => {
sender.send(JoinGameRequest::new(
game.setup().config().name().to_owned(),
));
commands.insert_resource(GameSocketAddrRes(game.setup().server()));
let server = game.setup().server();
multiplayer.send(StartMultiplayerEvent::new(NetGameConf::new(
server.ip(),
ConnectionType::JoinGame(server.port()),
)));
}
Err(error) => {
toasts.send(ToastEvent::new(error));
Expand All @@ -112,20 +107,30 @@ fn handle_get_response(
}
}

fn handle_joined_event(
game_name: Res<GameNameRes>,
mut events: EventReader<GameJoinedEvent>,
mut sender: Sender<JoinGameRequest>,
) {
let Some(event) = events.iter().last() else {
return;
};

sender.send(JoinGameRequest::new(
game_name.0.to_owned(),
GamePlayerInfo::new(event.player().to_num()),
));
}

fn handle_join_response(
server: Res<GameSocketAddrRes>,
mut next_state: ResMut<NextState<MultiplayerState>>,
mut receiver: Receiver<JoinGameRequest>,
mut multiplayer: EventWriter<StartMultiplayerEvent>,
mut toasts: EventWriter<ToastEvent>,
) {
while let Some(result) = receiver.receive() {
match result {
Ok(_) => {
multiplayer.send(StartMultiplayerEvent::new(NetGameConf::new(
server.0.ip(),
ConnectionType::JoinGame(server.0.port()),
)));
next_state.set(MultiplayerState::GameJoined);
}
Err(error) => {
toasts.send(ToastEvent::new(error));
Expand All @@ -134,7 +139,3 @@ fn handle_join_response(
}
}
}

fn handle_joined_event(mut next_state: ResMut<NextState<MultiplayerState>>) {
next_state.set(MultiplayerState::GameJoined);
}
16 changes: 14 additions & 2 deletions crates/multiplayer/src/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,19 @@ pub struct GameOpenedEvent(pub SocketAddr);

/// A game was just joined.
#[derive(Event)]
pub struct GameJoinedEvent;
pub struct GameJoinedEvent {
player: Player,
}

impl GameJoinedEvent {
fn new(player: Player) -> Self {
Self { player }
}

pub fn player(&self) -> Player {
self.player
}
}

#[derive(Resource)]
pub(crate) struct Players {
Expand Down Expand Up @@ -138,7 +150,7 @@ fn process_from_game(
info!("Joined game as Player {player}.");
players.local = Some(player);
next_state.set(NetState::Joined);
joined_events.send(GameJoinedEvent);
joined_events.send(GameJoinedEvent::new(player));
}
Err(err) => {
fatals.send(FatalErrorEvent::new(format!(
Expand Down

0 comments on commit ed5ea53

Please sign in to comment.