Persist and display high score
This commit is contained in:
@@ -327,6 +327,9 @@
|
||||
<div class="card">
|
||||
<strong>Score</strong> <span id="score">0</span>
|
||||
</div>
|
||||
<div class="card">
|
||||
<strong>High score</strong> <span id="high-score">0</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
Click or touch a ball to start a chain. Drag through balls of
|
||||
|
||||
28
main.js
28
main.js
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user