planetwars.dev/planetwars-matchrunner/src/lib.rs

91 lines
2.2 KiB
Rust
Raw Normal View History

2021-12-25 13:45:05 +00:00
mod bot_runner;
mod match_context;
mod pw_match;
use std::{
2021-12-25 20:49:16 +00:00
io::Write,
2021-12-25 13:45:05 +00:00
path::PathBuf,
sync::{Arc, Mutex},
};
use match_context::MatchCtx;
use planetwars_rules::PwConfig;
2021-12-25 20:49:16 +00:00
use serde::{Deserialize, Serialize};
2021-12-25 13:45:05 +00:00
use self::match_context::{EventBus, PlayerHandle};
pub struct MatchConfig {
2021-12-25 20:49:16 +00:00
pub map_name: String,
2021-12-25 13:45:05 +00:00
pub map_path: PathBuf,
pub log_path: PathBuf,
2021-12-28 13:57:41 +00:00
pub players: Vec<MatchPlayer>,
2021-12-25 13:45:05 +00:00
}
2021-12-25 20:49:16 +00:00
#[derive(Serialize, Deserialize)]
pub struct MatchMeta {
pub map_name: String,
pub timestamp: chrono::DateTime<chrono::Local>,
pub players: Vec<PlayerInfo>,
}
#[derive(Serialize, Deserialize)]
pub struct PlayerInfo {
pub name: String,
}
2021-12-28 13:57:41 +00:00
pub struct MatchPlayer {
2021-12-25 13:45:05 +00:00
pub name: String,
pub path: PathBuf,
pub argv: Vec<String>,
2021-12-25 13:45:05 +00:00
}
pub async fn run_match(config: MatchConfig) {
let pw_config = PwConfig {
map_file: config.map_path,
max_turns: 100,
};
let event_bus = Arc::new(Mutex::new(EventBus::new()));
// start bots
let players = config
.players
.iter()
.enumerate()
2021-12-28 13:57:41 +00:00
.map(|(player_id, player)| {
2021-12-25 13:45:05 +00:00
let player_id = (player_id + 1) as u32;
let bot = bot_runner::Bot {
working_dir: player.path.clone(),
argv: player.argv.clone(),
2021-12-25 13:45:05 +00:00
};
let handle = bot_runner::run_local_bot(player_id, event_bus.clone(), bot);
(player_id, Box::new(handle) as Box<dyn PlayerHandle>)
})
.collect();
2021-12-25 20:49:16 +00:00
let mut log_file = std::fs::File::create(config.log_path).expect("could not create log file");
// assemble the math meta struct
let match_meta = MatchMeta {
map_name: config.map_name.clone(),
timestamp: chrono::Local::now(),
players: config
.players
.iter()
.map(|bot| PlayerInfo {
name: bot.name.clone(),
})
.collect(),
};
write!(
log_file,
"{}\n",
serde_json::to_string(&match_meta).unwrap()
)
.unwrap();
2021-12-25 13:45:05 +00:00
let match_ctx = MatchCtx::new(event_bus, players, log_file);
let match_state = pw_match::PwMatch::create(match_ctx, pw_config);
match_state.run().await;
}