2019-06-01 19:24:17 +00:00
|
|
|
use rand::seq::SliceRandom;
|
2019-06-01 19:49:34 +00:00
|
|
|
use serde_json;
|
2019-06-01 19:24:17 +00:00
|
|
|
use std::fs::File;
|
2019-06-01 19:49:34 +00:00
|
|
|
use std::io::Error;
|
2019-06-01 19:24:17 +00:00
|
|
|
|
|
|
|
pub enum NpcKind {
|
|
|
|
Wolf,
|
2019-06-01 19:49:34 +00:00
|
|
|
Pig,
|
2019-06-01 19:24:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl NpcKind {
|
|
|
|
fn as_str(&self) -> &'static str {
|
|
|
|
match *self {
|
|
|
|
NpcKind::Wolf => "wolf",
|
2019-06-01 19:49:34 +00:00
|
|
|
NpcKind::Pig => "pig",
|
2019-06-01 19:24:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-01 19:49:34 +00:00
|
|
|
const npc_names_dir: &str = "common/assets/npc_names.json";
|
|
|
|
|
2019-06-01 19:24:17 +00:00
|
|
|
pub fn get_npc_name(npc_type: NpcKind) -> String {
|
2019-06-01 19:49:34 +00:00
|
|
|
let npc_names_file =
|
|
|
|
File::open(npc_names_dir).expect(&format!("opening {} in read-only mode", npc_names_dir));
|
|
|
|
let npc_names_json: serde_json::Value = serde_json::from_reader(npc_names_file)
|
|
|
|
.expect(&format!("reading json contents from {}", npc_names_dir));
|
|
|
|
let npc_names = npc_names_json
|
2019-06-01 19:24:17 +00:00
|
|
|
.get(npc_type.as_str())
|
|
|
|
.expect("accessing json using NPC type provided as key")
|
|
|
|
.as_array()
|
|
|
|
.expect("parsing accessed json value into an array");
|
|
|
|
let npc_name = npc_names
|
|
|
|
.choose(&mut rand::thread_rng())
|
|
|
|
.expect("getting a random NPC name")
|
|
|
|
.as_str()
|
|
|
|
.expect("parsing NPC name json value into a &str");
|
|
|
|
String::from(npc_name)
|
|
|
|
}
|