125 lines
2.8 KiB
Rust
125 lines
2.8 KiB
Rust
#[macro_use]
|
|
extern crate serde_derive;
|
|
|
|
use std::collections::HashMap;
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
/// The data contained from the json file generated by python.
|
|
pub struct JsonData {
|
|
/// The names of the AIs.
|
|
pub ais: Vec<String>,
|
|
|
|
/// The results of the battles.
|
|
pub battles: HashMap<String, f64>,
|
|
}
|
|
|
|
impl JsonData {
|
|
/// Creates some data data.
|
|
pub fn data() -> JsonData {
|
|
|
|
// Open the file
|
|
let mut file = File::open("./assets/data.json")
|
|
.expect("Couldn't open file");
|
|
|
|
let mut content = String::new();
|
|
file.read_to_string(&mut content)
|
|
.expect("Couldn't read data");
|
|
|
|
serde_json::from_str(&content)
|
|
.expect("Couldn't parse json")
|
|
}
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize, Clone)]
|
|
/// An AI.
|
|
pub struct Ai {
|
|
/// The name of the ai.
|
|
pub name: String,
|
|
|
|
/// The number of battles won by the ai.
|
|
pub victory_count: usize,
|
|
|
|
/// The number of battles lost by the ai.
|
|
pub defeat_count: usize,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct Data {
|
|
/// The AIs
|
|
pub ais: Vec<Ai>,
|
|
|
|
/// The battles.
|
|
///
|
|
/// This hashmap is symmetric.
|
|
pub battles: HashMap<String, f64>,
|
|
|
|
/// The ais sorted by victory count.
|
|
pub sorted_ais: Vec<Ai>,
|
|
}
|
|
|
|
impl Data {
|
|
/// Creates some data data.
|
|
pub fn data() -> Data {
|
|
JsonData::data().into()
|
|
}
|
|
}
|
|
|
|
impl From<JsonData> for Data {
|
|
fn from(d: JsonData) -> Data {
|
|
let mut ais = vec![];
|
|
|
|
for ai in d.ais {
|
|
ais.push(Ai {
|
|
name: ai,
|
|
victory_count: 0,
|
|
defeat_count: 0,
|
|
})
|
|
}
|
|
|
|
let mut battles = HashMap::new();
|
|
|
|
for (key, val) in d.battles {
|
|
|
|
let playing_ais = key.split("/")
|
|
.collect::<Vec<_>>();
|
|
|
|
let key1 = format!("{}/{}", playing_ais[0], playing_ais[1]);
|
|
let key2 = format!("{}/{}", playing_ais[1], playing_ais[0]);
|
|
|
|
battles.insert(key1, val);
|
|
battles.insert(key2, val);
|
|
|
|
if val != 0.5 {
|
|
let (winner, loser) = if val > 0.5 {
|
|
(playing_ais[0], playing_ais[1])
|
|
} else {
|
|
(playing_ais[1], playing_ais[0])
|
|
};
|
|
|
|
for ai in &mut ais {
|
|
if ai.name == winner {
|
|
ai.victory_count += 1;
|
|
}
|
|
|
|
if ai.name == loser {
|
|
ai.defeat_count += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut sorted_ais = ais.clone();
|
|
sorted_ais.sort_by_key(|ai| {
|
|
(std::usize::MAX - ai.victory_count, ai.defeat_count)
|
|
});
|
|
|
|
Data {
|
|
ais,
|
|
sorted_ais,
|
|
battles,
|
|
}
|
|
}
|
|
}
|