forked from deadvey/button
219f4086aa
removed the uncessesary null check in the validate_name
92 lines
2.6 KiB
HTML
92 lines
2.6 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<link rel="stylesheet" href="/index.css" />
|
|
</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>
|
|
<script src="/address.js"> </script>
|
|
<script>
|
|
let score = 0;
|
|
let locally = false;
|
|
// get the username
|
|
let name = validate_data(prompt("Nickname for the leaderboard\nOnly alphanumeric, - or _ please\nPress cancel to just play locally.","anon") ?? set_local());
|
|
let ws = "local";
|
|
if (!locally)
|
|
{
|
|
ws = new WebSocket(`ws://${ADDRESS}:8084/ws`);
|
|
};
|
|
ws.onopen = (event) => {
|
|
if (!locally) { ws.send(name); };
|
|
}
|
|
ws.onmessage = (event) => {
|
|
console.log(event.data);
|
|
score = validate_data(event.data);
|
|
}
|
|
|
|
const ws_leaderboard = new WebSocket(`ws://${ADDRESS}:8084/ws-leaderboard`); // download the 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);
|
|
};
|
|
function send_click()
|
|
{
|
|
if (!locally)
|
|
{
|
|
ws.send("");
|
|
if (score !== null)
|
|
{
|
|
document.getElementById("button").textContent=score;
|
|
score = null;
|
|
}
|
|
}
|
|
else // locally = true
|
|
{
|
|
if (Math.random() < (1/3)) { score = 0; } // fail
|
|
else { score += 1; } // success
|
|
document.getElementById("button").textContent=score;
|
|
|
|
}
|
|
}
|
|
function set_local()
|
|
{
|
|
score = 0
|
|
locally = true
|
|
return "anon"
|
|
}
|
|
function get_rand(min, max) {
|
|
return Math.round(Math.random() * (max - min) + min);
|
|
}
|
|
window.addEventListener('beforeunload', () => {
|
|
ws.close();
|
|
}, !locally);
|
|
function validate_data(data) { // Only allow a-z, A-Z, 0-9, - and _ characters, sorry Ramón
|
|
const regex = new RegExp("^[a-zA-Z0-9_-]+$");
|
|
if (regex.test(data)) { return data }
|
|
else { return "anon" }
|
|
}
|
|
</script>
|
|
</html>
|