JavaScript剪刀石头布游戏逻辑异常排查:胜负判定错误问题
修复剪刀石头布JavaScript游戏的核心Bug
你的代码存在两个关键问题,导致胜负判断异常和显示不一致:
问题1:控制台显示的电脑选择与游戏逻辑使用的不是同一个
你在控制台输出时调用了一次computerChoice(),在game()函数内部又调用了一次,这会触发两次随机生成,导致控制台显示的电脑选择和实际参与胜负判断的选择可能完全不同,结果自然混乱。
修复方式:
先一次性生成电脑选择并存储到变量中,再同时用于控制台输出和游戏逻辑:
// 统一生成电脑选择,避免两次随机结果不一致 const computerSelected = computerChoice(); console.log(`you chose ${playerChoice[0]}.`); console.log(`the computer chose ${computerSelected}.`); console.log(game(computerSelected)); // 将电脑选择传入game函数
同时修改game函数,改为接收外部传入的电脑选择,不再内部重新生成:
function game(computerSelectedChoice) { // 胜负判断逻辑写在这里 }
问题2:胜负条件判断逻辑完全错误
你写的playerChoice[0] && computerSelectedChoice === "stone"这类判断完全不符合逻辑——playerChoice[0]是字符串"scissor",属于真值,所以这个条件等价于只要电脑选了stone就返回"the computer won!",完全没有判断玩家当前的选择。另外还存在重复的错误条件(比如两次判断玩家选stone且电脑选paper,但返回结果矛盾)。
正确的条件判断逻辑:
先明确玩家当前选择,再针对每种玩家选择,匹配对应的电脑选择判断胜负:
function game(computerSelectedChoice) { const playerSelected = playerChoice[0]; // 目前固定玩家选scissor,后续可改为动态选择 // 平局判断 if (playerSelected === computerSelectedChoice) { return "its a draw!"; } // 玩家选剪刀的情况 if (playerSelected === "scissor") { return computerSelectedChoice === "stone" ? "the computer won!" : "you won!"; } // 玩家选石头的情况 if (playerSelected === "stone") { return computerSelectedChoice === "paper" ? "the computer won!" : "you won!"; } // 玩家选布的情况 if (playerSelected === "paper") { return computerSelectedChoice === "scissor" ? "the computer won!" : "you won!"; } }
完整修复后的代码
const playerChoice = ["scissor", "stone", "paper"]; const computerChoice = function() { let randomNumber = Math.floor(Math.random() * playerChoice.length); if (randomNumber === 0) { return "scissor"; } if (randomNumber === 1) { return "stone"; } if (randomNumber === 2) { return "paper"; } }; function game(computerSelectedChoice) { const playerSelected = playerChoice[0]; if (playerSelected === computerSelectedChoice) { return "its a draw!"; } if (playerSelected === "scissor") { return computerSelectedChoice === "stone" ? "the computer won!" : "you won!"; } if (playerSelected === "stone") { return computerSelectedChoice === "paper" ? "the computer won!" : "you won!"; } if (playerSelected === "paper") { return computerSelectedChoice === "scissor" ? "the computer won!" : "you won!"; } } const computerSelected = computerChoice(); console.log(`you chose ${playerChoice[0]}.`); console.log(`the computer chose ${computerSelected}.`); console.log(game(computerSelected));
内容的提问来源于stack exchange,提问作者Lance
相关产品推荐
相关产品推荐

