-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
74 lines (59 loc) · 1.98 KB
/
game.js
File metadata and controls
74 lines (59 loc) · 1.98 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
import { levelConfigurations } from './level.js';
console.log(levelConfigurations);
console.log("Code execution reached this point.");
let clickedCards = [];
// Flips the clicked card
function flipCard(event) {
// Event is the click function and target is the card, so this gets the clicked card and stores it in a variable.
const clickedCard = event.target;
// Edge case where user clicks card twice,
if(isAlreadyFlipped(clickedCard)) {
return;
}
showCardFront(clickedCard);
hideCardBack(clickedCard);
toggleFlippedClass(clickedCard);
handleFlippedCards(clickedCard)
}
// Checks if the card is already flipped
function isAlreadyFlipped(card) {
return card.classList.contains('flipped');
}
// Shows the front of the card
function showCardFront(card) {
card.querySelector('.card-front').style.display = 'block';
}
// Hides the back of the card
function hideCardBack(card) {
card.querySelector('.card-back').style.display = 'none';
}
// Toggles the 'flipped' class
function toggleFlippedClass(card) {
card.classList.toggle('flipped');
}
// Handles the flipped cards after a delay
function handleFlippedCards(clickedCard) {
const flippedCards = getFlippedCards();
if (flippedCards.length === 2) {
setTimeout(resetFlippedCards, 500);
}
}
// Returns an array of currently flipped cards
function getFlippedCards() {
return Array.from(document.querySelectorAll('.flipped'));
}
// Resets the flipped cards to their original state
function resetFlippedCards() {
const flippedCards = getFlippedCards();
flippedCards.forEach(card => {
card.classList.remove('flipped');
card.querySelector('.card-back').style.display = 'block';
card.querySelector('.card-front').style.display = 'none';
});
}
// Add event listeners to the cards
const cards = document.querySelectorAll('.card');
// Event Listener will detectt the click interactions
cards.forEach(card => {
card.addEventListener('click', flipCard);
});