cargo fmt

This commit is contained in:
ajuvercr 2020-04-09 23:03:36 +02:00
parent 6b804724b4
commit 05925f0622
7 changed files with 122 additions and 55 deletions

View file

@ -25,7 +25,7 @@ use tracing_subscriber::{EnvFilter, FmtSubscriber};
use std::net::SocketAddr; use std::net::SocketAddr;
use mozaic::modules::{game}; use mozaic::modules::game;
use futures::executor::ThreadPool; use futures::executor::ThreadPool;
use futures::future::FutureExt; use futures::future::FutureExt;
@ -39,8 +39,8 @@ mod util;
use util::Games; use util::Games;
use util::COLOURS; use util::COLOURS;
use rocket_contrib::templates::{Template, Engines};
use rocket_contrib::templates::tera::{self, Value}; use rocket_contrib::templates::tera::{self, Value};
use rocket_contrib::templates::{Engines, Template};
use std::collections::HashMap; use std::collections::HashMap;
@ -54,18 +54,34 @@ fn calc_viewbox(value: Value, _: HashMap<String, Value>) -> tera::Result<Value>
for v in value.as_array().unwrap() { for v in value.as_array().unwrap() {
let x = v.get("x").and_then(|v| v.as_f64()).unwrap(); let x = v.get("x").and_then(|v| v.as_f64()).unwrap();
let y = v.get("y").and_then(|v| v.as_f64()).unwrap(); let y = v.get("y").and_then(|v| v.as_f64()).unwrap();
if x < min_x { min_x = x; } if x < min_x {
if x > max_x { max_x = x; } min_x = x;
if y < min_y { min_y = y; } }
if y > max_y { max_y = y; } if x > max_x {
max_x = x;
}
if y < min_y {
min_y = y;
}
if y > max_y {
max_y = y;
}
} }
return Ok(Value::String(format!("{} {} {} {}", min_x - 3., min_y - 3., (max_x - min_x) + 6., (max_y - min_y) + 6.))); return Ok(Value::String(format!(
"{} {} {} {}",
min_x - 3.,
min_y - 3.,
(max_x - min_x) + 6.,
(max_y - min_y) + 6.
)));
} }
/// Get's the right colour for planets /// Get's the right colour for planets
fn get_colour(value: Value, _: HashMap<String, Value>) -> tera::Result<Value> { fn get_colour(value: Value, _: HashMap<String, Value>) -> tera::Result<Value> {
return Ok(Value::String(COLOURS[value.as_u64().unwrap_or(0) as usize].to_string())); return Ok(Value::String(
COLOURS[value.as_u64().unwrap_or(0) as usize].to_string(),
));
} }
/// Async main function, starting logger, graph and rocket /// Async main function, starting logger, graph and rocket

View file

@ -48,7 +48,11 @@ impl PlanetWarsGame {
log_file: file, log_file: file,
turns: 0, turns: 0,
name: name.to_string(), name: name.to_string(),
map: PathBuf::from(map).file_stem().and_then(|x| x.to_str()).unwrap().to_string(), map: PathBuf::from(map)
.file_stem()
.and_then(|x| x.to_str())
.unwrap()
.to_string(),
} }
} }

View file

