-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
275 lines (228 loc) · 6.61 KB
/
script.js
File metadata and controls
275 lines (228 loc) · 6.61 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// @ts-check
const symbols = ["⚡", "💎", "🔥", "🚀", "🌟", "🍀", "🎵", "⚓"];
let cards = [...symbols, ...symbols]; // Duplicating for pairs
/** @type {HTMLElement | null} */
let firstCard = null;
/** @type {HTMLElement | null} */
let secondCard = null;
let lockBoard = false;
let moves = 0;
let matchesFound = 0;
/** @type {number | null} */
let timerInterval = null;
let seconds = 0;
let gameStarted = false;
/**
* Gets element by ID and throws if missing
* @param {string} id
* @returns {HTMLElement}
*/
function getElement(id) {
const el = document.getElementById(id);
if (!el) throw new Error(`Missing element: ${id}`);
return el;
}
const board = getElement("gameBoard");
const movesDisplay = getElement("moves");
const timeDisplay = getElement("time");
const winModal = getElement("winModal");
const historyModal = getElement("historyModal");
const historyBody = getElement("historyBody");
/** Initialize Game */
function initGame() {
// Reset state
board.innerHTML = "";
moves = 0;
matchesFound = 0;
seconds = 0;
gameStarted = false;
lockBoard = false;
firstCard = null;
secondCard = null;
if (timerInterval !== null) {
clearInterval(timerInterval);
timerInterval = null;
}
// UI Reset
movesDisplay.innerText = moves.toString();
timeDisplay.innerText = "00:00";
winModal.classList.remove("visible");
// Shuffle
cards.sort(() => 0.5 - Math.random());
// Create Cards
cards.forEach((symbol) => {
const cardElement = document.createElement("div");
cardElement.classList.add("card");
cardElement.dataset.symbol = symbol;
cardElement.innerHTML = `
<div class="card-face card-front"></div>
<div class="card-face card-back">${symbol}</div>
`;
cardElement.addEventListener("click", (e) => flipCard(e.currentTarget));
board.appendChild(cardElement);
});
}
function startTimer() {
if (gameStarted) return;
gameStarted = true;
timerInterval = setInterval(() => {
seconds++;
const mins = Math.floor(seconds / 60)
.toString()
.padStart(2, "0");
const secs = (seconds % 60).toString().padStart(2, "0");
timeDisplay.innerText = `${mins}:${secs}`;
}, 1000);
}
/**
* Handles card flip logic
* @param {EventTarget | null} target
*/
function flipCard(target) {
if (!(target instanceof HTMLDivElement)) return;
if (lockBoard) return;
if (target === firstCard) return;
startTimer();
target.classList.add("flipped");
if (!firstCard) {
firstCard = target;
return;
}
secondCard = target;
incrementMoves();
checkForMatch();
}
function incrementMoves() {
moves++;
movesDisplay.innerText = moves.toString();
}
function checkForMatch() {
if (!firstCard || !secondCard) return;
let isMatch = firstCard.dataset.symbol === secondCard.dataset.symbol;
isMatch ? disableCards() : unflipCards();
}
function disableCards() {
if (!firstCard || !secondCard) return;
firstCard.classList.add("matched");
secondCard.classList.add("matched");
resetBoard();
matchesFound++;
if (matchesFound === symbols.length) {
setTimeout(endGame, 500);
}
}
function unflipCards() {
lockBoard = true;
setTimeout(() => {
if (!firstCard || !secondCard) return;
firstCard.classList.remove("flipped");
secondCard.classList.remove("flipped");
resetBoard();
}, 1000);
}
function resetBoard() {
[firstCard, secondCard, lockBoard] = [null, null, false];
}
function endGame() {
if (timerInterval !== null) {
clearInterval(timerInterval);
timerInterval = null;
}
getElement("finalTime").innerText = timeDisplay.innerText;
getElement("finalMoves").innerText = moves.toString();
saveToHistory(); // Save the score
winModal.classList.add("visible");
triggerConfetti();
}
function restartGame() {
initGame();
}
// --- HISTORY LOGIC --- //
/** @returns {{moves:number, timeStr:string, seconds:number, date:string}[]} */
function getHistory() {
const localHistory = localStorage.getItem("neonMemoryHistory");
if (!localHistory) return [];
return JSON.parse(localHistory);
}
function saveToHistory() {
let history = getHistory();
const newRecord = {
moves: moves,
timeStr: timeDisplay.innerText,
seconds: seconds,
date: new Date().toLocaleDateString(undefined, { month: "short", day: "numeric" }),
};
history.push(newRecord);
// Sort by lowest moves, then lowest time
history.sort((a, b) => a.moves - b.moves || a.seconds - b.seconds);
// Keep only top 5 scores
history = history.slice(0, 5);
localStorage.setItem("neonMemoryHistory", JSON.stringify(history));
}
function showHistory() {
let history = getHistory();
historyBody.innerHTML = "";
if (history.length === 0) {
historyBody.innerHTML = `<tr><td colspan="4">No games played yet.</td></tr>`;
} else {
history.forEach((record, index) => {
const row = `
<tr>
<td>#${index + 1}</td>
<td>${record.moves}</td>
<td>${record.timeStr}</td>
<td>${record.date}</td>
</tr>
`;
historyBody.innerHTML += row;
});
}
historyModal.classList.add("visible");
}
function closeHistory() {
historyModal.classList.remove("visible");
}
function clearHistory() {
if (confirm("Are you sure you want to clear your high scores?")) {
localStorage.removeItem("neonMemoryHistory");
showHistory(); // Refresh the modal view
}
}
// --- CONFETTI LOGIC --- //
function triggerConfetti() {
const canvas = /** @type {HTMLCanvasElement} */ (getElement("confetti"));
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/** @type {{x:number, y:number, vx:number, vy:number, color:string}[]} */
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height - canvas.height,
vx: Math.random() * 4 - 2,
vy: Math.random() * 4 + 2,
color: `hsl(${Math.random() * 360}, 100%, 50%)`,
});
}
function draw() {
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
let active = false;
particles.forEach((p) => {
p.x += p.vx;
p.y += p.vy;
if (p.y <= canvas.height) active = true;
ctx.fillStyle = p.color;
ctx.fillRect(p.x, p.y, 8, 8);
});
if (active && winModal.classList.contains("visible")) {
requestAnimationFrame(draw);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
draw();
}
// Initialize on load
document.addEventListener("DOMContentLoaded", initGame);