Skip to content

Commit 1b0d5f0

Browse files
parthkariamaibin
authored andcommitted
BAEL-984 Monte Carlo tree search (eugenp#2129)
* BAEL-984 Monte Carlo tree search BAEL-984 Implementation for tic tac toe using Monte Carlo tree search * BAEL-984 test cases for MCTS BAEL-984 test cases for Monte Carlo tree search implementation
1 parent 2cde0e3 commit 1b0d5f0

8 files changed

Lines changed: 614 additions & 0 deletions

File tree

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package com.baeldung.algorithms.mcts.montecarlo;
2+
3+
import java.util.List;
4+
5+
import com.baeldung.algorithms.mcts.tictactoe.Board;
6+
import com.baeldung.algorithms.mcts.tree.Node;
7+
import com.baeldung.algorithms.mcts.tree.Tree;
8+
9+
public class MonteCarloTreeSearch {
10+
11+
static final int WIN_SCORE = 10;
12+
int level;
13+
int oponent;
14+
15+
public MonteCarloTreeSearch() {
16+
this.level = 3;
17+
}
18+
19+
public int getLevel() {
20+
return level;
21+
}
22+
23+
public void setLevel(int level) {
24+
this.level = level;
25+
}
26+
27+
private int getMillisForCurrentLevel() {
28+
return 2 * (this.level - 1) + 1;
29+
}
30+
31+
public Board findNextMove(Board board, int playerNo) {
32+
long start = System.currentTimeMillis();
33+
long end = start + 60 * getMillisForCurrentLevel();
34+
35+
oponent = 3 - playerNo;
36+
Tree tree = new Tree();
37+
Node rootNode = tree.getRoot();
38+
rootNode.getState().setBoard(board);
39+
rootNode.getState().setPlayerNo(oponent);
40+
41+
while (System.currentTimeMillis() < end) {
42+
// Phase 1 - Selection
43+
Node promisingNode = selectPromisingNode(rootNode);
44+
// Phase 2 - Expansion
45+
if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
46+
expandNode(promisingNode);
47+
48+
// Phase 3 - Simulation
49+
Node nodeToExplore = promisingNode;
50+
if (promisingNode.getChildArray().size() > 0) {
51+
nodeToExplore = promisingNode.getRandomChildNode();
52+
}
53+
int playoutResult = simulateRandomPlayout(nodeToExplore);
54+
// Phase 4 - Update
55+
backPropogation(nodeToExplore, playoutResult);
56+
}
57+
58+
Node winnerNode = rootNode.getChildWithMaxScore();
59+
tree.setRoot(winnerNode);
60+
return winnerNode.getState().getBoard();
61+
}
62+
63+
private Node selectPromisingNode(Node rootNode) {
64+
Node node = rootNode;
65+
while (node.getChildArray().size() != 0) {
66+
node = UCT.findBestNodeWithUCT(node);
67+
}
68+
return node;
69+
}
70+
71+
private void expandNode(Node node) {
72+
List<State> possibleStates = node.getState().getAllPossibleStates();
73+
possibleStates.forEach(state -> {
74+
Node newNode = new Node(state);
75+
newNode.setParent(node);
76+
newNode.getState().setPlayerNo(node.getState().getOpponent());
77+
node.getChildArray().add(newNode);
78+
});
79+
}
80+
81+
private void backPropogation(Node nodeToExplore, int playerNo) {
82+
Node tempNode = nodeToExplore;
83+
while (tempNode != null) {
84+
tempNode.getState().incrementVisit();
85+
if (tempNode.getState().getPlayerNo() == playerNo)
86+
tempNode.getState().addScore(WIN_SCORE);
87+
tempNode = tempNode.getParent();
88+
}
89+
}
90+
91+
private int simulateRandomPlayout(Node node) {
92+
Node tempNode = new Node(node);
93+
State tempState = tempNode.getState();
94+
int boardStatus = tempState.getBoard().checkStatus();
95+
96+
if (boardStatus == oponent) {
97+
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
98+
return boardStatus;
99+
}
100+
while (boardStatus == Board.IN_PROGRESS) {
101+
tempState.togglePlayer();
102+
tempState.randomPlay();
103+
boardStatus = tempState.getBoard().checkStatus();
104+
}
105+
106+
return boardStatus;
107+
}
108+
109+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package com.baeldung.algorithms.mcts.montecarlo;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import com.baeldung.algorithms.mcts.tictactoe.Board;
7+
import com.baeldung.algorithms.mcts.tictactoe.Position;
8+
9+
public class State {
10+
Board board;
11+
int playerNo;
12+
int visitCount;
13+
double winScore;
14+
15+
public State() {
16+
board = new Board();
17+
}
18+
19+
public State(State state) {
20+
this.board = new Board(state.getBoard());
21+
this.playerNo = state.getPlayerNo();
22+
this.visitCount = state.getVisitCount();
23+
this.winScore = state.getWinScore();
24+
}
25+
26+
public State(Board board) {
27+
this.board = new Board(board);
28+
}
29+
30+
public Board getBoard() {
31+
return board;
32+
}
33+
34+
public void setBoard(Board board) {
35+
this.board = board;
36+
}
37+
38+
public int getPlayerNo() {
39+
return playerNo;
40+
}
41+
42+
public void setPlayerNo(int playerNo) {
43+
this.playerNo = playerNo;
44+
}
45+
46+
public int getOpponent() {
47+
return 3 - playerNo;
48+
}
49+
50+
public int getVisitCount() {
51+
return visitCount;
52+
}
53+
54+
public void setVisitCount(int visitCount) {
55+
this.visitCount = visitCount;
56+
}
57+
58+
public double getWinScore() {
59+
return winScore;
60+
}
61+
62+
public void setWinScore(double winScore) {
63+
this.winScore = winScore;
64+
}
65+
66+
public List<State> getAllPossibleStates() {
67+
List<State> possibleStates = new ArrayList<>();
68+
List<Position> availablePositions = this.board.getEmptyPositions();
69+
availablePositions.forEach(p -> {
70+
State newState = new State(this.board);
71+
newState.setPlayerNo(3 - this.playerNo);
72+
newState.getBoard().performMove(newState.getPlayerNo(), p);
73+
possibleStates.add(newState);
74+
});
75+
return possibleStates;
76+
}
77+
78+
public void incrementVisit() {
79+
this.visitCount++;
80+
}
81+
82+
public void addScore(double score) {
83+
if (this.winScore != Integer.MIN_VALUE)
84+
this.winScore += score;
85+
}
86+
87+
public void randomPlay() {
88+
List<Position> availablePositions = this.board.getEmptyPositions();
89+
int totalPossibilities = availablePositions.size();
90+
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
91+
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
92+
}
93+
94+
public void togglePlayer() {
95+
this.playerNo = 3 - this.playerNo;
96+
}
97+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.algorithms.mcts.montecarlo;
2+
3+
import java.util.Collections;
4+
import java.util.Comparator;
5+
import java.util.List;
6+
7+
import com.baeldung.algorithms.mcts.tree.Node;
8+
9+
public class UCT {
10+
final static double C = 1.41;
11+
12+
public static double uctValue(int totalVisit, double nodeWinScore, int nodeVisit) {
13+
if (nodeVisit == 0)
14+
return Integer.MAX_VALUE;
15+
return ((double) nodeWinScore / (double) nodeVisit) + 1.41 * Math.sqrt(Math.log(totalVisit) / (double) nodeVisit);
16+
}
17+
18+
public static Node findBestNodeWithUCT(Node node) {
19+
int parentVisit = node.getState().getVisitCount();
20+
List<Node> childNodes = node.getChildArray();
21+
return Collections.max(childNodes, Comparator.comparing(c -> {
22+
double score = uctValue(parentVisit, c.getState().getWinScore(), c.getState().getVisitCount());
23+
return score;
24+
}));
25+
}
26+
}
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
package com.baeldung.algorithms.mcts.tictactoe;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class Board {
8+
int[][] boardValues;
9+
int totalMoves;
10+
11+
public static final int DEFAULT_BOARD_SIZE = 3;
12+
13+
public static final int IN_PROGRESS = -1;
14+
public static final int DRAW = 0;
15+
public static final int P1 = 1;
16+
public static final int P2 = 2;
17+
18+
public Board() {
19+
boardValues = new int[DEFAULT_BOARD_SIZE][DEFAULT_BOARD_SIZE];
20+
}
21+
22+
public Board(int boardSize) {
23+
boardValues = new int[boardSize][boardSize];
24+
}
25+
26+
public Board(int[][] boardValues) {
27+
this.boardValues = boardValues;
28+
}
29+
30+
public Board(int[][] boardValues, int totalMoves) {
31+
this.boardValues = boardValues;
32+
this.totalMoves = totalMoves;
33+
}
34+
35+
public Board(Board board) {
36+
int boardLength = board.getBoardValues().length;
37+
this.boardValues = new int[boardLength][boardLength];
38+
int[][] boardValues = board.getBoardValues();
39+
int n = boardValues.length;
40+
for (int i = 0; i < n; i++) {
41+
int m = boardValues[i].length;
42+
for (int j = 0; j < m; j++) {
43+
this.boardValues[i][j] = boardValues[i][j];
44+
}
45+
}
46+
}
47+
48+
public void performMove(int player, Position p) {
49+
this.totalMoves++;
50+
boardValues[p.getX()][p.getY()] = player;
51+
}
52+
53+
public int[][] getBoardValues() {
54+
return boardValues;
55+
}
56+
57+
public void setBoardValues(int[][] boardValues) {
58+
this.boardValues = boardValues;
59+
}
60+
61+
public int checkStatus() {
62+
int boardSize = boardValues.length;
63+
int maxIndex = boardSize - 1;
64+
int[] diag1 = new int[boardSize];
65+
int[] diag2 = new int[boardSize];
66+
67+
for (int i = 0; i < boardSize; i++) {
68+
int[] row = boardValues[i];
69+
int[] col = new int[boardSize];
70+
for (int j = 0; j < boardSize; j++) {
71+
col[j] = boardValues[j][i];
72+
}
73+
74+
int checkRowForWin = checkForWin(row);
75+
if(checkRowForWin!=0)
76+
return checkRowForWin;
77+
78+
int checkColForWin = checkForWin(col);
79+
if(checkColForWin!=0)
80+
return checkColForWin;
81+
82+
diag1[i] = boardValues[i][i];
83+
diag2[i] = boardValues[maxIndex - i][i];
84+
}
85+
86+
int checkDia1gForWin = checkForWin(diag1);
87+
if(checkDia1gForWin!=0)
88+
return checkDia1gForWin;
89+
90+
int checkDiag2ForWin = checkForWin(diag2);
91+
if(checkDiag2ForWin!=0)
92+
return checkDiag2ForWin;
93+
94+
if (getEmptyPositions().size() > 0)
95+
return IN_PROGRESS;
96+
else
97+
return DRAW;
98+
}
99+
100+
private int checkForWin(int[] row) {
101+
boolean isEqual = true;
102+
int size = row.length;
103+
int previous = row[0];
104+
for (int i = 0; i < size; i++) {
105+
if (previous != row[i]) {
106+
isEqual = false;
107+
break;
108+
}
109+
previous = row[i];
110+
}
111+
if(isEqual)
112+
return previous;
113+
else
114+
return 0;
115+
}
116+
117+
public void printBoard() {
118+
int size = this.boardValues.length;
119+
for (int i = 0; i < size; i++) {
120+
for (int j = 0; j < size; j++) {
121+
System.out.print(boardValues[i][j] + " ");
122+
}
123+
System.out.println();
124+
}
125+
}
126+
127+
public List<Position> getEmptyPositions() {
128+
int size = this.boardValues.length;
129+
List<Position> emptyPositions = new ArrayList<>();
130+
for (int i = 0; i < size; i++) {
131+
for (int j = 0; j < size; j++) {
132+
if (boardValues[i][j] == 0)
133+
emptyPositions.add(new Position(i, j));
134+
}
135+
}
136+
return emptyPositions;
137+
}
138+
139+
public void printStatus() {
140+
switch (this.checkStatus()) {
141+
case P1:
142+
System.out.println("Player 1 wins");
143+
break;
144+
case P2:
145+
System.out.println("Player 2 wins");
146+
break;
147+
case DRAW:
148+
System.out.println("Game Draw");
149+
break;
150+
case IN_PROGRESS:
151+
System.out.println("Game In rogress");
152+
break;
153+
}
154+
}
155+
}

0 commit comments

Comments
 (0)