随机数生成器和if语句

时间:2013-12-01 02:44:02

标签: javascript if-statement random numbers

此代码可以提示两个玩家名称,并为每个玩家生成1到6之间的随机数。然后应该比较这两个数字并提供哪个玩家具有更高数字的输出或者如果存在平局则显示领带。有时它会起作用,有时它会反过来,但是当它们没有时,它会说两个数字匹配。

任何人对我都有任何想法?

var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "

main()



function main() 
{

    do {
      getNames()
      rollDice()
      displayResults()
      endProgram()
    }
  while (end == "yes")


}


function getNames()
{
    playerOne = prompt("Please enter the name of Player One: ")
    playerTwo = prompt("Please enter the name of Player Two: ")

}

function rollDice()
{

    p1Number = Math.floor((Math.random()*6)+1)
    p2Number = Math.floor((Math.random()*6)+1)



    if (p1Number > p2Number) 
    {
        return playerOne
    }

    else if (p1Number < p2Number)
    {       
        return playerTwo
    }

    else 
    {   
        return "Sorry no winner, there was a tie"
    }   


}

function displayResults()
{
    window.alert(playerOne + " rolled a " + p1Number)
    window.alert(playerTwo + " rolled a " + p2Number)
    window.alert("The winner is! " + rollDice())

}



function endProgram()
  {
    end = prompt("Do you want to play again? Enter yes or no")
    if (end == "no")
     window.alert("Thank you for playing");

    else if (end == "yes")

    return end;
   }

2 个答案:

答案 0 :(得分:1)

window.alert("The winner is! " + rollDice())

此行第二次再次调用rollDice。您显示第一个呼叫的结果,然后重新滚动并显示第二个呼叫的返回值(可能不同)。

// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)

// recall rollDice
window.alert("The winner is! " + rollDice())

答案 1 :(得分:0)

displayResults()中,您在为其分配值之前显示p1Numberp2Number的值(因为这发生在rollDice()内)。

所以你的程序正在运行,但你的诊断输出会误导你。