CpuHigherLower/src/game.ts

83 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-04-21 22:41:22 +02:00
// @ts-ignore
import { CountUp } from "https://cdnjs.cloudflare.com/ajax/libs/countup.js/2.6.0/countUp.min.js";
import { Stats } from "./statistics.js";
import { CpuRepository } from "./cpuRepository.js"
2023-04-21 23:23:32 +02:00
var repo: CpuRepository;
var localStats: Stats;
2023-04-21 22:41:22 +02:00
export async function main() {
localStats = new Stats("highScore_cpu");
repo = new CpuRepository();
await repo.init();
updateLayout();
}
export function btnLowerClick() {
2023-04-21 23:23:32 +02:00
repo.nextCpu.cpuScore < repo.currentCpu.cpuScore ? showResult(true) : showResult(false);
2023-04-21 22:41:22 +02:00
}
export function btnHigherClick() {
2023-04-21 23:23:32 +02:00
repo.nextCpu.cpuScore > repo.currentCpu.cpuScore ? showResult(true) : showResult(false);
2023-04-21 22:41:22 +02:00
}
function showResult(isCorrect) {
document.getElementById("btnHigher").setAttribute("disabled", "");
document.getElementById("btnLower").setAttribute("disabled", "");
document.getElementById("col2").style.backgroundColor = isCorrect ? "lightgreen" : "#FF4444";
isCorrect ? localStats.incrementScore() : localStats.resetScore();
2023-04-21 23:23:32 +02:00
document.getElementById("highScore").innerText = localStats.highScore.toString();
document.getElementById("score").innerText = localStats.score.toString();
2023-04-21 22:41:22 +02:00
countUp();
}
// updates view based on the cpu objects
function updateLayout() {
2023-04-21 23:23:32 +02:00
document.getElementById("highScore").innerText = localStats.highScore.toString();
2023-04-21 22:41:22 +02:00
2023-04-21 23:23:32 +02:00
document.getElementById("currentCpuTitle").innerText = repo.currentCpu.name;
2023-04-21 22:41:22 +02:00
// add "." to large numbers
2023-04-21 23:23:32 +02:00
document.getElementById("currentCpuScore").innerText = new Intl.NumberFormat().format(repo.currentCpu.cpuScore)
document.getElementById("nextCpuTitle").innerText = repo.nextCpu.name;
2023-04-21 22:41:22 +02:00
document.getElementById("nextCpuScore").innerText = "?";
document.getElementById("col2").style.backgroundColor = "";
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function countUp() {
const options = {
2023-04-21 23:23:32 +02:00
startVal: repo.nextCpu.cpuScore / 2,
2023-04-21 22:41:22 +02:00
separator: '.',
decimal: ',',
duration: 2
};
2023-04-21 23:23:32 +02:00
let counter = new CountUp('nextCpuScore', repo.nextCpu.cpuScore, options);
2023-04-21 22:41:22 +02:00
if (!counter.error) {
counter.start();
} else {
console.log(counter.error);
}
await delay(2500)
nextRound();
document.getElementById("btnHigher").removeAttribute("disabled");
document.getElementById("btnLower").removeAttribute("disabled");
}
function nextRound() {
2023-04-21 23:23:32 +02:00
repo.nextRound();
2023-04-21 22:41:22 +02:00
updateLayout();
}