lundi 2 avril 2018

Switch not applied according to given value

I am working on a project for school and have encountered a weird behavior with a switch statement in JavaScript. Here is a snippet of the code:

generate: function()
{
var seed = randomNumber(1, 3);

switch (seed)
{
  case 1:
    this.type = "Slime";
    this.attack = 2;
    this.defense = 4;
    this.speed = 2;
    break;

  case 2:
    this.type = "Rabid Dog";
    this.attack = 5;
    this.defense = 2;
    this.speed = 8;
    break;

  case 3:
    this.type = "Titan";
    this.attack = 10;
    this.defense = 10;
    this.speed = 2;
    break;
}


}

This is a fairly basic switch statement but for some reason, case 1, slime is always run. the line randomNumber(1, 3) generates a pseudo random number from 1 to 3 (inclusive). The random number is regenerated every time my game is started.

I have used console.log() to figure what is going on with the seed value and have found that it is being pseudorandomly generated each time the game is started up, like it should. The switch statement itself is not working properly it seems.

If seed = 3 and the switch statement is run, it will for some reason still run case 1 when it should run case 3. Any idea of what is going on here?




Aucun commentaire:

Enregistrer un commentaire