-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
75 lines (61 loc) · 2.59 KB
/
game.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
const tilesContainer=document.querySelector('.tiles');
const colors = ["Turquoise", "Lavender", "Coral", "Crimson", "gold", "SpringGreen", "Fuchsia", "RoyalBlue"];
const colorPicklist=[...colors,...colors];
const tileCount=colorPicklist.length;
for(let i=0;i<tileCount;i++){
const randomIndex=Math.floor(Math.random()*colorPicklist.length);
const color=colorPicklist[randomIndex];
const tile=buildMyTile(color);
colorPicklist.splice(randomIndex,1);
tilesContainer.appendChild(tile);
}
let revealedCount=0;
let activeTile=null;
let awaitingFinish=false;
function buildMyTile(color){
// Create a new tile element
const element = document.createElement("div");
// Set attributes for tiles
element.classList.add("tile");
element.setAttribute("data-color", color);
element.setAttribute("data-revealed", "false");
element.addEventListener('click',()=>{
const revealed = element.getAttribute("data-revealed");
// Check if user is waiting to reset tiles or if tile is already revealed
if(awaitingFinish || revealed === "true" || element == activeTile){
return;
}
element.style.backgroundColor = color;
// If no tile is turned (currently active), then jisko click kiya h usko active bnao
if(!activeTile){
activeTile = element;
return;
}
// Check if color matches the active tile
const colorToMatch = activeTile.getAttribute("data-color");
// Color Matches
if(colorToMatch === color){
// color matches, both tiles -> revealed
element.setAttribute("data-revealed", "true");
activeTile.setAttribute("data-revealed", "true");
// Reset activeTile & awaitingMove
activeTile = null;
awaitingFinish = false;
revealedCount +=2;
// Check if all tiles are revealed (game won)
if(revealedCount === tileCount){
alert("Yay, you won the game, pls refresh.");
}
return;
}
// Colors if not matched
awaitingFinish = true;
setTimeout(()=>{
activeTile.style.backgroundColor = null;
element.style.backgroundColor = null;
awaitingFinish = false;
activeTile = null;
}, 1000)
});
return element;
}