From b7ab700a57fb1155d4824f24fe9cc55111c977fe Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 20 Dec 2021 11:47:24 +0100 Subject: import planetwars-rules --- planetwars-rules/src/config.rs | 84 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 planetwars-rules/src/config.rs (limited to 'planetwars-rules/src/config.rs') diff --git a/planetwars-rules/src/config.rs b/planetwars-rules/src/config.rs new file mode 100644 index 0000000..32c23f5 --- /dev/null +++ b/planetwars-rules/src/config.rs @@ -0,0 +1,84 @@ +use std::fs::File; +use std::io; +use std::io::Read; + +use serde_json; + +use super::protocol as proto; +use super::rules::*; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Config { + pub map_file: String, + pub max_turns: u64, +} + +impl Config { + pub fn create_state(&self, num_players: usize) -> PwState { + let planets = self.load_map(num_players); + let players = (0..num_players) + .map(|player_num| Player { + id: player_num + 1, + alive: true, + }) + .collect(); + + PwState { + players: players, + planets: planets, + expeditions: Vec::new(), + expedition_num: 0, + turn_num: 0, + max_turns: self.max_turns, + } + } + + fn load_map(&self, num_players: usize) -> Vec { + let map = self.read_map().expect("[PLANET_WARS] reading map failed"); + + return map + .planets + .into_iter() + .enumerate() + .map(|(num, planet)| { + let mut fleets = Vec::new(); + let owner = planet.owner.and_then(|owner_num| { + // in the current map format, player numbers start at 1. + // TODO: we might want to change this. + // ignore players that are not in the game + if owner_num > 0 && owner_num <= num_players { + Some(owner_num - 1) + } else { + None + } + }); + if planet.ship_count > 0 { + fleets.push(Fleet { + owner: owner, + ship_count: planet.ship_count, + }); + } + return Planet { + id: num, + name: planet.name, + x: planet.x, + y: planet.y, + fleets: fleets, + }; + }) + .collect(); + } + + fn read_map(&self) -> io::Result { + let mut file = File::open(&self.map_file)?; + let mut buf = String::new(); + file.read_to_string(&mut buf)?; + let map = serde_json::from_str(&buf)?; + return Ok(map); + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Map { + pub planets: Vec, +} -- cgit v1.2.3