Learn Basic JavaScript by Building a Role Playing Game - Step 114

Hi All,

Could you describe why we need to include fighting like this:

monsterHealth = monsters[fighting].health;

I know we have a variable named monsters that have health but why we add [fighting] to the code? what does it do?
Know that I have set fighting with different numbers so far but they are at the bottom of the page

function fightSlime() {
    fighting = 0;
    goFight();
};


function fightBeast() {
    fighting = 1;
    goFight();
};

function fightDragon() {
    fighting = 2;
    goFight();
};

Thank you in advance for your help.

Hi @YoungZeeZee

To help answer your question, take a look at the monsters array.

const monsters = [
  {
    name: "slime",
    level: 2,
    health: 15
  },
  {
    name: "fanged beast",
    level: 8,
    health: 60
  },
  {
    name: "dragon",
    level: 20,
    health: 300
  }
]

When one of the functions to fight a monster is called, the fighting variable is assigned. Each monster has a fighting number, which corresponds to the index of the monsters array.

For example calling fightSlime sets fighting to 0.
Then, the goFight function is called, where the monsterHealth variable is assigned.

So, now the code has access to information about what monster the player is fighting, and then setting the health of just that monster.

Happy coding

Thank you now i understand it

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.