-
Notifications
You must be signed in to change notification settings - Fork 0
/
end.js
43 lines (39 loc) · 1.35 KB
/
end.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const username = document.getElementById("username");
const saveScoreBtn = document.getElementById("saveScoreBtn");
const finalScore = document.getElementById("finalScore");
const mostRecentScore = localStorage.getItem("mostRecentScore");
const highScores = JSON.parse(localStorage.getItem("highScores")) || [];
const MAX_HIGH_SCORES = 5;
// Display the most recent score
finalScore.innerText = ` ${"Your Score : "} ${mostRecentScore}`;
// Event listener for username input
username.addEventListener("input", () => {
if (username.value.trim() !== "") {
username.style.border = "1px solid green";
name_error.style.display = "none";
}
});
// Function to save the high score
saveHighScore = (e) => {
e.preventDefault();
if (username.value.trim() === "") {
username.style.border = "1px solid red";
name_error.style.display = "block";
username.focus();
} else {
username.style.border = "1px solid green";
name_error.style.display = "none";
const score = {
score: mostRecentScore,
name: username.value,
};
highScores.push(score);
// Sort the high scores array in descending order
highScores.sort((a, b) => b.score - a.score);
// Keep only the top 5 high scores
highScores.splice(5);
localStorage.setItem("highScores", JSON.stringify(highScores));
window.location.assign("/");
return true;
}
};