From f02f0de902e13026b1b19fd17e28c4ab9cda1ef0 Mon Sep 17 00:00:00 2001 From: zoe Date: Sun, 6 Feb 2022 13:30:35 +0100 Subject: [PATCH 1/3] add board --- src/main.rs | 38 ++++++++++---------------------------- src/plays.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 28 deletions(-) create mode 100644 src/plays.rs diff --git a/src/main.rs b/src/main.rs index 7e33826..7dd45e5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,33 +5,23 @@ extern crate lazy_static; use clap::Parser; use rocket::fs::{relative, FileServer}; -use rocket::{State, Shutdown}; -use rocket::serde::{Serialize, Deserialize}; use rocket_dyn_templates::Template; -use rocket::form::Form; -use rocket::tokio::sync::broadcast::{channel, Sender, error::RecvError}; -use rocket::response::stream::{EventStream, Event, TextStream}; +use rocket::response::stream::{EventStream, Event}; use std::{collections::HashMap, mem::drop, sync::Mutex}; mod names; mod rooms; mod templates; +mod plays; lazy_static! { static ref ARGS: Args = Args::parse(); static ref ROOMS: Mutex> = Mutex::new(HashMap::new()); + /// String is the room list + static ref PLAYS: Mutex>> = Mutex::new(HashMap::new()); } -#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] -#[serde(crate = "rocket::serde")] -struct Play { - pub roomname: String, - pub position: String, - pub player1: bool, -} - /* * Config options */ @@ -54,7 +44,7 @@ fn rocket() -> _ { rocket::custom(config) .attach(Template::fairing()) .mount("/", FileServer::from(relative!("static"))) - .mount("/", routes![index, room, stream, post]) + .mount("/", routes![index, room]) } /* @@ -124,20 +114,12 @@ async fn room(roomname: &str, token: usize, player1: bool) -> Template { } } -#[get("/stream")] -async fn stream(queue: &State>, mut end: Shutdown) -> TextStream![String]{ - let mut rx = queue.subscribe(); - TextStream! { +#[get("/stream//")] +fn stream(roomname: String, token: usize) -> EventStream![]{ + EventStream!{ loop { - yield "hello!".to_string(); + let event = plays::Board::new(roomname); + yield Event::json(&event); } } } - -/// Receive a message from a form submission and broadcast it to any receivers. -#[post("/message", data = "
")] -fn post(form: Form, queue: &State>) { - // A send 'fails' if there are no active subscribers. That's okay. - let _res = queue.send(form.into_inner()); -} - diff --git a/src/plays.rs b/src/plays.rs new file mode 100644 index 0000000..fb5a57e --- /dev/null +++ b/src/plays.rs @@ -0,0 +1,33 @@ +use rand::{thread_rng, Rng}; +use rocket::serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] +#[serde(crate = "rocket::serde")] +pub struct Play { + pub roomname: String, + #[field(validate = len(2...2))] + pub position: String, + pub player1: bool, +} + +#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] +#[serde(crate = "rocket::serde")] +pub struct Board { + pub roomname: String, + pub position: String, + pub player1: bool, +} + +impl Board { + pub fn new(rname: String) -> Board { + let rng = thread_rng(); + Board { + roomname: rname, + player1: rng.gen_bool(1.0 / 2.0), + // TODO change this!!! this doesn't make sense! i just put this here for testing + position: "".to_string(), + } + } +} From d692ace55faefa42ff59e1455b33f9bc1fe001d4 Mon Sep 17 00:00:00 2001 From: zoe Date: Sun, 6 Feb 2022 17:00:24 +0100 Subject: [PATCH 2/3] make function for adding boards to send queue --- Cargo.lock | 1 + Cargo.toml | 2 +- src/main.rs | 51 ++++++++++++++++++--- src/plays.rs | 33 -------------- src/rooms.rs | 85 +++++++++++++++++++++++++++++++++-- static/{script.js => join.js} | 0 6 files changed, 129 insertions(+), 43 deletions(-) delete mode 100644 src/plays.rs rename static/{script.js => join.js} (100%) diff --git a/Cargo.lock b/Cargo.lock index f9eb096..bb5dfbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1222,6 +1222,7 @@ dependencies = [ "rocket_codegen", "rocket_http", "serde", + "serde_json", "state", "tempfile", "time", diff --git a/Cargo.toml b/Cargo.toml index 171e42a..e7339df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rocket = "0.5.0-rc.1" +rocket = {version = "0.5.0-rc.1", features= ["json"]} lazy_static = "1.4.0" clap = { version = "3.0.6", features = ["derive"] } rocket_dyn_templates = {version="0.1.0-rc.1", features= ["handlebars"] } diff --git a/src/main.rs b/src/main.rs index 7dd45e5..b1b49d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,21 +4,22 @@ extern crate rocket; extern crate lazy_static; use clap::Parser; + use rocket::fs::{relative, FileServer}; use rocket_dyn_templates::Template; use rocket::response::stream::{EventStream, Event}; + use std::{collections::HashMap, mem::drop, sync::Mutex}; mod names; mod rooms; mod templates; -mod plays; lazy_static! { static ref ARGS: Args = Args::parse(); static ref ROOMS: Mutex> = Mutex::new(HashMap::new()); /// String is the room list - static ref PLAYS: Mutex>> = Mutex::new(HashMap::new()); + static ref PLAYS: Mutex>> = Mutex::new(HashMap::new()); } @@ -44,7 +45,7 @@ fn rocket() -> _ { rocket::custom(config) .attach(Template::fairing()) .mount("/", FileServer::from(relative!("static"))) - .mount("/", routes![index, room]) + .mount("/", routes![index, room, stream]) } /* @@ -98,7 +99,6 @@ async fn room(roomname: &str, token: usize, player1: bool) -> Template { // the room is real and the token is correct if room.token == token { drop(rooms); - //TODO: placeholder templates::get_room(roomname, token, player1) } // the room is real but the token is incorrect @@ -114,12 +114,51 @@ async fn room(roomname: &str, token: usize, player1: bool) -> Template { } } +//* +//sends new board if there have been updates +//* #[get("/stream//")] fn stream(roomname: String, token: usize) -> EventStream![]{ EventStream!{ loop { - let event = plays::Board::new(roomname); - yield Event::json(&event); + // TODO + // check if there are any new events, and then if the room token is correct + // if that's the case send the current playing board + // otherwise don't do anything + let mut i = 0; + if i == 0 { + let event = "something"; + yield Event::json(&event); + } + i += 1 } } } + + +//* +// adds new boards to the send queue after calculating move +//* +#[post("/play?&&&&")] +fn play (roomname: &str, token: usize, player1: bool, x: u8, y: u8){ + // get room mutex + let mut roomlist = ROOMS.lock().unwrap(); + // check if room is legal + if rooms::room_and_token_correct(&roomlist, &roomname, &token) { + let board = &roomlist.get_mut(roomname).unwrap().board; + if board.play_is_legal(&x, &y, &player1) { + // change the board by making a new play + board.make_play(&x, &y); + let mut playlist = PLAYS.lock().unwrap(); + // if the board doesn't exist yet, make a new one + if !(playlist.contains_key(roomname)){ + let rn = roomname.to_string(); + playlist.insert(rn, vec![]); + } + // add new board to the play queue + playlist.get_mut(roomname).unwrap().push(board.clone()); + drop(playlist); + } + } + drop(roomlist); +} diff --git a/src/plays.rs b/src/plays.rs deleted file mode 100644 index fb5a57e..0000000 --- a/src/plays.rs +++ /dev/null @@ -1,33 +0,0 @@ -use rand::{thread_rng, Rng}; -use rocket::serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] -#[serde(crate = "rocket::serde")] -pub struct Play { - pub roomname: String, - #[field(validate = len(2...2))] - pub position: String, - pub player1: bool, -} - -#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] -#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] -#[serde(crate = "rocket::serde")] -pub struct Board { - pub roomname: String, - pub position: String, - pub player1: bool, -} - -impl Board { - pub fn new(rname: String) -> Board { - let rng = thread_rng(); - Board { - roomname: rname, - player1: rng.gen_bool(1.0 / 2.0), - // TODO change this!!! this doesn't make sense! i just put this here for testing - position: "".to_string(), - } - } -} diff --git a/src/rooms.rs b/src/rooms.rs index 0c611c0..641f165 100644 --- a/src/rooms.rs +++ b/src/rooms.rs @@ -1,21 +1,100 @@ use rand::{thread_rng, Rng}; +use rocket::serde::{Deserialize, Serialize}; +use std::collections::HashMap; #[derive(Debug)] pub struct Room { pub token: usize, pub full: bool, pub play_queue: Vec, + pub board: Board, } impl Room { pub fn new() -> Room { // generate room token - let tok: usize = thread_rng().gen(); - // flip coin to see who starts + let token: usize = thread_rng().gen(); Room { full: false, - token: tok, + token, play_queue: vec![], + board: Board::new(), } } } + +pub fn room_and_token_correct( + rooms: &HashMap, + roomname: &str, + token: &usize, +) -> bool { + if rooms.contains_key(roomname) { + if &rooms.get(roomname).unwrap().token == token { + return true; + } + } + false +} + +#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] +#[serde(crate = "rocket::serde")] +pub struct Play { + pub roomname: String, + #[field(validate = len(2...2))] + pub position: String, + pub player1: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq))] +#[serde(crate = "rocket::serde")] +pub struct Board { + pub position: String, + pub player1: bool, + pub fields: Vec>, +} + +impl Board { + pub fn new() -> Board { + let mut rng = thread_rng(); + let mut fields: Vec> = vec![]; + let mut i: u8 = 0; + while i <= 8 { + let mut inner: Vec = vec![]; + let mut i_inner: u8 = 0; + while i_inner <= 8 { + inner.push(Field::new()); + i_inner += 1; + } + fields.push(inner); + i += 1; + } + Board { + player1: rng.gen_bool(1.0 / 2.0), + // TODO change this!!! this doesn't make sense! i just put this here for testing + position: "".to_string(), + fields, + } + } + pub fn make_play(&self, x: &u8, y: &u8) { + //TODO + } + pub fn play_is_legal(&self, x: &u8, y: &u8, player1: &bool) -> bool { + true + } +} + +#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] +#[serde(crate = "rocket::serde")] +pub struct Field { + owner: u8, +} + + +impl Field { + fn new() -> Field { + Field { owner: 0 } + } +} diff --git a/static/script.js b/static/join.js similarity index 100% rename from static/script.js rename to static/join.js From 58066c8abc9bdf7f0e74bb7f6442fe446d335936 Mon Sep 17 00:00:00 2001 From: zoe Date: Sun, 6 Feb 2022 18:32:36 +0100 Subject: [PATCH 3/3] oof --- src/main.rs | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index b1b49d1..d5ba36e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,10 +6,14 @@ extern crate lazy_static; use clap::Parser; use rocket::fs::{relative, FileServer}; +use rocket::response::stream::{Event, EventStream}; use rocket_dyn_templates::Template; -use rocket::response::stream::{EventStream, Event}; -use std::{collections::HashMap, mem::drop, sync::Mutex}; +use std::{ + collections::HashMap, + mem::drop, + sync::{mpsc, Mutex, RwLock}, +}; mod names; mod rooms; @@ -22,7 +26,6 @@ lazy_static! { static ref PLAYS: Mutex>> = Mutex::new(HashMap::new()); } - /* * Config options */ @@ -45,7 +48,7 @@ fn rocket() -> _ { rocket::custom(config) .attach(Template::fairing()) .mount("/", FileServer::from(relative!("static"))) - .mount("/", routes![index, room, stream]) + .mount("/", routes![index, room, stream, play]) } /* @@ -118,29 +121,25 @@ async fn room(roomname: &str, token: usize, player1: bool) -> Template { //sends new board if there have been updates //* #[get("/stream//")] -fn stream(roomname: String, token: usize) -> EventStream![]{ - EventStream!{ +async fn stream(roomname: String, token: usize) -> EventStream![] { + let roomlist = ROOMS.lock().unwrap(); + drop(roomlist); + EventStream! { loop { // TODO // check if there are any new events, and then if the room token is correct // if that's the case send the current playing board // otherwise don't do anything - let mut i = 0; - if i == 0 { - let event = "something"; - yield Event::json(&event); - } - i += 1 + yield Event::json(&"oof".to_string()); } } } - //* // adds new boards to the send queue after calculating move //* #[post("/play?&&&&")] -fn play (roomname: &str, token: usize, player1: bool, x: u8, y: u8){ +fn play(roomname: &str, token: usize, player1: bool, x: u8, y: u8) { // get room mutex let mut roomlist = ROOMS.lock().unwrap(); // check if room is legal @@ -151,7 +150,7 @@ fn play (roomname: &str, token: usize, player1: bool, x: u8, y: u8){ board.make_play(&x, &y); let mut playlist = PLAYS.lock().unwrap(); // if the board doesn't exist yet, make a new one - if !(playlist.contains_key(roomname)){ + if !(playlist.contains_key(roomname)) { let rn = roomname.to_string(); playlist.insert(rn, vec![]); }