-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
101 lines (80 loc) · 2.46 KB
/
Copy pathscript.js
File metadata and controls
101 lines (80 loc) · 2.46 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
97
98
99
100
101
const tableSize = 4;
//cards
let cards = [1, 2, 3, 4, 5, 6, 7, 8];
cards.forEach((c) => cards.push(c)); // Duplikate erzeugen
let visibleCards = [];
mixArray(cards);
printTable(cards);
// add click listener
document.getElementById("memory-table").addEventListener("click", (e) => {
if (e.target.classList.contains("shown-memory-card")) return;
if (visibleCards.length >= 2) return;
toggleCardVisibility(e.target);
// update visible cards array
visibleCards.push(e.target);
checkVisibleCards();
});
function checkVisibleCards() {
if (visibleCards.length < 2) return;
//check for equality
if (
visibleCards[0].innerHTML === visibleCards[1].innerHTML &&
visibleCards[0] !== visibleCards[1]
) {
//cards are equal
let intvervalId = setTimeout(() => {
removeBothCards(visibleCards[0], visibleCards[1]);
clearInterval(intervalId);
}, 500);
}
// wait for 5s to hide both cards
let intervalId = setTimeout(() => {
toggleCardVisibility(visibleCards[0]);
toggleCardVisibility(visibleCards[1]);
visibleCards = [];
clearInterval(intervalId);
}, 500);
}
function removeBothCards() {
visibleCards[0].style.opacity = 0;
visibleCards[0].style.pointerEvents = "none";
visibleCards[1].style.opacity = 0;
visibleCards[1].style.pointerEvents = "none";
// remove cards from cards array
const matchedCardContent = Number(visibleCards[0].innerHTML);
cards = cards.filter((c) => c !== matchedCardContent);
visibleCards = [];
checkUserWon();
}
function checkUserWon() {
if (cards.length === 0) {
printCongratulations();
}
}
function printCongratulations() {
document.getElementById('congratulations').innerHTML = '<h1>You won!</h1>'
}
function toggleCardVisibility(card) {
if (card.classList.contains("hidden-memory-card")) {
// die Karte war versteckt, wir müssen die aufmsachen
card.classList.remove("hidden-memory-card");
card.classList.add("shown-memory-card");
} else if (card.classList.contains("shown-memory-card")) {
card.classList.remove("shown-memory-card");
card.classList.add("hidden-memory-card");
}
}
function printTable(elements) {
let table = "<table class='my-table' id='memory-table'>";
for (let i = 0; i < tableSize; i++) {
table += "<tr>";
for (let j = 0; j < tableSize; j++) {
table +=
"<td class='hidden-memory-card'>" +
elements[i * tableSize + j] +
"</td>";
}
table += "</tr>";
}
document.body.innerHTML += table;
}