为什么石头剪刀布游戏始终输出‘not a tie’?附代码求助
问题分析与修复方案
核心问题:平局判断失效
你的getComputerChoice函数只在控制台打印了电脑的选择,但没有返回对应的字符串值。这导致playRound里的computerChoice变量始终是undefined,和用户输入的字符串永远无法相等,所以无论如何都会走else分支输出"not a tie"。
修复步骤
- 修改
getComputerChoice函数,让每个case返回对应的选择字符串:
function getComputerChoice () { let randomNumber = Math.floor(Math.random()*3); switch (randomNumber) { case 0: console.log("rock"); return "rock"; // 返回字符串值 case 1: console.log("paper"); return "paper"; // 返回字符串值 case 2: console.log ("scissors"); return "scissors"; // 返回字符串值 } }
- 关于函数调用位置的疑问:
在playRound内部调用getUserChoice和getComputerChoice是完全正确的。如果在外部定义这两个变量,每次引用变量时都会重新执行函数,导致多次弹窗;而放在playRound内部,只有调用一次playRound才会触发一次用户输入和电脑选择,符合你的需求。
修正后的完整代码
function getComputerChoice () { let randomNumber = Math.floor(Math.random()*3); switch (randomNumber) { case 0: console.log("rock"); return "rock"; case 1: console.log("paper"); return "paper"; case 2: console.log ("scissors"); return "scissors"; } } function getUserChoice () { let caseInsensitiveUserSelection = prompt("Rock, paper or scissors?"); let userChoice = caseInsensitiveUserSelection.toLowerCase(); return userChoice; } function playRound() { let userChoice = getUserChoice() let computerChoice = getComputerChoice() if (userChoice === computerChoice) { console.log("Tie game!") } else { console.log("not a tie") } } playRound()
这样修改后,平局的判断就能正常工作了,之后你可以继续补充胜负判断的逻辑。
内容的提问来源于stack exchange,提问作者kalper
相关产品推荐
相关产品推荐

