Odin项目JS基础作业:playRound函数无法正确读取参数求助
石头剪刀布代码问题修复
核心问题梳理
playRound函数未正确使用传入参数
你定义的playRound函数参数名是getComputerChoice和getHumanChoice,但实际传入的是computerSelection和humanSelection,而且函数内部直接调用全局变量,完全忽略了传入的参数,导致每轮游戏无法使用新的选择。拼写错误导致判断失效
失败条件里的humanSelection == "scissor"少了末尾的s,应该是"scissors",这个错误会让“石头击败剪刀”的场景无法被正确判定。全局选择仅初始化一次
全局作用域中computerSelection和humanSelection只调用一次获取选择,后续每轮游戏不会重新生成电脑选择或询问玩家,导致游戏无法正常多轮进行。无效输入无返回值
getHumanChoice函数在用户输入错误时仅弹出警告,没有返回值,会导致humanSelection变为undefined,引发后续判断逻辑错误。
修复后的完整代码
let humanScore = 0; let computerScore = 0; function getComputerChoice() { let computerRound = Math.random(); if (computerRound <= 0.33) { return "rock"; } else if (computerRound >= 0.34 && computerRound < 0.66) { return "paper"; } else { return "scissors"; } } function getHumanChoice() { while (true) { let humanRound = prompt("Rock, Paper or Scissors? ").toLowerCase(); if (humanRound === "rock" || humanRound === "paper" || humanRound === "scissors") { return humanRound; } alert("请输入有效的选项:rock、paper或scissors"); } } function playRound(computerSelection, humanSelection) { // 修正拼写错误,使用传入的参数而非全局变量 if ( (computerSelection === "paper" && humanSelection === "rock") || (computerSelection === "scissors" && humanSelection === "paper") || (computerSelection === "rock" && humanSelection === "scissors") ) { computerScore++; return `You lose ${computerSelection} beats ${humanSelection}`; } else if (computerSelection === humanSelection) { return `Draw`; } else { humanScore++; return `You win ${humanSelection} beats ${computerSelection}`; } } // 示例:进行一轮游戏 const computerChoice = getComputerChoice(); const humanChoice = getHumanChoice(); console.log(playRound(computerChoice, humanChoice)); console.log(`当前比分:玩家 ${humanScore} - ${computerScore} 电脑`);
关键修改说明
- 将
playRound的参数改为computerSelection和humanSelection,函数内部直接使用传入的参数,确保每轮使用最新选择。 - 修正
scissor为scissors,修复判断逻辑漏洞。 - 给
getHumanChoice添加循环,直到用户输入有效内容才返回,避免出现undefined。 - 在
playRound中添加分数更新逻辑,让游戏具备计分功能。
内容的提问来源于stack exchange,提问作者Michaela Čermáková
相关产品推荐
相关产品推荐

