diff options
author | Justin Wernick <justin@worthe-it.co.za> | 2022-04-19 21:28:54 +0200 |
---|---|---|
committer | Justin Wernick <justin@worthe-it.co.za> | 2022-04-19 21:28:54 +0200 |
commit | 59f8b6a8ef1abfd0556cc940ccb64305fcdf2968 (patch) | |
tree | af1e8424d7704cf7ccab5818c6d2adb915b183f3 /2017-battleships/src/files.rs | |
parent | dc01a3e25e6c4ef056467e36f876ebd68f3ade22 (diff) | |
parent | a866bde485c7d8bc82820f2def70af7b6c70a066 (diff) |
Merge branch 'battleships-main'
Diffstat (limited to '2017-battleships/src/files.rs')
-rw-r--r-- | 2017-battleships/src/files.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/2017-battleships/src/files.rs b/2017-battleships/src/files.rs new file mode 100644 index 0000000..0810a4e --- /dev/null +++ b/2017-battleships/src/files.rs @@ -0,0 +1,57 @@ +use json; +use serde_json; + +use std::io::prelude::*; +use std::fs::File; +use std::path::PathBuf; + +use actions::*; +use knowledge::*; + +const STATE_FILE: &'static str = "state.json"; + +const COMMAND_FILE: &'static str = "command.txt"; +const PLACE_FILE: &'static str = "place.txt"; + +const KNOWLEDGE_FILE: &'static str = "knowledge-state.json"; + + +pub fn read_file(working_dir: &PathBuf) -> Result<json::JsonValue, String> { + let state_path = working_dir.join(STATE_FILE); + let mut file = File::open(state_path.as_path()).map_err(|e| e.to_string())?; + let mut content = String::new(); + file.read_to_string(&mut content).map_err(|e| e.to_string())?; + json::parse(content.as_ref()).map_err(|e| e.to_string()) +} + +pub fn write_action(working_dir: &PathBuf, is_place_phase: bool, action: Action) -> Result<(), String> { + let filename = if is_place_phase { + PLACE_FILE + } + else { + COMMAND_FILE + }; + + let full_filename = working_dir.join(filename); + let mut file = File::create(full_filename.as_path()).map_err(|e| e.to_string())?; + write!(file, "{}", action).map_err(|e| e.to_string())?; + + println!("Making move: {}", action); + + Ok(()) +} + +pub fn read_knowledge() -> Result<Knowledge, String> { + let mut file = File::open(KNOWLEDGE_FILE).map_err(|e| e.to_string())?; + let mut content = String::new(); + file.read_to_string(&mut content).map_err(|e| e.to_string())?; + serde_json::from_str(content.as_ref()).map_err(|e| e.to_string()) +} + +pub fn write_knowledge(knowledge: &Knowledge) -> Result<(), String> { + let json = serde_json::to_string(knowledge).map_err(|e| e.to_string())?; + let mut file = File::create(KNOWLEDGE_FILE).map_err(|e| e.to_string())?; + write!(file, "{}", json).map_err(|e| e.to_string())?; + + Ok(()) +} |