private void createTileElements(Game game) { tileElemens = new HashMap<Position, Element>(); Element parent = doc.createElement("tiles"); if (game.getCurrentTile() != null) { parent.setAttribute("next", game.getCurrentTile().getId()); } root.appendChild(parent); //for() for(String group : game.getTilePack().getGroups()) { Element el = doc.createElement("group"); el.setAttribute("name", group); el.setAttribute("active", "" + game.getTilePack().isGroupActive(group)); parent.appendChild(el); } for(Tile tile : game.getBoard().getAllTiles()) { Element el = doc.createElement("tile"); el.setAttribute("name", tile.getId()); el.setAttribute("rotation", tile.getRotation().name()); XmlUtils.injectPosition(el, tile.getPosition()); parent.appendChild(el); tileElemens.put(tile.getPosition(), el); } for(String tileId : game.getBoard().getDiscardedTiles()) { Element el = doc.createElement("discard"); el.setAttribute("name", tileId); parent.appendChild(el); } }
public static int evaluate(Game game, char player) { if (game.isGameOver()) { for (int i = 0; i < Board.ROWS; i++) { for (int j = 0; j < Board.COLUMNS; j++) { if (game.getBoard().matrix[i][j] != Board.EMPTY) { int piece = game.getBoard().matrix[i][j]; if (piece == Board.BLACK_SOLDIER || piece == Board.BLACK_KING) { if (player == Move.BLACK) { return 100; } else { return -100; } } else if (piece == Board.RED_SOLDIER || piece == Board.RED_KING) { if (player == Move.RED) { return 100; } else { return -100; } } } } } } else { int numBlackKings = 0, numRedKings = 0; int numBlackPieces = 0, numRedPieces = 0; for (int i = 0; i < Board.ROWS; i++) { for (int j = 0; j < Board.COLUMNS; j++) { int piece = game.getBoard().matrix[i][j]; if (piece != Board.EMPTY) { if (piece == Board.BLACK_KING) { numBlackKings++; numBlackPieces++; } else if (piece == Board.RED_KING) { numRedKings++; numRedPieces++; } else if (piece == Board.BLACK_SOLDIER) { numBlackPieces++; } else if (piece == Board.RED_SOLDIER) { numRedPieces++; } } } } int score = 0; score += 6 * (numBlackPieces - numRedPieces); score += (28f / 12f) * (numBlackKings - numRedKings); if (player == Move.RED) { score *= -1; } return score; } return 0; }
public void jumpTo(int position) { // just bondaries safeguarding position = position % Game.getBoard().size(); StdOut.println( this.name + " jumped to tile #" + position + " " + Game.getBoard().getTile(position)); this.position = position; }
// Given a game board, return the current value for the state of that Game. private Double getValue(Game game) throws InvalidMoveException { int key = genStateKey(game.getBoard()); if (stateValues.containsKey(key)) return stateValues.get(key); else { throw new InvalidMoveException("value did not exist in stateValues table!"); } }
public BoardPanel( final JFrame frame, Game game, UnitTypeConfiguration unitTypeConfiguration, TileTypeConfiguration tileTypeConfiguration, TileStateConfiguration tileStateConfiguration, ChessMovementStrategy movementStrategy, UnitSelectorMode unitSelectorMode, BattleStrategyConfiguration battleStrategyConfiguration) { this.frame = frame; this.battleStrategyConfiguration = battleStrategyConfiguration; thisPanel = this; this.game = game; game.addGameObserver(this); this.board = game.getBoard(); this.movementStrategy = movementStrategy; int rows = board.getDimension().getHeight(); int columns = board.getDimension().getWidth(); setLayout(new GridLayout(rows, columns)); for (Tile tile : board.getTiles()) { final TilePanel tilePanel = new TilePanel(tileTypeConfiguration, unitTypeConfiguration, tileStateConfiguration, tile); if (UnitSelectorMode.MULTIPLE.equals(unitSelectorMode)) { tilePanel.addMouseListener( new MultipleUnitSelectorMouseListener(tilePanel, frame, thisPanel)); } if (UnitSelectorMode.SINGLE.equals(unitSelectorMode)) { tilePanel.addMouseListener( new SingleUnitSelectorMouseListener(tilePanel, frame, thisPanel)); } map.put(tile, tilePanel); add(tilePanel); } resetPositions(); }
public void setJailTime(int time) { if (this.jailTime < time) { // if the time is increasing from old value, // then you have bean thrown into jail this.jumpTo(Game.getBoard().getJailPosition()); } this.jailTime = time; }
// Includes stepping forwards and backwards public void step(int steps) { // make steps, check if you passed go, collect money // call tileActions(); this.position += steps; if (this.position < 0) { this.position += Game.getBoard().boardSize(); } // anton fix from > to >= if it's equal to 40 it needs to be set to 0 already if (this.position >= Game.getBoard().boardSize()) { this.position = this.position % Game.getBoard().boardSize(); StdOut.println("Passed GO. Collect €2M."); Game.getBank().getMoneyFromBank(2000000L); } UI.displayBoard(); Game.getBoard().tileActions(); }
public static int MiniMax(Game game, char player, int depth, int maxDepth) { if (depth == maxDepth || game.isGameOver()) { return evaluate(game, player); } Move bestMove = null; int bestScore; if (game.getTurn() == player) { bestScore = Integer.MIN_VALUE; } else { bestScore = Integer.MAX_VALUE; } List<Move> allMoves = getMoves(game, game.getTurn()); for (Move move : allMoves) { int[][] matrixCopy = game.getBoard().getMatrixCopy(); game.processMove(move.getCopy()); game.changeTurn(); int moveScore = MiniMax(game, player, depth + 1, maxDepth); game.changeTurn(); game.getBoard().setMatrix(matrixCopy); if (game.getTurn() == player) { if (moveScore > bestScore) { bestScore = moveScore; bestMove = move.getCopy(); } } else { if (moveScore < bestScore) { bestScore = moveScore; bestMove = move.getCopy(); } } } if (depth == 0) { computedBestMove = bestMove; } return bestScore; }
// recursively expand the game tree, exploring all possible moves. private void expandStateSpace(Game game) { int state = game.evaluateGameState(); // if key exists, we've expanded this subtree already. Returning now avoids unnecessary // traversals. if (stateValues.containsKey(genStateKey(game.getBoard()))) { return; } Integer[] moves = game.possibleMoves(); int initPolicy = Consts.NoMove; if (moves.length != 0) initPolicy = moves[0]; statePolicy.put(genStateKey(game.getBoard()), initPolicy); stateValues.put(genStateKey(game.getBoard()), Consts.InitialValue); // if the game is still in progress, recurse down the game tree. if (state == Consts.GameInProgress) { for (int nextMove : game.possibleMoves()) expandStateSpace(game.simulateMove(nextMove)); } }
public static List<Move> getMoves(Game game, char player) { List<Move> moves = new ArrayList<Move>(); for (int row = 0; row < Board.ROWS; row++) { for (int col = 0; col < Board.COLUMNS; col++) { int pieceColor = game.getBoard().matrix[row][col]; if (player == Move.RED) { if (pieceColor == Board.RED_KING || pieceColor == Board.RED_SOLDIER) { List<Move> pieceMoves = getMovesForPiece(game, new Point(col, row)); moves.addAll(pieceMoves); } } else if (player == Move.BLACK) { if (pieceColor == Board.BLACK_KING || pieceColor == Board.BLACK_SOLDIER) { List<Move> pieceMoves = getMovesForPiece(game, new Point(col, row)); moves.addAll(pieceMoves); } } } } return moves; }
// to pick a move, simply follow the action in the converged statePolicy table. public int pickMove(Game game) { return statePolicy.get(genStateKey(game.getBoard())); }
/** * @param args * @throws ClassNotFoundException */ public static void main(String[] args) throws ClassNotFoundException { Game game1 = new Game(); Move currMove; Move enemyMove; System.out.println("Welcome to Knight's Watch!!!"); System.out.println("Waiting for another player to connect..."); String host = args.length > 0 ? args[0] : DEFAULT_HOST; int port = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_PORT; try { // connect to the server Socket socket = new Socket(host, port); // create a scanner & printstream out of the socket's I/O streams ObjectInputStream socketIn = new ObjectInputStream(socket.getInputStream()); ObjectOutputStream socketOut = new ObjectOutputStream(socket.getOutputStream()); socketOut.flush(); String playerNum = (String) socketIn.readObject(); System.out.println("You are player number : " + playerNum); // prepare STDIN for reading String oppositePlayerNum = (playerNum.equals("1")) ? "2" : "1"; System.out.println( "You are player" + playerNum + ", your color is: " + ((playerNum.equals("1")) ? "white" : "black")); game1.setCurrPlayer((playerNum.equals("1")) ? ColorEnum.WHITE : ColorEnum.BLACK); System.out.println(game1.getBoard().toString()); if (playerNum.equals("2")) { System.out.println("Waiting for player" + oppositePlayerNum + " to make his move..."); enemyMove = (Move) socketIn.readObject(); // print to STDOUT System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); System.out.println( "Enemy has made this move: From " + enemyMove.getA().toString() + " to " + enemyMove.getB().toString()); game1.getBoard().movePiece(enemyMove); System.out.println(game1.getBoard().toString()); } while (game1.getStatus() == GameStatus.CONTINUE) { // Get the move currMove = game1.makeMoveForCurrentPlayer(); game1.getBoard().movePiece(currMove); currMove.setResultingGameStatus(game1.getStatus()); // send the move socketOut.writeObject(currMove); socketOut.flush(); System.out.println(game1.getBoard().toString()); if (game1.getStatus() == GameStatus.CONTINUE) { // receive the enemy move System.out.println("Waiting for player" + oppositePlayerNum + " to make his move..."); enemyMove = (Move) socketIn.readObject(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); System.out.println( "Enemy has made this move: From " + enemyMove.getA().toString() + " to " + enemyMove.getB().toString()); game1.getBoard().movePiece(enemyMove); System.out.println(game1.getBoard().toString()); } else { break; } } System.out.println("The Game is finished!"); switch (game1.getStatus()) { case WHITEWINS: System.out.println("White has won!"); break; case BLACKWINS: System.out.println("Black has won!"); break; case DRAW: System.out.println("it was a draw!"); break; } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private void debugOptions() { int choice = this.displayDebugMenu(); while (choice != 0) { switch (choice) { case 1: Game.setDebugDice(!Game.getDebugDice()); break; case 2: UI.displayBoard(); int pos = -1; // keep asking while it's not positive number while ((pos = UI.askNgetInt("Where you want to jump?")) < 0) ; // if it's too big, inside the jump it will be fixed with MODULO Game.getCurrentPlayer().jumpTo(pos); break; case 3: Game.getBoard().tileActions(); break; case 4: Long cash = -1L; while ((cash = UI.askNgetLong("How much cash you want to have?")) < 0) { // keep asking while it's not positive number } Game.getCurrentPlayer().setCash(cash); break; case 5: UI.displayBoard(); int jail = -1; while ((jail = UI.askNgetInt("Jail time. How much?")) < 0) { // keep asking while it's not positive number } Game.getCurrentPlayer().setJailTime(jail); break; case 6: Game.getCardsCommunity().pickCard(); break; case 7: Game.getCardsChance().pickCard(); break; case 8: StdOut.println(); StdOut.println("Community deck size: " + Game.getCardsCommunity().getCards().size()); StdOut.println("Chance deck size: " + Game.getCardsChance().getCards().size()); StdOut.println(); UI.pause(); break; case 9: // it will allow you to switch even to non playing player, so be // careful ArrayList<Player> playersPlaying = Game.getPlayers(); int swapTo = UI.displayMenuNGetChoice("Players", UI.playersToItems(playersPlaying), false, true); Game.setPlayersTurn(swapTo); break; case 10: UI.displayBoard(); break; case 11: StdOut.println("Houses :" + Game.getBank().getAvailableHouses()); StdOut.println("Hotels :" + Game.getBank().getAvailableHotels()); Game.getBank() .setAvailableHouses(UI.askNgetInt("How many houses you want to have spare?")); Game.getBank() .setAvailableHotels(UI.askNgetInt("How many hotels you want to have spare?")); break; case 0: default: break; } if (choice != 0) choice = this.displayDebugMenu(); } }
private void playerOptions() { int choice = this.displayPlayerMenu(); while (choice != 0) { switch (choice) { // player decided to roll dice case 1: PairDice dice = PairDice.getInstance(Game.getDebugDice()); UI.diceDisplay(dice); Game.getCurrentPlayer().step(dice.total); if (dice.same) { StdOut.println("\nYou threw a DOUBLE, you are rolling for the second time."); UI.pause(); dice = PairDice.getInstance(Game.getDebugDice()); UI.diceDisplay(dice); Game.getCurrentPlayer().step(dice.total); if (dice.same) { StdOut.println( "\nYou threw a DOUBLE for the second time, you are rolling the third time."); StdOut.println("Note: be careful or you are going to jail."); UI.pause(); dice = PairDice.getInstance(Game.getDebugDice()); UI.diceDisplay(dice); if (dice.same) { StdOut.println( "\nYou threw a DOUBLE for the third time, you are going straight to jail."); // Game.getCurrentPlayer().jumpTo(Game.getBoard().getJailPosition()); // will change possition as well Game.getCurrentPlayer().setJailTime(3); } else { Game.getCurrentPlayer().step(dice.total); } } } // step is already called in tileActions // Game.getBoard().tileActions(); choice = 0; UI.pause(); break; // to see what tiles he owns case 2: UI.displayMyProperties(); UI.pause(); break; // to see stats of all players together case 3: UI.displayChoiceItems( "Players", UI.playersToItems(Game.getAllPlayingPlayers()), false, false); UI.pause(); break; // Sell properties to other player case 4: // TODO test it more ArrayList<BoardTile> tiles = new ArrayList<BoardTile>(); for (BoardTile tile : BoardSearch.all().filterByOwner(Game.getCurrentPlayer()).getTiles()) { if (Game.getBoard() .getTile(Game.getCurrentPlayer().getPosition()) .ownAllofThisColorAreNotUpgraded()) { if (tile.getUpgradeLevel() == 0) { tiles.add(tile); } } } if (tiles.size() > 0) { int forSale = UI.displayMenuNGetChoice( "Choose tile to sell", BoardSearch.all(tiles).toMenuItems(), false, true); // BoardTile tileForSale = tiles Pair<Player, Long> winner = Game.getBank().auction("Auction for " + tiles.get(forSale), Game.getOtherPlayers()); if (winner.first != null) { tiles.get(forSale).setOwned(true); tiles.get(forSale).setOwner(winner.first); winner.first.payToPlayer(Game.getCurrentPlayer(), winner.second); } else { StdOut.println("Nobody was interested to buy your property."); } } else { StdOut.println( "You don't own any properties avaiable for selling. Can't be upgraded and:"); StdOut.println("To sell property all properties of this colour can't be upgraded!"); } UI.pause(); break; // Downgrade tiles case 5: // TODO test it more UI.displayMyProperties(); ArrayList<BoardTile> forDowngrade = new ArrayList<BoardTile>(); for (BoardTile tile : BoardSearch.all().filterByOwner(Game.getCurrentPlayer()).getTiles()) { if (tile.getUpgradeLevel() > 0) { forDowngrade.add(tile); } } if (forDowngrade.size() > 0) { if (UI.askNgetBoolean("Are you sure to downgrade some properties?")) { int downgradeIndex = UI.displayMenuNGetChoice( "Choose property to downgrade", BoardSearch.all(forDowngrade).toMenuItems(), false, true); forDowngrade.get(downgradeIndex).decUpgradeLevel(); } } else { StdOut.println("No properties for downgrading"); } UI.pause(); break; // Mortages case 6: // TODO test it more UI.displayMyProperties(); ArrayList<BoardTile> mortaged = BoardSearch.all() .filterByOwner(Game.getCurrentPlayer()) .filterByMortaged(true) .getTiles(); if (mortaged.size() > 0) { UI.displayChoiceItems( "Mortage properties", BoardSearch.all(mortaged).toMenuItems(), false, true); if (UI.askNgetBoolean("Do you want buy some of them back?")) { int buyBack = UI.displayMenuNGetChoice( "Mortage properties", BoardSearch.all(mortaged).toMenuItems(), false, true); if (mortaged.get(buyBack).mortageBuyOfPrice() <= Game.getCurrentPlayer().getCash()) { // you can afford it but still lets confirm it from you if (UI.askNgetBoolean( "It will cost " + Bank.roundMoney(mortaged.get(buyBack).mortageBuyOfPrice()) + ", do you want it back?")) { mortaged.get(buyBack).mortageFromBank(); } } else { StdOut.println( "You cannot affort to pay: " + Bank.roundMoney(mortaged.get(buyBack).mortageBuyOfPrice())); } } } else { StdOut.println("You didn't mortaged any properties."); } UI.pause(); break; // give up on this game case 7: if (UI.askNgetBoolean("Are you sure to give up?")) Game.getCurrentPlayer().giveUp(); choice = 0; break; // save game status and exit the application case 8: if (UI.askNgetBoolean("Are you sure to suspend the game?")) { Game.save(); Game.stopGame(); choice = 0; } break; case 9: boolean allAgree = true; Long max = 0L; UI.displayChoiceItems( "Players", UI.playersToItems(Game.getAllPlayingPlayers()), false, false); // at least empty player, just in case so there will be no NULL // pointer issues later Player winner = new Player(); for (Player player : Game.getAllPlayingPlayers()) { if (!UI.askNgetBoolean(player + " do you agree with stopping this game?")) { allAgree = false; } // while traversing all players we can also find who is the richest // one if (player.totalNetWorth() > max) { max = player.totalNetWorth(); winner = player; } } if (allAgree) { // we will leave the menu choice = 0; UI.anounceWinner(winner); Game.stopGame(); } else { StdOut.println("Not all players agreed with this request."); } break; case 10: debugOptions(); break; case 0: default: break; } if (choice != 0) choice = this.displayPlayerMenu(); } }