Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* OthelloApplet.java
- * The "Othello" game applet interface
- * @author rkasper (initial version)
- */
- package othello;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class OthelloApplet extends JApplet implements ActionListener {
- public static int // constants to define size of board
- ROWS = 8,
- COLUMNS = 8,
- SQUARE_SIZE = 40; // number of pixels for each square
- public static final char EMPTY = '.', // Represents an empty square.
- WHITE = 'W', // a white piece.
- BLACK = 'B', // a black piece.
- ILLEGAL = 'X'; // temporary mark for illegal move
- // the current player and opponent are either BLACK or WHITE
- // these variables are reset on each turn to allow the same methods
- // to be used for both players.
- private char player;
- private char opponent;
- // GUI components
- private Board gameBoard; // stores the configuration of the game
- private JLabel topLabel; // title shown at top of window
- private JLabel playerLabel; // displays which player may move
- private JLabel gameStatus; // available to display information about the game
- private JButton resetButton; // allow player to end the current game, and start a new game
- private Font boardFont;
- public void init() {
- /* customize applet size and appearance */
- // total applet window size
- setSize((COLUMNS + 1) * SQUARE_SIZE + 150, ROWS * SQUARE_SIZE + 160);
- Container content = getContentPane(); // Content pane of applet.
- content.setLayout(null); // place components at fixed positions
- content.setBackground(new Color(0, 0, 150)); // dark blue background.
- /* Create the components and add them to the applet. */
- boardFont = new Font("Arial", Font.BOLD, 14);
- topLabel = new JLabel("Othello version 0.5 by Prof. Kasper", JLabel.CENTER);
- topLabel.setForeground(Color.WHITE);
- playerLabel = new JLabel("Black's Turn", JLabel.CENTER);
- playerLabel.setForeground(Color.YELLOW);
- playerLabel.setFont(boardFont);
- gameStatus = new JLabel("Begin game.", JLabel.CENTER);
- gameStatus.setForeground(Color.RED);
- gameStatus.setFont(boardFont);
- resetButton = new JButton("New Game");
- resetButton.addActionListener(this);
- // set up the game board
- gameBoard = new Board();
- content.add(playerLabel);
- content.add(gameBoard);
- content.add(gameStatus);
- content.add(topLabel);
- content.add(resetButton);
- // Set the position and size of interface components by calling
- // its setBounds() method.
- topLabel.setBounds(0, 10, 450, 30);
- playerLabel.setBounds(20 + COLUMNS * SQUARE_SIZE, 100, 140, 30);
- resetButton.setBounds(20 + COLUMNS * SQUARE_SIZE, 140, 140, 40);
- gameBoard.setBounds(10, 80, COLUMNS * SQUARE_SIZE, ROWS * SQUARE_SIZE);
- gameStatus.setBounds(10, 90 + ROWS * SQUARE_SIZE, COLUMNS * SQUARE_SIZE, 30);
- // Start the game
- newGame();
- }
- /* newGame method: reinitialize variables and interface components */
- public void newGame() {
- gameBoard.clearBoard();
- player = BLACK;
- opponent = WHITE;
- playerLabel.setText((player == BLACK ? "Black" : "White") + "'s Turn");
- gameStatus.setText("Game Status");
- }
- /* changePlayer method: called after a valid move by either player. */
- public void changePlayer() {
- char swap;
- swap = player;
- player = opponent;
- opponent = swap;
- if (player == BLACK)
- playerLabel.setText("Black's Turn");
- else playerLabel.setText("White's Turn");
- if(gameBoard.anyLegalMove()==false){
- JOptionPane.showMessageDialog (this, "No legal moves");
- swap = player;
- player = opponent;
- opponent = swap;
- if (player == BLACK)
- playerLabel.setText("Black's Turn");
- else playerLabel.setText("White's Turn");
- }
- // TO DO:
- // check if game is over, and start new game
- // Otherwise, allow the next turn by swapping values of player and opponent variables
- // if there is no legal move for the new player, that player must pass a turn.
- // Update the interface to show which player's turn it is.
- }
- /* isGameOver method: returns whether game is over */
- public boolean isGameOver() {
- // PROJECT 3 TO DO: count the pieces of each color on the board to determine if the game is over
- // Two conditions stop the game:
- // A player loses if there are no pieces of his color.
- // When the board is full, the player with the most pieces wins.
- // When the game is over, display a popup dialog indicating who won and why,
- // and return after the popup dialog is dismissed.
- return false;
- }
- /* actionPerformed method is called whenever the user clicks a button. */
- public void actionPerformed(ActionEvent e) {
- // Use a separate branch to perform the action for each button
- if (e.getActionCommand().equals("New Game")) {
- int response = JOptionPane.showConfirmDialog(this, "Do you want to end this game?");
- if (response == JOptionPane.YES_OPTION) {
- newGame();
- gameBoard.repaint();
- }
- }
- }
- // inner class to represent game board
- public class Board extends JPanel implements MouseListener {
- // variables to represent status of the game
- char[][] board; // each board location is one of
- // EMPTY, BLACK, WHITE, ILLEGAL
- private int rows; // dimensions of board
- private int columns; // initialized by constructor method
- private int blackPieces = 2; // number of black pieces on board
- private int whitePieces = 2; // number of white pieces on board
- // variables to control visible interface
- private int squareSize; // size of each square in pixels
- private int panelLength, panelWidth;
- private Font boardFont;
- public Board() {
- // Constructor: create a board using default rows and columns
- rows = ROWS;
- columns = COLUMNS;
- squareSize = SQUARE_SIZE;
- panelLength = rows * squareSize;
- panelWidth = columns * squareSize;
- // dimensions of the board array are 2 greater than the actual board
- // to simplify checking possible actions for squares on the border
- board = new char[rows + 2][columns + 2];
- clearBoard();
- setBackground(Color.lightGray);
- addMouseListener(this); // listen for mouse clicks within the board panel
- } // end constructor
- /* Methods to update and access the board */
- /* clearBoard method */
- public void clearBoard() {
- // TO DO: initialize all cells of the board array to EMPTY,
- // and then place the 4 initial pieces to start of game.
- for (int i = 0; i < board.length; i++) {
- for (int j = 0; j < board.length; j++) {
- board[i][j] = EMPTY;
- }
- }
- board[4][4] = WHITE;
- board[4][5] = BLACK;
- board[5][4] = BLACK;
- board[5][5] = WHITE;
- board[6][5] = WHITE;
- }
- /* isLegalMove method: return true if the current player can move at
- * the square given by (row, col)
- */
- public boolean isLegalMove(int row, int col) {
- // TO DO: the target square must be empty.
- if (board[row][col] == EMPTY) {
- // check each neighboring square, including diagonals
- for (int dy = -1; dy <= 1; dy++) { // dy is change in y direction
- for (int dx = -1; dx <= 1; dx++) { // dx is change in x direction
- if (dy != 0 || dx != 0) { // do not consider current square
- // TO DO: check if board[row+dy][col+dx] has opponent's color
- // and then check for a line of opponent's pieces
- // followed by one of the player's pieces
- if (board[row + dy][col + dx] == opponent) {
- int x = col + dx, y = row + dy;
- while (board[y][x] == opponent) {
- y = y + dy;
- x = x + dx;
- }
- if (board[y][x] == player) {
- return true;
- }
- }
- }
- }
- }
- }
- return false;
- }
- /* doMove method: place the current player's color at (row, col),
- * and flip the opponent's pieces in one or more directions that
- * should be reversed.
- * pre-condition: the current player has a legal move at (row, col)
- */
- public void doMove(int row, int col) {
- // TO DO: use nested loops to check all 8 neighboring sqaures
- // as in isLegalMove method
- if (isLegalMove(row, col) == true) {
- board[row][col] = player;
- for (int dy = -1; dy <= 1; dy++) {
- for (int dx = -1; dx <= 1; dx++) {
- if (dy != 0 || dx != 0) {
- if (board[row + dy][col + dx] == opponent) {
- int x = col + dx, y = row + dy;
- while (board[y][x] == opponent) {
- System.out.println(x + " " + y + " " + board[y][x]);
- y = y + dy;
- x = x + dx;
- }
- if (board[y][x] == player) {
- while (y != row || x != col) {
- y = y - dy;
- x = x - dx;
- board[y][x] = player;
- System.out.println(x + " " + y);
- }
- }
- }
- }
- }
- }
- }
- changePlayer();
- }
- /* anyLegalMove method: returns true if there is any legal move
- * for the current player
- */
- public boolean anyLegalMove() {
- for (int i = 1; i < rows; i++) {
- for (int j = 1 ; j < columns; j++) {
- if (isLegalMove(i,j)==true)
- return true;
- }
- }
- // TO DO: check each square on board
- // until finding a square with a legal move
- return false;
- }
- /* countPieces method: counts pieces of each color on board,
- * updating the instance variables blackPieces and whitePieces.
- * This will be called by isGameOver to determine if one of the players
- * has won the game.
- */
- public void countPieces() {
- // PROJECT 3 TO DO: check each square on board
- // updating counters whenever a BLACK or WHITE piece is found
- }
- /* doComputerTurn: optional method to make a move automatically
- * for the current player (implements a simple AI for one player)
- */
- public void doComputerTurn() {
- // PROJECT 3 TO DO:
- }
- public void paintComponent(Graphics g) {
- super.paintComponent(g); // handles fill with background color
- /* Draw the board */
- g.setFont(boardFont);
- for (int row = 1; row <= rows; row++) {
- for (int col = 1; col <= columns; col++) {
- // First, draw a square around the cell
- g.setColor(Color.BLACK);
- g.drawRect((col - 1) * squareSize, (row - 1) * squareSize,
- squareSize, squareSize);
- // Draw colored pieces on a non-empty square
- if (board[row][col] != EMPTY) {
- drawPiece(g, board[row][col], row, col);
- }
- }
- }
- } // end paintComponent()
- /**
- * Draw a piece in the square at (row,col). The color is specified by
- * the piece parameter, which should be either BLACK or WHITE.
- */
- private void drawPiece(Graphics g, char piece, int row, int col) {
- if (piece == WHITE) {
- g.setColor(Color.WHITE);
- } else if (piece == BLACK) {
- g.setColor(Color.BLACK);
- } else if (piece == ILLEGAL) {
- g.setColor(Color.RED);
- } else {
- return; // unknown piece color
- }
- g.fillOval(2 + squareSize * (col - 1), 2 + squareSize * (row - 1),
- squareSize - 4, squareSize - 4);
- }
- /* doClickSquare method: performs an action when the mouse is clicked
- * within the square located by (row, col) in the board array.
- */
- public void doClickSquare(int row, int col) {
- // DIAGNOSTIC CONSOLE OUTPUT: show click locations
- System.out.println("doClick at row=" + row + ", col=" + col);
- // TO DO: check if move is legal.
- if (isLegalMove(row, col) == false) {
- JOptionPane.showMessageDialog(this, "Illegal move");
- } else {
- doMove(row, col);
- }
- // Either make the move and change players,
- // or display an error dialog message if the move is not legal.
- repaint(); // refreshes board display after changing the board
- }
- /* methods to implement MouseListener interface */
- public void mouseClicked(MouseEvent evt) {
- // Respond to a user click on the board.
- // Find the row and column that the user clicked
- int col = evt.getX() / squareSize;
- int row = evt.getY() / squareSize;
- System.out.println("mouseClicked at (" + evt.getX() + "," + evt.getY() + ")");
- if (col < 0 || col >= columns || row < 0 || row >= rows) {
- JOptionPane.showMessageDialog(this, "Error: click out of bounds"
- + "row=" + row + ", column=" + col);
- } else // add one to coordinates, because row 0 and column 0 are not used.
- {
- doClickSquare(row + 1, col + 1);
- }
- }
- // other methods required by MouseListener interface
- public void mousePressed(MouseEvent evt) {
- }
- public void mouseReleased(MouseEvent evt) {
- }
- public void mouseEntered(MouseEvent evt) {
- }
- public void mouseExited(MouseEvent evt) {
- }
- // methods used by layout manager
- public Dimension getPreferredSize() {
- // Specify desired size for this component.
- return new Dimension(panelWidth, panelLength);
- }
- public Dimension getMinimumSize() {
- return new Dimension(panelWidth, panelLength);
- }
- public Dimension getMaximumSize() {
- return new Dimension(panelWidth, panelLength);
- }
- } // end Board inner class
- } // end OthelloApplet class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement