-1
我最近开始学习Javascript,很享受它。所以,在了解了关于循环的一些信息后,我决定改进一个简单的Rock,Scissors,Paper游戏。改进是让玩家获胜和计算机胜利值作为变量,而不是循环函数,直到playerScore变量达到10的值。尽管我试图获得一般逻辑和我犯了一个错误,但语法还不是很好。 。需要帮助解决循环问题
为了达到我的目标,我已经声明了两个变量 - playerScore和computerScore,其初始值为0。每个玩家赢或电脑赢了,我决定增加+ 1变量之后。
比开始的比赛中,我声明了一个函数琐事(),并使用循环虽然它。循环似乎是无限的,不止于此,当前的结果不会记录到控制台。任何帮助非常感谢,将帮助我理解逻辑远远超过我通过的任何课程。
下面的代码:
var playerScore = 0;
var computerScore = 0;
function getUserChoice() {
var userInput = prompt('Choose stone, scissors or paper');
userInput = userInput.toLowerCase();
if(userInput === 'stone' || userInput === 'paper' || userInput === 'scissors' || userInput === 'bomb') {
return userInput;
}
else {
alert('Error! Choose stone, scissors or paper!');
}
}
function getComputerChoice() {
var randomNumber = Math.floor(Math.random() *3);
if(randomNumber === 1) {
return 'stone';
}
else if(randomNumber === 2) {
return 'paper';
}
else {
return 'scissors';
}
}
function determineWinner (userChoice, computerChoice) {
if(userChoice === computerChoice) {
return 'That's a tie!';
}
if(userChoice === 'stone') {
if(computerChoice === 'scissors') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
else {
if(computerChoice === 'paper') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!'
}
}
}
if(userChoice === 'paper') {
if(computerChoice === 'scissors') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'stone') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player wonи!';
}
}
}
if(userChoice === 'scissors') {
if(computerChoice === 'stone') {
computerScore = computerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Computer won!';
}
else {
if(computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
}
}
}
if(userChoice === 'bomb') {
if(computerChoice === 'stone' || computerChoice === 'scissors' || computerChoice === 'paper') {
playerScore = playerScore + 1;
сonsole.log(playerScore);
console.log(computerScore);
return 'Player won!';
return 'Player won!';
}
}
}
while(playerScore < 10) {
function playGame() {
var userChoice = getUserChoice();
var computerChoice = getComputerChoice();
alert('Player chose' + ' ' + userChoice + '!');
alert('Computer chose' + ' ' + computerChoice + '!');
alert(determineWinner(userChoice, computerChoice));
playGame() = false;
}
};
playGame();
非常感谢,这工作!我想要做的另一件事是跟踪电脑和玩家的当前分数。在'function determineWinner'中,在每一个if/else语句中我都添加了'console.log(playerScore); \t console.log(computerScore);',但它只显示循环完成时控制台的结果,而不是“在线”。任何明显的方法来解决这个问题 – atogz
你必须给浏览器“呼吸时间”。要做到这一点,你必须删除'while'循环,并使用诸如'setTimeout'或'setInterval'之类的东西。 –