首页 > 解决方案 > 我可以使用 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);
}

请注意,该函数每回合为机器人调用一次。如果机器人在板上选择了一个已经被填满的插槽,它也会自动重新调用。

标签: javascriptarraysmultidimensional-arrayartificial-intelligence

解决方案


推荐阅读