CpuHigherLower/game.js

68 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-04-11 13:00:03 +02:00
var cpuList;
var currentCpu;
var nextCpu;
2023-04-11 12:15:56 +02:00
async function main() {
await fetch('./data.json')
.then((response) => response.json())
.then((json) => cpuList = json);
2023-04-12 01:25:57 +02:00
updateLayout();
2023-04-11 12:15:56 +02:00
}
function getRandomCpu() {
2023-04-11 13:00:03 +02:00
let randomIndex = getRandomInt(0, cpuList.length)
return {
name: cpuList[randomIndex]["name"].split('@')[0],
score: cpuList[randomIndex]["cpuScore"]
}
2023-04-11 12:15:56 +02:00
}
2023-04-12 01:25:57 +02:00
function btnLowerClick() {
2023-04-12 09:00:36 +02:00
currentCpu.score < nextCpu.score ? showResult(true) : showResult(false);
2023-04-12 01:25:57 +02:00
}
function btnHigherClick() {
2023-04-12 09:00:36 +02:00
currentCpu.score > nextCpu.score ? showResult(true) : showResult(false);
2023-04-12 01:25:57 +02:00
}
function showResult(isCorrect) {
2023-04-12 09:00:36 +02:00
document.getElementById("col2").style.backgroundColor = isCorrect ? "lightgreen" : "#FF4444";
document.getElementById("nextCpuScore").innerHTML = nextCpu.score.toString();
countUp();
2023-04-12 01:25:57 +02:00
}
function updateLayout() {
currentCpu = getRandomCpu();
document.getElementById("currentCpuTitle").innerText = currentCpu.name;
// add "." to large numbers
document.getElementById("currentCpuScore").innerText = currentCpu.score.toString().length > 3 ? currentCpu.score.toString().slice(0, currentCpu.score.toString().length - 3) + "." + currentCpu.score.toString().slice(currentCpu.score.toString().length - 3) : currentCpu.score;
nextCpu = getRandomCpu();
document.getElementById("nextCpuTitle").innerText = nextCpu.name;
}
2023-04-12 09:00:36 +02:00
async function countUp() {
document.getElementById("btnHigher").setAttribute("disabled", "");
document.getElementById("btnLower").setAttribute("disabled", "");
const options = {
startVal: 7000,
separator: '.',
decimal: ',',
};
let counter = new CountUp('nextCpuScore', nextCpu.score, options);
if (!counter.error) {
await counter.start();
} else {
counter.error(demo.error);
}
}
2023-04-11 13:00:03 +02:00
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
2023-04-11 12:15:56 +02:00
main();