Reputation: 33
I'm new into this but basically I'm trying to make a JavaScript loop, where 2 fighters fight. I made an array with the 2 fighters and a button connected to my JavaScript from HTML. Now I need to make a loop where the fighters hit each other where the damage by 1 fighter is subtracted by the health of the other so on, later I need to display how the fight went in my html. but I don't know where to start I would be thankful for some help. This is what I have done and I don't know what to do after or if it is even right?
var fighters = [
{
"name":"Abdi",
"HP": 100,
"DMG": 20,
}
{
"name": "chriz",
"HP": 100,
"DMG": 11,
}
]
function myFunction() {
for (var i = 0; i < fighters.length; i++) {
fighters[i]
}
}
Upvotes: 1
Views: 70
Reputation: 33
function myFunction() {
while (fighters[0].HP > 0 && fighters[1].HP > 0) {
fighters[1].HP -= fighters[0].DMG;
fighters[0].HP -= fighters[1].DMG;
document.getElementById('Results').innerHTML+= fighters[1].HP ;
document.getElementById('Results').innerHTML+= fighters[0].HP;
}
Upvotes: 0
Reputation: 1221
You're doing perfect.
Few things --
fighters[i]
refers to a specific fighter. You may want to replace
that line with some actual logic, for example fighters[i].HP++
would increase their health by one.
Your fighters array doesn't have a comma. You need one.
You've defined the function that does what you need, but you haven't called it. You may want to call it by adding a line like myFunction();
Also, don't forget to output something or you'll never know what's happening! A lot of people use console.log()
for that, e.g. console.log(fighters[i].HP)
(Note: I specifically did not add the logic you mentioned because I believe that's homework ;)
Upvotes: 1