loscores and pingscores tables
This commit is contained in:
+80
-12
@@ -4,6 +4,7 @@ use axum::{
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use axum::extract::State;
|
||||
use rand::random_bool;
|
||||
use futures::stream::StreamExt;
|
||||
@@ -14,6 +15,7 @@ use std::fs;
|
||||
use std::io::Write;
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Mutex, Arc};
|
||||
use tokio::time::{sleep,Duration};
|
||||
use regex::Regex;
|
||||
|
||||
#[derive(Deserialize,Serialize,Debug,Ord,Eq,PartialEq,PartialOrd,Clone)]
|
||||
@@ -25,8 +27,10 @@ struct Entry
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
tx: mpsc::Sender<Entry>,
|
||||
tx: mpsc::Sender<(Entry,u8)>,
|
||||
hiscores: Arc<Mutex<Vec<Entry>>>,
|
||||
loscores: Arc<Mutex<Vec<Entry>>>,
|
||||
pingscores: Arc<Mutex<HashMap<String,u64>>>,
|
||||
}
|
||||
|
||||
static CHANCE: f64 = 1.0/3.0;
|
||||
@@ -35,17 +39,37 @@ static CHANCE: f64 = 1.0/3.0;
|
||||
async fn main() {
|
||||
let file_contents: String = fs::read_to_string("hiscores.json").unwrap();
|
||||
let hiscores: Arc<Mutex<Vec<Entry>>> = Arc::new(Mutex::new(serde_json::from_str(&file_contents).unwrap()));
|
||||
let file_contents: String = fs::read_to_string("loscores.json").unwrap();
|
||||
let loscores: Arc<Mutex<Vec<Entry>>> = Arc::new(Mutex::new(serde_json::from_str(&file_contents).unwrap()));
|
||||
let file_contents: String = fs::read_to_string("pingscores.json").unwrap();
|
||||
let pingscores: Arc<Mutex<HashMap<String,u64>>> = Arc::new(Mutex::new(serde_json::from_str(&file_contents).unwrap()));
|
||||
let hiscore_clone1 = Arc::clone(&hiscores);
|
||||
let loscore_clone1 = Arc::clone(&loscores);
|
||||
let pingscore_clone1 = Arc::clone(&pingscores);
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Entry>();
|
||||
let (tx, rx) = mpsc::channel::<(Entry,u8)>();
|
||||
|
||||
tokio::spawn(
|
||||
async move {
|
||||
handle_hiscores(rx, hiscore_clone1);
|
||||
handle_hiscores(rx, hiscore_clone1, loscore_clone1, pingscore_clone1);
|
||||
}
|
||||
);
|
||||
let pingscore_clone2 = Arc::clone(&pingscores);
|
||||
tokio::spawn(
|
||||
async move {
|
||||
loop // write pingscores every 30s
|
||||
{
|
||||
sleep(Duration::from_millis(30000)).await;
|
||||
let pingscores = pingscore_clone2.lock().unwrap();
|
||||
let file_contents: String = serde_json::to_string(&pingscores.clone()).unwrap();
|
||||
drop(pingscores);
|
||||
let mut file = fs::OpenOptions::new().write(true).truncate(true).open("pingscores.json").unwrap();
|
||||
file.write_all(file_contents.as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let state = AppState { tx,hiscores: Arc::clone(&hiscores) };
|
||||
let state = AppState { tx,hiscores: Arc::clone(&hiscores),loscores: Arc::clone(&loscores), pingscores: Arc::clone(&pingscores)};
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/ws", get(ws_handler))
|
||||
@@ -68,7 +92,8 @@ async fn index() -> Html<&'static str> {
|
||||
async fn leaderboard() -> Html<&'static str> {
|
||||
Html(include_str!("../leaderboard.html"))
|
||||
}
|
||||
fn handle_hiscores(rx: mpsc::Receiver<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>>>)
|
||||
// receiver: 0 for hiscore, 1 for loscore, 2 for pingscore
|
||||
fn handle_hiscores(rx: mpsc::Receiver<(Entry, u8)>, hiscores_arc: Arc<Mutex<Vec<Entry>>>, loscores_arc: Arc<Mutex<Vec<Entry>>>,pingscores_arc: Arc<Mutex<HashMap<String,u64>>>,)
|
||||
{
|
||||
// Panic galore
|
||||
let mut hiscores = hiscores_arc.lock().unwrap();
|
||||
@@ -83,11 +108,11 @@ fn handle_hiscores(rx: mpsc::Receiver<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>
|
||||
{
|
||||
match rx.recv()
|
||||
{
|
||||
Ok(new_entry) =>
|
||||
Ok((new_entry,0)) =>
|
||||
{
|
||||
let mut hiscores = hiscores_arc.lock().unwrap();
|
||||
if new_entry.score > hiscores[19].score {
|
||||
println!("New leaderboard {new_entry:?}");
|
||||
println!("New hiscore {new_entry:?}");
|
||||
hiscores.push(new_entry);
|
||||
hiscores.sort();
|
||||
hiscores.reverse();
|
||||
@@ -99,6 +124,30 @@ fn handle_hiscores(rx: mpsc::Receiver<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>
|
||||
file.flush().unwrap();
|
||||
}
|
||||
},
|
||||
Ok((new_entry,1)) =>
|
||||
{
|
||||
let mut loscores = loscores_arc.lock().unwrap();
|
||||
if new_entry.score > loscores[19].score {
|
||||
println!("New loscore {new_entry:?}");
|
||||
loscores.push(new_entry);
|
||||
loscores.sort();
|
||||
loscores.reverse();
|
||||
loscores.truncate(20);
|
||||
let file_contents: String = serde_json::to_string(&loscores.clone()).unwrap();
|
||||
drop(loscores);
|
||||
let mut file = fs::OpenOptions::new().write(true).truncate(true).open("loscores.json").unwrap();
|
||||
file.write_all(file_contents.as_bytes()).unwrap();
|
||||
file.flush().unwrap();
|
||||
}
|
||||
},
|
||||
Ok((new_entry,2)) =>
|
||||
{
|
||||
let name = new_entry.person;
|
||||
let mut pingscores = pingscores_arc.lock().unwrap();
|
||||
*pingscores.entry(name).or_insert(0) += 1;
|
||||
drop(pingscores);
|
||||
}
|
||||
Ok((_,_)) => println!("Invalid number"),
|
||||
Err(error) => println!("{error}"),
|
||||
}
|
||||
}
|
||||
@@ -111,18 +160,29 @@ async fn ws_handler(
|
||||
ws.on_upgrade(move |socket| {
|
||||
let tx = state.tx.clone();
|
||||
let hiscores = Arc::clone(&state.hiscores);
|
||||
let loscores = Arc::clone(&state.loscores);
|
||||
let pingscores = Arc::clone(&state.pingscores);
|
||||
async move {
|
||||
handle_socket(socket, tx, hiscores).await;
|
||||
handle_socket(socket, tx, hiscores, loscores, pingscores).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_socket(mut socket: WebSocket, tx: mpsc::Sender<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>>>) {
|
||||
async fn handle_socket
|
||||
(
|
||||
mut socket: WebSocket,
|
||||
tx: mpsc::Sender<(Entry,u8)>,
|
||||
hiscores_arc: Arc<Mutex<Vec<Entry>>>,
|
||||
loscores_arc: Arc<Mutex<Vec<Entry>>>,
|
||||
pingscores_arc: Arc<Mutex<HashMap<String, u64>>>,
|
||||
) {
|
||||
let mut value: u32 = 0;
|
||||
let msg =
|
||||
{
|
||||
let hiscores = hiscores_arc.lock().unwrap();
|
||||
json!({ "hiscores": &*hiscores }).to_string()
|
||||
let loscores = loscores_arc.lock().unwrap();
|
||||
let pingscores = pingscores_arc.lock().unwrap();
|
||||
json!({ "hiscores": &*hiscores, "loscores": &*loscores, "pingscores": &*pingscores}).to_string()
|
||||
};
|
||||
let name_message = socket.next().await.unwrap().unwrap();
|
||||
let name: String = match name_message
|
||||
@@ -130,7 +190,8 @@ async fn handle_socket(mut socket: WebSocket, tx: mpsc::Sender<Entry>, hiscores_
|
||||
Message::Text(text) => validate_name(text.to_string()),
|
||||
_ => "anon".to_string(),
|
||||
};
|
||||
//println!("Client connected: {name}");
|
||||
println!("Client connected: {name}");
|
||||
let mut resets: u32 = 0;
|
||||
|
||||
let _ = socket
|
||||
.send(Message::Text(msg.into()))
|
||||
@@ -140,7 +201,14 @@ async fn handle_socket(mut socket: WebSocket, tx: mpsc::Sender<Entry>, hiscores_
|
||||
match msg {
|
||||
Ok(Message::Text(_)) => {
|
||||
if random_bool(CHANCE) {
|
||||
let _ = tx.send(Entry{ person: name.clone(), score: value });
|
||||
let _ = tx.send((Entry{ person: name.clone(), score: value },0)); //hiscores
|
||||
let _ = tx.send((Entry{ person: name.clone(), score: 0 },2)); //hiscores
|
||||
if value == 0
|
||||
{
|
||||
resets += 1;
|
||||
let _ = tx.send((Entry{ person: name.clone(), score: resets },1));//loscores
|
||||
}
|
||||
else { resets = 0 };
|
||||
value = 0
|
||||
} // 1/3 chance of failing
|
||||
else { value += 1; }
|
||||
|
||||
Reference in New Issue
Block a user