-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
110 lines (101 loc) · 2.95 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
// GLOBALS:
const container = document.querySelector('#container')
let clickedCards = [];
let revealedPairs = 0;
const arrayOfCards = [
{
name: 'cardback',
src: './images/cardback.jpg'
},
{
name: 'tree',
src: './images/tree.jpg'
},{
name: 'blueleaves',
src: './images/blueleaves.jpg'
},
{
name: 'jaffa',
src: './images/jaffa.jpg'
},
{
name: 'jerusalem',
src: './images/jerusalem.jpg'
},
{
name: 'weird',
src: './images/weird.jpg'
},
{
name: 'man',
src: './images/man.jpg'
},
]
// fill with back of cards and shuffle
const cardsLength = createCardLengthArray()
cardsLength.push(...cardsLength)
cardsLength.sort(() => 0.5 - Math.random())
for (let i = 0; i < cardsLength.length; i++) {
const backOfCard = document.createElement('img')
backOfCard.setAttribute('src', arrayOfCards[0].src)
backOfCard.setAttribute('data-cardnum', cardsLength[i])
container.append(backOfCard)
}
const images = document.querySelectorAll('img')
images.forEach(image => {
image.addEventListener('click', flipOver)
})
function flipOver (e) {
const cardNumber = e.target.dataset.cardnum
e.target.setAttribute('src', arrayOfCards[cardNumber].src)
clickedCards.push(cardNumber)
if (clickedCards.length % 2 === 0) {
setTimeout(checkIfSame, 250, cardNumber)
}
}
function checkIfSame (cardNumber) {
if (clickedCards[0] === clickedCards[1]) {
revealedPairs++
updateClassName(cardNumber)
alert ("Found a match!")
if (revealedPairs === arrayOfCards.length - 1) {
alert("Well Done!")
const wellDone = document.createElement('h1')
wellDone.setAttribute('class', 'well-done')
wellDone.textContent = 'Well Done!'
document.body.append(wellDone)
const finishAnimation = document.createElement('img')
finishAnimation.setAttribute('src', './finished.gif')
finishAnimation.setAttribute('class', 'finish-animation')
document.body.setAttribute('style', 'background-color: aquamarine;')
document.body.append(finishAnimation)
document.body.removeChild(document.querySelector('#container'))
}
return clickedCards = []
} else {
alert ("Try agian")
flipToBackSide()
}
clickedCards = []
}
function flipToBackSide() {
images.forEach(image => {
if (!image.className.includes('revealed')) {
image.setAttribute('src', arrayOfCards[0].src)
}
})
}
function updateClassName (num) {
images.forEach(image => {
if (image.dataset.cardnum == num) {
image.classList.add('revealed')
}
})
}
function createCardLengthArray () {
const lengthArray = []
for (let i = 1; i < arrayOfCards.length; i++) {
lengthArray.push(i)
}
return lengthArray
}