|
@@ -1,6 +1,6 @@
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
-use crate::{Id, Inventory, Kind, Valid};
|
|
|
+use crate::{fs_util::{dir_exists, file_exists, join, mkdir, read_dir}, Id, Inventory, Kind, Valid};
|
|
|
|
|
|
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Default)]
|
|
|
pub struct Object {
|
|
@@ -54,20 +54,55 @@ impl Object {
|
|
|
|
|
|
pub fn load_file(filename: &String) -> Option<Object> {
|
|
|
let p = crate::fs_util::join(&format!("{}", filename));
|
|
|
+ if !file_exists(&p) {
|
|
|
+ return None;
|
|
|
+ }
|
|
|
let cont = crate::fs_util::read_file(&p);
|
|
|
if cont.is_empty() {
|
|
|
eprintln!("Err reading '{}'", p);
|
|
|
return None;
|
|
|
}
|
|
|
+ Object::load(&cont)
|
|
|
+ }
|
|
|
+ pub fn load(cont: &String) -> Option<Object> {
|
|
|
let obj: Result<Object, serde_json::Error> = serde_json::from_str(cont.as_str());
|
|
|
match obj {
|
|
|
Ok(obj) => Some(obj),
|
|
|
- Err(_) => {
|
|
|
- eprintln!("Err parsing '{}'", p);
|
|
|
+ Err(e) => {
|
|
|
+ eprintln!("Err parsing, {}", e);
|
|
|
None
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+ pub fn load_by_id(id: Id) -> Option<Object> {
|
|
|
+ Object::load_file(&format!("data/objects/{}.json", id))
|
|
|
+ }
|
|
|
+ pub fn load_player_by_name(name: &String) -> Option<Object> {
|
|
|
+ let p = join(&"data/objects".to_string());
|
|
|
+ let dir = read_dir(&p, false);
|
|
|
+ if dir.is_empty() {
|
|
|
+ if !dir_exists(&p) {
|
|
|
+ mkdir(&p);
|
|
|
+ }
|
|
|
+ return None;
|
|
|
+ }
|
|
|
+ for entry in dir.iter() {
|
|
|
+ eprintln!("Trying '{}'", entry);
|
|
|
+ let obj = Object::load_file(entry);
|
|
|
+ match obj {
|
|
|
+ Some(obj) => {
|
|
|
+ eprintln!("OK");
|
|
|
+ if obj.name == *name {
|
|
|
+ return Some(obj);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ None => {
|
|
|
+ eprintln!("ERR");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ None
|
|
|
+ }
|
|
|
pub fn save(&mut self) -> bool {
|
|
|
if !self.valid() {
|
|
|
eprintln!("Object not valid, won't save");
|