planet-wars/backend/src/util.rs

302 lines
7.4 KiB
Rust
Raw Normal View History

2020-03-25 22:14:26 +01:00
use async_std::fs;
2020-04-01 21:36:35 +02:00
use async_std::prelude::*;
2020-03-25 22:14:26 +01:00
2020-04-01 21:36:35 +02:00
static NAV: [(&'static str, &'static str); 5] = [
("/", "Home"),
("/lobby", "Lobby"),
("/mapbuilder", "Map Builder"),
("/visualizer", "Visualizer"),
("/debug", "Debug Station"),
];
2020-03-27 10:31:56 +01:00
2020-04-01 22:16:55 +02:00
pub static COLOURS: [&'static str; 9] = [
"gray", "blue", "cyan", "green", "yellow", "orange", "red", "pink", "purple",
];
2020-03-25 22:14:26 +01:00
#[derive(Serialize)]
pub struct Map {
name: String,
url: String,
}
2020-04-01 20:49:50 +02:00
#[derive(Serialize, Eq, PartialEq)]
pub struct PlayerStatus {
waiting: bool,
connected: bool,
reconnecting: bool,
value: String,
}
impl From<Connect> for PlayerStatus {
fn from(value: Connect) -> Self {
match value {
2020-04-01 21:36:35 +02:00
Connect::Connected(_, name) => PlayerStatus {
waiting: false,
connected: true,
reconnecting: false,
value: name,
},
Connect::Reconnecting(_, name) => PlayerStatus {
waiting: false,
connected: true,
reconnecting: true,
value: name,
},
Connect::Waiting(_, key) => PlayerStatus {
waiting: true,
connected: false,
reconnecting: false,
value: format!("Key: {}", key),
},
2020-04-01 20:49:50 +02:00
_ => panic!("No playerstatus possible from Connect::Request"),
}
}
}
#[derive(Serialize, Eq, PartialEq)]
#[serde(tag = "type")]
pub enum GameState {
Finished {
name: String,
map: String,
players: Vec<(String, bool)>,
turns: u64,
2020-04-01 21:36:35 +02:00
file: String,
2020-04-01 20:49:50 +02:00
},
Playing {
name: String,
map: String,
players: Vec<PlayerStatus>,
connected: usize,
total: usize,
2020-04-01 21:36:35 +02:00
},
2020-04-01 20:49:50 +02:00
}
use std::cmp::Ordering;
impl PartialOrd for GameState {
fn partial_cmp(&self, other: &GameState) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for GameState {
fn cmp(&self, other: &GameState) -> Ordering {
match self {
2020-04-01 21:36:35 +02:00
GameState::Finished { name, .. } => match other {
GameState::Finished { name: _name, .. } => name.cmp(_name),
_ => Ordering::Greater,
2020-04-01 20:49:50 +02:00
},
2020-04-01 21:36:35 +02:00
GameState::Playing { name, .. } => match other {
GameState::Playing { name: _name, .. } => name.cmp(_name),
_ => Ordering::Less,
},
}
}
}
impl From<FinishedState> for GameState {
2020-04-01 22:16:55 +02:00
fn from(mut state: FinishedState) -> Self {
state.players.sort_by_key(|x| x.0);
2020-04-01 21:36:35 +02:00
GameState::Finished {
map: String::new(),
players: state
.players
.iter()
.map(|(id, name)| (name.clone(), state.winners.contains(&id)))
.collect(),
name: state.name,
turns: state.turns,
file: state.file,
2020-04-01 20:49:50 +02:00
}
}
2020-03-28 19:07:55 +01:00
}
/// Visualiser game option
2020-03-27 17:32:18 +01:00
#[derive(Serialize)]
pub struct GameOption {
name: String,
location: String,
turns: u64,
}
impl GameOption {
pub fn new(name: &str, location: &str, turns: u64) -> Self {
Self {
name: name.to_string(),
location: location.to_string(),
2020-04-01 21:36:35 +02:00
turns,
2020-03-27 17:32:18 +01:00
}
}
}
2020-03-27 10:31:56 +01:00
#[derive(Serialize)]
struct Link {
name: String,
href: String,
active: bool,
}
2020-03-28 19:07:55 +01:00
#[derive(Serialize)]
pub struct Lobby {
pub games: Vec<GameState>,
pub maps: Vec<Map>,
}
2020-04-01 22:16:55 +02:00
// #[derive(Serialize)]
// #[serde(rename_all = "camelCase")]
// pub enum ContextT {
// Games(Vec<GameState>),
// }
2020-03-27 17:32:18 +01:00
2020-03-25 22:14:26 +01:00
#[derive(Serialize)]
2020-03-28 19:07:55 +01:00
pub struct Context<T> {
2020-03-25 22:14:26 +01:00
pub name: String,
2020-03-27 10:31:56 +01:00
nav: Vec<Link>,
2020-03-27 17:32:18 +01:00
#[serde(flatten)]
2020-04-01 21:36:35 +02:00
pub t: Option<T>,
2020-03-25 22:14:26 +01:00
}
2020-03-28 19:07:55 +01:00
impl<T> Context<T> {
pub fn new_with(active: &str, t: T) -> Self {
2020-04-01 21:36:35 +02:00
let nav = NAV
.iter()
.map(|(href, name)| Link {
name: name.to_string(),
href: href.to_string(),
active: *name == active,
})
.collect();
2020-03-27 10:31:56 +01:00
Context {
2020-04-01 21:36:35 +02:00
nav,
name: String::from(""),
t: Some(t),
2020-03-27 17:32:18 +01:00
}
}
2020-03-28 19:07:55 +01:00
}
2020-03-27 17:32:18 +01:00
2020-03-28 19:07:55 +01:00
impl Context<()> {
2020-03-27 17:32:18 +01:00
pub fn new(active: &str) -> Self {
2020-04-01 21:36:35 +02:00
let nav = NAV
.iter()
.map(|(href, name)| Link {
name: name.to_string(),
href: href.to_string(),
active: *name == active,
})
.collect();
2020-03-27 17:32:18 +01:00
Context {
2020-04-01 21:36:35 +02:00
nav,
name: String::from(""),
t: None,
2020-03-27 10:31:56 +01:00
}
}
}
2020-03-25 22:14:26 +01:00
pub async fn get_maps() -> Result<Vec<Map>, String> {
let mut maps = Vec::new();
2020-04-01 21:36:35 +02:00
let mut entries = fs::read_dir("maps")
.await
.map_err(|_| "IO error".to_string())?;
while let Some(file) = entries.next().await {
2020-03-25 22:14:26 +01:00
let file = file.map_err(|_| "IO error".to_string())?.path();
if let Some(stem) = file.file_stem().and_then(|x| x.to_str()) {
2020-04-01 21:36:35 +02:00
maps.push(Map {
name: stem.to_string(),
url: file.to_str().unwrap().to_string(),
});
2020-03-25 22:14:26 +01:00
}
}
Ok(maps)
}
2020-03-27 17:32:18 +01:00
2020-04-01 21:36:35 +02:00
use async_std::io::BufReader;
use futures::stream::StreamExt;
pub async fn get_games() -> Vec<GameState> {
match fs::File::open("games.ini").await {
Ok(file) => {
let mut file = BufReader::new(file);
2020-04-01 22:16:55 +02:00
file.lines()
.filter_map(move |maybe| async {
maybe
.ok()
.and_then(|line| serde_json::from_str::<FinishedState>(&line).ok())
})
.map(|state| state.into())
.collect()
.await
2020-03-27 17:32:18 +01:00
}
2020-04-01 21:36:35 +02:00
Err(_) => Vec::new(),
2020-03-27 17:32:18 +01:00
}
}
2020-03-28 19:07:55 +01:00
2020-04-01 20:49:50 +02:00
use crate::planetwars::FinishedState;
2020-03-28 19:07:55 +01:00
2020-04-01 21:36:35 +02:00
use futures::future::{join_all, FutureExt};
2020-03-28 19:07:55 +01:00
use mozaic::modules::game;
use mozaic::util::request::Connect;
2020-04-01 21:36:35 +02:00
pub async fn get_states(
game_ids: &Vec<(String, u64)>,
manager: &game::Manager,
) -> Result<Vec<GameState>, String> {
2020-03-28 19:07:55 +01:00
let mut states = Vec::new();
2020-04-01 21:36:35 +02:00
let gss = join_all(
game_ids
.iter()
.cloned()
.map(|(name, id)| manager.get_state(id).map(move |f| (f, name))),
)
.await;
2020-03-28 19:07:55 +01:00
for (gs, name) in gss {
if let Some(state) = gs {
2020-04-01 20:49:50 +02:00
match state {
Ok(conns) => {
2020-04-01 21:36:35 +02:00
let players: Vec<PlayerStatus> =
conns.iter().cloned().map(|x| x.into()).collect();
2020-04-01 20:49:50 +02:00
let connected = players.iter().filter(|x| x.connected).count();
2020-04-01 21:36:35 +02:00
states.push(GameState::Playing {
name: name,
total: players.len(),
players,
connected,
map: String::new(),
});
}
2020-04-01 20:49:50 +02:00
Err(value) => {
let state: FinishedState = serde_json::from_value(value).expect("Shit failed");
2020-04-01 21:36:35 +02:00
states.push(state.into());
2020-03-28 19:07:55 +01:00
}
2020-04-01 20:49:50 +02:00
}
2020-03-28 19:07:55 +01:00
}
}
2020-04-01 20:49:50 +02:00
states.sort();
2020-03-28 19:07:55 +01:00
Ok(states)
}
use std::sync::{Arc, Mutex};
pub struct Games {
inner: Arc<Mutex<Vec<(String, u64)>>>,
}
impl Games {
pub fn new() -> Self {
Self {
2020-04-01 21:36:35 +02:00
inner: Arc::new(Mutex::new(Vec::new())),
2020-03-28 19:07:55 +01:00
}
}
pub fn add_game(&self, name: String, id: u64) {
self.inner.lock().unwrap().push((name, id));
}
pub fn get_games(&self) -> Vec<(String, u64)> {
self.inner.lock().unwrap().clone()
}
}