有人可以帮我调试这个简单的石头剪刀布游戏吗?
我认为该错误与 playgame() 函数有关
function playgame() {
let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
let computerChoice = computerPlay();
console.log(rpsgame(computerPlay, userChoice));
}
function computerPlay() {
return Math.floor(Math.random() * (3) + 1);
if (computerPlay == 1) {
computerPlay = "ROCK";
} else if (computerPlay == 2) {
computerPlay = "PAPER";
} else {
computerPlay = "SCISSORS";
}
}
最佳答案
return
立即终止函数;您的 computerPlay
函数永远不会超过第一行。相反,您应该将random
调用放入变量中,然后返回ROCK
、PAPER
或剪刀
。您也不应该尝试将函数名称 (computerPlay
) 重新分配给字符串。
function playgame() {
let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
let computerChoice = computerPlay();
console.log(computerChoice);
}
function computerPlay() {
const rnd = Math.floor(Math.random() * (3));
if (rnd === 0) {
return "ROCK";
} else if (rnd === 1) {
return "PAPER";
} else {
return "SCISSORS";
}
}
playgame();
如果您想要两者随机数字索引和playgame
中的选项名称,您可以立即返回所选的随机数computerPlay
然后让 playgame
将其转换为名称。为了更简洁,使用对象查找而不是 if/else
:
function playgame() {
const playNames = {
0: 'ROCK',
1: 'PAPER',
2: 'SCISSORS'
}
let userChoice = prompt("Rock, Paper, or Scissors?").toUpperCase();
let computerChoice = computerPlay();
console.log(computerChoice + ' aka ' + playNames[computerChoice]);
}
function computerPlay() {
return Math.floor(Math.random() * 3);
}
playgame();
关于javascript - 调试石头剪刀布游戏? JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459468/