I’m trying to make a Simon says game and the problem is inside my answerCheck function. I have it set to be called when both the generated pattern and the user pattern length are equal to 4 and to pass in the user pattern as currentLevel.
The problem is that no matter what the input of the user pattern is the function logs both correct and incorrect as well as running the code inside both statements.
const pattern = [4];
function answerCheck(currentLevel) {
for (let i = 0; i < currentLevel.length; i++) {
if (currentLevel[i] === pattern[i]) {
console.log("success");
// setTimeout(nextSequence(), 2000)
} else if (currentLevel[i] !== pattern[i]) {
console.log("incorrect");
// var wrong = new Audio("./sounds/wrong.mp3");
// wrong.play();
$("body").addClass("game-over");
/*
setTimeout(function() {
$("body").removeClass("game-over");
}, 300);
*/
}
}
}
answerCheck([4]);
>Solution :
There are a few ways to compare simple arrays (see this question), here is one:
const pattern = [4,3,2,1];
function answerCheck(currentLevel) {
let success = currentLevel.length === pattern.length && currentLevel.every((el, i) => pattern[i] === el);
if (success) {
console.log("success");
} else {
console.log("incorrect");
}
}
answerCheck([4]);
answerCheck([4,1,1,1]);
answerCheck([4,3,2,1,0]);
answerCheck([4,3,2,1]);