【发布时间】:2014-07-25 16:30:08
【问题描述】:
我从 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”和“Aw...你输了”,因为第一次投出的是 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);
}
【问题讨论】:
-
分离出逻辑。例如,有一个掷骰子并存储结果的函数,以及一个返回结果的函数。或者,一个新对象调用:启动“骰子事务”、“向运行总和添加新骰子”、“返回运行总和”和“结束事务”。
-
您显示的代码过于集成。将其拆分为逻辑部分,然后组合这些部分——可能然后依次组合这些部分。
-
我相信你要找的是一个变量。
标签: javascript node.js random