Skip to content

Commit

Permalink
feat: implement player rejoin & check if player exists (#12)
Browse files Browse the repository at this point in the history
* feat: allow player rejoin

* feat: check if player already online / name already exists

* feat: bind to 0.0.0.0 by default for simplicity

* chore: change default port
  • Loading branch information
pbellchambers authored Feb 16, 2021
1 parent 52c8eda commit a0ec9cd
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 58 deletions.
10 changes: 8 additions & 2 deletions rustyhack_client/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ fn send_new_player_request(
server_addr
.parse()
.expect("Server address format is invalid."),
serialize(&PlayerMessage::CreatePlayer(CreatePlayerMessage {
serialize(&PlayerMessage::PlayerJoin(CreatePlayerMessage {
client_addr: client_addr.to_string(),
player_name: player_name.to_string(),
}))
Expand Down Expand Up @@ -157,11 +157,17 @@ fn wait_for_new_player_response(channel_receiver: &Receiver<PlayerReply>) -> Pla
let received = channel_receiver.recv();
if let Ok(received_message) = received {
match received_message {
PlayerReply::PlayerCreated(message) => {
PlayerReply::PlayerJoined(message) => {
info!("New player creation confirmed.");
new_player_confirmed = true;
player = message;
}
PlayerReply::PlayerAlreadyOnline => {
error!(
"This player name is already taken, and the player is currently online."
);
process::exit(1);
}
_ => {
info!(
"Ignoring other message types until new player confirmed. {:?}",
Expand Down
39 changes: 6 additions & 33 deletions rustyhack_client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,23 @@ fn get_server_addr() -> (String, String) {
let mut server_addr;
loop {
server_addr = String::new();
println!("1) Connect to which server? (default: 127.0.0.1:55301)");
println!("1) Connect to which server? (default: 127.0.0.1:50201)");
io::stdin()
.read_line(&mut server_addr)
.expect("Failed to read input");

if server_addr.trim() == "" {
println!("Using default server address.");
println!();
server_addr = String::from("127.0.0.1:55301");
server_addr = String::from("127.0.0.1:50201");
break;
}

let server_socket_addr: SocketAddr = match server_addr.trim().parse() {
Ok(value) => value,
Err(err) => {
println!(
"Not a valid socket address (e.g. 127.0.0.1:55301 ): {}",
"Not a valid socket address (e.g. 127.0.0.1:50201 ): {}",
err
);
continue;
Expand All @@ -72,36 +72,9 @@ fn get_server_addr() -> (String, String) {
break;
}

let mut client_addr;
loop {
client_addr = String::new();
println!(
"2) What is the client receive address (local listen address)? (default: 127.0.0.1:55302)"
);
io::stdin()
.read_line(&mut client_addr)
.expect("Failed to read input");

if client_addr.trim() == "" {
println!("Using default client listen address.");
println!();
client_addr = String::from("127.0.0.1:55302");
break;
}

let client_socket_addr: SocketAddr = match client_addr.trim().parse() {
Ok(value) => value,
Err(err) => {
println!(
"Not a valid socket address (e.g. 127.0.0.1:55302 ): {}",
err
);
continue;
}
};
client_addr = client_socket_addr.to_string();
break;
}
//handle client port allocation automatically
//maybe need to revisit in future if it causes problems
let client_addr = String::from("0.0.0.0:0");

(server_addr, client_addr)
}
Expand Down
8 changes: 6 additions & 2 deletions rustyhack_client/src/message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ pub fn run(

let channel_send_status;
match player_reply {
PlayerReply::PlayerCreated(message) => {
PlayerReply::PlayerJoined(message) => {
channel_send_status =
player_update_sender.send(PlayerReply::PlayerCreated(message));
player_update_sender.send(PlayerReply::PlayerJoined(message));
}
PlayerReply::AllMaps(message) => {
channel_send_status =
Expand All @@ -54,6 +54,10 @@ pub fn run(
channel_send_status = entity_update_sender
.send(PlayerReply::UpdateOtherEntities(message));
}
PlayerReply::PlayerAlreadyOnline => {
channel_send_status =
player_update_sender.send(PlayerReply::PlayerAlreadyOnline);
}
}

match channel_send_status {
Expand Down
4 changes: 2 additions & 2 deletions rustyhack_client/src/viewport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ fn draw_other_entities(

if relative_entity_position.x > 0
&& relative_entity_position.y > 0
&& relative_entity_position.x < viewport.width as i32
&& relative_entity_position.y < viewport.height as i32
&& relative_entity_position.x < (viewport.width - 1) as i32
&& relative_entity_position.y < (viewport.height - 1) as i32
{
console.set_pxl(
relative_entity_position.x,
Expand Down
5 changes: 3 additions & 2 deletions rustyhack_lib/src/message_handler/player_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ use crate::ecs::player::Player;

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PlayerMessage {
CreatePlayer(CreatePlayerMessage),
PlayerJoin(CreatePlayerMessage),
UpdateVelocity(VelocityMessage),
GetAllMaps,
Timeout(String),
}

#[derive(Debug, Serialize, Deserialize)]
pub enum PlayerReply {
PlayerCreated(Player),
PlayerJoined(Player),
PlayerAlreadyOnline,
AllMaps(AllMaps),
UpdatePosition(Position),
UpdateOtherEntities(EntityUpdates),
Expand Down
58 changes: 51 additions & 7 deletions rustyhack_server/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,12 @@ fn process_player_messages(
let received = channel_receiver.try_recv();
if let Ok(received_message) = received {
match received_message {
PlayerMessage::CreatePlayer(message) => {
PlayerMessage::PlayerJoin(message) => {
info!(
"New player request received for {} from: {}",
"Player joined request received for {} from: {}",
&message.player_name, &message.client_addr
);
create_player(world, message.player_name, message.client_addr, &sender);
join_player(world, message.player_name, message.client_addr, &sender);
}
PlayerMessage::UpdateVelocity(message) => {
debug!("Velocity update received for {}", &message.player_name);
Expand Down Expand Up @@ -145,13 +145,54 @@ fn set_player_disconnected(world: &mut World, address: String) {
player_details.client_addr = "".to_string();
info!(
"Player {} at {} now marked as disconnected.",
&player_details.player_name, &player_details.client_addr
&player_details.player_name, &address
);
break;
}
}
}

pub fn join_player(world: &mut World, name: String, client_addr: String, sender: &Sender<Packet>) {
let mut query = <(&mut PlayerDetails, &DisplayDetails, &Position)>::query();
let mut should_create_new_player = true;
for (player_details, display_details, position) in query.iter_mut(world) {
if player_details.player_name == name && !player_details.currently_online {
player_details.currently_online = true;
player_details.client_addr = client_addr.clone();
info!(
"Existing player \"{}\" logged in from: {}",
name, &client_addr
);
let player = Player {
player_details: player_details.clone(),
display_details: *display_details,
position: position.clone(),
};
send_player_joined_response(player, sender);
should_create_new_player = false;
break;
} else if player_details.player_name == name && player_details.currently_online {
warn!("Player join request from {} for existing player that's currently online ({} at {}).", &client_addr, &name, &player_details.client_addr);
let response = serialize(&PlayerReply::PlayerAlreadyOnline).unwrap_or_else(|err| {
error!(
"Failed to serialise player already online response, error: {}",
err
);
process::exit(1);
});
message_handler::send_packet(
Packet::reliable_ordered(client_addr.parse().unwrap(), response, Some(11)),
&sender,
);
should_create_new_player = false;
break;
}
}
if should_create_new_player {
create_player(world, name, client_addr, sender);
}
}

pub fn create_player(
world: &mut World,
name: String,
Expand All @@ -174,8 +215,11 @@ pub fn create_player(
components::Velocity { x: 0, y: 0 },
));
info!("New player \"{}\" created: {:?}", name, &player_entity);
send_player_joined_response(player, sender);
}

let response = serialize(&PlayerReply::PlayerCreated(player.clone())).unwrap_or_else(|err| {
fn send_player_joined_response(player: Player, sender: &Sender<Packet>) {
let response = serialize(&PlayerReply::PlayerJoined(player.clone())).unwrap_or_else(|err| {
error!(
"Failed to serialise player created response, error: {}",
err
Expand Down Expand Up @@ -223,7 +267,7 @@ fn update_entities_position(
warn!("Will return the default map, but this may cause problems.");
all_maps.get(DEFAULT_MAP).unwrap()
});
if !entity_is_colliding(current_map.get_tile_at(
if !entity_is_colliding_with_tile(current_map.get_tile_at(
(position.x + velocity.x) as usize,
(position.y + velocity.y) as usize,
)) {
Expand All @@ -234,7 +278,7 @@ fn update_entities_position(
velocity.y = 0;
}

fn entity_is_colliding(tile: Tile) -> bool {
fn entity_is_colliding_with_tile(tile: Tile) -> bool {
match tile {
Tile::Door(door) => door.collidable == Collidable::True,
Tile::Wall(wall) => wall.collidable == Collidable::True,
Expand Down
14 changes: 6 additions & 8 deletions rustyhack_server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn main() {
let args: Vec<String> = env::args().collect();
initialise_log(&args);
let server_addr = get_server_addr();
info!("Server listen address is set to: {}", &server_addr);
info!("Server listen port is set to: {}", &server_addr);
engine::run(&server_addr);
info!("Program terminated.");
}
Expand All @@ -27,24 +27,22 @@ fn get_server_addr() -> String {
let mut server_addr;
loop {
server_addr = String::new();
println!("1) What is the server listen address? (default: 127.0.0.1:55301)");
println!("1) What is the server listen port? (default: 50201)");
io::stdin()
.read_line(&mut server_addr)
.expect("Failed to read line");

if server_addr.trim() == "" {
println!("Using default server listen address.");
server_addr = String::from("127.0.0.1:55301");
println!("Using default server listen port.");
server_addr = String::from("0.0.0.0:50201");
break;
}

server_addr = String::from("0.0.0.0:") + &*server_addr;
let server_socket_addr: SocketAddr = match server_addr.trim().parse() {
Ok(value) => value,
Err(err) => {
println!(
"Not a valid socket address (e.g. 127.0.0.1:55301 ): {}",
err
);
println!("Not a valid port (e.g. 50201 ): {}", err);
continue;
}
};
Expand Down
4 changes: 2 additions & 2 deletions rustyhack_server/src/message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ pub fn run(
debug!("Received {:?} from {:?}", player_message, address);

match player_message {
PlayerMessage::CreatePlayer(message) => {
PlayerMessage::PlayerJoin(message) => {
let mut create_player_message = message.clone();
create_player_message.client_addr = packet.addr().to_string();
send_channel_message(
PlayerMessage::CreatePlayer(create_player_message),
PlayerMessage::PlayerJoin(create_player_message),
&channel_sender,
);
}
Expand Down

0 comments on commit a0ec9cd

Please sign in to comment.