Sunday, January 22, 2017

TicTacToe AI with Minimax Algorithm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class TicTacToeMinimax extends TicTacToeAI {
    public int []nextMove(int token) {
        int enemy = inverse(token);
        if(isWin(enemy)) return new int[]{-1,-1,-1};
        int []ret = null;
        int best = -2;
        for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
            if(getBoardValue(i, j)==EMPTY) {
                setBoardValue(i,j,token);
                int []res = nextMove(enemy);
                int score = res==null ? 0 : -res[2];
                if(score > best) {
                    best = score;
                    ret = new int[]{i,j,best};
                }
                setBoardValue(i,j,EMPTY);
            }
        }
        return ret;
    }
}

No comments:

Post a Comment