-
Notifications
You must be signed in to change notification settings - Fork 0
/
AI.java
97 lines (72 loc) · 2.2 KB
/
AI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.io.IOException;
public class AI {
private static final int WEIGHT = 100;
public Move minimax(Board b, int depth, int alpha, int beta, String player, Move move) throws IOException, InterruptedException {
// Base case
if(depth == 0 || b.boardScore >= 50000) {
return move;
}
else if(player.equals("computer")) {
Move maxMove = new Move(0,0); // Keep track of the best human's move for the computer
maxMove.moveScore = WEIGHT*-10000;
Move returnMove = new Move(0,0); // Keep track of the computer's best move
//Do this for every possible column
for(int x = 0; x < 7; x++) {
//If column is filled, move on.
while(b.findYSpot(x) == -1) {
x++;
if(x > 6) {
return move;
}
}
Move m = new Move(b.findYSpot(x), x); // Create the move
m.moveScore = b.boardScore;
b.putPiece(m.yMove, m.xMove); // Put the piece down
Move miniMaxMove = minimax(b, depth-1, alpha, beta, "human", m);
//If the best score beats out the current best,
//store it and save the move
if(miniMaxMove.moveScore >= maxMove.moveScore) {
maxMove = miniMaxMove;
returnMove = m;
}
b.removePiece(m); //Remove the piece
//Adjust for alpha-beta pruning
alpha = Math.max(alpha, maxMove.moveScore);
if (alpha >= beta) {
break;
}
}
return returnMove;
}
else {
Move minMove = new Move(0, 0);
minMove.moveScore = WEIGHT*10000;
Move returnMove = new Move(0,0);
//Do this for every possible column
for(int x = 0; x < 7; x++) {
// If column is filled, move on
while(b.findYSpot(x) == -1) {
x++;
if(x > 6) {
return move;
}
}
Move m = new Move(b.findYSpot(x), x); // Make the move
b.putPiece(player, m.xMove); // Put the piece down
m.moveScore = b.boardScore;
Move miniMaxMove = minimax(b, depth-1, alpha, beta, "computer", m);
if(miniMaxMove.moveScore <= minMove.moveScore) {
minMove = miniMaxMove;
returnMove = m;
}
b.removePiece(m);
//Adjust for alpha-beta pruning
beta = Math.min(beta, minMove.moveScore);
if(alpha >= beta) {
break;
}
}
return returnMove;
}
}
}