javascript - 平局结果无法输出
问题描述
在创建石头、纸、剪刀应用程序时,我的任务是在控制台中输出特定的结果,例如输出纸-纸并接收'It's a tie' 结果。好吧,我试图这样做,但由于某种原因,我不能这样做。代码如下:
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
const winner = () => {
const choice1 = user('rock');
const choice2 = computer();
if(choice1 === choice2) {
return 'It\'s a tie!';
}
if(choice1 === 'rock') {
if(choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'paper') {
if(choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'scissors') {
if(choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
console.log(winner('paper', 'paper'));
例如,当我尝试输入 console.log(winner('paper', 'paper')) 时,结果是随机的,这意味着它可能是赢、输或平局(或者我认为是原因) ) 计算机的选择是随机的,但这就是我被要求创建计算机选择的方式。如果我输入 console.log(('paper', 1)) 我会得到相同的结果,但不知何故,任务要求我使用 console.log(winner('paper', 'paper')) 并告诉我结果应该是平局。我也尝试让用户在choice1 中没有参数,但由于用户的选择中没有输入,我得到一个错误。
任务如下:
console.log(determineWinner('paper', 'scissors')); // prints something like 'The computer won!'
console.log(determineWinner('paper', 'paper')); // prints something like 'The game is a tie!'
console.log(determineWinner('paper', 'rock')); // prints something like 'The user won!'
任何帮助或想法将不胜感激。谢谢!
解决方案
像这样的东西会起作用。如果这是你需要的。
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
const random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
// Here is where you need to change something
const determineWinner = (userChoice, computerChoice) => {
// And use the parameters here:
const choice1 = userChoice;
const choice2 = computerChoice;
if (choice1 === choice2) {
return 'It\'s a tie!';
}
if (choice1 === 'rock') {
if (choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'paper') {
if (choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'scissors') {
if (choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
};
const userInput = 'rock';
console.log(determineWinner(user(userInput), computer()));
console.log(determineWinner('rock', 'paper'));
console.log(determineWinner('paper', 'paper'));
// For you requirement:
console.log(determineWinner('paper', 'scissors'));
console.log(determineWinner('paper', 'paper'));
console.log(determineWinner('paper', 'rock'));
但是,如果您按照您的要求对参数进行硬编码,那么您的功能user
将computer
不会被使用。