记忆颜色图案游戏重启后Level异常及按钮同步触发问题排查
记忆颜色图案游戏异常修复方案
问题概述
开发的记忆颜色图案游戏存在两处异常:
- 玩家失败重启游戏后,Level值变为2而非预期的1;
- 新游戏启动时前两个按钮会同时触发,仅第一轮游戏运行正常。
问题根源与修复说明
1. Level值异常修复
问题原因:
resetGame函数重复绑定键盘启动事件,导致按下键盘时startGame被多次触发,level被多次累加;createLevel循环条件错误(y <= level),生成的序列长度为level+1,不符合Level对应序列长度的逻辑。
修复措施:
- 在
resetGame中先移除原有键盘事件再重新绑定,避免重复监听; - 修正
createLevel循环条件为y < level,生成与Level数值匹配长度的序列; - 游戏启动后暂时移除键盘事件,避免游戏过程中误触触发重复启动。
2. 按钮同时触发修复
问题原因:
playPattern中的循环变量未声明为局部变量,属于全局变量,异步延迟过程中变量被覆盖,导致序列播放逻辑混乱;- 原播放逻辑通过倒序计算索引获取颜色,逻辑复杂且易出错。
修复措施:
- 给
playPattern的循环变量添加let声明,转为局部变量避免全局污染; - 简化播放逻辑,直接遍历
gamePattern依次播放颜色。
修复后的完整代码
var gamePattern = []; var playerPattern = []; var buttonColors = ["red", "blue", "green", "yellow"]; var level = 0; var patternDone = false; // 补充全局变量声明,避免未定义报错 $(".btn").click(function () { if (patternDone) { pressButton(this.id); playerPattern.push(this.id); checkAnswer(); } }); function resetGame() { gamePattern = []; playerPattern = []; patternDone = false; level = 0; $("h1").html("Press A Key to Start"); // 先移除再绑定,避免重复监听键盘事件 $(document).off("keypress").keypress(startGame); } // 初始绑定启动事件 $(document).keypress(startGame); function startGame() { level += 1; console.log("level " + level); gamePattern = []; playerPattern = []; createLevel(); console.log(gamePattern); playPattern(); patternDone = true; $("h1").html("Level " + level); // 启动后移除键盘事件,避免游戏中误触 $(document).off("keypress"); } async function playPattern() { // 直接遍历序列,使用局部变量避免全局污染 for(let color of gamePattern) { await delay(1000); pressButton(color); } } function createLevel() { // 生成与Level长度匹配的序列 for(let y = 0; y < level; y++) { var randomColor = buttonColors[Math.floor(Math.random() * buttonColors.length)]; gamePattern.push(randomColor); } } function pressButton(colord) { animatePress(colord); playSound(colord); } function playSound(nameSound) { var audio = new Audio("sounds/" + nameSound + ".mp3"); audio.play(); } function animatePress(currentColor) { $("#" + currentColor).addClass("pressed"); setTimeout(function () { $("#" + currentColor).removeClass("pressed"); }, 100); } const delay = millis => new Promise((resolve, reject) => { setTimeout(_ => resolve(), millis); }); async function checkAnswer() { if (playerPattern.length === gamePattern.length) { if (playerPattern.join(',') === gamePattern.join(',')) { $("h1").html("Correct!"); console.log("correct"); await delay(1000); startGame(); } else { $("h1").html("Wrong!"); console.log("wrong"); await delay(3000); resetGame(); } } }
内容的提问来源于stack exchange,提问作者xMenko
相关产品推荐
相关产品推荐

