forked from deadvey/button
94 lines
2.5 KiB
HTML
94 lines
2.5 KiB
HTML
<!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_-]+$");
|
|
const ws = new WebSocket('ws://localhost:8084/ws');
|
|
console.log(name)
|
|
let latestMessage = 0;
|
|
ws.onopen = (event) => {
|
|
let name = validate_data(prompt("Nickname for the leaderboard"));
|
|
ws.send(name);
|
|
}
|
|
const ws_leaderboard = new WebSocket('ws://localhost:8084/ws-leaderboard');
|
|
ws_leaderboard.onopen = (event) => {
|
|
ws_leaderboard.send("1");
|
|
};
|
|
ws_leaderboard.onmessage = (event) => {
|
|
console.log(event.data);
|
|
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);
|
|
};
|
|
ws.onmessage = (event) => {
|
|
console.log(event.data);
|
|
latestMessage = validate_data(event.data);
|
|
}
|
|
function send_click()
|
|
{
|
|
ws.send("");
|
|
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>
|