2016-07-12 29 views
-3

爲什麼我的程序無法正常工作?Javascript Rock Paper Scissors

我的Math.random有什麼問題嗎?

「你選擇石頭,紙還是剪刀?」

「你選擇石頭,紙還是剪刀?」

「你選擇石頭,紙還是剪刀?」

//////////////////////////////

var userChoice = prompt("Do you choose Rock, Paper or Scissors?") 

var computerChoice = Math.random(); 

//====================================== 

if(computerChoice <= 0.33) 
{ 
    computerChoice = "Rock"; 
} 

else if(computerChoice <= 0.66) 
{ 
    computerChoice = "Paper"; 
} 

else 
{ 
    computerChoice = "Scissors"; 
} 

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

//========================================== 

var compare = function(choice1, choice2) 
{ 
    if(choice1 === choice2) 
    { 
     return "The result is a tie!"; 
    } 

    else if(choice1 === "Rock") 
    { 
     if(choice2 === "Scissors") 
     { 
      return "Rock wins"; 
     } 
     else 
     { 
      return "Paper wins"; 
     } 
    } 

    else if(choice1 === "Paper") 
    { 
     if(choice2 === "Rock") 
     { 
      return "Paper wins"; 
     } 
     else 
     { 
      return "Scissors wins"; 
     } 
    } 

    else if(choice1 === "Scissors") 
    { 
     if(choice2 === "Paper") 
     { 
      return "Scissors wins"; 
     } 
     else 
     { 
      return "Rock wins"; 
     } 
    } 
}; 

compare(); 

回答

1

你打電話compare()不帶任何參數。你需要類似compare(userChoice, computerChoice)

0

我認爲你的邏輯總體上太複雜了。如果你以可能的選項的關聯數組和他們打的東西簡化,您可以簡化很多你的邏輯,就像這樣:

var userChoice = prompt("Do you choose Rock, Paper, or Scissors?"); 
userChoice = userChoice.toLowerCase(); 

var rules = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'}; 
var choices = Object.keys(rules); 

var computerChoice = choices[Math.floor(Math.random() * 3)]; 

// User entered an invalid option 
if (choices.indexOf(userChoice) < 0) { 
    console.log('You entered an invalid choice'); 
} else if (userChoice === computerChoice) { 
    console.log('Tie!!'); 
} else { 
    // now actually see who won 
    var userBeats = rules[userChoice]; 
    if (userBeats === computerChoice) { 
    console.log('User won with ' + userChoice + ' vs ' + computerChoice); 
    } else { 
    console.log('Computer won with ' + computerChoice + ' vs ' + userChoice); 
    } 
} 

Working fiddle

當然,你仍然可以分開的事進入功能。

另一件容易的事情是Math.floor(Math.random() * 3)將產生一個介於0和2之間的數字,因此您可以使用它訪問choices數組中的選項並跳過大部分賦值邏輯。

相關問題