-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMachinePlayer.java
77 lines (69 loc) · 1.46 KB
/
MachinePlayer.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
import java.util.ArrayList;
import java.util.Random;
public class MachinePlayer extends Player
{
private class Best
{
int[] move;
int score;
}
public MachinePlayer(int[][] state, int x)
{
super(state, x);
}
//side flips between 1 and 2
public Best chooseMove(int[][] grid, int side, int alpha, int beta, int depth)
{
Best myBest = new Best();
Best reply;
int status = Game.win(grid);
if (status != 0)
{
Best endBest = new Best();
if (status == -1) {
endBest.score = 0;
} else if (status == this.side) {
endBest.score = 1;
} else {
endBest.score = -1;
}
return endBest;
}
if (side == this.side) {
myBest.score = alpha;
} else {
myBest.score = beta;
}
ArrayList<int[]> moves = allLegalMoves(grid);
myBest.move = moves.get(0);
for (int[] move : moves)
{
grid[move[0]][move[1]] = side;
reply = chooseMove(grid, 3 - side, alpha, beta, depth + 1);
grid[move[0]][move[1]] = 0;
if (side == this.side && reply.score > myBest.score)
{
myBest.move = move;
myBest.score = reply.score;
alpha = reply.score;
}
else if (side == 3 - this.side && reply.score < myBest.score)
{
myBest.move = move;
myBest.score = reply.score;
beta = reply.score;
}
if (alpha >= beta)
{
return myBest;
}
}
return myBest;
}
public int[] getMove()
{
int[][] grid = Game.copy2D(state);
Best bestMove = chooseMove(grid, this.side, -1, 1, 0);
return bestMove.move;
}
}