-
Notifications
You must be signed in to change notification settings - Fork 0
/
script2.js
101 lines (98 loc) · 2.67 KB
/
script2.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
var squares = document.getElementsByClassName("square");
var resetGame = document.querySelector("#reset");
var easyButton = document.querySelector("#easy");
var hardButton = document.querySelector("#hard");
var state = document.querySelector("#score");
var rgbValue = document.querySelector(".rgbValue");
var gameover=false,pickedRgb,isHard=true;
//start game on hard mode
loadGame();
//click event for reset,hard,easy
resetGame.addEventListener("click",resetHtml);
easyButton.addEventListener("click",function(){
isHard=false;
resetHtml();//reset and reload
});
hardButton.addEventListener("click",function(){
isHard=true;
resetHtml();//reset and reload
});
//function to pick RGB by picking easy(0-3) hard(0-6)
function pickRgb(value)
{
return Math.floor(Math.random() * value);
}
//function to create RGB value
function setRgbValue()
{
var r=Math.floor(Math.random() * 255);
var g=Math.floor(Math.random() * 255);
var b=Math.floor(Math.random() * 255);
col = "rgb(" + r + ", " + g + ", " + b + ")";
return col;
}
//load game function set hard or easy game by ishard bolean value
function loadGame()
{
gameover=false;
var value;
if(isHard)
{
value=6;
hardButton.classList.add("selected");
easyButton.classList.remove("selected");
isHard=true;
}
else
{
value=3;
hardButton.classList.remove("selected");
easyButton.classList.add("selected");
isHard=false;
}
for(var i=0;i<value;i++)
{
squares[i].addEventListener("click",function(){
if(!gameover)
{
if(this.style.background === pickedRgb)
{
gameover=true;
winner(this.style.background);
}
else
{
this.style.background="#232323";
state.textContent = "Try Again";
}
}
});
squares[i].style.background=setRgbValue();
}
pickedRgb=squares[pickRgb(value)].style.background;
rgbValue.textContent=pickedRgb; // winner pick RGB value
}
//function reset the game and reload it even when switching between hard and easy
function resetHtml()
{
resetGame.textContent = "NEW COLORS";
state.textContent = "Start";
document.querySelector("#container").style.backgroundColor="steelblue";
gameover=false;
for(var i=0;i<6;i++)
{
squares[i].style.background = "#232323";
}
loadGame();
}
//function deal with the winner
function winner(back)
{
for(var i=0;i<6;i++)
{
squares[i].style.background=pickedRgb;
}
document.querySelector("#container").style.backgroundColor=pickedRgb;
resetGame.textContent = "Replay?";
state.textContent = "You Win!";
}