-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
124 lines (110 loc) · 2.59 KB
/
app.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const characters = [
{
id: 1,
backImg: 'assets/Rick.png'
},
{
id: 2,
backImg: 'assets/Summer.png'
},
{
id: 3,
backImg: 'assets/Morty.png'
},
{
id: 4,
backImg: 'assets/missix.png'
},
{
id: 5,
backImg: 'assets/Jerry.png'
},
{
id: 6,
backImg: 'assets/Beth.png'
},
{
id: 7,
backImg: 'assets/pickle-rick.png'
},
{
id: 8,
backImg: 'assets/tele.png'
}
]
const playingField = document.querySelector('.playing-field');
const cards = [...characters, ...characters];
const cardsCollection = document.getElementsByClassName('card');
const checkTimeout = 1000;
const resetTimeout = 2000;
let firstClicked = null;
let countCards = cards.length;
const shuffleCards = () => cards.sort(function() { return 0.5 - Math.random() });
function createCards() {
let card = '';
cards.forEach(({id, backImg}) => {
card += `<div data-id="${id}" class="card closed"><div class="front"><img src="assets/cover.jpg" alt="cover"></div><div class="back"><img src="${backImg}" alt="back"></div></div>`
})
playingField.innerHTML = card;
};
function fillField() {
shuffleCards();
createCards();
countCards = cards.length;
}
function resetField() {
playingField.innerHTML = '';
fillField();
}
function flipCards({target}) {
const cardClicked = target.closest('.card.closed');
if (!cardClicked) {
return
}
cardClicked.classList.remove('closed');
cardClicked.classList.add('flipped');
if (!firstClicked) {
firstClicked = cardClicked;
} else {
checkIdentity(cardClicked);
playingField.classList.add('blocked');
}
}
function checkIdentity(secondClicked) {
const isIdentity = secondClicked.dataset.id == firstClicked.dataset.id;
setTimeout(() => {
playingField.classList.remove('blocked');
}, checkTimeout)
if (!isIdentity) {
setTimeout(() => {
closeCards(firstClicked);
closeCards(secondClicked);
firstClicked = null;
}, checkTimeout);
} else {
secondClicked.classList.add('opened');
firstClicked.classList.add('opened');
firstClicked = null;
countCards -= 2;
getWin();
}
}
function closeCards ( elem ) {
elem.classList.remove('flipped');
elem.classList.add('closed');
}
function getWin() {
const winnerContent = `<div class="winner">
<p>Wubba Lubba Dub Dub!</p>
</div>`
if (countCards === 0) {
playingField.insertAdjacentHTML('afterbegin', winnerContent);
setTimeout (() => {
resetField();
}, resetTimeout)
}
}
document.addEventListener("DOMContentLoaded", function() {
fillField();
playingField.addEventListener('click', flipCards);
})