http: new_game and get_game demo

This commit is contained in:
2024-01-30 07:06:30 +01:00
parent a0edf8f87e
commit f5820656c3
4 changed files with 54 additions and 5 deletions

View File

@@ -7,7 +7,7 @@ use rand::distributions::WeightedIndex;
use rand::prelude::*;
#[derive(Serialize, Deserialize)]
struct GameState {
pub struct GameState {
n_players: usize,
current_player: usize,
starting_player: usize,
@@ -21,10 +21,10 @@ struct GameState {
players: Vec<Player>,
#[serde(skip)]
#[serde(default = "make_rng")]
rng: Box<dyn RngCore>,
rng: Box<dyn RngCore + Send>,
}
fn make_rng() -> Box<dyn RngCore> {
fn make_rng() -> Box<dyn RngCore + Send> {
Box::new(StdRng::from_entropy())
}

View File

@@ -1,15 +1,50 @@
use rocket::response::status::NotFound;
use rocket::serde::{json::Json, Serialize};
use rocket::State;
#[macro_use]
extern crate rocket;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
mod azul;
#[derive(Default)]
struct SharedState {
games: Arc<Mutex<HashMap<uuid::Uuid, azul::GameState>>>,
}
#[get("/")]
fn index() -> String {
"Hello, world!".to_string()
}
#[get("/game/<id>")]
fn get_game(
id: uuid::Uuid,
shared: &State<SharedState>,
) -> Result<Json<azul::GameState>, NotFound<&'static str>> {
let games = shared.games.lock().unwrap();
let game = games.get(&id).ok_or(NotFound("Game not found"))?;
return Ok(Json(game.to_owned()));
}
#[get("/new_game")]
fn new_game(shared: &State<SharedState>) -> Result<Json<uuid::Uuid>, &'static str> {
let id = uuid::Uuid::new_v4();
let game = azul::GameState::new(2)?;
let mut games = shared.games.lock().unwrap();
games.insert(id, game);
return Ok(Json(id));
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
rocket::build()
.manage(SharedState::default())
.mount("/", routes![index])
.mount("/api/", routes![get_game, new_game])
}