javascript - 我可以使用 2D 数组在 JS 中创建井字游戏 AI 吗?
问题描述
我正在使用 HTML 和 JS 创建井字游戏。我将任何可变大小(宽度和高度相同)的板存储在二维数组中。也就是存储数据行的数组。这些行中的数据是列,因此您可以使用 访问数组中的位置array[row][column]
。我正在尝试创建一个尝试与玩家对抗的机器人。我正在考虑用尽可能少的人类玩家碎片对半空行/列/对角线进行暴力破解。我还阅读了有关 minmax 机器人更好地利用资源的信息。但是我在 JS 中找不到任何东西,也找不到任何可以转换为 JS 的东西,因为我见过的大多数其他机器人都使用具有 9 个元素的一维数组。同样,我的板子实际上可以是任何等宽等高的尺寸,所以我需要制作一个能够理解这一点的机器人。这是我到目前为止的损坏代码。
function startArtificialIdiot() {
// General analytical skills.
// First the bot will look for open rows, once it finds one it will check adjacent columns, and diagonals for the best play...
let optimalPlay = [];
let safeRows = [];
// Generate row css.
for (let row = 1; row <= boardSize; row++) {
safeRows.push(row);
}
console.log(safeRows)
// Loop through and remove rows that have player one's tile in them, or are full.
rows:
for (let checkedRow = 1; checkedRow <= boardSize; checkedRow++) {
// Go through each row, and check if all columns are empty.
let columnsFull = 0;
for (let column = 1; column <= boardSize; column++) {
// If a row is occupied, we te add to the columnsFull counter.
if (board[checkedRow][column] != "") {
columnsFull ++;
}
}
// If this row is full, then we remove it from the list.
if (columnsFull == boardSize) {
console.warn(`AI: Row ${checkedRow} is full. Deleting it from the list.`);
safeRows.splice(safeRows.indexOf(checkedRow), 1);
}
}
// If we can't find a good play we safely abort with a random play.
if (safeRows.length == 0) {
console.warn("AI: Playing randomly because I can't find a good place to play...");
changePiece(Math.ceil(Math.random()*boardSize), Math.ceil(Math.random()*boardSize));
}
// Temporarily randomly play in one of the safe rows.
let rowPick = safeRows[Math.floor(Math.random() * safeRows.length)];
console.warn(`AI: Moving to row ${rowPick} from ${safeRows}`);
changePiece(rowPick, Math.ceil(Math.random()*boardSize));
console.log(safeRows);
}
请注意,该函数每回合为机器人调用一次。如果机器人在板上选择了一个已经被填满的插槽,它也会自动重新调用。
解决方案
推荐阅读
- graphql - 带参数的 Apollo graphql 查询
- c++ - std::cout 不打印浮点数作为例外
- c# - WPF 在鼠标悬停时更改 ListBoxItem 的背景
- swift - 当 CV contentInset 更新时(带视频),尽管 .isHidden = true,仍会显示 collectionViewCell 子视图
- excel - 跟踪工作表上的更改,复制活动单元格更改列标题和 NewColumnValue
- python - 如何在python中将时间序列数据移动一个月
- kubernetes - Ingress 不会路由到 EKS 上的服务
- javascript - 使用 R 的 bsplus、Shiny 和 JavaScript 停止轮播自动播放
- python - ImportError:无法从部分初始化的模块“src.windows”导入名称“RegisterWindow”
- asynchronous - 在 tokio::select 中生锈 lazy_static 和 tokio::sync::mpsc::channel