-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (66 loc) · 1.96 KB
/
script.js
File metadata and controls
85 lines (66 loc) · 1.96 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
const gameBoard = document.getElementById("game-board");
const restartBtn = document.getElementById("restart-btn");
const icons = ["🧠", "☕️", "💻", "💡", "🩷", "🥡", "🍔", "🍟"];
let cards = [...icons, ...icons];
function shuffle(array) {
return array.sort(() => Math.random() - 0.5);
}
function createBoard() {
gameBoard.innerHTML = "";
shuffle(cards).forEach(icon => {
const card = document.createElement("div");
card.classList.add("card");
card.textContent = icon;
card.dataset.icon = icon;
card.addEventListener("click", flipCard);
gameBoard.appendChild(card);
})
}
createBoard();
let flippedCards = [];
let lockBoard = false;
function flipCard() {
if(lockBoard || this.classList.contains("flipped")) return;
this.classList.add("flipped");
flippedCards.push(this);
if (flippedCards.length === 2) {
checkMatch();
}
}
let attempts = 0;
const scoreDisplay = document.createElement("p");
document.body.insertBefore(scoreDisplay, gameBoard);
function updateScore() {
scoreDisplay.textContent = `Attempts: ${attempts}`;
}
updateScore();
function checkMatch() {
const[card1, card2] = flippedCards;
attempts++;
updateScore();
if(card1.dataset.icon === card2.dataset.icon) {
flippedCards = [];
checkWin();
} else {
lockBoard = true;
setTimeout(() => {
card1.classList.remove("flipped");
card2.classList.remove("flipped");
flippedCards = [];
lockBoard = false;
}, 1000);
}
}
restartBtn.addEventListener("click", () => {
attempts = 0;
updateScore();
flippedCards = [];
lockBoard = false;
createBoard();
});
function checkWin() {
const allFlipped = [...document.querySelectorAll('.card')].every(card => card.classList.contains("flipped"));
if (allFlipped) {
setTimeout(() => alert(`You won in ${attempts} attempts!`), 300);
}
}