2015-01-12 88 views
-2

我剛剛完成了一些關於「CodeAcademy」的練習,它教會了我創建一個岩石,紙和剪刀遊戲。一切工作正常,除了我想要接收的輸出。我沒有得到「紙勝利」。我所有得到它「紙」。我剛剛開始掌握Javascript的基礎,這就是爲什麼我還不是一個強大的腳本。Javascript遊戲給出錯誤的輸出

var userChoice = prompt("Do you choose rock, paper or scissors?"); 
var computerChoice = Math.random(0); 

if (computerChoice < 0.34) { 
    computerChoice = "rock"; 
} else if(computerChoice <= 0.67) { 
    computerChoice = "paper"; 
} else { 
    computerChoice = "scissors"; 
} 

console.log("Computer: " + computerChoice); 

var compare = function(choice1, choice2) { 
    if(choice1 === choice2) { 

     return ("The result is a tie!"); 
    } 

    if (choice1 === "paper") { 
     if (choice2 === "rock") { 
      return "paper wins"; 
     } else { 
      if (choice2 === "scissors") { 
       return "scissors wins"; 
      } 
     } 
     if (choice1 === "scissors") { 
      if (choice2 === "rock") { 
       return "rock wins"; 
      } else { 
       if (choice2 === "paper") { 
        return "scissors wins"; 
       } 
      } 
     } 
    } 

}; 
+3

代碼的行爲與設計相同 - 您正在記錄'computerChoice',而不是'compare()'返回的值。 –

+0

無論如何,你的代碼永遠不會調用你的'compare()'函數。簡單地聲明一個函數只是使其*可用* - 它實際上不會*做任何事情,直到它被調用。 – Pointy

回答

0

我想你是選擇選擇調用比較功能。所以你正在發送用戶選擇的功能。現在你應該將它與computerChoice進行比較。那裏有什麼選擇?

0

正如其他人所說,你永遠不會調用你的比較函數,你永遠不會返回任何該函數的值。即使你的功能無論如何也會在大部分時間裏失效。

您結構:

if (choice1 === "paper") { 
    if (choice2 === "rock") { 
     return "paper wins"; 
    } else { 
     if (choice2 === "scissors") { 
      return "scissors wins"; 
     } 
    } 
    if (choice1 === "scissors") { //is never true because choice1 is always "paper" 
     if (choice2 === "rock") { 
      return "rock wins"; 
     } else { 
      if (choice2 === "paper") { 
       return "scissors wins"; 
      } 
     } 
    } 
} //if choice1 === "paper" ends here 
//no love for the rock? 

你想實現什麼:

if (choice1 === "paper") { 
     if (choice2 === "rock") 
     { 
      return "paper wins"; 
     } 
     else if (choice2 === "scissors") 
     { 
      return "scissors wins"; 
     } 
} 
else if (choice1 === "scissors") 
{ 
     if (choice2 === "rock") 
     { 
      return "rock wins"; 
     } 
     else if (choice2 === "paper") 
     { 
      return "scissors wins"; 
     } 
} 
else if (choice1 === "rock") //don't forget the rock 
{ 
     if (choice2 === "paper") 
     { 
      return "paper wins"; 
     } 
     else if (choice2 === "scissors") 
     { 
      return "rock wins"; 
     } 
} 

然後,你將不得不調用你的函數是這樣的:

var result = compare(userChoice, computerChoice); 

你登錄的result變量。在你的例子中,你記錄computerChoice,它只能是「紙」,「剪刀」或「搖滾」,因爲這是你給它的值,而不是函數的值。

既然你讓用戶輸入任何他/她想要的東西,你顯然也必須驗證他們的輸入,否則if/else結構將會失敗。