-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
133 lines (110 loc) · 2.98 KB
/
script.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
125
126
127
128
129
130
131
132
133
let cardsArray = [
{
'name': 'laugh',
'img': './img/Laugh.png',
},
{
'name': 'SmilingFace',
'img': './img/SmilingFace.png',
},
{
'name': 'boared',
'img': './img/Boared.png',
},
{
'name': 'loveonface',
'img': './img/Loveonface.png',
},
{
'name': 'cool',
'img': './img/cool.png',
},
{
'name': 'explosion',
'img': './img/explosion.png',
},
{
'name': 'confused',
'img': './img/confused.png',
},
{
'name': 'smile',
'img': './img/smile.png',
}
];
const parentDiv = document.querySelector('#card-section')
// to duplicate each card
const gameCards = cardsArray.concat(cardsArray)
// suffle the coards randomly
const suffle =(array)=>{
for(let i = array.length-1; i > 0; i--){
let j = Math.floor(Math.random() * (i+1))
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array
}
suffle(gameCards)
let clickCount = 0;
let firstCard = "";
let secondCard = "";
// styling the match card
const card_matches = ()=>{
let card_selected = document.querySelectorAll('.card_selected')
card_selected.forEach((curEle)=>{
curEle.classList.add('card_match')
})
}
// if 2 cards does not match
const resetGame = () => {
firstCard = "";
secondCard = "";
clickCount = 0;
let card_selected = document.querySelectorAll('.card_selected');
card_selected.forEach((curElem) => {
curElem.classList.remove('card_selected')
})
}
parentDiv.addEventListener('click',(event)=>{
currCard = event.target
clickCount++;
if(clickCount <=2 && currCard.id !== "card-section" ){
if(clickCount ===1){
firstCard = currCard.parentNode.dataset.name;
currCard.parentNode.classList.add('card_selected')
}
else{
secondCard = currCard.parentNode.dataset.name;
currCard.parentNode.classList.add('card_selected')
}
if(firstCard !== "" && secondCard !== ""){
if(firstCard === secondCard){
setTimeout(()=>{
card_matches()
resetGame()
},1000)
}
else{
setTimeout(() => {
resetGame()
}, 1000)
}
}
}
})
// add card
for(let i=0; i<gameCards.length; i++){
const childDiv = document.createElement('div')
childDiv.setAttribute('class','card')
childDiv.dataset.name = gameCards[i].name
// childDiv.style.backgroundImage = `url(${gameCards[i].img})`
const front_div = document.createElement('div')
front_div.classList.add('front-card')
const back_div = document.createElement('div')
back_div.classList.add('back-card')
back_div.style.backgroundImage = `url(${gameCards[i].img})`
childDiv.appendChild(front_div)
childDiv.appendChild(back_div)
parentDiv.appendChild(childDiv)
}