有人可以帮我调试这个简单的剪刀石头布游戏吗?
我相信该错误与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
或SCISSORS
。您也不应尝试将函数名称(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();