-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (76 loc) · 2.33 KB
/
index.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
let buttonColours = ["red","blue","green","yellow"]
let gamePattern = []
let userClickedPattern = []
var userTurn = false
let gameStarted = false
var roundCount = 1
const updateTopScore = () => {
var topScore = localStorage.getItem("top-score")? localStorage.getItem("top-score") : 0
if(roundCount > topScore){
localStorage.setItem("top-score", roundCount-1)
topScore = roundCount-1
}
$("#top-score").text("Top score: " + topScore)
}
updateTopScore()
const nextSequence = async () => {
$("#level-title").text("Level "+ roundCount)
userTurn = false
roundCount++
await new Promise(r => setTimeout(r, 1000))
userClickedPattern.length = 0
let randomNumber = Math.round((Math.random()*3))
let randomChosenColour = buttonColours[randomNumber]
gamePattern.push(randomChosenColour)
for (let i = 0; i < gamePattern.length-1; i++){
$("#" + gamePattern[i]).fadeOut(100).fadeIn(100)
playSound(gamePattern[i])
await new Promise(r => setTimeout(r, 400))
}
$("#" + randomChosenColour).fadeOut(100).fadeIn(100)
playSound(randomChosenColour)
userTurn = true
}
$(".btn").click(function() {
if(!userTurn) return
let pressedColour = $(this).attr("id")
userClickedPattern.push(pressedColour)
$(this).fadeOut(100).fadeIn(100)
playSound(pressedColour)
checkAnswer()
})
const playSound = (button) => {
let audio = new Audio("sounds/" + button + ".mp3")
audio.play()
}
const checkAnswer = () => {
if(JSON.stringify(userClickedPattern) != JSON.stringify(gamePattern.slice(0, userClickedPattern.length))) {
gameOver()
return
}
if((userClickedPattern.length === gamePattern.length) && (userClickedPattern[userClickedPattern.length - 1] === gamePattern[gamePattern.length - 1])){
nextSequence()
}
}
const gameOver = () => {
userTurn = false
gameStarted = false
updateTopScore()
gamePattern.length = 0
userClickedPattern.length = 0
playSound("wrong")
$("#level-title").text("Game Over!")
$("body").addClass("game-over")
setTimeout(() => {
$("body").removeClass("game-over")
}, 200)
$("#play-btn").show()
}
$("#play-btn").click(() => {
if(!gameStarted){
gameStarted = true
roundCount = 1
$("#play-btn").hide()
nextSequence()
}
})