forked from deadvey/button
initial
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
Generated
+1236
File diff suppressed because it is too large
Load Diff
+14
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "button"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = {version="0.8.9",features=["ws"]}
|
||||||
|
futures = "0.3.32"
|
||||||
|
rand = "0.10.1"
|
||||||
|
regex = "1.12.3"
|
||||||
|
serde = {version="1.0.228",features=["derive"]}
|
||||||
|
serde_json = "1.0.149"
|
||||||
|
tokio = {version="1.52.3",features=["full"]}
|
||||||
|
tower-http = {version="0.6.11",features=["fs"]}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
[{"score":60,"person":"error"},{"score":57,"person":"deadvey"},{"score":53,"person":"error"},{"score":51,"person":"error"},{"score":51,"person":"deadvey"},{"score":50,"person":"error"},{"score":49,"person":"error"},{"score":49,"person":"error"},{"score":49,"person":"deadvey"},{"score":48,"person":"error"},{"score":48,"person":"error"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":48,"person":"deadvey"},{"score":47,"person":"error"},{"score":47,"person":"error"}]
|
||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Each time you press the button there's a 1/3 chance of returning to 0</h1>
|
||||||
|
<button id="button" onclick="send_click()">0</button>
|
||||||
|
<div id="score-table"></div>
|
||||||
|
</body>
|
||||||
|
<style>
|
||||||
|
#button {
|
||||||
|
background-color: red;
|
||||||
|
border: darkred solid 15px;
|
||||||
|
border-radius: 50%;
|
||||||
|
font-size: 50px;
|
||||||
|
padding: 100px;
|
||||||
|
width: 300px;
|
||||||
|
height: 300px;
|
||||||
|
font-family: monospace, arial;
|
||||||
|
}
|
||||||
|
#button:active {
|
||||||
|
background-color: red;
|
||||||
|
border: red solid 20px;
|
||||||
|
}
|
||||||
|
#score-table {
|
||||||
|
position: absolute;
|
||||||
|
top: 0px;
|
||||||
|
right: 0px;
|
||||||
|
}
|
||||||
|
td,tr,table,th {
|
||||||
|
border: black solid;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
const regex = new RegExp("^[a-zA-Z0-9_-]+$");
|
||||||
|
let name = validate_data(prompt("Nickname for the leaderboard"));
|
||||||
|
console.log(name)
|
||||||
|
const ws = new WebSocket('ws://deadvey.com:8084/ws');
|
||||||
|
ws.onopen = (event) => {
|
||||||
|
ws.send(name);
|
||||||
|
};
|
||||||
|
let firstMessage = true;
|
||||||
|
let latestMessage = 0;
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
console.log(event.data);
|
||||||
|
if (firstMessage) {
|
||||||
|
firstMessage = false;
|
||||||
|
data = JSON.parse(event.data);
|
||||||
|
const tableDiv = document.getElementById("score-table");
|
||||||
|
const table = document.createElement("table");
|
||||||
|
// Add header row
|
||||||
|
table.innerHTML = `<tr><th>Rank</th><th>Score</th><th>Name</th><th>P</th></tr>`;
|
||||||
|
// Add data rows concisely using forEach
|
||||||
|
data.hiscores.forEach((entry, index) => {
|
||||||
|
table.innerHTML += `<tr>
|
||||||
|
<td>#${index + 1}</td>
|
||||||
|
<td>${validate_data(entry.score)}</td>
|
||||||
|
<td>${validate_data(entry.person)}</td>
|
||||||
|
<td>${((2/3)**validate_data(entry.score)).toExponential(2)}</td>
|
||||||
|
</tr>`;
|
||||||
|
});
|
||||||
|
tableDiv.appendChild(table);
|
||||||
|
}
|
||||||
|
else { latestMessage = validate_data(event.data); }
|
||||||
|
};
|
||||||
|
function send_click()
|
||||||
|
{
|
||||||
|
ws.send(true);
|
||||||
|
if (latestMessage !== null) {
|
||||||
|
document.getElementById("button").textContent=latestMessage;
|
||||||
|
latestMessage = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function get_rand(min, max) {
|
||||||
|
return Math.round(Math.random() * (max - min) + min);
|
||||||
|
}
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
ws.close();
|
||||||
|
});
|
||||||
|
function validate_data(data) { // Only allow a-z, A-Z, 0-9, - and _ characters, sorry Ramón
|
||||||
|
if (regex.test(data)) { return data }
|
||||||
|
else { return "anon" }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<h1>Each time you press the button there's a 1/3 chance of returning to 0</h1>
|
||||||
|
<button id="button" onclick="send_click()">0</button>
|
||||||
|
<div id="score-table"></div>
|
||||||
|
</body>
|
||||||
|
<style>
|
||||||
|
#button {
|
||||||
|
background-color: red;
|
||||||
|
border: darkred solid 15px;
|
||||||
|
border-radius: 50%;
|
||||||
|
font-size: 50px;
|
||||||
|
padding: 100px;
|
||||||
|
width: 300px;
|
||||||
|
height: 300px;
|
||||||
|
font-family: monospace, arial;
|
||||||
|
}
|
||||||
|
#button:active {
|
||||||
|
background-color: red;
|
||||||
|
border: red solid 20px;
|
||||||
|
}
|
||||||
|
#score-table {
|
||||||
|
position: absolute;
|
||||||
|
top: 0px;
|
||||||
|
right: 0px;
|
||||||
|
}
|
||||||
|
td,tr,table,th {
|
||||||
|
border: black solid;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
const ws = new WebSocket('ws://localhost:8084/ws');
|
||||||
|
const regex = new RegExp("^[a-zA-Z0-9_-]+$");
|
||||||
|
let name = validate_data(prompt("Nickname for the leaderboard"));
|
||||||
|
ws.onopen = (event) => {
|
||||||
|
ws.send(name);
|
||||||
|
};
|
||||||
|
let firstMessage = true;
|
||||||
|
let latestMessage = 0;
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
console.log(event.data);
|
||||||
|
if (firstMessage) {
|
||||||
|
firstMessage = false;
|
||||||
|
data = JSON.parse(event.data);
|
||||||
|
const tableDiv = document.getElementById("score-table");
|
||||||
|
const table = document.createElement("table");
|
||||||
|
// Add header row
|
||||||
|
table.innerHTML = `<tr><th>Rank</th><th>Score</th><th>Name</th><th>P</th></tr>`;
|
||||||
|
// Add data rows concisely using forEach
|
||||||
|
data.hiscores.forEach((entry, index) => {
|
||||||
|
table.innerHTML += `<tr>
|
||||||
|
<td>#${index + 1}</td>
|
||||||
|
<td>${validate_data(entry.score)}</td>
|
||||||
|
<td>${validate_data(entry.person)}</td>
|
||||||
|
<td>${((2/3)**validate_data(entry.score)).toExponential(2)}</td>
|
||||||
|
</tr>`;
|
||||||
|
});
|
||||||
|
tableDiv.appendChild(table);
|
||||||
|
}
|
||||||
|
else { latestMessage = validate_data(event.data); }
|
||||||
|
};
|
||||||
|
function send_click()
|
||||||
|
{
|
||||||
|
ws.send(true);
|
||||||
|
if (latestMessage !== null) {
|
||||||
|
document.getElementById("button").textContent=latestMessage;
|
||||||
|
latestMessage = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function get_rand(min, max) {
|
||||||
|
return Math.round(Math.random() * (max - min) + min);
|
||||||
|
}
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
ws.close();
|
||||||
|
});
|
||||||
|
function validate_data(data) { // Only allow a-z, A-Z, 0-9, - and _ characters, sorry Ramón
|
||||||
|
if (regex.test(data)) { return data }
|
||||||
|
else { return "anon" }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="score-table"></div>
|
||||||
|
</body>
|
||||||
|
<style>
|
||||||
|
td,tr,table,th {
|
||||||
|
border: black solid;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
const ws = new WebSocket('ws://deadvey.com:8084/ws');
|
||||||
|
const regex = new RegExp("^[a-zA-Z0-9_-]+$");
|
||||||
|
ws.onopen = (event) => {
|
||||||
|
ws.send("");
|
||||||
|
};
|
||||||
|
let latestMessage = 0;
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
console.log(event.data);
|
||||||
|
data = JSON.parse(event.data);
|
||||||
|
const tableDiv = document.getElementById("score-table");
|
||||||
|
const table = document.createElement("table");
|
||||||
|
// Add header row
|
||||||
|
table.innerHTML = `<tr><th>Rank</th><th>Score</th><th>Name</th><th>P</th></tr>`;
|
||||||
|
// Add data rows concisely using forEach
|
||||||
|
data.hiscores.forEach((entry, index) => {
|
||||||
|
table.innerHTML += `<tr>
|
||||||
|
<td>#${index + 1}</td>
|
||||||
|
<td>${validate_data(entry.score)}</td>
|
||||||
|
<td>${validate_data(entry.person)}</td>
|
||||||
|
<td>${((2/3)**validate_data(entry.score)).toExponential(8)}</td>
|
||||||
|
</tr>`;
|
||||||
|
});
|
||||||
|
tableDiv.appendChild(table);
|
||||||
|
};
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
ws.close();
|
||||||
|
});
|
||||||
|
function validate_data(data) { // Only allow a-z, A-Z, 0-9, - and _ characters, sorry Ramón
|
||||||
|
if (regex.test(data)) { return data }
|
||||||
|
else { return "anon" }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
+180
@@ -0,0 +1,180 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::ws::{Message, WebSocket, WebSocketUpgrade},
|
||||||
|
response::{Html, IntoResponse},
|
||||||
|
routing::get,
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
use axum::extract::State;
|
||||||
|
use rand::random_bool;
|
||||||
|
use futures::stream::StreamExt;
|
||||||
|
use serde_json;
|
||||||
|
use serde_json::json;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::sync::{Mutex, Arc};
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
#[derive(Deserialize,Serialize,Debug,Ord,Eq,PartialEq,PartialOrd,Clone)]
|
||||||
|
struct Entry
|
||||||
|
{
|
||||||
|
score: u32,
|
||||||
|
person: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct AppState {
|
||||||
|
tx: mpsc::Sender<Entry>,
|
||||||
|
hiscores: Arc<Mutex<Vec<Entry>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static CHANCE: f64 = 1.0/3.0;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
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 hiscore_clone1 = Arc::clone(&hiscores);
|
||||||
|
|
||||||
|
let (tx, rx) = mpsc::channel::<Entry>();
|
||||||
|
|
||||||
|
tokio::spawn(
|
||||||
|
async move {
|
||||||
|
handle_hiscores(rx, hiscore_clone1);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let state = AppState { tx,hiscores: Arc::clone(&hiscores) };
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/", get(index))
|
||||||
|
.route("/ws", get(ws_handler))
|
||||||
|
.route("/leaderboard", get(leaderboard))
|
||||||
|
.with_state(state);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("0.0.0.0:8084")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
println!("http://0.0.0.0:8084");
|
||||||
|
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn index() -> Html<&'static str> {
|
||||||
|
Html(include_str!("../index.html"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn leaderboard() -> Html<&'static str> {
|
||||||
|
Html(include_str!("../leaderboard.html"))
|
||||||
|
}
|
||||||
|
fn handle_hiscores(rx: mpsc::Receiver<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>>>)
|
||||||
|
{
|
||||||
|
// Panic galore
|
||||||
|
let mut hiscores = hiscores_arc.lock().unwrap();
|
||||||
|
hiscores.sort();
|
||||||
|
hiscores.reverse();
|
||||||
|
let file_contents: String = serde_json::to_string(&hiscores.clone()).unwrap();
|
||||||
|
drop(hiscores);
|
||||||
|
let mut file = fs::OpenOptions::new().write(true).truncate(true).open("hiscores.json").unwrap();
|
||||||
|
file.write_all(file_contents.as_bytes()).unwrap();
|
||||||
|
file.flush().unwrap();
|
||||||
|
loop
|
||||||
|
{
|
||||||
|
match rx.recv()
|
||||||
|
{
|
||||||
|
Ok(new_entry) =>
|
||||||
|
{
|
||||||
|
let mut hiscores = hiscores_arc.lock().unwrap();
|
||||||
|
if new_entry.score > hiscores[19].score {
|
||||||
|
println!("New leaderboard {new_entry:?}");
|
||||||
|
hiscores.push(new_entry);
|
||||||
|
hiscores.sort();
|
||||||
|
hiscores.reverse();
|
||||||
|
hiscores.truncate(20);
|
||||||
|
let file_contents: String = serde_json::to_string(&hiscores.clone()).unwrap();
|
||||||
|
drop(hiscores);
|
||||||
|
let mut file = fs::OpenOptions::new().write(true).truncate(true).open("hiscores.json").unwrap();
|
||||||
|
file.write_all(file_contents.as_bytes()).unwrap();
|
||||||
|
file.flush().unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(error) => println!("{error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ws_handler(
|
||||||
|
ws: WebSocketUpgrade,
|
||||||
|
State(state): State<AppState>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
ws.on_upgrade(move |socket| {
|
||||||
|
let tx = state.tx.clone();
|
||||||
|
let hiscores = Arc::clone(&state.hiscores);
|
||||||
|
async move {
|
||||||
|
handle_socket(socket, tx, hiscores).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_socket(mut socket: WebSocket, tx: mpsc::Sender<Entry>, hiscores_arc: Arc<Mutex<Vec<Entry>>>) {
|
||||||
|
let mut value: u32 = 0;
|
||||||
|
let msg =
|
||||||
|
{
|
||||||
|
let hiscores = hiscores_arc.lock().unwrap();
|
||||||
|
json!({ "hiscores": &*hiscores }).to_string()
|
||||||
|
};
|
||||||
|
let name_message = socket.next().await.unwrap().unwrap();
|
||||||
|
let name: String = match name_message
|
||||||
|
{
|
||||||
|
Message::Text(text) => validate_name(text.to_string()),
|
||||||
|
_ => "anon".to_string(),
|
||||||
|
};
|
||||||
|
//println!("Client connected: {name}");
|
||||||
|
|
||||||
|
let _ = socket
|
||||||
|
.send(Message::Text(msg.into()))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
while let Some(msg) = socket.next().await {
|
||||||
|
match msg {
|
||||||
|
Ok(Message::Text(_)) => {
|
||||||
|
if random_bool(CHANCE) {
|
||||||
|
let _ = tx.send(Entry{ person: name.clone(), score: value });
|
||||||
|
value = 0
|
||||||
|
} // 1/3 chance of failing
|
||||||
|
else { value += 1; }
|
||||||
|
let _ = socket.send(Message::Text(value.to_string().into())).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Message::Close(_)) => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fn validate_name(input: String) -> String {
|
||||||
|
let input = input.trim();
|
||||||
|
if input == "null"
|
||||||
|
{
|
||||||
|
return "anon".to_string();
|
||||||
|
}
|
||||||
|
// Length check
|
||||||
|
if input.is_empty() || input.len() > 32 {
|
||||||
|
return "anon".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow only letters, numbers, _ and -
|
||||||
|
let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
|
||||||
|
|
||||||
|
if re.is_match(input) {
|
||||||
|
input.to_string()
|
||||||
|
} else {
|
||||||
|
"anon".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user