-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
93 lines (84 loc) · 2.47 KB
/
script.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
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
const cards = document.querySelectorAll(".image-card");
const scoreText = document.querySelector(".score");
const FlipsLeftText = document.querySelector(".FlipsLeft");
// const welcomeSound = ;
var flipped = false;
var firstCard, secondCard;
var statue = false;
var score = 0;
var flipsLeft = 8;
function flipCard() {
if (statue) return; // if game statued, no flipping allowed
if (this === firstCard) return; // handle double click on same card
this.classList.add("flip");
document.getElementById("flip-sound").play();
if (!flipped) {
//not flipped
flipped = true;
firstCard = this;
return;
}
//flipped
flipped = false;
secondCard = this;
document.getElementById("flip-sound").play();
matchCard();
}
function matchCard() {
//disbale cards
if (firstCard.dataset["game"] === secondCard.dataset["game"]) {
firstCard.removeEventListener("click", flipCard);
secondCard.removeEventListener("click", flipCard);
score += 1;
scoreText.innerHTML = `SCORE: ${score}/4`;
document.getElementById("score-inc").play();
} //unflip cards
else {
statue = true;
setTimeout(() => {
firstCard.classList.remove("flip");
secondCard.classList.remove("flip");
statue = false;
resetFirstCard();
}, 460);
}
flipsLeft -= 1;
FlipsLeftText.innerHTML = `FLIPS LEFT: ${flipsLeft}`;
if (flipsLeft === 0 || score === 4) {
document.getElementById("game-over-sound").play();
setTimeout(() => {
alert("Game Over. Press 'Enter' or click 'OK' to play again.");
window.location.reload();
}, 500);
}
}
function resetFirstCard() {
[firstCard] = [null];
}
// setInterval(null, 1000); 1
// setInterval(null, 1000); 2
// setInterval(null, 1000); 3
let intervalId = setInterval(function () {
//intervalID = 4
document
.querySelector("#audio")
.play()
.then(() => {
//promise fulfilled
clearInterval(intervalId); //remove the interval
})
.catch(() => {}); //promise rejected. If removed, then an error will be displayed in the console.
}, 100);
// console.log(intervalId);
window.onload = () => {
shuffle();
scoreText.innerHTML = `SCORE: ${score}`;
FlipsLeftText.innerHTML = `FLIPS LEFT: ${flipsLeft}`;
};
function shuffle() {
cards.forEach((card) => {
let randomID = Math.floor(Math.random() * 9); // because we have 8 cards so we need a random no. in the range [0,9)
card.style.order = randomID;
});
}
cards.forEach((card) => card.addEventListener("click", flipCard));