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 mozaic::modules::{game};
use mozaic::modules::game;
use futures::executor::ThreadPool;
use futures::future::FutureExt;
@ -39,8 +39,8 @@ mod util;
use util::Games;
use util::COLOURS;
use rocket_contrib::templates::{Template, Engines};
use rocket_contrib::templates::tera::{self, Value};
use rocket_contrib::templates::{Engines, Template};
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() {
let x = v.get("x").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 > max_x { max_x = x; }
if y < min_y { min_y = y; }
if y > max_y { max_y = y; }
if x < min_x {
min_x = x;
}
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
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

View file

@ -48,7 +48,11 @@ impl PlanetWarsGame {
log_file: file,
turns: 0,
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::Route;
use rocket_contrib::templates::Template;
@ -16,11 +16,14 @@ fn info_base() -> Redirect {
/// Renders the <page> info page
#[get("/info/<page>")]
async fn info(page: usize) -> Template {
let context = Context::new_with("info", json!({
"page": page,
"next": if page + 1 <= MAX { Some(page + 1) } else { None },
"prev": if page - 1 > 0 { Some(page - 1) } else { None }
}));
let context = Context::new_with(
"info",
json!({
"page": page,
"next": if page + 1 <= MAX { Some(page + 1) } else { None },
"prev": if page - 1 > 0 { Some(page - 1) } else { None }
}),
);
Template::render(format!("info/info_{}", page), &context)
}

View file

@ -1,7 +1,7 @@
use crate::planetwars;
use crate::util::*;
use rocket::{State, Route};
use rocket::{Route, State};
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
@ -37,7 +37,10 @@ struct GameRes {
/// Standard get function for the lobby tab
#[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 games = get_states(&state.get_games(), &gm).await?;
let context = Context::new_with("Lobby", Lobby { games, maps });
@ -46,36 +49,55 @@ async fn get_lobby(gm: State<'_, game::Manager>, state: State<'_, Games>) -> Res
/// The lobby get's this automatically on load and on refresh.
#[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 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))
}
/// Post function to create a game.
/// Returns the keys of the players in json.
#[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> {
let game = build_builder(tp.clone(), game_req.nop, game_req.max_turns, &game_req.map, &game_req.name);
#[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> {
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();
state.add_game(game_req.name.clone(), game_id);
match gm.get_state(game_id).await {
Some(Ok((state, conns))) => {
let players: Vec<u64> = conns.iter().map(|conn| match conn {
Connect::Waiting(_, key) => *key,
_ => 0,
}).collect();
let players: Vec<u64> = conns
.iter()
.map(|conn| match conn {
Connect::Waiting(_, key) => *key,
_ => 0,
})
.collect();
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()
.sample_iter(&rand::distributions::Alphanumeric)
.take(15)
.collect::<String>() + ".json"
.collect::<String>()
+ ".json"
}
/// game::Manager spawns game::Builder to start games.
@ -101,8 +124,12 @@ fn build_builder(
max_turns: max_turns,
};
let game =
planetwars::PlanetWarsGame::new(config.create_game(number_of_clients as usize), &generate_string_id(), name, map);
let game = planetwars::PlanetWarsGame::new(
config.create_game(number_of_clients as usize),
&generate_string_id(),
name,
map,
);
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]);
}
#[derive(Serialize)]
pub struct Lobby {
pub games: Vec<GameState>,

View file

@ -1,12 +1,12 @@
use serde::{Deserialize};
use serde::Deserialize;
use rocket::{Route};
use rocket_contrib::templates::Template;
use rocket::Route;
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
use async_std::prelude::*;
use async_std::fs;
use async_std::io::ReadExt;
use async_std::prelude::*;
use std::path::{Path, PathBuf};
@ -18,7 +18,7 @@ struct MapReq {
}
/// Post route to create a map.
#[post("/maps", data="<map_req>")]
#[post("/maps", data = "<map_req>")]
async fn map_post(map_req: Json<MapReq>) -> Result<String, String> {
let MapReq { name, map } = map_req.into_inner();
@ -27,8 +27,12 @@ async fn map_post(map_req: Json<MapReq>) -> Result<String, String> {
return Err("File already exists!".into());
}
let mut file = fs::File::create(path).await.map_err(|_| "IO error".to_string())?;
file.write_all(&serde_json::to_vec_pretty(&map).unwrap()).await.map_err(|_| "IO error".to_string())?;
let mut file = fs::File::create(path)
.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())
}
@ -38,13 +42,19 @@ async fn map_post(map_req: Json<MapReq>) -> Result<String, String> {
#[get("/maps/<file>")]
async fn map_get(file: String) -> Result<Template, String> {
let mut content = String::new();
let mut file = fs::File::open(Path::new("maps/").join(file)).await.map_err(|_| "IO ERROR".to_string())?;
file.read_to_string(&mut content).await.map_err(|_| "IO ERROR".to_string())?;
let mut file = fs::File::open(Path::new("maps/").join(file))
.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>) {
routes.extend(routes![map_post, map_get]);
}

View file

@ -1,21 +1,21 @@
use crate::util::*;
use crate::planetwars::FinishedState;
use crate::util::*;
use rocket::{Route};
use rocket::response::NamedFile;
use rocket::Route;
use rocket_contrib::templates::Template;
use async_std::prelude::*;
use async_std::io::BufReader;
use async_std::fs;
use async_std::io::BufReader;
use async_std::prelude::*;
use futures::stream::StreamExt;
use std::path::{Path, PathBuf};
mod info;
mod lobby;
mod maps;
mod info;
/// Handles all files located in the static folder
#[get("/<file..>", rank = 6)]
@ -48,13 +48,22 @@ async fn debug_get() -> Result<Template, String> {
#[get("/visualizer")]
async fn visualizer_get() -> Template {
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)
}
/// Fuels all routes
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);
maps::fuel(routes);
info::fuel(routes);

View file

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