【发布时间】:2021-07-21 17:20:03
【问题描述】:
所以基本上,我正在为我参与的 Discord 机器人项目编写井字游戏。我只希望board[]; 是一个多维数组。我该怎么做?
代码如下:
require('dotenv').config();
const { Client } = require('discord.js');
const client = new Client();
const PREFIX = process.env.DISCORD_BOT_PREFIX;
class TicTacToe {
/* here's the variable */
board[];
boardSize;
#emptyPiece;
#firstPiece;
#secondPiece;
constructor(boardSize, emptyPiece, firstPiece, secondPiece) {
this.boardSize = boardSize;
this.#emptyPiece = emptyPiece;
this.#firstPiece = firstPiece;
this.#secondPiece = secondPiece;
/* Initializing it here */
for (let i = 0; i < boardSize; i++)
for (let j = 0; j < boardSize; j++)
this.board[i][j] = emptyPiece;
}
isBoardEmpty() {
for (let i = 0; i < this.boardSize; i++)
for (let j = 0; j < this.boardSize; j++)
if (this.board[i][j] !== this.#emptyPiece) return false;
return true;
}
isPieceEmpty(x, y) {
return this.board[x][y] === this.#emptyPiece;
}
}
let ticTacToe = new TicTacToe(3, '-', 'x', 'o');
client.on('message', (message) => {
if (message.author.bot && !message.content.startsWith(PREFIX)) return;
const [COMMAND_NAME, ...args] = message.content.toLowerCase().trim().substring(PREFIX.length).split(/\s+/g);
if (COMMAND_NAME === 'showBoard') message.channel.send(ticTacToe.board);
});
client.login(process.env.DISCORD_BOT_TOKEN).then(r => {
console.log(`${client.user.tag} logged in!`);
});
【问题讨论】:
-
在类中,它只是
board = [],但为什么不在构造函数中将其设为this变量,即this.board = []?如果你想要一个预先分配的大小,你想要board = [...Array(boardSize)].map(() => Array(boardSize).fill(0))或board = [[0,0,0],[0,0,0],[0,0,0]]之类的东西吗? -
你必须用
[]初始化数组和数组的每一行。
标签: javascript node.js arrays multidimensional-array