-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
115 lines (90 loc) · 2.43 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
let computer = []
let user = []
let round = 0
let roundCounter = document.querySelector("#round")
// FUNCTIONS
function getRandomColor(){
let green = document.querySelector("#green")
let red = document.querySelector("#red")
let yellow = document.querySelector("#yellow")
let blue = document.querySelector("#blue")
let colors = [green, red, yellow, blue]
let color = colors[Math.floor(Math.random() * colors.length)]
return color;
}
function lightSelectedColor(color){
color.classList.add("color-selected")
setTimeout( () => {
color.classList.remove("color-selected")
}, 300)
return color;
}
function checkUserInput(){
let errorCounter = 0
user.forEach( (color, index) => {
if (color !== computer[index]){
return errorCounter++
}
else if (user.length === computer.length){
handleErrors(errorCounter)
}
})
if (errorCounter === 1){
handleErrors(errorCounter)
}
}
function handleErrors(errorAmount){
if (errorAmount === 0){
user = []
newTurn()
}
else if (errorAmount === 1) {
alert("You lose!")
resetEverything()
}
}
function newTurn(){
computer.push(getRandomColor())
changeRoundNumber()
blockUserInput()
computer.forEach((color, index) => {
setTimeout(() => {
lightSelectedColor(color)
}, 800 * (index + 1))
})
let secondsBeforeUserTurn = computer.length * 900
setTimeout( function() {
unblockUserInput()
}, secondsBeforeUserTurn);
}
function blockUserInput(){
const colors = document.querySelector("#container")
colors.onclick = function(){
console.log("You have to wait until computer's turn ends!")
}
}
function unblockUserInput(){
const colors = document.querySelector("#container")
colors.onclick = function(e) {
lightSelectedColor(e.target)
user.push(e.target)
checkUserInput()
}
}
function changeRoundNumber(){
round++
roundCounter.innerText = round
}
function resetEverything(){
user = []
computer = []
round = 0
roundCounter.innerText = round
startButton.style.display = ""
}
/////////////////////////////////////////////////////////////////////////////////
const startButton = document.querySelector("#start")
startButton.addEventListener("click", function() {
newTurn()
startButton.style.display = "none"
})