完全是新手...
研究一个用户杀死龙或被吃掉的盲目概率“游戏”的在线示例。我知道游戏使用 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");
}
}
谢谢
最佳答案
你的循环条件是问题所在
var youHit, damageThisRound;
for (var totalDamage = 0; totalDamage < 4; totalDamage += damageThisRound) {
youHit = Math.floor(Math.random() * 2);
if (youHit) {
//need to calculare the damage in each loop
damageThisRound = Math.floor(Math.random() * 5 + 1);
snippet.log("You hit and did " + damageThisRound);
} else {
snippet.log("The dragon kills you");
//you need to stop the loop here
break;
}
}
//need this outside of the loop since the increment is in the for loop block
if (youHit) {
snippet.log("You did it! You slew the dragon!");
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - Javascript 中的 For 循环与 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31153285/