-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
113 lines (106 loc) Β· 2.53 KB
/
script.js
File metadata and controls
113 lines (106 loc) Β· 2.53 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
102
103
104
105
106
107
108
109
110
111
112
113
const cardArray = [
{
name: '1',
img:"imgs/1.png"
},
{
name: '2',
img:"imgs/2.png"
},
{
name: '3',
img:"imgs/3.png"
},
{
name: '4',
img:"imgs/4.png"
},
{
name: '5',
img:"imgs/5.png"
},
{
name: '6',
img:"imgs/6.png"
},
{
name: '1',
img:"imgs/1.png"
},
{
name: '2',
img:"imgs/2.png"
},
{
name: '3',
img:"imgs/3.png"
},
{
name: '4',
img:"imgs/4.png"
},
{
name: '5',
img:"imgs/5.png"
},
{
name: '6',
img:"imgs/6.png"
}
]
cardArray.sort(() => 0.5 - Math.random())
const grid = document.querySelector('.grid')
const result = document.querySelector('#result')
var cardsChosen = []
var cardsChosenId = []
const cardsWon = []
//create your board
function createGrid() {
for (let i = 0; i < cardArray.length; i++) {
var card = document.createElement('img')
card.setAttribute('src', 'imgs/placeholder.png')
card.setAttribute('data-id', i)
card.addEventListener('click', flipCard)
grid.appendChild(card)
}
}
//check for matches
function checkMatch() {
var cards = document.querySelectorAll('img')
const optionOneId = cardsChosenId[0]
const optionTwoId = cardsChosenId[1]
if(optionOneId == optionTwoId) {
cards[optionOneId].setAttribute('src', 'imgs/placeholder.png')
cards[optionTwoId].setAttribute('src', 'imgs/placeholder.png')
alert('You have clicked the same image!')
}
else if (cardsChosen[0] === cardsChosen[1]) {
alert('You found a match')
cards[optionOneId].setAttribute('src', 'imgs/blank.png')
cards[optionTwoId].setAttribute('src', 'imgs/blank.png')
cards[optionOneId].removeEventListener('click', flipCard)
cards[optionTwoId].removeEventListener('click', flipCard)
cardsWon.push(cardsChosen)
} else {
cards[optionOneId].setAttribute('src', 'imgs/placeholder.png')
cards[optionTwoId].setAttribute('src', 'imgs/placeholder.png')
alert('Sorry, try again')
}
cardsChosen = []
cardsChosenId = []
result.textContent = cardsWon.length
if (cardsWon.length === cardArray.length/2) {
result.textContent = ' Congratulations! You found them all!'
}
}
//flip card
function flipCard() {
var cardId = this.getAttribute('data-id')
cardsChosen.push(cardArray[cardId].name)
cardsChosenId.push(cardId)
this.setAttribute('src', cardArray[cardId].img)
if (cardsChosen.length ===2) {
setTimeout(checkMatch, 500)
}
}
createGrid()