-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIEngine.java
More file actions
78 lines (70 loc) · 2.54 KB
/
AIEngine.java
File metadata and controls
78 lines (70 loc) · 2.54 KB
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
package api;
import boards.TicTacToeBoard;
import game.*;
public class AIEngine {
public Move getBasicMove(Player player, TicTacToeBoard board){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board.getSymbol(i,j)==null){
return new Move(player,new Cell(i,j));
}
}
}
return null;
}
public Move getSmartMove(Player player, TicTacToeBoard board){
RuleEngine ruleEngine = new RuleEngine();
// Victorious Move = We found a move where Computer Wins
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board.getSymbol(i,j)==null){
Move move = new Move(player, new Cell(i,j));
Board boardCopy = board.copy();
boardCopy.move(move);
if(ruleEngine.getState(boardCopy).isOver()){
return move;
}
}
}
}
// Defensive Move = We found a move where Player Wins and we replace it with computer move
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board.getSymbol(i,j)==null){
Move move = new Move(player.flip(), new Cell(i,j));
Board boardCopy = board.copy();
boardCopy.move(move);
if(ruleEngine.getState(boardCopy).isOver()){
return new Move(player, new Cell(i,j));
}
}
}
}
return getBasicMove(player, board);
}
public Move suggestMove(Player player, Board board){
if(board instanceof TicTacToeBoard board1){
Move suggestedMove = null;
if(hasLessMove(board1,2)){
suggestedMove = getBasicMove(player,board1);
} else {
suggestedMove = getSmartMove(player,board1);
}
if(suggestedMove != null) return suggestedMove;
throw new IllegalStateException();
} else{
throw new IllegalArgumentException();
}
}
public boolean hasLessMove(TicTacToeBoard board, int threshHold) {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board.getSymbol(i, j) != null) {
count++;
}
}
}
return count<threshHold;
}
}