-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tournament.java
executable file
·377 lines (334 loc) · 13.8 KB
/
Tournament.java
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Tournament {
private int numPlayers;
private Random rand;
private DecimalFormat numberFormat;
private Watch watch;
private boolean verbose;
private PlayerFactory playerFactory = new PlayerFactory();
public Tournament(boolean verbose) {
rand = new Random(System.currentTimeMillis());
numberFormat = new DecimalFormat("#.000");
watch = new Watch();
this.verbose = verbose;
// Registering Players
registerPlayers();
numPlayers = 0; // Initializing, this will be calculated during the run.
}
private void registerPlayers() {
// New players can be registered here
playerFactory.registerPlayer("TeamMonkey", i -> new TeamMonkey(i));
playerFactory.registerPlayer("TeamNihilist", i -> new TeamNihilist(i));
playerFactory.registerPlayer("TeamRationalOptimist", i -> TeamRational.createOptimist(i));
playerFactory.registerPlayer("TeamRationalPessimist", i -> TeamRational.createPessimist(i));
playerFactory.registerPlayer("TeamRationalQueller", i -> TeamRational.createQueller(i));
playerFactory.registerPlayer("TeamRationalRealist", i -> TeamRational.createRealist(i));
playerFactory.registerPlayer("TeamRationalScrapper", i -> TeamRational.createScrapper(i));
playerFactory.registerPlayer("TeamRationalTruster", i -> TeamRational.createTruster(i));
playerFactory.registerPlayer("TeamRationalUtilitarian", i -> TeamRational.createUtilitarian(i));
playerFactory.registerPlayer("TeamHandshaker", i -> new TeamHandshaker(i));
playerFactory.registerPlayer("TeamDoubleAgent", i -> new TeamDoubleAgent(i));
playerFactory.registerPlayer("TeamTitForTat", i -> new TeamTitForTat(i));
playerFactory.registerPlayer("TeamTitForTatRecovery", i -> new TeamTitForTat(i));
playerFactory.registerPlayer("TeamTitForTatTat", i -> new TeamTitForTatTat(i));
playerFactory.registerPlayer("TeamTatForTit", i -> new TeamTatForTit(i));
playerFactory.registerPlayer("TeamGrudger", i -> new TeamGrudger(i));
playerFactory.registerPlayer("TeamCondescension", i -> new TeamCondescension(i));
playerFactory.registerPlayer("TeamTwitchForTat", i -> new TeamTwitchForTat(i));
playerFactory.registerPlayer("TeamForgiveness", i -> new TeamForgiveness(i));
playerFactory.registerPlayer("TeamMoreCoopTFT", i -> new TeamMoreCoopTFT(i));
playerFactory.registerPlayer("TeamMoreBetrayalTFT", i -> new TeamMoreBetrayalTFT(i));
playerFactory.registerPlayer("TeamMoreMoreTFT", i -> new TeamMoreMoreTFT(i));
playerFactory.registerPlayer("TeamTFTADC", i -> new TeamTFTADC(i));
playerFactory.registerPlayer("TeamRank3", i -> new TeamRank3(i));
playerFactory.registerPlayer("TeamWatermelon", i -> new TeamWatermelon(i));
playerFactory.registerPlayer("TeamAM", i -> new TeamAM(i));
}
public Player getPlayer(String id) {
watch.startMemoryComparison();
watch.startCounting();
System.out.println("Calling Constructor of player: " + id);
Player player = playerFactory.createPlayer(id, Parameters.MAX_NUM_MOVES);
boolean noLimitViolation = true;
noLimitViolation &= watch.enforceTimeLimit(player, Parameters.TIME_LIMIT_CONSTRUCTOR, "constructor");
System.out.println("Constructor of player " + player.getName() + " took "
+ numberFormat.format(watch.getElapsedTime()) + " seconds.");
noLimitViolation &= watch.enforceMemoryLimit(player, Parameters.MEMORY_LIMIT_CONSTRUCTOR, "constructor");
System.out.println("Constructor of player " + player.getName() + " used " + Long.toString(watch.getMemoryUse())
+ " megabytes.\n");
if (!noLimitViolation) {
System.out.println("Turning player " + id + " into a monkey");
player = playerFactory.createPlayer("TeamMonkey", Parameters.MAX_NUM_MOVES);
}
// Set player name to id
player.setName(id);
return player;
}
public Cell[] randomStartingPositions() {
int numCells = Parameters.NUM_COLUMNS * Parameters.NUM_ROWS;
Cell[] allCells = new Cell[numCells];
int pos = 0;
for (int column = 1; column <= Parameters.NUM_COLUMNS; ++column) {
for (int row = 1; row <= Parameters.NUM_ROWS; ++row) {
allCells[pos++] = new Cell(column, row);
}
}
Cell positions[] = new Cell[Parameters.NUM_PIECES];
for (int i = 0; i < Parameters.NUM_PIECES; ++i) {
int j = rand.nextInt(numCells);
positions[i] = allCells[j];
allCells[j] = allCells[numCells - 1];
--numCells;
}
return positions;
}
private int getNumBoards() {
int numBoards = Parameters.MIN_NUM_DIFFERENT_BOARDS;
while (rand.nextBoolean()) {
++numBoards;
}
return numBoards;
}
public void run() throws IOException {
PrintWriter log = null;
try {
log = new PrintWriter("../logs/logs.tex", "UTF-8");
} catch (FileNotFoundException e) {
File file = new File("../logs/logs.tex");
file.getParentFile().mkdirs();
log = new PrintWriter("../logs/logs.tex", "UTF-8");
}
if (Parameters.PRINT_LOG) {
log.println("\\documentclass[11pt,letterpaper]{article}");
log.println("\\usepackage{xskak,chessboard}");
log.println("\\usepackage[margin=0.2in]{geometry}");
log.println("\\begin{document}");
}
// verify playermanifest.txt
if (!verifyPlayerManifest()) {
System.out.println("Tournament closing due to playermanifest.txt error");
log.close();
return;
}
// initialize players
ArrayList<Player> allPlayers = getPlayers();
// Setting number of players
numPlayers = allPlayers.size();
// pair off players, by id number.
int[][] pairsOfIds;
pairsOfIds = new int[(numPlayers * (numPlayers - 1)) / 2][];
int count = 0;
for (int idPlayer1 = 0; idPlayer1 < numPlayers; ++idPlayer1) {
for (int idPlayer2 = idPlayer1 + 1; idPlayer2 < numPlayers; ++idPlayer2) {
pairsOfIds[count++] = new int[] { idPlayer1, idPlayer2 };
}
}
// Setting Scores
double[] totalScore = new double[numPlayers];
Collections.shuffle(Arrays.asList(pairsOfIds));
for (int[] idsInThisRound : pairsOfIds) {
System.out.println("************************************************************************************");
System.out.println("Starting new series:");
// Generate all of the boards that will be played in the series.
// This is Parameters.MIN_NUM_DIFFERENT_BOARDS + (#heads when we
// flip a coin until tails).
int numBoards = getNumBoards();
Player[] playersInThisRound = new Player[] { allPlayers.get(idsInThisRound[0]),
allPlayers.get(idsInThisRound[1]) };
Cell[][] startingPositions = new Cell[2 * numBoards][];
int[] whiteTeamNumbers = new int[2 * numBoards];
int[] blackTeamNumbers = new int[2 * numBoards];
// Loop over all mirror matches (so jump by 2 at a time):
for (int matchNumber = 0; matchNumber < 2 * numBoards; matchNumber += 2) {
startingPositions[matchNumber] = randomStartingPositions();
startingPositions[matchNumber + 1] = startingPositions[matchNumber];
// I hope this is safe... Should I make a proper copy instead?
// Each mirror match has a random starting player:
if (rand.nextBoolean()) {
whiteTeamNumbers[matchNumber] = 0;
blackTeamNumbers[matchNumber] = 1;
whiteTeamNumbers[matchNumber + 1] = 1;
blackTeamNumbers[matchNumber + 1] = 0;
} else {
whiteTeamNumbers[matchNumber] = 1;
blackTeamNumbers[matchNumber] = 0;
whiteTeamNumbers[matchNumber + 1] = 0;
blackTeamNumbers[matchNumber + 1] = 1;
}
}
// prepare players for round
for (Player player : playersInThisRound) {
watch.startCounting();
player.prepareForSeries();
watch.enforceTimeLimit(player, Parameters.TIME_LIMIT_PREPARE_FOR_SERIES, "prepareForSeries()");
}
double[] averagePayoffInThisRound = new double[2];
for (int teamNumber = 0; teamNumber <= 1; ++teamNumber) {
System.out.println("Team " + teamNumber + ": " + playersInThisRound[teamNumber].getName());
}
// list the round numbers, and who plays white at each round:
if (!verbose) {
/*
* System.out.print("Match #: "); for (int matchNumber = 0;
* matchNumber < 2 * numBoards; matchNumber +=2) {
* System.out.print(String.format("%02d", matchNumber));
* System.out.print(" "); } System.out.print("\nWhite team: ");
*/
System.out.print("White team: ");
for (int matchNumber = 0; matchNumber < 2 * numBoards; matchNumber += 2) {
System.out.print(whiteTeamNumbers[matchNumber]);
System.out.print(whiteTeamNumbers[matchNumber + 1]);
System.out.print(" ");
}
System.out.print("\nOutcome: ");
}
for (int matchNumber = 0; matchNumber < 2 * numBoards; ++matchNumber) {
// These were randomly chosen so that in mirror matches, each
// team plays each colour:
int whiteTeamNumberInMatch = whiteTeamNumbers[matchNumber];
Player whitePlayer = playersInThisRound[whiteTeamNumberInMatch];
int blackTeamNumberInMatch = blackTeamNumbers[matchNumber];
Player blackPlayer = playersInThisRound[blackTeamNumberInMatch];
if (Parameters.PRINT_LOG) {
log.println("\n\\clearpage\n");
log.println("Starting match:\n");
log.println("White player: " + whitePlayer.getName() + "\n");
log.println("Black player: " + blackPlayer.getName() + "\n");
}
if (verbose) {
System.out.println(
"************************************************************************************");
System.out.println();
System.out.println("Starting match number: " + matchNumber);
System.out.println("White player: " + whitePlayer.getName());
System.out.println("Black player: " + blackPlayer.getName());
System.out.println();
}
Board board = new Board(startingPositions[matchNumber]);
Match match = new Match(whitePlayer, blackPlayer, board, log, verbose);
MatchOutcome matchOutcome = match.run();
if (verbose) {
System.out.println("Outcome: " + matchOutcome.toString());
System.out.println();
} else {
switch (matchOutcome) {
case WHITE_WINS:
System.out.print(whiteTeamNumberInMatch);
break;
case BLACK_WINS:
System.out.print(blackTeamNumberInMatch);
break;
case TIE:
System.out.print('T');
break;
case DRAW:
System.out.print('D');
}
if (matchNumber % 2 == 1) {
System.out.print(' ');
} // separate mirror matches for readability.
}
double[] payoffs = matchOutcome.getPayoffs();
averagePayoffInThisRound[whiteTeamNumberInMatch] += payoffs[0] / (2 * numBoards);
averagePayoffInThisRound[blackTeamNumberInMatch] += payoffs[1] / (2 * numBoards);
}
System.out.println();
System.out.println("************************************************************************************");
System.out.println();
System.out.println("Round ended.");
for (int teamNumber = 0; teamNumber <= 1; ++teamNumber) {
System.out.println("Average payoff of player " + playersInThisRound[teamNumber].getName() + ": "
+ numberFormat.format(averagePayoffInThisRound[teamNumber]));
totalScore[idsInThisRound[teamNumber]] += averagePayoffInThisRound[teamNumber];
}
System.out.println();
System.out.println("************************************************************************************");
System.out.println();
}
if (Parameters.PRINT_LOG) {
log.println("\\end{document}");
log.close();
}
printRanking(allPlayers, totalScore);
}
private boolean verifyPlayerManifest() {
Scanner scanner;
try {
scanner = new Scanner(new File("playermanifest.txt"));
} catch (FileNotFoundException e) {
System.out.println("Please add a playermanifest.txt file to current working directory");
return false;
}
int line = 0;
while (scanner.hasNextLine()) {
// each pair of lines in the manifest after the first should be of
// the form:
// teamName
// n
// where n is the number of players of team "teamName" you want in
// tournament
++line;
String teamClassName = scanner.nextLine();
if (!playerFactory.hasPlayer(teamClassName)) {
System.out.println("Error in playermanifest.txt line: " + line);
System.out.println("Team Name: " + teamClassName + " not found in playerFactory.registeredPlayers");
scanner.close();
return false;
}
// now check population
++line;
try {
Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error in playermanifest.txt line: " + line);
System.out.println(
"Expected a single integer corresponding to number of players from team " + teamClassName);
scanner.close();
return false;
}
}
scanner.close();
return true;
}
private ArrayList<Player> getPlayers() throws FileNotFoundException {
ArrayList<Player> allPlayers = new ArrayList<Player>();
Scanner scanner = new Scanner(new File("playermanifest.txt"));
while (scanner.hasNextLine()) {
// each pair of lines in the manifest after the first should be of
// the form:
// teamName
// n
// where n is the number of players of team "teamName" you want in
// tournament
String teamClassName = scanner.nextLine();
int population = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < population; ++i) {
allPlayers.add(getPlayer(teamClassName));
}
}
scanner.close();
// randomize player order
Collections.shuffle(allPlayers);
return allPlayers;
}
public void printRanking(ArrayList<Player> allPlayers, double[] totalScore) {
Integer[] rankedPlayers = new Integer[numPlayers];
for (int i = 0; i < numPlayers; ++i) {
rankedPlayers[i] = i;
}
Arrays.sort(rankedPlayers, new ScoreComparator(totalScore));
System.out.println("Final ranking:");
for (int i = 0; i < numPlayers; ++i) {
System.out.println(i + " (" + numberFormat.format(totalScore[rankedPlayers[i]]) + ") : "
+ allPlayers.get(rankedPlayers[i]).getName());
}
}
public static void main(String[] args) throws IOException {
boolean verbose = (args.length >= 1 && args[0].equals("verbose"))
|| (args.length == 2 && args[1].equals("verbose"));
Tournament tournament = new Tournament(verbose);
tournament.run();
}
}