/** * Generate nextMove according to Minimax algorithm * * @param currPlayer * @param globaldepth * @return */ public Move getMiniMaxMove(Player currPlayer, int globaldepth) { // System.out.println("In getMiniMaxMove "); MiniMaxNode rootNode = new MiniMaxNode( mancalaBoard.getBoard(), currPlayer.playerNum, 0, Integer.MIN_VALUE, null, new Move(-1), false); MiniMaxTree gameTree = new MiniMaxTree(); gameTree.insert(rootNode, null); gameTree = miniMaxHelperWithGO2( gameTree, rootNode, currPlayer, mancalaBoard.getBoard(), 0, globaldepth, true); // System.out.println("Out"); MiniMaxNode root = gameTree.getRoot(); MiniMaxNode retNode = evaluateGameTree(root, 0, 2); Move retMove = new Move(); // Selecting from roots child nodes - Maximizing for (MiniMaxNode childNode : retNode.getChildrenList()) { // System.out.println(childNode.moveIndex.getMoveIndex() + " : " + childNode.getEvalVal()); if (retNode.getEvalVal() < childNode.getEvalVal()) { retNode.setEvalVal(childNode.getEvalVal()); retMove = childNode.getMoveIndex(); } } // sort and get the minimum value of moveindex // System.out.println("the next move is with moveindex : "+ retMove.getMoveIndex()); return (retMove); }
public PromotionDialog(Square location) { // Creating promotion dialog if (Board.getBoard().isWhiteMove()) { setTitle( "Promotion for " + Board.getBoard().getWhitePlayer().getName() + " - Choose a figure"); } else { setTitle( "Promotion for " + Board.getBoard().getBlackPlayer().getName() + " - Choose a figure"); } this.location = location; JPanel pane = (JPanel) getContentPane(); pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); pane.setLayout(new GridLayout(1, 4, 10, 10)); JButton rookButton = new JButton(); rookButton.setIcon(rook.getFigureIcon()); rookButton.addActionListener(this); rookButton.setFocusPainted(false); pane.add(rookButton); JButton knightButton = new JButton(); knightButton.setIcon(knight.getFigureIcon()); knightButton.addActionListener(this); knightButton.setFocusPainted(false); pane.add(knightButton); JButton bishopButton = new JButton(); bishopButton.setIcon(bishop.getFigureIcon()); bishopButton.addActionListener(this); bishopButton.setFocusPainted(false); pane.add(bishopButton); JButton queenButton = new JButton(); queenButton.setIcon(queen.getFigureIcon()); queenButton.addActionListener(this); queenButton.setFocusPainted(false); pane.add(queenButton); // Has to choose setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); // Set to be always on top setAlwaysOnTop(true); // http://goo.gl/h3vnma // Makes dialog customizable setModal(true); // Disable resize setResizable(false); // Makes the dialog like an application (with swing components, etc.) setModalityType(ModalityType.APPLICATION_MODAL); // Size of dialog setMinimumSize(new Dimension(300, 100)); // Centering by default setLocationRelativeTo(null); pack(); setVisible(true); }
public boolean performAction() { // Charge the player here if they have been in jail for too long int jailCount = Board.getBoard().getCurrentPlayer().getJailCount(); if (jailCount >= 3) { movePlayer(); Board.getBoard().getCurrentPlayer().chargePlayer(50); } else { if (diceRoll.isDoubles()) { movePlayer(); } else { Board.getBoard().getCurrentPlayer().incrementJailCount(); } } return true; }
/** Updates the matrix with current board and current pentomino */ public void updateMatrix() { int[][] tmpBoard = new int[gameBoard.getBoard().length][gameBoard.getBoard()[0].length]; // Copy the old board to the tmp for (int i = 0; i < gameBoard.getBoard().length; i++) { System.arraycopy(gameBoard.getBoard()[i], 0, tmpBoard[i], 0, gameBoard.getBoard()[i].length); } // Add the pentomino to the tmpBoard for (Point p : activePentomino.getLocation()) { int newX = (int) (pentominoLocation.getX() + p.getX()); int newY = (int) (pentominoLocation.getY() + p.getY()); if (newY >= 0) tmpBoard[newX][newY] = activePentomino.getID(); } matrix = tmpBoard; }
/** Sets the location for predicted pentomino */ public void predictDrop() { predictedLocation = (Point) pentominoLocation.clone(); while (nextDropLegal(activePentomino, gameBoard.getBoard(), predictedLocation)) { predictedLocation.setLocation(predictedLocation.getX(), predictedLocation.getY() + 1); } }
/** * Check if the move is illegal : if pit contains nothing * * @param myMove * @return true for an illegal move */ public boolean isIllegalMove(Move myMove) { if (mancalaBoard.getBoard()[myMove.getMoveIndex()] == 0) { System.out.println("The move you selected is not allowed. Select again."); return true; } return false; }
// Test if Board class creates 3*3 char array @Test public void newBoard() { char[][] testArray = new char[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { testArray[i][j] = '-'; } } Board testBoard = new Board(); assertArrayEquals(testArray, testBoard.getBoard()); }
@Test public void markBoard() { char[][] testArray = new char[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { testArray[i][j] = '-'; } } testArray[1][2] = 'x'; Board testBoard = new Board(); testBoard.mark(1, 2, 'x'); assertArrayEquals(testArray, testBoard.getBoard()); }
public Frame(boolean isStar) { super("2048"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); this.isStar = isStar; background = new JLabel(new ImageIcon("Images\\background.png")); this.setResizable(false); add(background); background.setLayout(new FlowLayout()); newGameButton = new JButton(new ImageIcon("Images\\newGame.png")); recordTableButton = new JButton(new ImageIcon("Images\\recordTableButton.png")); designButton = new JButton(new ImageIcon("Images\\changeDesign.png")); newGameButton.setBorder(BorderFactory.createEmptyBorder()); newGameButton.setContentAreaFilled(false); recordTableButton.setBorder(BorderFactory.createEmptyBorder()); recordTableButton.setContentAreaFilled(false); designButton.setBorder(BorderFactory.createEmptyBorder()); designButton.setContentAreaFilled(false); background.add(newGameButton); background.add(recordTableButton); background.add(designButton); newGameButton.addActionListener(this); recordTableButton.addActionListener(this); designButton.addActionListener(this); this.addKeyListener(this); board = new Board(highscores, this); this.pack(); nextImage = new JLabel(new ImageIcon("images\\next2.png")); background.add(board.getBoard()); background.add(nextImage); background.add(board.getScoreLabel()); if (isStar != this.board.getChangedDesign()) { this.board.ChaneDesign(); background.setIcon(new ImageIcon("Images\\Background2.png")); newGameButton.setIcon(new ImageIcon("Images\\newGameStar.png")); recordTableButton.setIcon(new ImageIcon("Images\\recordTableStarButton.png")); designButton.setIcon(new ImageIcon("Images\\changeDesignStar.png")); nextImage.setIcon(new ImageIcon("Images\\next2Star.png")); this.board.getScoreLabel().setText("Stars collected:" + this.board.getScore().getScore()); } // board.ChaneDesign(); this.setSize(476, 570); this.pack(); this.setVisible(true); this.requestFocusInWindow(); }
/** * Makes the move temporarily for seeing the moves ahead * * @param move * @param currPlayer * @return the board */ public int[] makeTempMove(Move move, Player currPlayer) { int moveIndex = move.getMoveIndex(); mancalaBoard.displayBoard(); int boardSize = mancalaBoard.getBoardSize(); int[] tempBoard = new int[boardSize]; int[] srcBoard = mancalaBoard.getBoard(); System.arraycopy(srcBoard, 0, tempBoard, 0, boardSize); int numOfStones = tempBoard[moveIndex]; tempBoard[moveIndex] = 0; moveIndex++; while (numOfStones > 0) { if ((moveIndex % boardSize) == mancalaBoard.getOpponentsMancala(currPlayer.playerNum)) { moveIndex++; continue; } tempBoard[(moveIndex) % boardSize]++; moveIndex++; numOfStones--; } // Just to check if we get a free turn int indexToCompare = (moveIndex - 1) % boardSize; int myMancala = mancalaBoard.getMancala(currPlayer.playerNum); if (!(indexToCompare == myMancala)) { if (tempBoard[indexToCompare] == 1) { if ((currPlayer.playerNum == 1 && indexToCompare < mancalaBoard.getPitSize()) || (currPlayer.playerNum == 2 && indexToCompare > mancalaBoard.getPitSize())) { // check opponents opp pit - 2*p - index int oppPit = (mancalaBoard.getPitSize() * 2) - indexToCompare; if (tempBoard[oppPit] > 0) { tempBoard[myMancala] += tempBoard[oppPit] + tempBoard[indexToCompare]; tempBoard[oppPit] = 0; tempBoard[indexToCompare] = 0; } } } } return tempBoard; }
/** * Make the selected move * * @param move : the move the player wants to take * @param currPlayer * @return true if after making a turn we get a free turn */ public boolean makeMove(Move move, Player currPlayer) { boolean freeTurn = false; int moveIndex = move.getMoveIndex(); int[] tempBoard = mancalaBoard.getBoard(); int boardSize = mancalaBoard.getBoardSize(); int numOfStones = tempBoard[moveIndex]; tempBoard[moveIndex] = 0; moveIndex++; while (numOfStones > 0) { if ((moveIndex % boardSize) == mancalaBoard.getOpponentsMancala(currPlayer.playerNum)) { moveIndex++; continue; } tempBoard[(moveIndex) % boardSize]++; moveIndex++; numOfStones--; } int indexToCompare = (moveIndex - 1) % boardSize; int myMancala = mancalaBoard.getMancala(currPlayer.playerNum); // Check if you get a free turn if (indexToCompare == myMancala) { freeTurn = true; System.out.println("You got a free turn with this move"); } else { // Check if you can steal the stones if (tempBoard[indexToCompare] == 1) { if ((currPlayer.playerNum == 1 && indexToCompare < mancalaBoard.getPitSize()) || (currPlayer.playerNum == 2 && indexToCompare > mancalaBoard.getPitSize())) { int oppPit = (mancalaBoard.getPitSize() * 2) - indexToCompare; if (tempBoard[oppPit] > 0) { tempBoard[myMancala] += tempBoard[oppPit] + tempBoard[indexToCompare]; tempBoard[oppPit] = 0; tempBoard[indexToCompare] = 0; } } } } mancalaBoard.setBoard(tempBoard); return freeTurn; }
/** * Gives the number of mancala stones for a move * * @param currMove * @param mancalaIndex * @return the number of stones */ public int checkMove(Move currMove, int mancalaIndex) { int moveIndex = currMove.getMoveIndex(); int distFromMancala = mancalaIndex - moveIndex; System.out.println("mancala is at: " + mancalaIndex); System.out.println("dis from mancala: " + distFromMancala); int[] tempBoard = mancalaBoard.getBoard(); int numOfStones = tempBoard[moveIndex]; System.out.println("num of stones: " + numOfStones + " for move: " + moveIndex); if (numOfStones < distFromMancala) { return 0; } else { return (1 + ((numOfStones - distFromMancala) / (2 * mancalaBoard.getPitSize() + 1))); } }
/** * Prints the given board (Radar or PlayerBoard) to the terminal. If we were going to use a GUI * then separate printRadar and printPlayerBoard methods may be necessary. For ASCII art they're * not. * * @param board A class that extends the abstract class Board */ public void displayBoard(Board board) { char[][] playerBoard = board.getBoard(); StringBuilder sb = new StringBuilder(); /* Add the row of alphabet labels */ sb.append(" "); // top left corner is blank for (int i = 1; i < playerBoard[0].length; i++) sb.append(" " + (char) (i + 64)); /* Start adding the rows of the board * Start at 1 because we already did row 0 */ for (int i = 1; i < playerBoard.length; i++) { // extra padding for single digit # if (i < 10) sb.append(EOL + i + " "); else sb.append(EOL + i + " "); for (int j = 1; j < playerBoard[i].length; j++) { sb.append(playerBoard[i][j] + " "); } } sb.append(EOL); System.out.println(sb.toString()); }
@Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(newGameButton)) { new Frame(isStar); // frame.requestFocusInWindow(); this.setVisible(false); this.setFocusable(false); board.getBoard().requestFocusInWindow(); board.getBoard().setFocusable(true); } if (e.getSource().equals(recordTableButton)) { board.showHighscores(); this.requestFocusInWindow(); } if (e.getSource().equals(designButton)) { this.board.ChaneDesign(); this.requestFocusInWindow(); if (this.board.getChangedDesign()) { background.setIcon(new ImageIcon("Images\\Background2.png")); newGameButton.setIcon(new ImageIcon("Images\\newGameStar.png")); recordTableButton.setIcon(new ImageIcon("Images\\recordTableStarButton.png")); designButton.setIcon(new ImageIcon("Images\\changeDesignStar.png")); nextImage.setIcon(new ImageIcon("Images\\next2Star.png")); this.board.getScoreLabel().setText("Stars collected:" + this.board.getScore().getScore()); } else { background.setIcon(new ImageIcon("Images\\Background.png")); newGameButton.setIcon(new ImageIcon("Images\\newGame.png")); recordTableButton.setIcon(new ImageIcon("Images\\recordTableButton.png")); designButton.setIcon(new ImageIcon("Images\\changeDesign.png")); nextImage.setIcon(new ImageIcon("Images\\next2.png")); this.board.getScoreLabel().setText("Banana Score: " + this.board.getScore().getScore()); } } }
/** * Handles the events for keypresses * * @param e the pressed key */ public void keyPressed(KeyEvent e) { if (activePentomino != null) { // Keys for moveing the pentomino sideways if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) { // Initialize direction to 0 to make sure we don't get null pointer exception // or do something weird with the movement int direction = 0; if (e.getKeyCode() == KeyEvent.VK_LEFT) direction = -1; if (e.getKeyCode() == KeyEvent.VK_RIGHT) direction = 1; // +1 right, -1 left // Check if we are allowed to actually move the pentomino to the new position boolean legalMove = true; for (Point p : activePentomino.getLocation()) { int newX = (int) (p.getX() + pentominoLocation.getX() + direction); int newY = (int) (p.getY() + pentominoLocation.getY()); // Check only if the pentomino is not above the board if (newY >= 0) { // Check that we are horizontally within the board and not trying to overlap another // piece if (newX < 0 || newX >= gameBoard.getBoard().length || gameBoard.getBoard()[newX][newY] != -1) legalMove = false; } } // Check passed so we do the actual movement of the pentomino if (legalMove) { pentominoLocation.setLocation( (pentominoLocation.getX() + direction), pentominoLocation.getY()); predictDrop(); updateMatrix(); } } // Key for rotating the pentomino if (e.getKeyCode() == KeyEvent.VK_UP) { // Create a temporary pentomino to check if the rotated position free Pentomino tmpPentomino = activePentomino.copy(); tmpPentomino.rotate(); boolean legalMove = true; // For reach block of the position check that it's free and within the grid // ignoring the check if we're above the grid for (Point p : tmpPentomino.getLocation()) { int newX = (int) (p.getX() + pentominoLocation.getX()); int newY = (int) (p.getY() + pentominoLocation.getY()); if (newY > 0) { if (newY >= gameBoard.getBoard()[0].length || newX < 0 || newX >= gameBoard.getBoard().length || gameBoard.getBoard()[newX][newY] != -1) { legalMove = false; } } } // If the check passed then simply do the rotation if (legalMove) { activePentomino.rotate(); predictDrop(); } // Update the matrix so we don't have lag in display updateMatrix(); } // Key for speeding up the fall if (e.getKeyCode() == KeyEvent.VK_DOWN) { // If next position is available, put the current pentomino to it if (nextDropLegal(activePentomino, gameBoard.getBoard(), pentominoLocation)) { pentominoLocation.setLocation(pentominoLocation.getX(), pentominoLocation.getY() + 1); } // Update to avoid lag updateMatrix(); } // Key for entirely dropping the pentomino if (e.getKeyCode() == KeyEvent.VK_ENTER) { // We make the pentomino fall as many times as it can while (nextDropLegal(activePentomino, gameBoard.getBoard(), pentominoLocation)) { pentominoLocation.setLocation(pentominoLocation.getX(), pentominoLocation.getY() + 1); } // Update to avoid lag updateMatrix(); } // Key for flipping the pentomino if (e.getKeyCode() == KeyEvent.VK_SPACE) { // Create a temporary pentomino for checking the flipped position Pentomino tmpPentomino = activePentomino.copy(); tmpPentomino.reflect(); // Check that each position in the temporary pentomino is available and within the matrix boolean legalMove = true; for (Point p : tmpPentomino.getLocation()) { int newX = (int) (p.getX() + pentominoLocation.getX()); int newY = (int) (p.getY() + pentominoLocation.getY()); if (newY < 0 || newY >= gameBoard.getBoard()[0].length || newX < 0 || newX >= gameBoard.getBoard().length || gameBoard.getBoard()[newX][newY] != -1) { legalMove = false; } } // Flip the pentomino if check is passed if (legalMove) { activePentomino.reflect(); predictDrop(); } // Update to avoid lag updateMatrix(); } // Key for storing the currently falling pentomino if (e.getKeyCode() == KeyEvent.VK_SHIFT) { // If we haven't stored after fixing the pentomino to the grid if (storageable) { // Change the active and stored pentomino and set the location to the top of the screen pentominoLocation = new Point(gameBoard.getWidth() / 2, 0); Pentomino tmp = activePentomino; activePentomino = storagedPentomino; storagedPentomino = tmp; storageable = false; // Get new prediction predictDrop(); // Update to avoid lag updateMatrix(); } } // Key for a chect for testing purposes if (e.getKeyCode() == KeyEvent.VK_X) { // If pressed enough, add score cheat++; if (cheat > 10) { cheat = 0; addScore(12); } } } }
/** * Find the score for a player * * @param currPlayer * @return the score */ public int getScore(Player currPlayer) { return (mancalaBoard.getBoard())[(mancalaBoard.getMancala(currPlayer.playerNum))]; }
public class PromotionDialog extends JDialog implements ActionListener { // Location of move private Square location; // Instance of each figure - one of them will be inserted private Rook rook = new Rook(Board.getBoard().isWhiteMove()); private Bishop bishop = new Bishop(Board.getBoard().isWhiteMove()); private Knight knight = new Knight(Board.getBoard().isWhiteMove()); private Queen queen = new Queen(Board.getBoard().isWhiteMove()); public PromotionDialog(Square location) { // Creating promotion dialog if (Board.getBoard().isWhiteMove()) { setTitle( "Promotion for " + Board.getBoard().getWhitePlayer().getName() + " - Choose a figure"); } else { setTitle( "Promotion for " + Board.getBoard().getBlackPlayer().getName() + " - Choose a figure"); } this.location = location; JPanel pane = (JPanel) getContentPane(); pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); pane.setLayout(new GridLayout(1, 4, 10, 10)); JButton rookButton = new JButton(); rookButton.setIcon(rook.getFigureIcon()); rookButton.addActionListener(this); rookButton.setFocusPainted(false); pane.add(rookButton); JButton knightButton = new JButton(); knightButton.setIcon(knight.getFigureIcon()); knightButton.addActionListener(this); knightButton.setFocusPainted(false); pane.add(knightButton); JButton bishopButton = new JButton(); bishopButton.setIcon(bishop.getFigureIcon()); bishopButton.addActionListener(this); bishopButton.setFocusPainted(false); pane.add(bishopButton); JButton queenButton = new JButton(); queenButton.setIcon(queen.getFigureIcon()); queenButton.addActionListener(this); queenButton.setFocusPainted(false); pane.add(queenButton); // Has to choose setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); // Set to be always on top setAlwaysOnTop(true); // http://goo.gl/h3vnma // Makes dialog customizable setModal(true); // Disable resize setResizable(false); // Makes the dialog like an application (with swing components, etc.) setModalityType(ModalityType.APPLICATION_MODAL); // Size of dialog setMinimumSize(new Dimension(300, 100)); // Centering by default setLocationRelativeTo(null); pack(); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // If figure icon matches the the button selected's icon - insert figure into board Icon icon = ((JButton) e.getSource()).getIcon(); if (icon.equals(rook.getFigureIcon())) { location.setFigure(rook); } else if (icon.equals(knight.getFigureIcon())) { location.setFigure(knight); } else if (icon.equals(bishop.getFigureIcon())) { location.setFigure(bishop); } else if (icon.equals(queen.getFigureIcon())) { location.setFigure(queen); } // Delete frame when clicked dispose(); } }
/** Playing the game */ public void playGame() { Player currPlayer = player1; int numOfTotalMoveplayer1 = 0; int numOfTotalMoveplayer2 = 0; while (true) { // System.out.println(); /*System.out.println(); System.out.println("##################################"); System.out.println("Current Player is player " + currPlayer.playerNum); System.out.println(); System.out.println(); System.out.println("################################"); System.out.println(" TURN CHANGED"); System.out.println("################################"); */ // Find the nextMove Move nextMove; if (!currPlayer.isHuman) { nextMove = getCompMove(mancalaBoard.getPitSize(), searchType, currPlayer); } else { nextMove = getHumanMove(mancalaBoard.getPitSize(), currPlayer); } // Play the move boolean gotFreeTurn = makeMove(nextMove, currPlayer); if (currPlayer.equals(player1)) { numOfTotalMoveplayer1++; } else { numOfTotalMoveplayer2++; } // Check for game over if (isGameOver(mancalaBoard.getBoard())) { mancalaBoard.setBoard(getAllStones(mancalaBoard.getBoard())); if (isGameDrawn()) { System.out.println("No winner : Game draw"); } else { int winner = findWinner(); System.out.println("Game over. Player " + winner + " won."); System.out.println("Scores are"); System.out.println("Player 1: " + getScore(player1)); System.out.println("Player 2: " + getScore(player2)); } System.out.println("Player1 took : " + numOfTotalMoveplayer1 + "moves"); System.out.println("Player2 took : " + numOfTotalMoveplayer2 + "moves"); break; } // Toggle the turn if no free turn if (!gotFreeTurn) { if (currPlayer.equals(player1)) { currPlayer = player2; } else { currPlayer = player1; } } } }