Persist and display high score

This commit is contained in:
Daddy32
2025-12-12 12:20:01 +01:00
parent 1759cf2fdf
commit a3be004c12
2 changed files with 31 additions and 0 deletions

28
main.js
View File

@@ -26,6 +26,7 @@
const minLinkEl = document.getElementById("min-link");
const paletteLegendEl = document.getElementById("palette-legend");
const scoreEl = document.getElementById("score");
const highScoreEl = document.getElementById("high-score");
const gameOverEl = document.getElementById("game-over");
const finalScoreEl = document.getElementById("final-score");
const restartBtn = document.getElementById("restart-btn");
@@ -87,9 +88,30 @@
const balls = [];
let spawnTimer = null;
let score = 0;
let highScore = 0;
let gameOver = false;
let isPaused = false;
const STORAGE_KEY = "physilinks-highscore";
const loadHighScore = () => {
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = parseInt(raw, 10);
return Number.isFinite(parsed) ? parsed : 0;
} catch (err) {
return 0;
}
};
const saveHighScore = () => {
try {
localStorage.setItem(STORAGE_KEY, String(highScore));
} catch (err) {
// ignore write failures (private mode or blocked storage)
}
};
const chain = {
active: false,
color: null,
@@ -258,6 +280,10 @@
if (chain.bodies.length >= config.minChain) {
const gain = 10 * Math.pow(chain.bodies.length, 2);
score += gain;
if (score > highScore) {
highScore = score;
saveHighScore();
}
spawnScorePopup(releasePoint || chain.pointer, gain, chain.color);
chain.constraints.forEach((c) => World.remove(world, c));
chain.bodies.forEach((body) => {
@@ -365,6 +391,7 @@
minLinkEl.textContent = config.minChain;
chainLenEl.textContent = chain.bodies.length;
scoreEl.textContent = score;
highScoreEl.textContent = highScore;
if (chain.color) {
activeColorEl.textContent = "";
activeColorEl.style.display = "inline-block";
@@ -447,6 +474,7 @@
setPaused(!isPaused);
}
});
highScore = loadHighScore();
buildLegend();
updateHud();
startSpawner();