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

如何实现玩家选择后电脑重新生成随机选择(剪刀石头布游戏)

问题解决思路

你的代码核心问题是电脑的选择只在页面加载时生成了一次:全局变量computerSelection在页面初始化时就调用computerPicks()生成了随机值,之后再也不会重新计算,所以不管玩家点击多少次,电脑的选项都固定不变。

修改方案

把电脑选择的生成逻辑移到play函数内部,确保每次玩家做出选择时,都会重新生成一个随机选项:

  1. 删除全局作用域里的这行代码:
const computerSelection = computerPicks();
  1. 在play函数的开头,添加电脑选择的生成代码:

修改后的完整代码

//UI
let userScore = 0;
let compScore = 0;

const userScoreSpan = document.getElementById("userScore");
const compScoreSpan = document.getElementById("compScore");
const rockDiv = document.getElementById("r");
const paperDiv = document.getElementById("p");
const scissorsDiv = document.getElementById("s");
const results = document.getElementById("result");

//UI

rockDiv.addEventListener("click", function () {
play("rock");
});
paperDiv.addEventListener("click", function () {
play("paper");
});
scissorsDiv.addEventListener("click", function () {
play("scissors");
});

// How the game functions
const options = ["rock", "paper", "scissors"];

function computerPicks() {
const choice = options[Math.floor(Math.random() * options.length)];
return choice;
}

function play(playerSelection) {
// 每次游戏时重新生成电脑选择
const computerSelection = computerPicks();
if (playerSelection == computerSelection) {
results.innerHTML = `Its a tie`;
} else if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper")
) {
userScore++;
userScoreSpan.innerHTML = userScore;
results.innerHTML = `${playerSelection} beats ${computerSelection}`;
} else {
compScore++;
compScoreSpan.innerHTML = compScore;
results.innerHTML = `${computerSelection} beats ${playerSelection}`;
}
}

修改后,玩家每点击一次选项,电脑都会重新随机生成一个选择,不会再固定为同一选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:23:21