I am doing a school project that involves a Connect 3 game. One of my AI algorithms is set to check if a piece is played in the current column, if the opponent has the possibility of winning the next turn.
The problem is, the code seems to occasionally cause my AI to be unable to pick a move, therefore freezing the game unless a play is manually chosen. Attached below are images of where it typically freezes.
Here is my code:
for (Player p: new Player[]{player, opponentOf(player)}) {
for (int c = 0; c < GRID_COLUMNS; c++) {
int r = free(state, c);
if (r >= 0) {
state[r][c] = p;
// checks if the opponent could win to the right
if (c+1 < GRID_COLUMNS) {
state[r][c+1] = opponentOf(p);
if (getWinner(state, r, c) == p)
if (getWinner(state, r, c+1) == opponentOf(p))
return c+1;
}
// checks if the opponent could win to the left
if (c-1 >= 0) {
state[r][c-1] = opponentOf(p);
if (getWinner(state, r, c) == p)
if (getWinner(state, r, c-1) == opponentOf(p))
return c-1;
}
// checks if the opponent could win above
if (r-1 >= 0) {
state[r-1][c] = opponentOf(p);
if (getWinner(state, r, c) == p)
if (getWinner(state, r-1, c) == opponentOf(p))
return c+1;
}
state[r][c] = Player.NONE;
}
}
}
Album of the images of it freezing: Failure #1
** The getWinner() method is my win detection and it works fine with my other algorithms. This is the only one that works incorrectly (I have made sure of this)
The goal of the project is to create the highest win ratio possible between my AI as the second player and the professor's AI as first player. This method increases that ratio substantially, but the freezing in the middle is not up to my own standards. I just can't seem to figure it out. Any help would be appreciated!
Thank you!
Aucun commentaire:
Enregistrer un commentaire