【发布时间】:2015-09-18 03:16:01
【问题描述】:
这里是初学者...
通过一个用户杀死一条龙或被吃掉的无意识概率“游戏”的在线示例。我知道游戏使用 while 循环运行,所以我尝试使用 for 循环复制它,但失败了。我很好奇为什么 for 循环不起作用,以及是否有一些明显的原因需要使用 while 循环来完成。
下面是 工作 示例,其中有一个 while 循环来提供上下文。
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;
while (slaying) {
if (youHit) {
console.log("You hit the dragon and did " + damageThisRound + " damage!");
totalDamage += damageThisRound;
if (totalDamage >= 4) {
console.log("You did it! You slew the dragon!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon burninates you! You're toast.");
slaying = false;
}
}
这是 不工作 for 循环。
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
for(totalDamage=0;totalDamage>3;totalDamage+=damageThisRound){
if(youHit){
console.log("You hit and did "+damageThisRound);
totalDamage += damageThisRound;
if(totalDamage>3){
console.log("You did it! You slew the dragon!");
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon kills you");
}
}
谢谢
【问题讨论】:
-
你的 for 循环永远不会开始。
标签: javascript loops for-loop while-loop