【发布时间】:2021-04-06 08:58:10
【问题描述】:
我是 Javascript 新手,到目前为止,我刚刚看了一个 3 小时的教程并参加了一些私人编程课程。我被分配了我的第一个项目,在那里我尝试模拟两支军队之间的战斗。这是代码。
var myArmy = ["arcieri", "fanteria", "cavalleria", "morale"] // <--- my Army brigades
function rng_loop() {
Math.floor(Math.random * myArmy.length) // <---- the rng function
}
while (myArmyStrength > 0 && enemyArmyStrength > 0) {
rng_loop()
} if (rng_loop() > 1) {
enemyArmyStrength - 25
} else if (rng_loop() < 1) {
myArmyStrength - 20
}
/* this is what was supposed to be my loop generating random numbers and killing off both armies based on the value of said random numbers until one of the two armies got to 0. myArmyStrength and enemyArmyStrength were specified earlier on. */
if (myArmyStrength > 0 && enemyArmyStrength <= 0) {
console.log("we won the battle! Roma invicta!")
} else if (myArmyStrength <= 0 && enemyArmyStrength > 0) {
console.log("We lost the battle...")
}
/* this if else statement was supposed to console.log a message either announcing a victory or defeat to the enemy army, but it's not console.logging anything. Why is that so? */
【问题讨论】:
-
rng_loop缺少退货声明 -
我注意到的第一件事是您没有从
nrg_loop()返回值。在该函数体中使用return Math.floor(....。 -
另外
Math.random()是一种方法。你必须使用()来调用它
标签: javascript math random while-loop