// Computer randomly selects Rock, Paper / Scissors
computerChoice = function computerPlay() {
let r = Math.random() * 3;
let choice;
if(r > 2) {
console.log('Rock');
return 'rock';
} else if (r > 1) {
console.log('Scissors');
return 'scissors';
} else {
console.log('Paper');
return 'paper';
}
}
//compare results
function compareChoice(userChoice, computerChoice) {
if (userChoice === computerChoice) {
console.log('Draw')
} else if(userChoice === 'paper') {
if(computerChoice == 'scissors') {
console.log ('You lose, try again!')
} else {
console.log('You win!')
}
} else if(userChoice === 'rock') {
if(computerChoice === 'paper') {
console.log('You lose! Try again!')
} else {
console.log('You win!')
}
} else if(userChoice === 'scissors') {
if (computerChoice === 'rock') {
console.log('You Lose! Try again!')
} else {
console.log('You win!')
}
}
}
function game() {
let userChoice = prompt('Choose rock, paper, or scissors!');
console.log('Your choice was ' + userChoice);
computerChoice();
compareChoice();
}
game();
你好!我正在尝试为Java中的Odin项目完成一个简单的剪刀石头布项目,但是,每当我尝试将字符串值与用户输入的内容进行比较时,它都会记录日志绘制,这意味着对于第一个if语句,与用户输入的内容无关。我已经搜索过,但不确定自己在做什么错。任何帮助将由衷的感谢!
您需要将用户选择和计算机选择传递到compareChoice中。
function game() {
let userChoice = prompt('Choose rock, paper, or scissors!');
console.log('Your choice was ' + userChoice);
compareChoice(userChoice, computerChoice());
}
在您的游戏功能中,您正在不带参数的情况下调用compareChoice()
。我不确定该语句如何运行,但唯一的解释似乎是两个参数都被分配了null
。因此是“抽奖”响应。
尝试此方法
function game() {
let userChoice = prompt('Choose rock, paper, or scissors!');
console.log('Your choice was ' + userChoice);
compareChoice(userChoice, computerChoice());
}
当您调用compareChoice()
函数时,代码不知道userchoice
和computerChoice()
的值。更改代码,以将这些值作为参数传递给compareChoice()
,如下所示:
computerChoice = function computerPlay() {
let r = Math.random() * 3;
let choice;
if (r > 2) {
console.log('Rock');
return 'rock';
} else if (r > 1) {
console.log('Scissors');
return 'scissors';
} else {
console.log('Paper');
return 'paper';
}
}
compareChoice = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
console.log('Draw')
} else if (userChoice === 'paper') {
if (computerChoice == 'scissors') {
console.log ('You lose, try again!')
} else {
console.log('You win!')
}
} else if (userChoice === 'rock') {
if(computerChoice === 'paper') {
console.log('You lose! Try again!')
} else {
console.log('You win!')
}
} else if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
console.log('You Lose! Try again!')
} else {
console.log('You win!')
}
}
}
game = () => {
let userChoice = prompt('Choose rock, paper, or scissors!');
console.log('Your choice was ' + userChoice);
compareChoice(userChoice, computerChoice());
}
game();