用井字游戏制作我的AI播放器



我正在做一个项目,给了我一段4x4井字游戏的代码,但我必须在其中实现我自己的人工智能,它可以击败预装的人工智能。2个人工智能的界面简单而随机。Random只是在一个正方形上随机插入X,Simple播放器从左上角的正方形开始,向右迭代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可能会幸运地偶然发现,从而毁掉你的一天。我认为这个想法是创建一种算法,将这种情况发生的可能性降到可忽略的程度。也许你不只是写一篇专栏文章,而是朝着不同的方向前进,并总是优先考虑你上一次走的方向,除非这是不可能的。

一天结束时,游戏是确定的,选项的数量也不像国际象棋那样疯狂,你可以编写一个算法,只要有足够的运行时间,就可以一直获胜。我建议你看看最小-最大方法,这是为国际象棋、跳棋或井字游戏编写第一个人工智能的经典方法。

最新更新