我不知道如何在我的西蒙游戏中添加重启计时器。我知道setInterval(),SetTimeout但如果在前 10 秒内通过关卡,我不知道如何为每个关卡重置计时器。我是否需要 if/else 才能工作并将其连接到 level 或 userClickPattern?我不知道,我都试过了。目标:有一个 10 秒的计时器,开始 .click,如果模式完成则移动到下一个序列,如果没有完成,则 alert("... ) 并重新开始游戏。计时器功能在底部。请帮我!!!var buttonColours = ["red", "blue", "green", "yellow"];var gamePattern = [];var userClickedPattern = [];var started = false;var level = 0;$(document).keypress(function() { if (!started) { $("#level-title").text("Level " + level); nextSequence(); started = true; }});$(".btn").click(function() { var userChosenColour = $(this).attr("id"); userClickedPattern.push(userChosenColour); playSound(userChosenColour); animatePress(userChosenColour); checkAnswer(userClickedPattern.length - 1);});function checkAnswer(currentLevel) { if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) { console.log("success"); if (userClickedPattern.length === gamePattern.length) { setTimeout(function() { nextSequence(); }, 1000); } } else { console.log("wrong"); playSound("wrong"); $("body").addClass("game-over"); setTimeout(function() { $("body").removeClass("game-over"); }, 200); $("#level-title").text("Game Over, Press Any Key to Restart"); startOver(); }}function nextSequence() { userClickedPattern = []; level++; $("#level-title").text("Level " + level); var randomNumber = Math.floor(Math.random() * 4); var randomChosenColour = buttonColours[randomNumber]; gamePattern.push(randomChosenColour); $("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100); playSound(randomChosenColour);}function playSound(name) { var audio = new Audio("sounds/" + name + ".mp3"); audio.play();}function animatePress(currentColor) { $("#" + currentColor).addClass("pressed"); setTimeout(function() { $("#" + currentColor).removeClass("pressed"); }, 100);}
1 回答
紫衣仙女
TA贡献1839条经验 获得超15个赞
拥有一个计时器很容易setInterval,与 不同的是setTimeout,它将继续以指定的延迟执行处理程序函数,直到间隔被清除。
如果你想要全局的值,你可以这样做:
let seconds = 0
let timerInterval
function startTimer() {
timerInterval = setInterval(() => seconds++, 1000)
}
function resetTimer() {
seconds = 0
clearInterval(timerInterval)
}
添加回答
举报
0/150
提交
取消