Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Forked from anonymous/TicTacToe.java
Created July 30, 2014 07:54
Show Gist options
  • Save jooyunghan/ca7244dc00abf8731bb7 to your computer and use it in GitHub Desktop.
Save jooyunghan/ca7244dc00abf8731bb7 to your computer and use it in GitHub Desktop.
int[][] data = new int[3][3];
private void aiMove() {
Score s = minimax(null, true);
data[s.move.x][s.move.y] = COMPUTER;
}
static class Score {
Point move;
int score;
public Score(Point move, int score) {
this.move = move;
this.score = score;
}
};
private Score minimax(Point move, final boolean maximizing) {
if (gameEnd()) {
return new Score(null, score()); // use score only
}
Score best = new Score(null, maximizing ? -10 : 10);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (data[i][j] == 0) {
// for each empty cells
Point child = new Point(i, j);
data[i][j] = maximizing ? COMPUTER : YOU;
Score score = minimax(child, !maximizing);
// find mini or max
if (maximizing && score.score > best.score) {
best.score = score.score;
best.move = child;
} else if (!maximizing && score.score < best.score) {
best.score = score.score;
best.move = child;
}
data[i][j] = 0; // backtracking
}
}
}
return best;
}
private int score() {
int winner = winner();
if (winner == COMPUTER)
return 1;
if (winner == YOU)
return -1;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment