javascript - 大小为 8x8 的 2D Array,第一列实际上是最后一列
问题描述
我正在使用 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];
}
}
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 };
如您所见,第一列实际上是第二列。第一个我做了测试,它是最后一列。
提前致谢。
解决方案
当您将瓷砖添加到 gameBoard 数组时,这应该gameBoard[i][j] = new Tile(i, j);
是gameBoard[j][i] = new Tile(i, j);
推荐阅读
- c++ - 用 string_view 构造 istringstream 不会编译
- javascript - 下拉列表的第一项未定义
- game-maker - 数字模数加法的函数(如度数)
- c# - 我怎样才能将ActionLink“添加图片”放在导航栏的中间?
- javascript - 如何向此代码添加一个函数,使我能够从下拉菜单中选择选项?
- python - 如何使用python从本地网站获取数据
- python - 从邻接矩阵中绘制具有边权重的特定网络
- jquery - 如何使 jquery 数据表呈现的搜索框可访问?
- android - 无法构建发布应用程序,gradle 说找不到封闭方法'boolean onCreateOptionsMenu(android.view.Menu)
- python - 为什么形状不会在屏幕上移动?