我们可以为每个方块创建一个唯一的ID,以便在回合之间跟踪它们。在每个玩家的回合结束时,我们应该更新棋盘数组中的相应索引,以便记录当前棋子的位置。
下面是一个示例代码:
// Create empty game board
let gameBoard = [
[null, null, null],
[null, null, null],
[null, null, null]
];
// Initialize unique IDs for each game board square
let idCounter = 0;
for (let i = 0; i < gameBoard.length; i++) {
for (let j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = idCounter++;
}
}
// Player 1's turn
let player1Selection = gameBoard[0][0]; // Example: Player 1 selects top-left square
gameBoard[0][0] = null; // Clear square on game board
// Update game board array to reflect new position of player 1's selection
// (Assume selected ID is stored in variable player1Selection)
// ...
// Player 2's turn
let player2Selection = gameBoard[1][1]; // Example: Player 2 selects middle square
gameBoard[1][1] = null; // Clear square on game board
// Update game board array to reflect new position of player 2's selection
// (Assume selected ID is stored in variable player2Selection)
// ...
该代码示例使用一个嵌套的循环来初始化每个游戏棋格的唯一ID。在每个玩家的回合结束时,游戏棋子在棋盘数组中的位置将更新,以反映它们的新位置。