From 631f5e484f261fb68d2b5e8bbeb5a2056477d862 Mon Sep 17 00:00:00 2001 From: Marcel Schwarz Date: Wed, 12 Apr 2023 15:14:01 +0200 Subject: [PATCH] Implement high-score function --- game.html | 1 + game.js | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/game.html b/game.html index fba5b75..2d31a3b 100644 --- a/game.html +++ b/game.html @@ -41,6 +41,7 @@
Current Score: 0
+
Personal Highscore: 0
diff --git a/game.js b/game.js index 5a62ad0..6a3aa1d 100644 --- a/game.js +++ b/game.js @@ -6,6 +6,15 @@ var nextCpu; // current user score var score; +var highscore; + +function setHighscore(score) { + const currHighscore = localStorage.getItem("highscore_cpu") + if (currHighscore < score) { + localStorage.setItem("highscore_cpu", score) + highscore = score + } +} export async function main() { await fetch('./data.json') @@ -15,6 +24,7 @@ export async function main() { currentCpu = getRandomCpu(); nextCpu = getRandomCpu(); score = 0; + highscore = localStorage.getItem("highscore_cpu") ?? 0 updateLayout(); } @@ -39,6 +49,9 @@ function showResult(isCorrect) { document.getElementById("btnLower").setAttribute("disabled", ""); document.getElementById("col2").style.backgroundColor = isCorrect ? "lightgreen" : "#FF4444"; + if (!isCorrect) { + setHighscore(score) + } score = isCorrect ? score + 1 : 0; document.getElementById("score").innerText = score; @@ -47,6 +60,7 @@ function showResult(isCorrect) { // updates view based on the cpu objects function updateLayout() { + document.getElementById("highscore").innerText = highscore; document.getElementById("currentCpuTitle").innerText = currentCpu.name; // add "." to large numbers document.getElementById("currentCpuScore").innerText = new Intl.NumberFormat().format(currentCpu.score)