Я практикую циклы в javascript, но, написав его, получил бесконечный цикл, который я не могу решить. Я уверен, что его задним числом является проблема 20/20, но Я не вижу этого. Цикл в meleeChoiceНе могу понять, почему возникает бесконечный цикл
/*var meleeValues = function() {*/
var userDmg = Math.floor(Math.random()* 5 + 10);
var ghoulDmg = Math.floor(Math.random()* 4 + 8);
var ghoulHealth = 100;
var userHealth = 110 ;
var userTotalDmg = 0 ;
var ghoulTotalDmg = 0;
var firstAtk = function() {
firstStrike = Math.floor(Math.random()* 2 + 1);
if(firstStrike === 1) {
ghoulHealth = 100 - userTotalDmg;
console.log("You hit the ghoul for " + userDmg + " damage");
console.log("The ghoul has " + ghoulHealth + " health left");
userHealth = 110 - ghoulTotalDmg;
console.log("Ghoul hits you for " + userDmg + " damage");
console.log("You have " + userHealth + " health left");
} else {
userHealth = 110 - ghoulTotalDmg;
console.log("Ghoul hits you for " + userDmg + " damage");
console.log("You have " + userHealth + " health left");
ghoulHealth = 100 - userTotalDmg;
console.log("You hit the ghoul for " + userDmg + " damage");
console.log("The ghoul has " + ghoulHealth + " health left");
}
}
var meleeChoice = function() {
while(ghoulHealth > 0 && userHealth > 0) {
userTotalDmg += userDmg;
ghoulTotalDmg += ghoulDmg;
firstAtk;
userDmg = Math.floor(Math.random()* 5 + 10);
ghoulDmg = Math.floor(Math.random()* 4 + 8);
if (ghoulHealth < 0 && userHealth > 0) {
console.log("Congratulations, you have defeated the ghoul and gained 20xp");
} else if (ghoulHealth > 0 && userHealth < 0) {
console.log("You have been slain by the ghoul, may your corpse serve as a warning to future explorers");
} else {
console.log("It's not over yet");
}
}
}
meleeChoice()
/*var user = prompt("You run into a ghoul whilst exploring a dungeon, what do you choose to do?", "Fight | Sneak | Run").toLowerCase();
switch(user) {
case "fight":
var fight = prompt("Do you use melee or magic").toLowerCase()
if(fight === "melee") {
meleeChoice
}
}*/
Thanks
вы вызываете 'firstAtk' без скобок и так далее' meleeChoice' позже. в основном вы ничего не делаете с этим, просто нажимая ссылку на пустоту. –
Обратите внимание: в firstAtk вы, в основном, дважды используете тот же код - рассмотрите отдельные функции userAttack() и ghoulAttack(), которые вы меняете в порядке, в зависимости от того, кто первым ударит. –