@ -1,5 +1,5 @@
use rocket::{Route};
use rocket::response::Redirect; use rocket::response::Redirect;
use rocket::Route;
use rocket_contrib::templates::Template; use rocket_contrib::templates::Template;
@ -16,11 +16,14 @@ fn info_base() -> Redirect {
/// Renders the <page> info page /// Renders the <page> info page
#[get("/info/<page>")] #[get("/info/<page>")]
async fn info(page: usize) -> Template { async fn info(page: usize) -> Template {
let context = Context::new_with("info", json!({ let context = Context::new_with(
"info",
json!({
"page": page, "page": page,
"next": if page + 1 <= MAX { Some(page + 1) } else { None }, "next": if page + 1 <= MAX { Some(page + 1) } else { None },
"prev": if page - 1 > 0 { Some(page - 1) } else { None } "prev": if page - 1 > 0 { Some(page - 1) } else { None }
})); }),
);
Template::render(format!("info/info_{}", page), &context) Template::render(format!("info/info_{}", page), &context)
} }

View file

@ -1,7 +1,7 @@
use crate::planetwars; use crate::planetwars;
use crate::util::*; use crate::util::*;
use rocket::{State, Route}; use rocket::{Route, State};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use rocket_contrib::templates::Template; use rocket_contrib::templates::Template;
@ -37,7 +37,10 @@ struct GameRes {
/// Standard get function for the lobby tab /// Standard get function for the lobby tab
#[get("/lobby")] #[get("/lobby")]
async fn get_lobby(gm: State<'_, game::Manager>, state: State<'_, Games>) -> Result<Template, String> { async fn get_lobby(
gm: State<'_, game::Manager>,
state: State<'_, Games>,
) -> Result<Template, String> {
let maps = get_maps().await?; let maps = get_maps().await?;
let games = get_states(&state.get_games(), &gm).await?; let games = get_states(&state.get_games(), &gm).await?;
let context = Context::new_with("Lobby", Lobby { games, maps }); let context = Context::new_with("Lobby", Lobby { games, maps });
@ -46,9 +49,18 @@ async fn get_lobby(gm: State<'_, game::Manager>, state: State<'_, Games>) -> Res
/// The lobby get's this automatically on load and on refresh. /// The lobby get's this automatically on load and on refresh.
#[get("/partial/state")] #[get("/partial/state")]
async fn state_get(gm: State<'_, game::Manager>, state: State<'_, Games>) -> Result<Template, String> { async fn state_get(
gm: State<'_, game::Manager>,
state: State<'_, Games>,
) -> Result<Template, String> {
let games = get_states(&state.get_games(), &gm).await?; let games = get_states(&state.get_games(), &gm).await?;
let context = Context::new_with("Lobby", Lobby { games, maps: Vec::new() }); let context = Context::new_with(
"Lobby",
Lobby {
games,
maps: Vec::new(),
},
);
Ok(Template::render("state_partial", &context)) Ok(Template::render("state_partial", &context))
} }
@ -56,26 +68,36 @@ async fn state_get(gm: State<'_, game::Manager>, state: State<'_, Games>) -> Res
/// Post function to create a game. /// Post function to create a game.
/// Returns the keys of the players in json. /// Returns the keys of the players in json.
#[post("/lobby", data = "<game_req>")] #[post("/lobby", data = "<game_req>")]
async fn post_game(game_req: Json<GameReq>, tp: State<'_, ThreadPool>, gm: State<'_, game::Manager>, state: State<'_, Games>) -> Result<Json<GameRes>, String> { async fn post_game(
let game = build_builder(tp.clone(), game_req.nop, game_req.max_turns, &game_req.map, &game_req.name); game_req: Json<GameReq>,
tp: State<'_, ThreadPool>,
gm: State<'_, game::Manager>,
state: State<'_, Games>,
) -> Result<Json<GameRes>, String> {
let game = build_builder(
tp.clone(),
game_req.nop,
game_req.max_turns,
&game_req.map,
&game_req.name,
);
let game_id = gm.start_game(game).await.unwrap(); let game_id = gm.start_game(game).await.unwrap();
state.add_game(game_req.name.clone(), game_id); state.add_game(game_req.name.clone(), game_id);
match gm.get_state(game_id).await { match gm.get_state(game_id).await {
Some(Ok((state, conns))) => { Some(Ok((state, conns))) => {
let players: Vec<u64> = conns.iter().map(|conn| match conn { let players: Vec<u64> = conns
.iter()
.map(|conn| match conn {
Connect::Waiting(_, key) => *key, Connect::Waiting(_, key) => *key,
_ => 0, _ => 0,
}).collect(); })
.collect();
Ok(Json(GameRes { players, state })) Ok(Json(GameRes { players, state }))
},
Some(Err(v)) => {
Err(serde_json::to_string(&v).unwrap())
},
None => {
Err(String::from("Fuck the world"))
} }
Some(Err(v)) => Err(serde_json::to_string(&v).unwrap()),
None => Err(String::from("Fuck the world")),
} }
} }
@ -84,7 +106,8 @@ fn generate_string_id() -> String {
rand::thread_rng() rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
.take(15) .take(15)
.collect::<String>() + ".json" .collect::<String>()
+ ".json"
} }
/// game::Manager spawns game::Builder to start games. /// game::Manager spawns game::Builder to start games.
@ -101,8 +124,12 @@ fn build_builder(
max_turns: max_turns, max_turns: max_turns,
}; };
let game = let game = planetwars::PlanetWarsGame::new(
planetwars::PlanetWarsGame::new(config.create_game(number_of_clients as usize), &generate_string_id(), name, map); config.create_game(number_of_clients as usize),
&generate_string_id(),
name,
map,
);
let players: Vec<PlayerId> = (0..number_of_clients).collect(); let players: Vec<PlayerId> = (0..number_of_clients).collect();
@ -117,7 +144,6 @@ pub fn fuel(routes: &mut Vec<Route>) {
routes.extend(routes![post_game, get_lobby, state_get]); routes.extend(routes![post_game, get_lobby, state_get]);
} }
#[derive(Serialize)] #[derive(Serialize)]
pub struct Lobby { pub struct Lobby {
pub games: Vec<GameState>, pub games: Vec<GameState>,

View file

@ -1,12 +1,12 @@
use serde::{Deserialize}; use serde::Deserialize;
use rocket::{Route}; use rocket::Route;
use rocket_contrib::templates::Template;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
use async_std::prelude::*;
use async_std::fs; use async_std::fs;
use async_std::io::ReadExt; use async_std::io::ReadExt;
use async_std::prelude::*;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -27,8 +27,12 @@ async fn map_post(map_req: Json<MapReq>) -> Result<String, String> {
return Err("File already exists!".into()); return Err("File already exists!".into());
} }
let mut file = fs::File::create(path).await.map_err(|_| "IO error".to_string())?; let mut file = fs::File::create(path)
file.write_all(&serde_json::to_vec_pretty(&map).unwrap()).await.map_err(|_| "IO error".to_string())?; .await
.map_err(|_| "IO error".to_string())?;
file.write_all(&serde_json::to_vec_pretty(&map).unwrap())
.await
.map_err(|_| "IO error".to_string())?;
Ok("ok".into()) Ok("ok".into())
} }
@ -38,13 +42,19 @@ async fn map_post(map_req: Json<MapReq>) -> Result<String, String> {
#[get("/maps/<file>")] #[get("/maps/<file>")]
async fn map_get(file: String) -> Result<Template, String> { async fn map_get(file: String) -> Result<Template, String> {
let mut content = String::new(); let mut content = String::new();
let mut file = fs::File::open(Path::new("maps/").join(file)).await.map_err(|_| "IO ERROR".to_string())?; let mut file = fs::File::open(Path::new("maps/").join(file))
file.read_to_string(&mut content).await.map_err(|_| "IO ERROR".to_string())?; .await
.map_err(|_| "IO ERROR".to_string())?;
file.read_to_string(&mut content)
.await
.map_err(|_| "IO ERROR".to_string())?;
Ok(Template::render("map_partial", &serde_json::from_str::<serde_json::Value>(&content).unwrap())) Ok(Template::render(
"map_partial",
&serde_json::from_str::<serde_json::Value>(&content).unwrap(),
))
} }
pub fn fuel(routes: &mut Vec<Route>) { pub fn fuel(routes: &mut Vec<Route>) {
routes.extend(routes![map_post, map_get]); routes.extend(routes![map_post, map_get]);
} }

View file

@ -1,21 +1,21 @@
use crate::util::*;
use crate::planetwars::FinishedState; use crate::planetwars::FinishedState;
use crate::util::*;
use rocket::{Route};
use rocket::response::NamedFile; use rocket::response::NamedFile;
use rocket::Route;
use rocket_contrib::templates::Template; use rocket_contrib::templates::Template;
use async_std::prelude::*;
use async_std::io::BufReader;
use async_std::fs; use async_std::fs;
use async_std::io::BufReader;
use async_std::prelude::*;
use futures::stream::StreamExt; use futures::stream::StreamExt;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
mod info;
mod lobby; mod lobby;
mod maps; mod maps;
mod info;
/// Handles all files located in the static folder /// Handles all files located in the static folder
#[get("/<file..>", rank = 6)] #[get("/<file..>", rank = 6)]
@ -48,13 +48,22 @@ async fn debug_get() -> Result<Template, String> {
#[get("/visualizer")] #[get("/visualizer")]
async fn visualizer_get() -> Template { async fn visualizer_get() -> Template {
let game_options = get_played_games().await; let game_options = get_played_games().await;
let context = Context::new_with("Visualizer", json!({"games": game_options, "colours": COLOURS})); let context = Context::new_with(
"Visualizer",
json!({"games": game_options, "colours": COLOURS}),
);
Template::render("visualizer", &context) Template::render("visualizer", &context)
} }
/// Fuels all routes /// Fuels all routes
pub fn fuel(routes: &mut Vec<Route>) { pub fn fuel(routes: &mut Vec<Route>) {
routes.extend(routes![files, index, builder_get, visualizer_get, debug_get]); routes.extend(routes![
files,
index,
builder_get,
visualizer_get,
debug_get
]);
lobby::fuel(routes); lobby::fuel(routes);
maps::fuel(routes); maps::fuel(routes);
info::fuel(routes); info::fuel(routes);

View file

@ -171,7 +171,6 @@ impl Context<()> {
} }
} }
/// Games is the game manager wrapper so Rocket can manage it /// Games is the game manager wrapper so Rocket can manage it
pub struct Games { pub struct Games {
inner: Arc<Mutex<Vec<(String, u64)>>>, inner: Arc<Mutex<Vec<(String, u64)>>>,