-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathGame.java
More file actions
814 lines (715 loc) · 32.4 KB
/
Copy pathGame.java
File metadata and controls
814 lines (715 loc) · 32.4 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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
package core;
import core.actions.AbstractAction;
import core.actions.DoNothing;
import core.interfaces.IExtendedSequence;
import core.interfaces.IPrintable;
import core.turnorders.ReactiveTurnOrder;
import evaluation.listeners.IGameListener;
import evaluation.metrics.Event;
import evaluation.summarisers.TAGNumericStatSummary;
import games.GameType;
import gui.AbstractGUIManager;
import gui.GUI;
import gui.GamePanel;
import players.basicMCTS.BasicMCTSPlayer;
import players.human.ActionController;
import players.human.HumanConsolePlayer;
import players.human.HumanGUIPlayer;
import players.simple.RandomPlayer;
import utilities.Pair;
import utilities.Utils;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class Game {
private static final AtomicInteger idFountain = new AtomicInteger(0);
// Type of game
private final GameType gameType;
public boolean paused;
// List of agents/players that play this game.
protected List<AbstractPlayer> players;
// Real game state and forward model
protected AbstractGameState gameState;
protected AbstractForwardModel forwardModel;
private List<IGameListener> listeners = new ArrayList<>();
/* Game Statistics */
private int lastPlayer; // used to track actions per 'turn'
private JFrame frame;
// Timers for various function calls
private double nextTime, copyTime, agentTime, actionComputeTime;
// Keeps track of action spaces for each game tick, pairs of (player ID, #actions)
private ArrayList<Pair<Integer, Integer>> actionSpaceSize;
// Number of times an agent is asked for decisions
private int nDecisions;
// Number of actions taken in a turn by a player
private int nActionsPerTurn, nActionsPerTurnSum, nActionsPerTurnCount;
private boolean pause, stop;
private boolean debug = false;
// Video recording
private Rectangle areaBounds;
private boolean recordingVideo = false;
String fileName = "output.mp4";
String formatName = "mp4";
String codecName = null;
int snapsPerSecond = 10;
private int turnPause;
/**
* Game constructor. Receives a list of players, a forward model and a game state. Sets unique and final
* IDs to all players in the game, and performs initialisation of the game state and forward model objects.
*
* @param players - players taking part in this game.
* @param realModel - forward model used to apply game rules.
* @param gameState - object used to track the state of the game in a moment in time.
*/
public Game(GameType type, List<AbstractPlayer> players, AbstractForwardModel realModel, AbstractGameState gameState) {
this.gameType = type;
this.gameState = gameState;
this.forwardModel = realModel;
reset(players);
}
/**
* Game constructor. Receives a forward model and a game state.
* Performs initialisation of the game state and forward model objects.
*
* @param model - forward model used to apply game rules.
* @param gameState - object used to track the state of the game in a moment in time.
*/
public Game(GameType type, AbstractForwardModel model, AbstractGameState gameState) {
this.gameType = type;
this.forwardModel = model;
this.gameState = gameState;
reset(Collections.emptyList(), gameState.gameParameters.randomSeed);
}
/**
* Runs one game.
*
* @param gameToPlay - game to play
* @param players - list of players for the game
* @param seed - random seed for the game
* @param randomizeParameters - if true, parameters are randomized for each run of each game (if possible).
* @return - game instance created for the run
*/
public static Game runOne(GameType gameToPlay, String parameterConfigFile, List<AbstractPlayer> players, long seed,
boolean randomizeParameters, List<IGameListener> listeners, ActionController ac, int turnPause) {
// Creating game instance (null if not implemented)
Game game;
if (parameterConfigFile != null) {
AbstractParameters params = AbstractParameters.createFromFile(gameToPlay, parameterConfigFile);
game = gameToPlay.createGameInstance(players.size(), seed, params);
} else game = gameToPlay.createGameInstance(players.size(), seed);
if (game == null)
System.out.println("Error game: " + gameToPlay);
if (listeners != null) {
Set<String> agentNames = players.stream()
// .peek(a -> System.out.println(a.toString()))
.map(AbstractPlayer::toString).collect(Collectors.toSet());
for (IGameListener gameTracker : listeners) {
gameTracker.init(game, players.size(), agentNames);
game.addListener(gameTracker);
}
}
// Randomize parameters
if (randomizeParameters) {
AbstractParameters gameParameters = game.getGameState().getGameParameters();
gameParameters.randomize();
System.out.println("Parameters: " + gameParameters);
}
// Reset game instance, passing the players for this game
game.reset(players);
game.setTurnPause(turnPause);
if (ac != null) {
// We spawn the GUI off in another thread
GUI frame = new GUI();
GamePanel gamePanel = new GamePanel();
frame.setContentPane(gamePanel);
AbstractGUIManager gui = gameToPlay.createGUIManager(gamePanel, game, ac);
frame.setFrameProperties();
frame.validate();
frame.pack();
// Video recording setup
if (game.recordingVideo) {
game.areaBounds = new Rectangle(0, 0, frame.getWidth(), frame.getHeight());
}
Timer guiUpdater = new Timer((int) game.getCoreParameters().frameSleepMS, event -> game.updateGUI(gui, frame));
guiUpdater.start();
game.run();
guiUpdater.stop();
// and update GUI to final game state
game.updateGUI(gui, frame);
} else {
// Run!
game.run();
}
return game;
}
public void setTurnPause(int turnPause) {
this.turnPause = turnPause;
}
/**
* Performs GUI update.
*
* @param gui - gui to update.
*/
private void updateGUI(AbstractGUIManager gui, JFrame frame) {
// synchronise on game to avoid updating GUI in middle of action being taken
AbstractGameState gameState = getGameState();
int currentPlayer = gameState.getCurrentPlayer();
AbstractPlayer player = getPlayers().get(currentPlayer);
if (gui != null) {
gui.update(player, gameState, isHumanToMove());
frame.repaint();
}
}
public final void reset(List<AbstractPlayer> players) {
reset(players, gameState.gameParameters.randomSeed);
}
/**
* Resets the game. Sets up the game state to the initial state as described by game rules, assigns players
* and their IDs, and initialises all players.
*
* @param players - new players for the game
* @param newRandomSeed - random seed is updated in the game parameters object and used throughout the game.
*/
public final void reset(List<AbstractPlayer> players, long newRandomSeed) {
reset(gameState, forwardModel, players, newRandomSeed);
}
/**
* Resets the game. Sets up the game state to the initial state as described by game rules, assigns players
* and their IDs, and initialises all players.
*
* @param gameState - game state to apply the reset to
* @param forwardModel - the forward model to use for resetting the game state
* @param players - new players for the game
* @param newRandomSeed - random seed is updated in the game parameters object and used throughout the game.
*/
public final void reset(AbstractGameState gameState, AbstractForwardModel forwardModel, List<AbstractPlayer> players, long newRandomSeed) {
gameState.reset(newRandomSeed);
forwardModel.abstractSetup(gameState);
if (players.size() == gameState.getNPlayers()) {
this.players = players;
} else if (players.isEmpty()) {
// keep existing players
} else if (players.size() == gameState.nTeams){
this.players = new ArrayList<>();
// In this case we use (copies of) each agent for all players on the team
// loop over each player; find out what team they are in; and add an agent copy
for (int i = 0; i < gameState.getNPlayers(); i++) {
int team = gameState.getTeam(i);
AbstractPlayer player = players.get(team);
player.setForwardModel(this.forwardModel.copy());
this.players.add(player.copy());
}
} else
throw new IllegalArgumentException("PlayerList provided to Game.reset() must be empty, or have the same number of entries as there are players");
int id = 0;
if (this.players != null)
for (AbstractPlayer player : this.players) {
// Give player their ID
player.playerID = id++;
// Create a FM copy for this player (different random seed)
player.setForwardModel(this.forwardModel.copy());
// Create initial state observation
AbstractGameState observation = gameState.copy(player.playerID);
// Allow player to initialize
player.initializePlayer(observation);
}
int gameID = idFountain.incrementAndGet();
gameState.setGameID(gameID);
resetStats();
}
/**
* All timers and game tick set to 0.
*/
public void resetStats() {
nextTime = 0;
copyTime = 0;
agentTime = 0;
actionComputeTime = 0;
nDecisions = 0;
actionSpaceSize = new ArrayList<>();
nActionsPerTurnSum = 0;
nActionsPerTurn = 1;
nActionsPerTurnCount = 0;
lastPlayer = -1;
}
/**
* Runs the game, with synchronisation facilities for GUI and terminal players; not to be used for
* (possibly multithreaded) ParameterSearch and RunGames instances
*/
public final void run() {
listeners.forEach(l -> l.onEvent(Event.createEvent(Event.GameEvent.ABOUT_TO_START, gameState)));
boolean firstEnd = true;
while (gameState.isNotTerminal() && !stop) {
synchronized (this) {
// Now synchronized with possible intervention from the GUI
// This is only relevant if the game has been paused...so should not affect
// performance in non-GUI situations
try {
while (pause && !isHumanToMove()) {
wait();
}
} catch (InterruptedException e) {
// Meh.
}
int activePlayer = gameState.getCurrentPlayer();
if (debug) System.out.printf("Entered synchronized block in Game for player %s%n", activePlayer);
AbstractPlayer currentPlayer = players.get(activePlayer);
// we check via a volatile boolean, otherwise GUI button presses do not trigger this
// as the JVM hoists pause and isHumanToMove() ouside the while loop on the basis that
// they cannot be changed in this thread....
/*
* The Game is responsible for tracking the players and the current game state
* It is important that the Game never passes the main AbstractGameState to the individual players,
* but instead always uses copy(playerId) to both:
* i) shuffle any hidden data they cannot see
* ii) ensure that any changes the player makes to the game state do not affect the genuine game state
*
* Players should never have access to the Game, or the main AbstractGameState, or to each other!
*/
// Get player to ask for actions next (This horrendous line is for backwards compatibility).
boolean reacting = gameState instanceof AbstractGameStateWithTurnOrder &&
((AbstractGameStateWithTurnOrder) gameState).getTurnOrder() instanceof ReactiveTurnOrder &&
!((ReactiveTurnOrder) ((AbstractGameStateWithTurnOrder) gameState).getTurnOrder()).getReactivePlayers().isEmpty();
// Check if this is the same player as last, count number of actions per turn
if (!reacting) {
if (currentPlayer != null && activePlayer == lastPlayer) {
nActionsPerTurn++;
} else {
nActionsPerTurnSum += nActionsPerTurn;
nActionsPerTurn = 1;
nActionsPerTurnCount++;
}
}
if (gameState.isNotTerminal()) {
if (debug) System.out.printf("Invoking oneAction from Game for player %d%n", activePlayer);
oneAction();
} else {
if (firstEnd) {
if (gameState.coreGameParameters.verbose) {
System.out.println("Ended");
}
terminate();
firstEnd = false;
}
}
if (debug) System.out.println("Exiting synchronized block in Game");
}
}
if (firstEnd) {
if (gameState.coreGameParameters.verbose) {
System.out.println("Ended");
}
terminate();
}
}
/**
* Runs an instance of the game, with the possibility to run fully parallel from any other game instances.
* Not to be used when there is a human player, only useful when parallelization needs to be possible.
* @return The final gameState object after finishing the game run(s)
*/
public AbstractGameState runInstance(LinkedList<AbstractPlayer> players, int seed, boolean randomGameParameters) {
AbstractGameState gameState = this.gameState.copy(); // our own copy of the gameState, to play games with
AbstractForwardModel forwardModel = this.forwardModel.copy(); // our own copy of the forwardModel, to avoid concurrency issues
reset(gameState, forwardModel, players, seed); // reset gameState before playing
synchronized (this) {
listeners.forEach(l -> l.onEvent(Event.createEvent(Event.GameEvent.ABOUT_TO_START, gameState)));
}
if (randomGameParameters) {
gameState.getGameParameters().randomize();
System.out.println("Game parameters: " + gameState.getGameParameters());
}
int lastPlayer = -1; // initialise with no last player, since we are starting a new game
int nActionsPerTurn = 1; // keep track within this scope to avoid parallel processes to modify this game's stats
boolean firstEnd = true;
// System.out.println("Running game: "+matchUpPlayers);
while (gameState.isNotTerminal()) {
int activePlayer = gameState.getCurrentPlayer();
AbstractPlayer currentPlayer = players.get(activePlayer);
/*
* The Game is responsible for tracking the players and the current game state
* It is important that the Game never passes the main AbstractGameState to the individual players,
* but instead always uses copy(playerId) to both:
* i) shuffle any hidden data they cannot see
* ii) ensure that any changes the player makes to the game state do not affect the genuine game state
*
* Players should never have access to the Game, or the main AbstractGameState, or to each other!
*/
// Get player to ask for actions next (This horrendous line is for backwards compatibility).
boolean reacting = gameState instanceof AbstractGameStateWithTurnOrder &&
((AbstractGameStateWithTurnOrder) gameState).getTurnOrder() instanceof ReactiveTurnOrder &&
!((ReactiveTurnOrder) ((AbstractGameStateWithTurnOrder) gameState).getTurnOrder()).getReactivePlayers().isEmpty();
// Check if this is the same player as last, count number of actions per turn
if (!reacting) {
if (currentPlayer != null && activePlayer == lastPlayer) {
nActionsPerTurn++;
} else {
nActionsPerTurnSum += nActionsPerTurn; // atomic
nActionsPerTurn = 1;
nActionsPerTurnCount++; // atomic
}
}
if (gameState.isNotTerminal()) {
if (debug) System.out.printf("Invoking oneAction from Game for player %d%n", activePlayer);
// keep track of last player within this scope, since parallel processes may modify this.lastPlayer
lastPlayer = gameState.getCurrentPlayer();
oneAction(gameState, forwardModel, players);
} else {
if (firstEnd) {
if (gameState.coreGameParameters.verbose) {
System.out.println("Ended");
}
terminate(gameState, forwardModel);
firstEnd = false;
}
}
if (debug) System.out.println("Exiting synchronized block in Game");
}
if (firstEnd) {
if (gameState.coreGameParameters.verbose) {
System.out.println("Ended");
}
terminate(gameState, forwardModel);
}
return gameState;
}
public final boolean isHumanToMove() {
int activePlayer = gameState.getCurrentPlayer();
return this.getPlayers().get(activePlayer) instanceof HumanGUIPlayer;
}
public final AbstractAction oneAction() {
return oneAction(gameState, forwardModel, players);
}
public final AbstractAction oneAction(AbstractGameState gameState, AbstractForwardModel forwardModel, List<AbstractPlayer> players) {
// we pause before each action is taken if running with a delay (e.g. for video recording with random players)
if (turnPause > 0)
synchronized (this) {
try {
wait(turnPause);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// This is the next player to be asked for a decision
int activePlayer = gameState.getCurrentPlayer();
if (!gameState.isNotTerminalForPlayer(activePlayer))
throw new AssertionError("Player " + activePlayer + " is not allowed to move");
AbstractPlayer currentPlayer = players.get(activePlayer);
if (debug) System.out.printf("Starting oneAction for player %s%n", activePlayer);
// Get player observation, and time how long it takes
double s = System.nanoTime();
// copying the gamestate also copies the game parameters and resets the random seed (so agents cannot use this
// to reconstruct the starting hands etc.)
AbstractGameState observation = gameState.copy(activePlayer);
copyTime = (System.nanoTime() - s);
// System.out.printf("Total copyTime in ms = %.2f at tick %d (Avg %.3f) %n", copyTime / 1e6, tick, copyTime / (tick +1.0) / 1e6);
// Get actions for the player
s = System.nanoTime();
List<AbstractAction> observedActions = forwardModel.computeAvailableActions(observation, currentPlayer.getParameters().actionSpace);
if (observedActions.isEmpty()) {
Stack<IExtendedSequence> actionsInProgress = gameState.getActionsInProgress();
IExtendedSequence topOfStack = null;
AbstractAction lastAction = null;
if (!actionsInProgress.isEmpty()) {
topOfStack = actionsInProgress.peek();
}
if (gameState.getHistory().size() > 1) {
lastAction = gameState.getHistory().get(gameState.getHistory().size() - 1).b;
}
forwardModel.computeAvailableActions(gameState);
throw new AssertionError("No actions available for player " + activePlayer
+ (lastAction != null ? ". Last action: " + lastAction.getClass().getSimpleName() + " (" + lastAction + ")" : ". No actions in history")
+ ". Actions in progress: " + actionsInProgress.size()
+ (topOfStack != null ? ". Top of stack: " + topOfStack.getClass().getSimpleName() + " (" + topOfStack + ")" : ""));
}
actionComputeTime = (System.nanoTime() - s);
actionSpaceSize.add(new Pair<>(activePlayer, observedActions.size()));
if (gameState.coreGameParameters.verbose) {
System.out.println("Round: " + gameState.getRoundCounter());
}
if (observation instanceof IPrintable && gameState.coreGameParameters.verbose) {
((IPrintable) observation).printToConsole();
}
// Start the timer for this decision
gameState.playerTimer[activePlayer].resume();
// Either ask player which action to use or, in case no actions are available, report the updated observation
AbstractAction action = null;
if (!observedActions.isEmpty()) {
if (observedActions.size() == 1 && (!(currentPlayer instanceof HumanGUIPlayer || currentPlayer instanceof HumanConsolePlayer) || observedActions.get(0) instanceof DoNothing)) {
// Can only do 1 action, so do it.
action = observedActions.get(0);
currentPlayer.registerUpdatedObservation(observation);
} else {
// Get action from player, and time it
s = System.nanoTime();
if (debug)
System.out.printf("About to get action for player %d%n", gameState.getCurrentPlayer());
action = currentPlayer.getAction(observation, observedActions);
if (!observedActions.contains(action)) {
throw new AssertionError("Action played that was not in the list of available actions: " + action);
}
if (debug)
System.out.printf("Game: %2d Tick: %3d\t%s%n", gameState.getGameID(), getTick(), action.getString(gameState));
agentTime = (System.nanoTime() - s);
nDecisions++;
}
if (gameState.coreGameParameters.competitionMode && action != null && !observedActions.contains(action)) {
System.out.printf("Action played that was not in the list of available actions: %s%n", action.getString(gameState));
action = null;
}
// We publish an ACTION_CHOSEN message before we implement the action, so that observers can record the state that led to the decision
AbstractAction finalAction = action;
synchronized (this) {
listeners.forEach(l -> l.onEvent(Event.createEvent(Event.GameEvent.ACTION_CHOSEN, gameState, finalAction, activePlayer)));
}
} else {
currentPlayer.registerUpdatedObservation(observation);
}
// End the timer for this decision
gameState.playerTimer[activePlayer].pause();
gameState.playerTimer[activePlayer].incrementAction();
if (gameState.coreGameParameters.verbose && !(action == null)) {
System.out.println(action);
}
if (action == null)
throw new AssertionError("We have a NULL action in the Game loop");
// Check player timeout
if (observation.playerTimer[activePlayer].exceededMaxTime()) {
action = forwardModel.disqualifyOrRandomAction(gameState.coreGameParameters.disqualifyPlayerOnTimeout, gameState);
} else {
// Resolve action and game rules, time it
s = System.nanoTime();
// we copy the action before using it..so that the action returned by oneAction() does not have a state link
forwardModel.next(gameState, action.copy());
nextTime = (System.nanoTime() - s);
}
lastPlayer = activePlayer;
// We publish an ACTION_TAKEN message once the action is taken so that observers can record the result of the action
// (such as the next player)
AbstractAction finalAction1 = action;
synchronized (this) {
listeners.forEach(l -> l.onEvent(Event.createEvent(Event.GameEvent.ACTION_TAKEN, gameState, finalAction1.copy(), activePlayer)));
}
if (debug) System.out.printf("Finishing oneAction for player %s%n", activePlayer);
return action;
}
/**
* Called at the end of game loop execution, when the game is over.
*/
private void terminate() {
terminate(gameState, forwardModel);
}
/**
* Called at the end of game loop execution, when the game is over, given some gameState
* @param gameState The game state to handle termination for.
* @param forwardModel The forward model to handle termination with.
*/
private void terminate(AbstractGameState gameState, AbstractForwardModel forwardModel) {
// Print last state
if (gameState instanceof IPrintable && gameState.coreGameParameters.verbose) {
((IPrintable) gameState).printToConsole();
}
// Perform any end of game computations as required by the game
forwardModel.endGame(gameState);
synchronized (this) {
listeners.forEach(l -> l.onEvent(Event.createEvent(Event.GameEvent.GAME_OVER, gameState)));
}
if (gameState.coreGameParameters.recordEventHistory) {
gameState.recordHistory(Event.GameEvent.GAME_OVER.name());
for (int i = 0; i < gameState.getNPlayers(); i++) {
gameState.recordHistory(String.format("Player %d finishes at position %d with score: %.0f", i, gameState.getOrdinalPosition(i), gameState.getGameScore(i)));
}
}
if (gameState.coreGameParameters.verbose) {
System.out.println("Game Over");
}
// Allow players to terminate
for (AbstractPlayer player : players) {
player.finalizePlayer(gameState.copy(player.getPlayerID()));
}
}
/**
* Retrieves the current game state.
*
* @return - current game state.
*/
public final AbstractGameState getGameState() {
return gameState;
}
/**
* Retrieves the forward model.
*
* @return - forward model.
*/
public AbstractForwardModel getForwardModel() {
return forwardModel;
}
/**
* Retrieves agent timer value, i.e. how long the AI players took to make decisions in this game.
*
* @return - agent time
*/
public double getAgentTime() {
return agentTime;
}
/**
* Retrieves the copy timer value, i.e. how long the game state took to produce player observations in this game.
*
* @return - copy time
*/
public double getCopyTime() {
// System.out.printf("Average copy time was %.3f microseconsds%n", copyTime / 1e3);
return copyTime;
}
/**
* Retrieves the next timer value, i.e. how long the forward model took to advance the game state with an action.
*
* @return - next time
*/
public double getNextTime() {
return nextTime;
}
/**
* Retrieves the action compute timer value, i.e. how long the forward model took to compute the available actions
* in a game state.
*
* @return - action compute time
*/
public double getActionComputeTime() {
return actionComputeTime;
}
/**
* Retrieves the number of game loop repetitions performed in this game.
*
* @return - tick number
*/
public int getTick() {
return gameState.getGameTick();
}
/**
* Retrieves number of decisions made by the AI players in the game.
*
* @return - number of decisions
*/
public int getNDecisions() {
return nDecisions;
}
/**
* Number of actions taken in a turn by a player, before turn moves to another.
*
* @return - number of actions per turn
*/
public int getNActionsPerTurn() {
return nActionsPerTurnSum;
}
/**
* Retrieves a list with one entry per game tick, each a pair (player ID, # actions)
*
* @return - list of action space sizes
*/
public ArrayList<Pair<Integer, Integer>> getActionSpaceSize() {
return actionSpaceSize;
}
/**
* Which game is this?
*
* @return type of game.
*/
public GameType getGameType() {
return gameType;
}
public void addListener(IGameListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
gameState.addListener(listener);
listener.setGame(this);
}
}
public List<IGameListener> getListeners() {
return listeners;
}
public void clearListeners() {
listeners.clear();
getGameState().clearListeners();
}
/**
* Retrieves the list of players in the game.
*
* @return - players list
*/
public List<AbstractPlayer> getPlayers() {
return players;
}
public boolean isPaused() {
return pause;
}
public void setPaused(boolean paused) {
this.pause = paused;
}
public void flipPaused() {
this.paused = !this.paused;
}
public boolean isStopped() {
return stop;
}
public void setStopped(boolean stopped) {
this.stop = stopped;
}
public CoreParameters getCoreParameters() {
return gameState.coreGameParameters;
}
public void setCoreParameters(CoreParameters coreParameters) {
this.gameState.setCoreGameParameters(coreParameters);
}
@Override
public String toString() {
return gameType.toString();
}
/**
* The recommended way to run a game is via evaluations.Frontend, however that may not work on
* some games for some screen sizes due to the vagaries of Java Swing...
* <p>
* Test class used to run a specific game. The user must specify:
* 1. Action controller for GUI interactions / null for no visuals
* 2. Random seed for the game
* 3. Players for the game
* 4. Game parameter configuration
* 5. Mode of running
* and then run this class.
*/
public static void main(String[] args) {
String gameType = Utils.getArg(args, "game", "Saboteur");
boolean useGUI = Utils.getArg(args, "gui", true);
int turnPause = Utils.getArg(args, "turnPause", 0);
long seed = Utils.getArg(args, "seed", System.currentTimeMillis());
ActionController ac = new ActionController();
/* Set up players for the game */
ArrayList<AbstractPlayer> players = new ArrayList<>();
players.add(new BasicMCTSPlayer());
players.add(new BasicMCTSPlayer());
// RMHCParams params = new RMHCParams();
// params.horizon = 15;
// params.discountFactor = 0.99;
// params.heuristic = AbstractGameState::getHeuristicScore;
// AbstractPlayer rmhcPlayer = new RMHCPlayer(params);
// players.add(rmhcPlayer);
// MCTSParams params = new MCTSParams();
// players.add(new MCTSPlayer(params));
// players.add(new OSLAPlayer());
// players.add(new RMHCPlayer());
// players.add(new HumanConsolePlayer());
// players.add(new FirstActionPlayer());
/* Game parameter configuration. Set to null to ignore and use default parameters */
String gameParams = null;
/* Run! */
runOne(GameType.valueOf(gameType), gameParams, players, seed, false, null, useGUI ? ac : null, turnPause);
/* Run multiple games */
// ArrayList<GameType> games = new ArrayList<>();
// games.add(Connect4);
// runMany(games, players, 100L, 5, false, false, null, turnPause);
// runMany(new ArrayList<GameType>() {{add(Uno);}}, players, 100L, 100, false, false, null, turnPause);
}
}