我正在创建Simon游戏作为Freecodecamp挑战,我完成了基本的事情,现在我正在努力重置游戏。 我有一个函数可以重置它,清除数组,超时等。
问题是当我再次点击开始按钮开始新游戏时,它会重置,开始新游戏,但是单击颜色会在玩家数组中将颜色推两次。
以下是一些代码:codepen
问题是当我再次点击开始按钮开始新游戏时,它会重置,开始新游戏,但是单击颜色会在玩家数组中将颜色推两次。
以下是一些代码:codepen
function reset() {
clearTimeout(repeating);
clearTimeout(genColor);
pickedColors = []; // computer random colors
guessingColors = []; //colors that player picks, should match picked ones
gameOn = false;
countNumber = 0;
}
function game() {
// Counting
console.log(pickedColors, guessingColors);
counter.innerHTML = countNumber;
// New color
genRandom = setTimeout(() => {
getRandomColor();
}, 5);
guessingColors = [];
// Add click listener for each color
for(let i=0; i<colors.children.length; i++) {
// Guessing
colors.children[i].addEventListener("click", function(e) {
if(!running) {
// Add clicked color to user clicked array
guessingColors.push(this);
console.log(guessingColors);
// Add animation class
clickClass(this);
} else {
e.stopPropagation();
}
// repeating.....
running
是一个布尔值,用于在计算机回合结束时停止点击监听器。
game
函数之外附加监听器,或者在reset
函数中分离监听器。 - Teemu