com.brettonw.game.Game Maven / Gradle / Ivy
The newest version!
package com.brettonw.game;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
public class Game {
private static final Logger log = LogManager.getLogger (Game.class);
private static int count = 0;
private static int winCount = 0;
private static Map gameMap = new HashMap<> (5500);
public static int getCount () {
return count;
}
public static int getWinCount () {
return winCount;
}
private Board board;
private List parents;
private List children;
private Game (Board board, int playerToMove) {
// update statistics, and set the
++count;
// play the game from the board given for the requested number of moves
this.board = board;
}
private void addParent (Game parentGame) {
if (parents == null) {
parents = new ArrayList<> ();
}
parents.add (parentGame);
}
private void addChild (Game childGame) {
if (children == null) {
children = new ArrayList<> (Board.DIMENSION);
}
children.add (childGame);
childGame.addParent (this);
}
public static Game play (Board board, int playerToMove) {
String signature = board.toString ();
if (gameMap.containsKey (signature)) {
log.debug ("Linking existing node (" + signature + ")");
return gameMap.get (signature);
} else {
Game game = new Game (board, playerToMove);
gameMap.put (signature, game);
// play the board
int winner = Referee.checkWinner (board);
if (winner != 0) {
++winCount;
log.debug ("Win for " + Player.display (winner) + " (" + board.toString () + ")");
} else {
List moves = board.getAvailableMoves ();
if (moves.size () > 0) {
log.debug ("Playing out " + moves.size () + " moves");
int nextPlayerToMove = Player.next (playerToMove);
for (Move move : moves) {
Board afterMove = new Board (board, move, playerToMove);
Game afterMoveGame = play (afterMove, nextPlayerToMove);
game.addChild (afterMoveGame);
}
log.debug ("Done playing out " + moves.size () + " moves");
}
}
return game;
}
}
}