我正在创建一个石头,纸,剪刀游戏,只是测试我未完成的代码。游戏是在用户和计算机之间。
如您所见,computerselect
将生成随机的“石头”、“纸”或“剪刀”。问题是,在没有刷新页面的情况下,每次我在提示中键入“石头”并点击确定时,我都会循环得到相同的 console.log 消息:“干得好!石头打败剪刀”或“对不起!纸打败石头”。换句话说,游戏已经变得一边倒;每次我键入“岩石”并点击确定,要么我总是赢,要么电脑总是赢。
更新:我已经修改了代码,但另一个问题是有时代码会在console.log中重复,而不会增加任何分数。如果你看截图,它已经重复了代码2次,但没有添加分数。
const playerSelection = ''
const computerSelection = computerPlay()
let computerScore = 0;
let playerScore = 0;
console.log(playRound(playerSelection, computerSelection))
function computerPlay(){
let values = ['rock', 'paper', 'scissors'],
valueToUse = values [Math.floor(Math.random()* values.length)];
return valueToUse;
};
function playRound(playerSelection, computerSelection) {
while(true){
playerSelection = prompt ('Pick your poison');
if (playerSelection.toLowerCase() === 'rock' && computerPlay() === 'paper'){
computerScore += 1
console.log('Sorry! Paper beats Rock')
}
else if (playerSelection.toLowerCase() === 'rock'.toLowerCase() && computerPlay() === 'scissors'){
playerScore += 1
console.log('Good job! Rock beats Scissors');
}
else
{
console.log('Please type Rock, Paper, or Scissors')
}
console.log (`User Selection: ${playerSelection.toUpperCase()} | Player Score: ${playerScore}
Computer Selection: ${computerSelection.toUpperCase()} | Computer Score: ${computerScore}`);
}
}
对代码进行以下更改将使其正常工作:
新版本:
const playerSelection = ''
const computerSelection = ''
原始版本:
const playerSelection = ''
const computerSelection = computerPlay()
新版本:
playerSelection= prompt ('Pick your...');
computerSelection = computerPlay();
原始版本:
playerSelection= prompt ('Pick your...');
(免责声明:我已尽可能接近原始代码。)