繁体   English   中英

大小为 8x8 的二维数组,第一列实际上是最后一列

[英]A 2D Array of size 8x8, the first column is actually the last column

我正在使用 p5.js 库和 JavaScript 创建一个国际象棋游戏,我为棋盘创建了一个二维数组。 问题是第二列是第一列,第一列是最后一列。

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

在此处输入图像描述

如您所见,第一列实际上是第二列。 第一个我做了测试,它是最后一列。

提前致谢。

当您将图块添加到 gameBoard 数组时,这应该是gameBoard[i][j] = new Tile(i, j); 而不是gameBoard[j][i] = new Tile(i, j);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM