I am currently making a simple game called the simon game. It works pretty fine until the game is restarted. It calls on the function handler() multiple times. I tried to clear out the array with a function called startOver(). But I think the only problem is that it calls on the handler function multiple times. I don't understand why. Is there a way to clear out a function? or just a way to fix it? Here is my code:
let buttonColors = ["red", "blue", "green", "yellow"]
let gamePattern = []
let level = 1;
let userClickedPattern = []
let currentLevel = gamePattern.length
let started = false
document.addEventListener("keydown",function(event){
if (!started){
if (event.key=="a"){
nextSequence();
handler();
started = true
}
}
})
function checker(){
if(userClickedPattern[currentLevel]===gamePattern[currentLevel]){
if(userClickedPattern.length===gamePattern.length){
level++;
userClickedPattern =[];
setTimeout(nextSequence, 1000)
}
}
else if(userClickedPattern[currentLevel]!=gamePattern[currentLevel]){
document.querySelector("h1").innerText = "Game Over. Press 'B' key to start again";
let error1 = new Audio("sounds/wrong.mp3");
error1.play()
document.querySelector("body").classList.add("game-over")
setTimeout(function(){
document.querySelector("body").classList.remove("game-over")
}, 200)
startOver();
}
}
function nextSequence(){
let randomChosenColor = buttonColors[Math.floor(Math.random()*4)];
let sound1 = new Audio("sounds/"+randomChosenColor+".mp3");
sound1.play()
gamePattern.push(randomChosenColor)
document.querySelector("h1").innerText = "Level "+(level);
//STYLE
document.querySelector("#"+randomChosenColor).classList.add("pressed");
setTimeout(function (){document.querySelector("#"+randomChosenColor).classList.remove("pressed")
}, 200)
}
function handler(){
for(let i = 0; i<document.querySelectorAll(".btn").length; i++){
document.querySelectorAll(".btn")[i].addEventListener("click", function(){
let userChosenColor = this.getAttribute("id");
userClickedPattern.push(userChosenColor)
//SOUND
let sound1 = new Audio("sounds/"+userChosenColor+".mp3");
sound1.play()
//STYLE
document.querySelector("#"+userChosenColor).classList.add("pressed");
setTimeout(function ()
{document.querySelector("#"+userChosenColor).classList.remove("pressed")
}, 200)
checker();
console.log(gamePattern);
console.log(userClickedPattern);
})
}
}
function startOver(){
gamePattern = [];
userClickedPattern = [];
level = 1;
started = false
}
I know my code is pretty ugly, I'm still very new to coding.