让我的 AI 玩家玩井字游戏

Making my AI player in tic tac toe

我正在做一个项目,我给了一段 4x4 井字游戏的代码,但必须在其中实现我自己的 AI,它可以击败预装的 AI。我面对的 2 个 AI 简单而随机。 Random 只是在一个正方形上随机插入 X,而 Simple player 从左上角的正方形开始并向右迭代 1 个正方形。所以为了拦截简单的球员,我把我的第一个 O 放在第一行,基本上做一条垂直线,直到连续 4 个。但是,随机播放器可以拦截我的线,然后我的电脑播放器随机将 O 放在空方格中进行绘制。但是,这不能正常工作,因为我的播放器可能因为不知道去哪里而停止轮流。所以如果有人能纠正我的概念,我将不胜感激。

这只是我的代码的一部分

package noughtsAndCrossesV3;

import ncErrors.outOfRangeError;
import java.util.ArrayList;
import java.util.Random;

public class MyCompPlayer extends GenericPlayer implements NCPlayer {

    Random theGenerator;

    public MyCompPlayer()
    {
        super();        // no further initialisation required
        theGenerator = new Random();
    }

   // NCGrid is the grid the class that displays the grid and rules to win

    @Override
    public GridCoordinate getNextMove(NCGridV3 currentGrid) {
        int Row;
        int Col;
        GridCoordinate theSquare = null;
        int randomSelection;
        ArrayList<GridCoordinate> freeSquares = new ArrayList<GridCoordinate>(); // array finding free squares

        //iterates through row and column
        for (Row = 0; (theSquare == null) && (Row < currentGrid.getGridRowDimension()); Row++){
            for (Col = 0; (theSquare == null) && (Col < currentGrid.getGridColDimension()); Col++){


                try{

                    //If last column is empty, then draw a row of O's downwards in a straight line.

                    if(currentGrid.getSquareStatus(Row,3)==NCGridV3.SquareStatus.EMPTY){
                    theSquare = new GridCoordinate(Row,3);
                    return theSquare;
                }
                //If there is a nought then randomize movement. This doesnt work yet.
                else if(currentGrid.getSquareStatus(Row,3)==NCGridV3.SquareStatus.NOUGHT)
                    freeSquares.add(new GridCoordinate(Row, Col));
                // adds free sqaures to array and plots coordinate there but doesnt work.

                }

                catch (outOfRangeError e)
                {

                }

            }

        }

    randomSelection = theGenerator.nextInt(freeSquares.size());


    return freeSquares.get(randomSelection);
 }

}

归根结底,如果您使用简单的计数器 AI,随机 AI 可能幸运地偶然发现一些东西来毁掉您的一天。我认为这个想法是创建一种算法,将这种情况发生的可能性降到可以忽略不计的程度。也许你不只是在一个专栏中往下走,而是继续朝着不同的方向前进,并始终优先考虑你上次选择的方向,除非这是不可能的。

归根结底,游戏是确定性的,选项的数量并不像国际象棋那样疯狂,您可以编写一个算法,只要有足够的 运行 时间,它就会一直获胜。我建议您看看 minimax 方法,这是为国际象棋、跳棋或井字游戏等游戏编写第一个 AI 的经典方法。