diff options
Diffstat (limited to 'src/state.rs')
-rw-r--r-- | src/state.rs | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..df66ec9 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,78 @@ +use json; + +pub struct State { + pub map_size: u16, + pub opponent_map: OpponentMap +} + +impl State { + pub fn new(json: &json::JsonValue) -> Result<State, String> { + let map_size = State::map_size_from_json(&json)?; + let ref opponent_map_json = json["OpponentMap"]; + let opponent_map = OpponentMap::new(&opponent_map_json, map_size)?; + + Ok(State { + map_size: map_size, + opponent_map: opponent_map + }) + } + + pub fn map_size_from_json(json: &json::JsonValue) -> Result<u16, String> { + json["MapDimension"] + .as_u16() + .ok_or(String::from("Did not find the map dimension in the state json file")) + } +} + +pub struct OpponentMap { + pub cells: Vec<Vec<Cell>> +} + +impl OpponentMap { + fn new(json: &json::JsonValue, map_size: u16) -> Result<OpponentMap, String> { + let mut cells = Vec::with_capacity(map_size as usize); + for _ in 0..map_size { + let mut row = Vec::with_capacity(map_size as usize); + for _ in 0..map_size { + row.push(Cell::new()); + } + cells.push(row); + } + + for json_cell in json["Cells"].members() { + let x = json_cell["X"] + .as_u16() + .ok_or(String::from("Failed to read X value of opponent map cell in json file"))?; + let y = json_cell["Y"] + .as_u16() + .ok_or(String::from("Failed to read Y value of opponent map cell in json file"))?; + let damaged = json_cell["Damaged"] + .as_bool() + .ok_or(String::from("Failed to read Damaged value of opponent map cell in json file"))?; + let missed = json_cell["Missed"] + .as_bool() + .ok_or(String::from("Failed to read Missed value of opponent map cell in json file"))?; + + cells[x as usize][y as usize].damaged = damaged; + cells[x as usize][y as usize].missed = missed; + } + + Ok(OpponentMap { + cells: cells + }) + } +} + +pub struct Cell { + pub damaged: bool, + pub missed: bool +} + +impl Cell { + fn new() -> Cell { + Cell { + damaged: false, + missed: false + } + } +} |