Skip to content

Commit

Permalink
Merge pull request #360 from AnthonyTornetta/348-spawn-player-near-as…
Browse files Browse the repository at this point in the history
…teroids-and-shop

348 spawn player near asteroids and shop
  • Loading branch information
AnthonyTornetta authored Dec 14, 2024
2 parents 05e1a48 + 97813b6 commit af6871c
Show file tree
Hide file tree
Showing 16 changed files with 747 additions and 176 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,7 @@ docs/mermaid.min.js
docs/book/

# Generated via `cargo run --features print-schedule | dot -Tsvg > ./debug.svg`
debug.svg
debug.svg

# Local to this player
name.env
101 changes: 101 additions & 0 deletions cosmos_client/assets/adjectives.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
Absurd
Agitated
Ample
Angus
Astonishing
Awkward
Balmy
Batty
Bizarre
Bouncy
Bulbous
Bungling
Bumbling
Burly
Carefree
Chaotic
Chipper
Clammy
Clumsy
Cranky
Crinkly
Dainty
Dashing
Dazed
Dizzy
Dopey
Drippy
Droopy
Drowsy
Ductile
Dull
Elastic
Erratic
Excitable
Fidgety
Flaky
Flamboyant
Floppy
Fluffy
Foolhardy
Frisky
Frothy
Fuzzy
Gabby
Gangly
Giddy
Giggly
Goofy
Grouchy
Hairy
Hapless
Hardy
Hefty
Hilarious
Jabbering
Jolly
Jumpy
Lazy
Loopy
Lumpy
Maddening
Meandering
Melodramatic
Mushy
Nimble
Nosy
Nutty
Oafish
Obnoxious
Oddball
Outlandish
Peppy
Perky
Plucky
Portly
Puffy
Quirky
Rambunctious
Raucous
Restless
Rowdy
Rumbling
Sassy
Scatterbrained
Silly
Skittish
Snooty
Snugly
Spindly
Spunky
Squishy
Stodgy
Sturdy
Surly
Tacky
Topsy-turvy
Ungainly
Unruly
Wacky
Wobbly
Zany
101 changes: 101 additions & 0 deletions cosmos_client/assets/animals.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
Aardvark
Albatross
Alpaca
Anteater
Antelope
Armadillo
Axolotl
Baboon
Badger
Barracuda
Bat
Beaver
Bison
Blobfish
Bluejay
Booby
Camel
Capybara
Caribou
Cassowary
Catfish
Chameleon
Cheetah
Chicken
Chinchilla
Clam
Cockatoo
Cockroach
Condor
Crab
Crane
Crocodile
Crow
Cuttlefish
Dingo
Dolphin
Donkey
Dragonfly
Duck
Duck-billed Platypus
Eagle
Eel
Egret
Elephant
Emu
Falcon
Ferret
Flamingo
Fox
Frog
Gecko
Giraffe
Gnat
Goat
Goose
Gorilla
Grasshopper
Grouper
Gull
Hamster
Hedgehog
Heron
Hippopotamus
Hornet
Horse
Hyena
Ibex
Ibis
Jellyfish
Kangaroo
Kiwi
Koala
Ladybug
Lemur
Leopard
Lizard
Lobster
Loon
Lynx
Manatee
McFife
Meerkat
Mole
Moose
Narwhal
Newt
Octopus
Opossum
Ostrich
Otter
Owl
Panda
Pangolin
Parrot
Pelican
Penguin
Pigeon
Porcupine
Quokka
Raccoon
Salamander
18 changes: 13 additions & 5 deletions cosmos_client/src/netty/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use renet2::transport::NativeSocket;

use crate::netty::lobby::{ClientLobby, MostRecentTick};

