-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
96 lines (79 loc) · 2.76 KB
/
script.js
File metadata and controls
96 lines (79 loc) · 2.76 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
class MemoryGame {
constructor() {
this.cardsContainer = document.querySelector('.js-cards');
this.cards = Array.from(this.cardsContainer.children);
this.flippedCards = [];
this.delay = 1000;
this.startTime = null;
this.timerElement = document.createElement('div');
this.timerElement.className = 'timer';
document.body.appendChild(this.timerElement);
this.updateTimerInterval = null;
this.initGame();
}
initGame() {
this.cards.forEach(card => {
card.addEventListener('click', this.flip.bind(this, card));
});
this.rearrangeCards();
this.startTime = new Date();
this.updateTimerInterval = setInterval(this.updateTimer.bind(this), 1000);
}
rearrangeCards() {
this.cards.forEach(card => {
const randomNumber = Math.floor(Math.random() * this.cards.length);
card.classList.remove('has-match', 'flipped');
setTimeout(() => {
card.style.order = `${randomNumber}`;
}, 400);
});
}
validateCards() {
const [firstCard, secondCard] = this.flippedCards;
this.cardsContainer.classList.add('no-event');
if (firstCard.dataset.animal === secondCard.dataset.animal) {
firstCard.classList.replace('flipped', 'has-match');
secondCard.classList.replace('flipped', 'has-match');
this.flippedCards = [];
setTimeout(() => {
const allHaveMatches = this.cards.every(card => (
card.classList.contains('has-match')
));
this.cardsContainer.classList.remove('no-event');
if (allHaveMatches) {
clearInterval(this.updateTimerInterval);
this.showCongratulations();
}
}, this.delay);
}
else {
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
this.flippedCards = [];
this.cardsContainer.classList.remove('no-event');
}, this.delay);
}
}
flip(selectedCard) {
selectedCard.classList.add('flipped');
this.flippedCards.push(selectedCard);
if (this.flippedCards.length === 2) {
this.validateCards();
}
}
updateTimer() {
const currentTime = new Date();
const elapsedTime = Math.floor((currentTime - this.startTime) / 1000);
this.timerElement.textContent = `Time: ${elapsedTime} seconds`;
}
showCongratulations() {
const elapsedTime = Math.floor((new Date() - this.startTime) / 1000);
const message = `Congratulations! You matched all cards in ${elapsedTime} seconds.`;
alert(message);
this.rearrangeCards();
this.startTime = new Date();
this.updateTimerInterval = setInterval(this.updateTimer.bind(this), 1000);
}
}
const game = new MemoryGame();