2D-массив размером 8x8, первый столбец фактически является последним столбцом - PullRequest
1 голос
/ 03 августа 2020

Я создаю игру в шахматы с библиотекой p5. js и JavaScript, я создал 2D-массив для доски. Проблема в том, что второй столбец является первым, а первый столбец - последним.

"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);

У меня также есть другие отдельные файлы

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];
  }
}

Отдельный файл для констант:

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 };

введите описание изображения здесь

Как видите, первый столбец на самом деле является вторым. и первый я провел тесты, и это последний столбец.

Заранее спасибо.

1 Ответ

0 голосов
/ 03 августа 2020

Когда вы добавляете плитки в массив gameBoard, это должно быть gameBoard[i][j] = new Tile(i, j); вместо gameBoard[j][i] = new Tile(i, j);

...