Because we want to have multiple guns, it would be a waste of time creating each one, one at a time. So we create a parent class, and have many subclasses to that, just to make our lives easier, also making the code run faster.

class Gun {
	// code
}

In our gun class, we will need a constructor that sets all the constants for how the gun works.

constructor(tank) {
      this.bullet_size = 5;
      this.bullet_speed = 1.5;
      this.ammo = 1000; // Max shots for current gun
      this.clip = 5; // Max simultaenous shots
      this.fire_delay = 0.5;
      this.last_shot = Date.now();
      this.tank = tank; // Used for ignoring collisions when firing
      this.type = GunTypes.normal;
      this.damage_amount = 4;
      this.randomize_direction = false;
    }

All these variables are self explanatory, like how big they are, and the type. Things like that.

Our next method will be how the gun fires. We need coordinates to see where the direction of the bullet fires. We also add a random bit because the bullet will never fire completely straight.

fire(x, y, direction) {
      var bullet;
      if (this.randomize_direction) {
        direction += Math.random() * 10 - 5; // Add a random offset of +-5 degrees
      }
      if (this.clip > 0 && this.ammo > 0) {
        if (Date.now() - this.last_shot > this.fire_delay * 1000) {
          GUI_REDRAW_NEEDED = true; // GUI has info about remaining ammo
          this.clip--;
          this.ammo--;
          this.last_shot = Date.now();
          bullet = new Bullet(x, y, direction, this.damage_amount, this, this.bullet_size, this.bullet_speed);
        }
      }
      return bullet;
    }

A reload method to reload the gun.

reload() {
      // Adds one bullet to clip.
      this.clip++;
    }

A getter to get the name of the gun, for which our “normal” gun is called 40mm gun.

get_name() {
      return "40mm gun";
    }

A getter for the amount of ammo that our gun has, because it is normal, we will just keep it infinite.

get_ammo_str() {
      switch (this.type) {
        case GunTypes.normal:
          return "infinite";
          break;
        default:
          return this.ammo;
      }
    }
  };

Machine Gun Class

Now that we are done with our parent class. We can add a subclass of our parent class Gun. Coding our subclasses is very easy, all we have to change are the constructors, because subclasses inherit all methods from their parent class.