-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuleEngine.java
More file actions
75 lines (67 loc) · 2.75 KB
/
Copy pathRuleEngine.java
File metadata and controls
75 lines (67 loc) · 2.75 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
package api;
import boards.TicTacToeBoard;
import game.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class RuleEngine {
Map<String, RuleSet> ruleMap = new HashMap<>();
public RuleEngine(){
ruleMap.put(TicTacToeBoard.class.getName(),TicTacToeBoard.getRules());
}
public GameState getState(Board board){
if(board instanceof TicTacToeBoard board1) {
for(Rule rule: ruleMap.get(TicTacToeBoard.class.getName())){
GameState gameState = rule.condition.apply(board1);
if(gameState.isOver()){
return gameState;
}
}
return new GameState(false,"-");
} else {
return new GameState(true, "-");
}
}
public GameInfo getInfo(Board board) {
if (board instanceof TicTacToeBoard) {
TicTacToeBoard ticTacToeBoard = (TicTacToeBoard) board;
GameState gameState = getState(ticTacToeBoard);
final String [] players = new String[] {"X","O"};
Cell forkCell = null;
for (int index =0; index <2 ;index++) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Player player = new Player(players [index]);
TicTacToeBoard b = ((TicTacToeBoard) board).dummyMove(new Move(player,new Cell(i,j)));
boolean canStillWin = false;
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
forkCell= new Cell(k,l);
Board b1 = b.dummyMove(new Move(player.flip(),new Cell(k,l)));
if(getState(b1).getWinner().equals(player.flip().symbol())){
canStillWin = true;
break;
}
}
}
if(canStillWin) {
return new GameInfoBuilder()
.isOver(gameState.isOver())
.winner(gameState.getWinner())
.hasFork(true)
.player(player.flip())
.forkCell(forkCell)
.build();
}
}
}
}
return new GameInfoBuilder()
.isOver(gameState.isOver())
.winner(gameState.getWinner())
.build();
} else {
throw new IllegalArgumentException();
}
}
}