1

I'm creating a chess game with p5.js library and JavaScript, I've created a 2D Array for the board. The problem is that the second column is the fisrt one, and the fisrt column is the last column.

"use strict";

import * as CONSTANTS from "./constants.js";
import { Tile } from "./Tile.js";

function create2DArray(cols, rows) {
  let array = new Array(cols);
  for (let i = 0; i < array.length; i++) {
    array[i] = new Array(rows);
  }
  return array;
}

let gameBoard = create2DArray(CONSTANTS.boardCols, CONSTANTS.boardRows);

const sketch = (p5) => {
  Tile.prototype.draw = function () {
    p5.stroke(0);
    p5.rect(this.position()[0], this.position()[1], this.width, this.width);

    //Va por col*fila
    if (this.absPosition()[0] == 0) {
      p5.fill(50);
    } else {
      p5.fill(255);
    }
  };

  p5.setup = () => {
    p5.createCanvas(CONSTANTS.boardSize, CONSTANTS.boardSize);
    for (let i = 0; i < CONSTANTS.boardCols; i++) {
      for (let j = 0; j < CONSTANTS.boardRows; j++) {
        gameBoard[j][i] = new Tile(i, j);
      }
    }
  };

  p5.draw = () => {
    for (let i = 0; i < CONSTANTS.boardCols; i++) {
      for (let j = 0; j < CONSTANTS.boardRows; j++) {
        gameBoard[i][j].draw();
      }
    }
  };
};

let board = new p5(sketch, CONSTANTS.chessBoard);

I also have other separate files

import * as CONSTANTS from "./constants.js";

export class Tile {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = CONSTANTS.tileWidth;
  }

  absPosition() {
    return [this.x, this.y];
  }
  position() {
    return [this.x * this.width, this.y * this.width];
  }
}

Separate file for consts:

const chessBoard = document.querySelector(".board");
const lightTile = [240, 217, 181];
const darkTile = [181, 136, 99];
const boardSize = 480;
const tileWidth = 60;
const boardRows = boardSize/tileWidth;
const boardCols = boardSize/tileWidth;
    
export { boardSize, chessBoard, lightTile, darkTile, boardRows, boardCols, tileWidth };

enter image description here

As you can see the first column is actually the second one. and the first one Ive made tests and it is the last column.

Thanks in advance.

1 Answer 1

0

When you're adding the tiles to the gameBoard array, this should be gameBoard[i][j] = new Tile(i, j); instead of gameBoard[j][i] = new Tile(i, j);

2
  • i.imgur.com/K7xc8Vm.png now this is happening. Aug 3, 2020 at 16:40
  • You might have to put the if statement in the sketch function before you draw the rectangle.
    – person
    Aug 3, 2020 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.