Skip to content
1        10        20        30        40        50        60        70        801mod api;2mod map;3mod world;45use std::env;6use std::sync::Arc;7use std::time::Duration;89use actix_files::Files;10use actix_web::{App, HttpServer, web};1112use api::AppState;13use world::TICK_SECS;1415#[actix_web::main]16async fn main() -> std::io::Result<()> {17    env_logger::init();1819    let port: u16 = env::var("PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(8080);20    let bind = env::var("BIND_ADDRESS").unwrap_or_else(|_| "127.0.0.1".into());21    let static_dir = env::var("STATIC_DIR").unwrap_or_else(|_| "static".into());2223    let state = Arc::new(AppState::new());24    spawn_tick(state.clone());2526    let data = web::Data::from(state);27    log::info!("serving on http://{bind}:{port} (static: {static_dir})");28    HttpServer::new(move || {29        App::new()30            .app_data(data.clone())31            .configure(api::configure)32            .service(Files::new("/", &static_dir).index_file("index.html"))33    })34    .bind((bind, port))?35    .run()36    .await37}3839// One simulation loop for everyone. Each tick advances the world and pushes a40// state snapshot to every connected client.41fn spawn_tick(state: Arc<AppState>) {42    actix_web::rt::spawn(async move {43        let mut interval = tokio::time::interval(Duration::from_secs_f64(TICK_SECS));44        loop {45            interval.tick().await;46            let (snapshot, logs) = {47                let mut world = state.world.lock().unwrap();48                let logs = world.step(TICK_SECS);49                (world.snapshot_json(), logs)50            };51            state.send_logs(logs);52            let _ = state.events.send(format!("event: state\ndata: {snapshot}\n\n"));53        }54    });55}