fn new_netcode_transport(mut host: &str, port: u16) -> NetcodeClientTransport {
fn new_netcode_transport(player_name: &str, mut host: &str, port: u16) -> NetcodeClientTransport {
if host == "localhost" {
host = "127.0.0.1"; // to_socket_addrs turns localhost into an ipv6 IP, which fails to connect to the server listening on an ipv4 address.
}
Expand All @@ -39,12 +39,14 @@ fn new_netcode_transport(mut host: &str, port: u16) -> NetcodeClientTransport {
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let client_id = current_time.as_millis() as u64;

let name = "CoolPlayer";

let mut token = [0; 256];

// Bincode because this is stored un a u8, with a fixed length of 256
let serialized_name = bincode::serialize(&name).expect("Unable to serialize name");
let serialized_name = bincode::serialize(&player_name).expect("Unable to serialize name");
if serialized_name.len() > 256 {
panic!("name too long. TODO: Handle this gracefully");
}

for (i, byte) in serialized_name.iter().enumerate() {
token[i] = *byte;
}
Expand All @@ -71,6 +73,8 @@ pub struct HostConfig {
pub host_name: String,
/// The server's port
pub port: u16,
/// The player's name
pub name: String,
}

/// Establishes a connection with the server.
Expand All @@ -81,7 +85,11 @@ pub fn establish_connection(mut commands: Commands, host_config: Res<HostConfig>
commands.insert_resource(ClientLobby::default());
commands.insert_resource(MostRecentTick(None));
commands.insert_resource(RenetClient::new(connection_config()));
commands.insert_resource(new_netcode_transport(host_config.host_name.as_str(), host_config.port));
commands.insert_resource(new_netcode_transport(
&host_config.name,
host_config.host_name.as_str(),
host_config.port,
));
commands.init_resource::<NetworkMapping>();
}

Expand Down
77 changes: 73 additions & 4 deletions cosmos_client/src/ui/main_menu/title_screen/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::net::ToSocketAddrs;
use std::{fs, net::ToSocketAddrs};

use bevy::{
app::{App, AppExit},
prelude::*,
};
use cosmos_core::state::GameState;
use rand::seq::IteratorRandom;

use crate::{
netty::connect::HostConfig,
Expand All @@ -24,6 +25,19 @@ use super::{
MainMenuSubState, MainMenuSystemSet,
};

#[derive(Debug, Clone, Component, PartialEq, Eq)]
struct PlayerName(String);

impl ReactableValue for PlayerName {
fn as_value(&self) -> String {
self.0.clone()
}

fn set_from_value(&mut self, new_value: &str) {
self.0 = new_value.to_owned();
}
}

#[derive(Debug, Clone, Component, PartialEq, Eq)]
struct ConnectionString(String);

Expand Down Expand Up @@ -109,7 +123,51 @@ fn create_main_menu(mut commands: Commands, default_font: Res<DefaultFont>, q_ui
},
));

let vars_entity = p.spawn((ConnectionString("localhost".into()), ErrorMessage::default())).id();
let name = fs::read_to_string("name.env").unwrap_or_else(|_| {
let adjective = fs::read_to_string("assets/adjectives.txt").expect("Missing adjectives :O");
let adjective = adjective
.split_whitespace()
.choose(&mut rand::thread_rng())
.expect("No adjectives ;(");

let animal = fs::read_to_string("assets/animals.txt").expect("Missing animals :O");
let animal = animal.split_whitespace().choose(&mut rand::thread_rng()).expect("No animals ;(");

format!("{adjective} {animal}")
});

let vars_entity = p
.spawn((
PlayerName(name.clone()),
ConnectionString("localhost".into()),
ErrorMessage::default(),
))
.id();

p.spawn((
BindValues::single(BindValue::<PlayerName>::new(vars_entity, ReactableFields::Value)),
text_style_small.clone(),
TextInput {
input_type: InputType::Text { max_length: Some(32) },
..Default::default()
},
InputValue::new(name),
BorderColor(Srgba::hex("555555").unwrap().into()),
BackgroundColor(Srgba::hex("111111").unwrap().into()),
Node {
border: UiRect::all(Val::Px(2.0)),
width: Val::Px(500.0),
min_height: Val::Px(45.0),
align_self: AlignSelf::Center,
margin: UiRect::top(Val::Px(20.0)),
padding: UiRect {
top: Val::Px(4.0),
bottom: Val::Px(4.0),
..Default::default()
},
..Default::default()
},
));

p.spawn((
BindValues::single(BindValue::<ConnectionString>::new(vars_entity, ReactableFields::Value)),
Expand Down Expand Up @@ -214,11 +272,11 @@ fn goto_settings(mut mms: ResMut<MainMenuSubState>) {
}

fn trigger_connection(
mut q_vars: Query<(&ConnectionString, &mut ErrorMessage)>,
mut q_vars: Query<(&PlayerName, &ConnectionString, &mut ErrorMessage)>,
mut state: ResMut<NextState<GameState>>,
mut commands: Commands,
) {
let Ok((connection_string, mut em)) = q_vars.get_single_mut() else {
let Ok((player_name, connection_string, mut em)) = q_vars.get_single_mut() else {
return;
};

Expand Down Expand Up @@ -260,7 +318,17 @@ fn trigger_connection(
return;
}

if player_name.0.is_empty() || player_name.0.len() > 32 {
em.0 = "Must have a name".to_owned();
return;
}

fs::write("name.env", &player_name.0).unwrap_or_else(|e| {
error!("Failed to save name ;(\n{e:?}");
});

commands.insert_resource(HostConfig {
name: player_name.0.clone(),
host_name: host_name.into(),
port,
});
Expand All @@ -282,6 +350,7 @@ pub(super) fn register(app: &mut App) {
register_button::<QuitButtonEvent>(app);

add_reactable_type::<ConnectionString>(app);
add_reactable_type::<PlayerName>(app);

app.configure_sets(
Update,
Expand Down
6 changes: 6 additions & 0 deletions cosmos_server/src/entities/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
//! Contains all server information about various entities
use bevy::prelude::App;

pub mod player;

pub(super) fn register(app: &mut App) {
player::register(app);
}
Loading

0 comments on commit af6871c

Please sign in to comment.