-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
113 lines (101 loc) · 2.79 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
const cardArray = [
{
name: 'fries',
img: 'images/fries.jpeg',
},
{
name: 'cheeseburger',
img: 'images/cheeseburger.jpeg',
},
{
name: 'hotdog',
img: 'images/hotdog.jpeg',
},
{
name: 'icecream',
img: 'images/icecream.jpeg',
},
{
name: 'milkshake',
img: 'images/milkshake.jpeg',
},
{
name:'pizza',
img:'images/pizza.jpeg',
},
{
name: 'fries',
img: 'images/fries.jpeg',
},
{
name: 'cheeseburger',
img: 'images/cheeseburger.jpeg',
},
{
name: 'hotdog',
img: 'images/hotdog.jpeg',
},
{
name: 'icecream',
img: 'images/icecream.jpeg',
},
{
name: 'milkshake',
img: 'images/milkshake.jpeg',
},
{
name:'pizza',
img:'images/pizza.jpeg',
},
]
cardArray.sort(() => 0.5 - Math.random());
const gridDisplay = document.querySelector('#grid');
const resultDisplay = document.querySelector('#result');
let cardsChosen=[];
let cardsChosenIds = [];
const cardsWon = [];
function createBoard(){
for(let i=0; i< cardArray.length; i++){
const card = document.createElement('img');
card.setAttribute('src','images/blank.jpeg');
card.setAttribute('data-id',i);
card.addEventListener('click',flipCard);
gridDisplay.appendChild(card);
}
}
createBoard();
function checkMatch(){
const cards = document.querySelectorAll('#grid img');
console.log('check for match');
if (cardsChosenIds[0] == cardsChosenIds[1]){
alert("You have clicked the same image!");
}
if (cardsChosen[0] == cardsChosen[1]){
alert('You found a match!')
cards[cardsChosenIds[0]].setAttribute('src', 'images/white.png');
cards[cardsChosenIds[1]].setAttribute('src', 'images/white.png');
cards[cardsChosenIds[0]].removeEventListener('click',flipCard);
cards[cardsChosenIds[1]].removeEventListener('clcik',flipCard);
cardsWon.push(cardsChosen)
} else{
cards[cardsChosenIds[0]].setAttribute('src', 'images/blank.jpeg');
cards[cardsChosenIds[1]].setAttribute('src', 'images/blank.jpeg');
alert("Sorry try again!");
}
resultDisplay.textContent= cardsWon.length;
cardsChosen = [];
cardsChosenIds = [];
if (cardsWon.length == (cardArray.length/2)){
resultDisplay.textContent = "Congragulations you found them all!";
}
}
function flipCard(){
console.log(cardArray)
let cardId = this.getAttribute('data-id');
cardsChosen.push(cardArray[cardId].name);
cardsChosenIds.push(cardId);
this.setAttribute('src', cardArray[cardId].img);
if (cardsChosen.length == 2){
setTimeout(checkMatch,500)
}
}