提问人:LuckyTiger 提问时间:8/11/2023 最后编辑:Heretic MonkeyLuckyTiger 更新时间:8/12/2023 访问量:55
为什么即使我没有点击图案的全长,循环仍然是正确的?
How come the loop is still true even though I haven't clicked the full length of the pattern?
问:
我正在做一个在线课程,我的任务是用 JavaScript 编写一个 Simon 游戏。我的代码可以工作,但我无法理解为什么 checkAnswer 函数中的循环在一个新的级别上是正确的,即使它没有我的模式的完整长度。
防爆 1 级
const gamePattern = ['blue'];
我点击蓝色
2级
const gamePattern = ['blue', 'red'];
我点击蓝色。循环检查是否相同。但是在这里我还没有点击第二种颜色,循环仍然可以。关于循环,我有什么不明白的地方?userClickedPattern
这是我的代码。
"use strict";
// Declared Variables
const buttonColours = ["red", "blue", "green", "yellow"];
let userClickedPattern = [];
const gamePattern = [];
let level = 0;
// Plays the sound of the input color
function playSound(name) {
const sound = new Audio("/sounds/" + name + ".mp3");
sound.play();
}
// Function that randomly selects the next color to be clicked
function nextSequence() {
const randomNumber = Math.floor(Math.random() * 4);
const randomChosenColour = buttonColours[randomNumber];
$("#" + randomChosenColour)
.fadeOut(100)
.fadeIn(100);
playSound(randomChosenColour);
level++;
// Updates the level text
$("h1").text(`Level ${level}`);
return gamePattern.push(randomChosenColour);
}
// User click function
$("div[type='button']").click(function(e) {
const userChosenColour = e.currentTarget.id;
playSound(userChosenColour);
// Makes the button greyed out when clicked
function animatePress(currentColour) {
$("#" + currentColour).addClass("pressed");
setTimeout(() => {
$("#" + currentColour).removeClass("pressed");
}, 100);
}
userClickedPattern.push(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userClickedPattern);
return;
});
// Runs once to start the game
$(document).keypress(function() {
if (level === 0) {
// Runs the nextSequence
nextSequence();
}
});
function checkAnswer(currentLevel) {
for (let i = 0; i < currentLevel.length; i++)
if (gamePattern[i] !== currentLevel[i]) {
$("h1").css("color", "red");
$("h1").text("GAME OVER");
return;
}
if (currentLevel.length === gamePattern.length) {
setTimeout(nextSequence, 1000);
userClickedPattern = [];
}
}
答: 暂无答案
评论