-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
107 lines (99 loc) · 3.02 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
// Card Options
let cardArray = [
{
name: "Apple",
img: "assets/Apple.png"
},
{
name: "Apple",
img: "assets/Apple.png"
},
{
name: "Banana",
img: "assets/Banana.png"
},
{
name: "Banana",
img: "assets/Banana.png"
},
{
name: "Carrot",
img: "assets/Carrot.png"
},
{
name: "Carrot",
img: "assets/Carrot.png"
},
{
name: "Hamburger",
img: "assets/Hamburger.png"
},
{
name: "Hamburger",
img: "assets/Hamburger.png"
},
{
name: "Lemon",
img: "assets/Lemon.png"
},
{
name: "Lemon",
img: "assets/Lemon.png"
},
{
name: "Strawberry",
img: "assets/Strawberry.png"
},
{
name: "Strawberry",
img: "assets/Strawberry.png"
}
];
cardArray.sort(() => 0.5 - Math.random());
let resultDisplay = document.getElementById('result');
let grid = document.getElementById('grid');
let cardsChosen = [];
let cardsChosenId = [];
let cardsWon = [];
// Create Board
function createBoard() {
for (let i = 0; i < cardArray.length; i++) {
var card = document.createElement('img');
card.setAttribute('src', 'assets/Blank.png');
card.setAttribute('data-id', i);
// Flip your card
card.addEventListener('click', function() {
var cardId = this.getAttribute('data-id');
cardsChosen.push(cardArray[cardId].name);
cardsChosenId.push(cardId);
this.setAttribute('src', cardArray[cardId].img);
// Check for match
var cards = document.querySelectorAll('img');
var optionOneId = cardsChosenId[0];
var optionTwoId = cardsChosenId[1];
if (cardsChosen.length === 2) {
setTimeout(function() {
if (cardsChosen[0] === cardsChosen[1]) {
alert('You found a match!');
cards[optionOneId].setAttribute('src', 'assets/White.png');
cards[optionTwoId].setAttribute('src', 'assets/White.png');
cardsWon.push(cardsChosen);
} else {
cards[optionOneId].setAttribute('src', 'assets/Blank.png');
cards[optionTwoId].setAttribute('src', 'assets/Blank.png');
alert('Sorry, try again!');
}
cardsChosen = [];
cardsChosenId = [];
resultDisplay.textContent = cardsWon.length;
if (resultDisplay.textContent == cardArray.length / 2) {
resultDisplay.textContent = 'Congratulations, you found them all!';
grid.remove(cards);
}
}, 500);
}
});
grid.appendChild(card);
}
}
createBoard();