如何只生成一次随机数,并重用其输出?

时间:2014-07-25 16:30:08

标签: javascript node.js random

我从Javascript开始学习编程,我的导师让我们做了一个随机骰子,一个简单的Math.ceil(6 * Math.random())

我试图稍微对其进行游戏化并判断结果。所以,如果你掷出一个7,你就赢了,任何其他的你输了。最终的结果是,

"你滚了一下:7 你赢了!"

但是,我试图通过大约说明来完成:

console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose.  Better luck next time");

}

diceSum()函数每次都会进行评估,所以我可以得到"你滚动了一个:7"并且"噢......你输了#34;因为第一卷是7,但是当if语句进来时,diceSum是不同的。

如何像掷骰子一样生成一个随机数,然后反复重复使用它?

这是我当前的代码(远远超过必要,因为我试图显示值,所以我知道它是否正在返回正确答案):

//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
    return Math.ceil(6*Math.random());
};

//Sum up two dice rolls
var diceSum = function() {
   var firstDie = getDieRoll();
   var secondDie = getDieRoll();
   return firstDie+secondDie;
};
//

//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose.  Better luck next time."
//

//Outputs
//show total sum to compare with message below
console.log(diceSum())

//Return a message stating the result
console.log("You rolled a " + diceSum())

//View true false status to compare with message returned below
console.log(diceSum()==7)

//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){ 
console.log(winMsg);
 } else {
console.log(loseMsg);
}

2 个答案:

答案 0 :(得分:1)

您将结果放在变量中,并使用变量:

var sum = diceSum();

//Outputs
//show total sum to compare with message below
console.log(sum);

//Return a message stating the result
console.log("You rolled a " + sum)

//View true false status to compare with message returned below
console.log(sum == 7);

//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){ 
  console.log(winMsg);
} else {
  console.log(loseMsg);
}

顺便说一下,计算随机数的方法是错误的。 random method被定义为返回0 <= n <0的值。 1,即它可以为零,但它永远不会是一个。

如果您使用Math.ceil,效果是结果有时会为零,获得6的机会略小于其他数字。

改为使用Math.floor

function getDieRoll() {
  return Math.floor(6 * Math.random()) + 1;
};

答案 1 :(得分:0)

将其保存到变量:

var sum = diceSum();

console.log("You rolled a " + sum);

if (sum == 7) { 
    console.log(winMsg);
} else {
    console.log(loseMsg);
}

或者:

var sum = diceSum(),
    msg = sum == 7 ? winMsg : loseMsg;
console.log("You rolled a " + sum);
console.log(msg);