lundi 23 décembre 2019

Is there something wrong with this JS?

I am trying to code the game of chess using JS and p5.js and I have a problem in my code that I have not been able to resolve for a few days now.

Here is the code:

function setup() {
  // some other stuff: init canvas & board, set noStroke()

  let wp1 = new Piece('white', ['a', 2], 'p', board);
  wp1._draw();
}

I get an error at let wp1 = new Piece('white', ['a', 2], 'p', board);. It is from the constructor. I have plenty of other code in there, but this is the part with the error:

  switch (type) { // "type refers to the third argument, 'p', from the code above
      case 'p':
        this.type = new Pawn(this.color, this.square);
      case 'r':
        this.type = new Rook(this.color, this.square);
      case 'n':
        this.type = new Knight(this.color, this.square);
      case 'b':
        this.type = new Bishop(this.color, this.square);
      case 'k':
        this.type = new King(this.color, this.square);
      case 'q':
        this.type = new Queen(this.color, this.square);
      default:
        console.error(`Expected piece type as a one-letter string, but got "${type}".`);
    }

I am getting the error at the bottom even though I am passing 'p' into the function, and, obviously, 'p' === 'p' so there should be no error. I have tried several different approaches to solve this. Firstly, I tried rewriting the code as an if statement instead of a switch statement, in the following format:

if (type == 'p') {
  this.type = new Pawn(this.color, this.square);
} else if (type == 'r') {
  // same as above but with Rook()
} // ... and as such for all the other piece types
else {
  console.error(`Expected piece type as a one-letter string, but got "${type}".`);
}

... and I still get the error!

I also tried replacing the string 'p' with all the other piece types ('r', 'n', 'b', 'q', and 'k') to no avail.

Why isn't this working? I can't see a single thing wrong?

Aucun commentaire:

Enregistrer un commentaire