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

JavaScript石头剪刀布游戏多轮循环实现遇阻求助

石头剪刀布游戏多轮循环问题修复

首先,你的代码存在几个关键问题导致无法正常实现多轮循环和正确计分:

  • 计算机选择固定不变:randomvalue 在全局作用域只初始化一次,导致 getComputerChoice() 每次都返回相同结果。必须每次调用该函数时重新生成随机数。
  • 语法错误:playerchoice() 函数里的 ese 是拼写错误,应该是 else,这会导致函数无法正常执行。
  • 计分逻辑错误:在 results() 函数中,剪刀输给石头的分支里,computerscore++ 写在 return 语句之后,永远不会执行,导致该情况计算机无法得分。
  • 循环未处理游戏逻辑:最后的 while 循环仅弹出输入框,没有调用游戏核心逻辑(获取玩家选择、计算机选择、计算结果、更新分数、显示结果)。
  • 未触发游戏结束判断:WinGame() 函数定义后从未被调用,无法在一方达到5分时宣布最终结果。

以下是修复后的完整代码:

let rock = "rock";
let paper = "paper";
let scissors = "scissors";

function getComputerChoice() {
  // 每次调用都生成新的随机数
  let randomvalue = Math.random();
  if (randomvalue <= 0.33) {
    return rock;
  } else if (randomvalue <= 0.66) {
    return paper;
  } else {
    return scissors;
  }
}

let playerscore = 0;
let computerscore = 0;

function results(player, computer) {
  if (player === rock && computer === rock) {
    return "平局!";
  } else if (player === rock && computer === paper) {
    computerscore++;
    return "你输了!纸包石头。";
  } else if (player === rock && computer === scissors) {
    playerscore++;
    return "你赢了!石头砸剪刀。";
  }

  if (player === scissors && computer === scissors) {
    return "平局!";
  } else if (player === scissors && computer === rock) {
    computerscore++; // 修正位置,放在return之前
    return "你输了!石头砸剪刀。";
  } else if (player === scissors && computer === paper) {
    playerscore++;
    return "你赢了!剪刀剪纸。";
  }

  if (player === paper && computer === paper) {
    return "平局!";
  } else if (player === paper && computer === scissors) {
    computerscore++;
    return "你输了!剪刀剪纸。";
  } else if (player === paper && computer === rock) {
    playerscore++;
    return "你赢了!纸包石头。";
  }
}

function playerchoice() {
  let choice = prompt("请选择:rock, paper, scissors");
  // 统一转为小写,避免大小写输入错误
  choice = choice.toLowerCase();
  if (choice === "rock") {
    return rock;
  } else if (choice === "paper") { // 修正拼写错误
    return paper;
  } else {
    return scissors;
  }
}

function checkGameEnd() {
  if (playerscore === 5) {
    alert("你赢得了整个游戏!");
    return true;
  } else if (computerscore === 5) {
    alert("你输掉了整个游戏!");
    return true;
  }
  return false;
}

// 主游戏循环
while (playerscore < 5 && computerscore < 5) {
  let player = playerchoice();
  let computer = getComputerChoice();
  let result = results(player, computer);
  alert(result);
  alert(`玩家得分:${playerscore}\n电脑得分:${computerscore}`);
  
  // 检查游戏是否结束
  if (checkGameEnd()) {
    break;
  }
}

额外优化点:

  • 给玩家输入做了小写转换,避免因输入大写导致的错误判断。
  • 将游戏结束判断改为 checkGameEnd() 并在循环中调用,达到5分时立即结束游戏并弹窗提示。

内容的提问来源于stack exchange,提问作者johhny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:08:27