如何修改JavaScript代码实现记忆游戏玩家回合重置30秒计时器
修复记忆游戏玩家回合计时器重置问题
问题描述
开发一款记忆游戏,规则为每位玩家拥有30秒时间选择2张卡牌,若卡牌不匹配则切换至另一玩家回合。当前存在问题:玩家1在剩余20秒时结束回合,玩家2会从20秒开始计时,而非每次都从30秒启动。
原代码问题分析
startTimer函数仅判断timeLeft1是否超时,未处理玩家2的timeLeft2超时情况switchPlayers函数中重复执行全局时间重置,同时重复调用clearInterval(timer),逻辑冗余且易导致计时混乱- 切换玩家时未立即更新对应计时器的显示值,导致视觉上未同步重置状态
修改后的代码
const cards = document.querySelectorAll(".cards .card"); const currentPlayer = document.querySelector(".current-player"); const player1ScoreElement = document.querySelector(".player1-score"); const player2ScoreElement = document.querySelector(".player2-score"); const player1Timer = document.querySelector('.player1-timer'); const player2Timer = document.querySelector('.player2-timer'); let timer; let timeLeft1 = 30; let timeLeft2 = 30; function startTimer() { timer = setInterval(function() { const isPlayer1Turn = currentPlayer.textContent === "1"; let currentTimeLeft = isPlayer1Turn ? timeLeft1 : timeLeft2; if (currentTimeLeft <= 0) { clearInterval(timer); switchPlayers(); return; } // 更新当前玩家的计时器显示并递减时间 if (isPlayer1Turn) { player1Timer.textContent = timeLeft1; timeLeft1--; } else { player2Timer.textContent = timeLeft2; timeLeft2--; } }, 1000); } function switchPlayers() { clearInterval(timer); if (currentPlayer.textContent === "1") { // 切换到玩家2,重置其时间并更新显示 currentPlayer.textContent = "2"; timeLeft2 = 30; player2Timer.textContent = "30"; player1Timer.classList.remove('active'); player2Timer.classList.add('active'); } else { // 切换到玩家1,重置其时间并更新显示 currentPlayer.textContent = "1"; timeLeft1 = 30; player1Timer.textContent = "30"; player2Timer.classList.remove('active'); player1Timer.classList.add('active'); } startTimer(); } // 初始化游戏状态 player1Timer.textContent = "30"; player2Timer.textContent = "30"; startTimer(); player1Timer.classList.add('active');
关键修改说明
- 优化
startTimer函数的超时判断逻辑,根据当前玩家动态检查对应计时器的剩余时间 - 在
switchPlayers函数中,仅重置即将切换到的玩家的计时器时间,并立即更新其显示值,确保回合开始时计时器从30秒显示启动 - 移除冗余的重复代码,简化计时器启停逻辑,避免状态混乱
内容的提问来源于stack exchange,提问作者Yor
相关产品推荐
相关产品推荐

