如何在满足条件时重启JavaScript石头剪刀布游戏并显示胜负提示
石头剪刀布游戏代码优化方案
核心修改逻辑
你当前代码已经实现了单轮胜负的展示,缺少全局胜负判定和重启前的提示延迟逻辑,按以下步骤修改即可实现需求:
1. 新增全局状态变量
在game函数顶部的分数定义下方,添加获胜阈值和游戏锁定变量:
const game = () => { let pScore = 0; let cScore = 0; // 新增内容开始 const WIN_THRESHOLD = 3; // 自定义先达到多少分算全局获胜 let isGameEnd = false; // 全局结束后锁定点击,防止误操作 // 新增内容结束 // 原有startGame等函数不变
2. 新增点击拦截和状态重置逻辑
修改playMatch中选项按钮的点击事件,开头添加拦截和状态重置:
options.forEach((option) => { option.addEventListener("click", function () { // 新增:游戏已结束时不响应点击 if (isGameEnd) return; // 新增:新回合开始清空上一轮胜负提示,重置手势为默认石头 const winner = document.querySelector(".winner"); const playerHand = document.querySelector(".player-hand"); const computerHand = document.querySelector(".computer-hand"); winner.textContent = "对决中..."; playerHand.src = "./assets/rock.png"; computerHand.src = "./assets/rock.png"; // 原有逻辑不变 const computerNumber = Math.floor(Math.random() * 3); const computerChoice = computerOptions[computerNumber]; // 剩余原有代码不变
3. 添加全局胜负判定和重启前提示逻辑
修改compareHands函数,在所有胜负判定完成后添加全局结束逻辑:
const compareHands = (playerChoice, computerChoice) => { // 原有所有判定逻辑完全不变 // ... // 新增全局结束判定 if (pScore >= WIN_THRESHOLD || cScore >= WIN_THRESHOLD) { isGameEnd = true; // 先展示最终胜负提示 const winner = document.querySelector(".winner"); winner.textContent = pScore >= WIN_THRESHOLD ? "玩家获胜!" : "电脑获胜!"; // 延迟3秒后重启游戏,保证用户能看到提示 setTimeout(() => { // 重置所有游戏状态 pScore = 0; cScore = 0; isGameEnd = false; updateScore(); winner.textContent = "请选择出拳开始新游戏"; document.querySelector(".player-hand").src = "./assets/rock.png"; document.querySelector(".computer-hand").src = "./assets/rock.png"; // 如果需要回到初始intro页面,额外加下面两行,不需要可以删除 // document.querySelector(".intro").classList.remove("fadeOut"); // document.querySelector(".match").classList.remove("fadeIn"); }, 3000); return; } };
可选优化建议
- 把DOM节点的查询操作统一提到
game函数最顶部,避免每次调用函数都重复查询DOM,提升运行性能 - 可以简化胜负判定逻辑,减少冗余if判断:
// 提前定义胜负映射关系 const winRelation = { rock: "scissors", scissors: "paper", paper: "rock" }; // 判定胜负时直接用下面的逻辑替换原有多组if判断 if (playerChoice === computerChoice) { winner.textContent = "It's a tie!"; return; } if (winRelation[playerChoice] === computerChoice) { winner.textContent = "Player wins!"; pScore++; } else { winner.textContent = "Computer wins!"; cScore++; } updateScore();
内容的提问来源于stack exchange,提问作者nahian-007
相关产品推荐
相关产品推荐

