-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHardAIPlayer.java
More file actions
91 lines (76 loc) · 2.51 KB
/
HardAIPlayer.java
File metadata and controls
91 lines (76 loc) · 2.51 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
79
80
81
82
83
84
85
86
87
88
89
90
91
package tictactoe;
import java.util.ArrayList;
public class HardAIPlayer extends AIPlayer {
public HardAIPlayer(char identifier) {
super(identifier, "hard");
}
@Override
public int getTurn(char[][] gameboard) {
TicTacToe ttt = new TicTacToe();
ttt.createInitializedBoard(getBoardArr(gameboard));
ArrayList<Integer> open = getOpenSpaces(getBoardArr(gameboard));
char[] boardArr = getBoardArr(gameboard);
int move = open.get(0);
int score = Integer.MIN_VALUE;
for (int i : open) {
char[] tempArr = boardArr.clone();
tempArr[i] = ttt.isXTurn() ? 'X' : 'O';
int tempScore = getBestMove(tempArr);
if (tempScore > score) {
score = tempScore;
move = i;
}
}
move = translateToPos(gameboard.length, move / 3, move % 3);
return move;
}
//@Override
public int getBestMove(char[] boardArr) {
TicTacToe ttt = new TicTacToe();
ttt.createInitializedBoard(boardArr);
ArrayList<Integer> open = getOpenSpaces(boardArr);
ArrayList<Integer> scores = new ArrayList<>();
if (ttt.isGameOver()) {
String result = ttt.getResult();
if (result.equals("X wins") ^ identifier == 'O') {
return 10;
} else if (result.equals("Draw")) {
return 0;
} else {
return -10;
}
}
for (int i : open) {
char[] tempArr = boardArr.clone();
tempArr[i] = ttt.isXTurn() ? 'X' : 'O';
scores.add(getBestMove(tempArr));
}
int score = scores.get(0);
for (int s : scores) {
if (ttt.isXTurn() ^ identifier == 'O') {
score = Math.max(s, score);
} else {
score = Math.min(s, score);
}
}
return score;
}
private char[] getBoardArr(char[][] gameboard) {
StringBuilder str = new StringBuilder();
for (char[] row : gameboard) {
for (char ch : row) {
str.append(ch);
}
}
return str.toString().toCharArray();
}
private ArrayList<Integer> getOpenSpaces(char[] boardArr) {
ArrayList<Integer> open = new ArrayList<>();
for (int i = 0; i < boardArr.length; i++) {
if (boardArr[i] == '_' || boardArr[i] == ' ') {
open.add(i);
}
}
return open;
}
}