-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (69 loc) · 2.71 KB
/
index.js
File metadata and controls
82 lines (69 loc) · 2.71 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
const cards = [
{ name: "aquaman", img: "aquaman.jpg" },
{ name: "batman", img: "batman.jpg" },
{ name: "captain america", img: "captain-america.jpg" },
{ name: "fantastic four", img: "fantastic-four.jpg" },
{ name: "flash", img: "flash.jpg" },
{ name: "green arrow", img: "green-arrow.jpg" },
{ name: "green lantern", img: "green-lantern.jpg" },
{ name: "ironman", img: "ironman.jpg" },
{ name: "spiderman", img: "spiderman.jpg" },
{ name: "superman", img: "superman.jpg" },
{ name: "the avengers", img: "the-avengers.jpg" },
{ name: "thor", img: "thor.jpg" },
{ name: "aquaman", img: "aquaman.jpg" },
{ name: "batman", img: "batman.jpg" },
{ name: "captain america", img: "captain-america.jpg" },
{ name: "fantastic four", img: "fantastic-four.jpg" },
{ name: "flash", img: "flash.jpg" },
{ name: "green arrow", img: "green-arrow.jpg" },
{ name: "green lantern", img: "green-lantern.jpg" },
{ name: "ironman", img: "ironman.jpg" },
{ name: "spiderman", img: "spiderman.jpg" },
{ name: "superman", img: "superman.jpg" },
{ name: "the avengers", img: "the-avengers.jpg" },
{ name: "thor", img: "thor.jpg" },
];
const memoryGame = new MemoryGame(cards);
window.addEventListener("load", (event) => {
let html = "";
memoryGame.cards.forEach((pic) => {
html += `
<div class="card" data-card-name="${pic.name}">
<div class="back" name="${pic.img}"></div>
<div class="front" style="background: url(img/${pic.img}) no-repeat"></div>
</div>
`;
});
// Add all the divs to the HTML
document.querySelector("#memory-board").innerHTML = html;
document.querySelectorAll(".card").forEach((card) => {
card.addEventListener("click", () => {
if (memoryGame.pickedCards.length === 2) return;
card.classList.add("turned");
memoryGame.pickedCards.push(card);
if (memoryGame.pickedCards.length !== 2) return;
const firstCard = memoryGame.pickedCards[0];
const secondCard = memoryGame.pickedCards[1];
const firstName = firstCard.getAttribute("data-card-name");
const secondName = secondCard.getAttribute("data-card-name");
const isPair = memoryGame.checkIfPair(firstName, secondName);
document.querySelector("#pairs-clicked").textContent =
memoryGame.pairsClicked;
document.querySelector("#pairs-guessed").textContent =
memoryGame.pairsGuessed;
if (isPair) {
memoryGame.pickedCards = [];
if (memoryGame.checkIfFinished()) {
alert("You won!");
}
} else {
setTimeout(() => {
firstCard.classList.remove("turned");
secondCard.classList.remove("turned");
memoryGame.pickedCards = [];
}, 800);
}
});
});
});