Skip to content

Commit

Permalink
refactor: seperate game options from server options
Browse files Browse the repository at this point in the history
  • Loading branch information
Erb3 committed Jun 13, 2024
1 parent d429895 commit 7f7f2c3
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 22 deletions.
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub struct Cli {
#[arg(short, long, env = "SVEIO_PORT")]
pub port: Option<u32>,

/// Optional logging level to use. Default is INFO
/// Optional logging level to use. Default is info
#[arg(short, long, env = "SVEIO_LOGGING_LEVEL")]
pub logging: Option<LoggingLevel>,
}
Expand Down
17 changes: 12 additions & 5 deletions src/game.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::state::GameState;
use crate::{datasource, packets, state, utils};
use chrono::Utc;
use geoutils::Location;
Expand All @@ -10,6 +9,11 @@ use std::sync::Arc;
use std::time::Duration;
use tokio::time;
use tracing::{debug, info};

pub struct GameOptions {
pub cities: Vec<datasource::City>,
}

pub fn on_connect(socket: SocketRef) {
debug!("🆕 Client connected with client id {}", socket.id);

Expand Down Expand Up @@ -62,20 +66,20 @@ pub fn on_connect(socket: SocketRef) {

socket.on(
"guess",
|socket: SocketRef, Data::<packets::GuessPacket>(data), state: State<GameState>| async move {
|socket: SocketRef, Data::<packets::GuessPacket>(data), state: State<state::GameState>| async move {
debug!("📬 Received message: {:?}", data);
state.insert_guess(socket.id, data).await;
state.update_last_packet(socket.id).await;
},
);

socket.on_disconnect(|s: SocketRef, state: State<GameState>| async move {
socket.on_disconnect(|s: SocketRef, state: State<state::GameState>| async move {
state.remove_player(s.id).await;
debug!("🚪 User {} disconnected.", s.id);
});
}

pub async fn game_loop(cities: Vec<datasource::City>, io: Arc<SocketIo>, state: GameState) {
pub async fn game_loop(options: GameOptions, io: Arc<SocketIo>, state: state::GameState) {
let mut interval = time::interval(Duration::from_secs(5));
let mut last_city: Option<&datasource::City> = None;

Expand Down Expand Up @@ -111,7 +115,10 @@ pub async fn game_loop(cities: Vec<datasource::City>, io: Arc<SocketIo>, state:

interval.tick().await;

let city: &datasource::City = cities.get(thread_rng().gen_range(0..cities.len())).unwrap();
let city: &datasource::City = options
.cities
.get(thread_rng().gen_range(0..options.cities.len()))
.unwrap();
let target_message = datasource::AnonymizedCity {
name: &city.name,
country: &city.country,
Expand Down
6 changes: 2 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ mod server;
mod state;
mod utils;
use dotenvy::dotenv;
use server::ServerOptions;
use tracing::info;

#[tokio::main]
Expand All @@ -19,13 +18,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.init();

info!("👋 Sveio says hi!");

info!("⏳ Loading cities!");
let cities = datasource::get_cities().await;
info!("✨ Loaded {} cities", cities.len());

server::start_server(ServerOptions {
cities,
server::start_server(server::ServerOptions {
game: game::GameOptions { cities },
port: settings.port.unwrap_or(8085),
})
.await;
Expand Down
7 changes: 3 additions & 4 deletions src/packets.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::datasource;
use crate::state::{GuessMap, PlayerMap};
use crate::{datasource, state};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize, Clone)]
Expand All @@ -11,8 +10,8 @@ pub struct GuessPacket {
#[derive(Serialize)]
pub struct SolutionPacket {
pub location: datasource::City,
pub guesses: GuessMap,
pub leaderboard: PlayerMap,
pub guesses: state::GuessMap,
pub leaderboard: state::PlayerMap,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
Expand Down
10 changes: 4 additions & 6 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use crate::datasource::City;
use crate::state::GameState;
use crate::{game, packets};
use crate::{game, packets, state};
use axum::http::Method;
use memory_serve::{load_assets, MemoryServe};
use socketioxide::{SocketIo, SocketIoBuilder};
Expand All @@ -13,12 +11,12 @@ use tower_http::timeout::TimeoutLayer;
use tracing::info;

pub struct ServerOptions {
pub cities: Vec<City>,
pub game: game::GameOptions,
pub port: u32,
}

pub async fn start_server(opts: ServerOptions) {
let socketio_state = GameState::new();
let socketio_state = state::GameState::new();

let (socketio_layer, io) = SocketIoBuilder::new()
.with_state(socketio_state.clone())
Expand Down Expand Up @@ -55,7 +53,7 @@ pub async fn start_server(opts: ServerOptions) {
let shutdown_io = Arc::clone(&io_arc);

tokio::spawn(async move {
game::game_loop(opts.cities, game_io, socketio_state).await;
game::game_loop(opts.game, game_io, socketio_state).await;
});

info!("⏳ Starting HTTP server");
Expand Down
4 changes: 2 additions & 2 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::packets::{self, GuessPacket};
use crate::packets;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use socketioxide::socket::Sid;
Expand Down Expand Up @@ -56,7 +56,7 @@ impl GameState {
self.guesses.write().await.clear()
}

pub async fn insert_guess(&self, sid: Sid, guess: GuessPacket) {
pub async fn insert_guess(&self, sid: Sid, guess: packets::GuessPacket) {
self.guesses.write().await.insert(sid, guess);
}

Expand Down

0 comments on commit 7f7f2c3

Please sign in to comment.