Implement user js
This commit is contained in:
parent
51a47e6b5b
commit
d8af7c3ae0
@ -1,40 +1,17 @@
|
||||
"use strict"
|
||||
|
||||
function render_scoreboard(data) {
|
||||
const users = Object.values(data.users);
|
||||
const token = document.location.pathname.split("/").pop();
|
||||
const api_path = `../../api/token${token}/`;
|
||||
|
||||
users.sort((a, b) => b.score - a.score);
|
||||
const min_score = users[users.length-1].score,
|
||||
max_score = users[0].score;
|
||||
|
||||
const tbody = document.querySelector("#scoreboard tbody");
|
||||
const greeting = document.getElementById("greeting"),
|
||||
currentcoins = document.getElementById("currentcoins"),
|
||||
maxcoins = document.getElementById("maxcoins"),
|
||||
sellvalue = document.getElementById("sellvalue");
|
||||
|
||||
while (tbody.children.length) {
|
||||
tbody.removeChild(tbody.firstChild);
|
||||
}
|
||||
async function redraw() {
|
||||
|
||||
const template = document.querySelector("#scoreboard template");
|
||||
|
||||
for (const user of users) {
|
||||
|
||||
const clone = template.content.cloneNode(true);
|
||||
const name = clone.querySelector(".name"),
|
||||
score = clone.querySelector(".score"),
|
||||
bar = clone.querySelector(".bar");
|
||||
|
||||
const score_percent = Math.floor(10 + (user.score - min_score) / (max_score - min_score) * 90) + "%";
|
||||
bar.style.width = score_percent;
|
||||
|
||||
name.innerText = user.name;
|
||||
score.innerText = user.score;
|
||||
|
||||
tbody.appendChild(clone);
|
||||
}
|
||||
}
|
||||
|
||||
async function update_scoreboard() {
|
||||
|
||||
const r = await fetch('api/get_public_model', {
|
||||
const r = await fetch(api_path + 'get_user', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
@ -44,9 +21,34 @@ async function update_scoreboard() {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await r.json();
|
||||
render_scoreboard(data);
|
||||
const user = await r.json();
|
||||
|
||||
greeting.innerText = `Hey, ${user.name}`;
|
||||
currentcoins.innerText = user.score;
|
||||
maxcoins.innerText = user.maxscore;
|
||||
sellvalue.max = user.maxscore - user.score;
|
||||
|
||||
}
|
||||
|
||||
update_scoreboard();
|
||||
setInterval(update_scoreboard, 1000);
|
||||
redraw();
|
||||
|
||||
const button = document.getElementById("sell");
|
||||
|
||||
button.addEventListener("click", async () => {
|
||||
const newscore = parseInt(currentcoins.innerText) + parseInt(sellvalue.value);
|
||||
console.log(newscore);
|
||||
|
||||
const r = await fetch(api_path + 'set_score', {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
newscore: newscore,
|
||||
}),
|
||||
});
|
||||
|
||||
if (r.status !== 200) {
|
||||
console.log("something went wrong");
|
||||
return;
|
||||
}
|
||||
|
||||
redraw();
|
||||
})
|
Loading…
Reference in New Issue
Block a user