You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odin项目JS基础作业:playRound函数无法正确读取参数求助

石头剪刀布代码问题修复

核心问题梳理

  1. playRound函数未正确使用传入参数
    你定义的playRound函数参数名是getComputerChoice和getHumanChoice,但实际传入的是computerSelection和humanSelection,而且函数内部直接调用全局变量,完全忽略了传入的参数,导致每轮游戏无法使用新的选择。

  2. 拼写错误导致判断失效
    失败条件里的humanSelection == "scissor"少了末尾的s,应该是"scissors",这个错误会让“石头击败剪刀”的场景无法被正确判定。

  3. 全局选择仅初始化一次
    全局作用域中computerSelection和humanSelection只调用一次获取选择,后续每轮游戏不会重新生成电脑选择或询问玩家,导致游戏无法正常多轮进行。

  4. 无效输入无返回值
    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á

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 20:33:20