forked from careercup/ctci
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutomator.java
More file actions
88 lines (75 loc) · 2.39 KB
/
Automator.java
File metadata and controls
88 lines (75 loc) · 2.39 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
package Question8_8;
import java.util.ArrayList;
import CtCILibrary.AssortedMethods;
/* A helper class to automate this game. This is just used for testing purposes. */
public class Automator {
private Player[] players;
private Player lastPlayer = null;
public ArrayList<Location> remainingMoves = new ArrayList<Location>();
private static Automator instance;
private Automator() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Location loc = new Location(i, j);
remainingMoves.add(loc);
}
}
}
public static Automator getInstance() {
if (instance == null) {
instance = new Automator();
}
return instance;
}
public void initialize(Player[] ps) {
players = ps;
lastPlayer = players[1];
}
public void shuffle() {
for (int i = 0; i < remainingMoves.size(); i++) {
int t = AssortedMethods.randomIntInRange(i, remainingMoves.size() - 1);
Location other = remainingMoves.get(t);
Location current = remainingMoves.get(i);
remainingMoves.set(t, current);
remainingMoves.set(i, other);
}
}
public void removeLocation(int r, int c) {
for (int i = 0; i < remainingMoves.size(); i++) {
Location loc = remainingMoves.get(i);
if (loc.isSameAs(r, c)) {
remainingMoves.remove(i);
}
}
}
public Location getLocation(int index) {
return remainingMoves.get(index);
}
public boolean playRandom() {
Board board = Game.getInstance().getBoard();
shuffle();
lastPlayer = lastPlayer == players[0] ? players[1] : players[0];
String color = lastPlayer.getColor().toString();
for (int i = 0; i < remainingMoves.size(); i++) {
Location loc = remainingMoves.get(i);
boolean success = lastPlayer.playPiece(loc.getRow(), loc.getColumn());
if (success) {
System.out.println("Success: " + color + " move at (" + loc.getRow() + ", " + loc.getColumn() + ")");
board.printBoard();
printScores();
return true;
}
}
System.out.println("Game over. No moves found for " + color);
return false;
}
public boolean isOver() {
if (players[0].getScore() == 0 || players[1].getScore() == 0) {
return true;
}
return false;
}
public void printScores() {
System.out.println("Score: " + players[0].getColor().toString() + ": " + players[0].getScore() + ", " + players[1].getColor().toString() + ": " + players[1].getScore());
}
}