2016-07-12 23 views
-3

私のプログラムはなぜ機能しませんか?Javascriptロックペーパーはさみ

私の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

を、あなたはまだ別の事をすることができます機能に組み込む。

もう1つは、Math.floor(Math.random() * 3)が0と2の間の数値を生成するため、それを使用してchoices配列の選択肢にアクセスし、割り当てロジックのほとんどをスキップすることができます。

関連する問題