-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'之類的東西。 –