Advertisement
Guest User

Othello Code

a guest
Nov 21st, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.87 KB | None | 0 0
  1. /* OthelloApplet.java
  2. * The "Othello" game applet interface
  3. * @author rkasper (initial version)
  4. */
  5. package othello;
  6.  
  7. import java.awt.*;
  8. import java.awt.event.*;
  9. import javax.swing.*;
  10.  
  11. public class OthelloApplet extends JApplet implements ActionListener {
  12.  
  13. public static int // constants to define size of board
  14. ROWS = 8,
  15. COLUMNS = 8,
  16. SQUARE_SIZE = 40; // number of pixels for each square
  17. public static final char EMPTY = '.', // Represents an empty square.
  18. WHITE = 'W', // a white piece.
  19. BLACK = 'B', // a black piece.
  20. ILLEGAL = 'X'; // temporary mark for illegal move
  21. // the current player and opponent are either BLACK or WHITE
  22. // these variables are reset on each turn to allow the same methods
  23. // to be used for both players.
  24. private char player;
  25. private char opponent;
  26.  
  27. // GUI components
  28. private Board gameBoard; // stores the configuration of the game
  29. private JLabel topLabel; // title shown at top of window
  30. private JLabel playerLabel; // displays which player may move
  31. private JLabel gameStatus; // available to display information about the game
  32. private JButton resetButton; // allow player to end the current game, and start a new game
  33. private Font boardFont;
  34.  
  35. public void init() {
  36. /* customize applet size and appearance */
  37. // total applet window size
  38. setSize((COLUMNS + 1) * SQUARE_SIZE + 150, ROWS * SQUARE_SIZE + 160);
  39. Container content = getContentPane(); // Content pane of applet.
  40. content.setLayout(null); // place components at fixed positions
  41. content.setBackground(new Color(0, 0, 150)); // dark blue background.
  42.  
  43. /* Create the components and add them to the applet. */
  44. boardFont = new Font("Arial", Font.BOLD, 14);
  45. topLabel = new JLabel("Othello version 0.5 by Prof. Kasper", JLabel.CENTER);
  46. topLabel.setForeground(Color.WHITE);
  47. playerLabel = new JLabel("Black's Turn", JLabel.CENTER);
  48. playerLabel.setForeground(Color.YELLOW);
  49. playerLabel.setFont(boardFont);
  50. gameStatus = new JLabel("Begin game.", JLabel.CENTER);
  51. gameStatus.setForeground(Color.RED);
  52. gameStatus.setFont(boardFont);
  53. resetButton = new JButton("New Game");
  54. resetButton.addActionListener(this);
  55.  
  56. // set up the game board
  57. gameBoard = new Board();
  58. content.add(playerLabel);
  59. content.add(gameBoard);
  60. content.add(gameStatus);
  61. content.add(topLabel);
  62. content.add(resetButton);
  63.  
  64. // Set the position and size of interface components by calling
  65. // its setBounds() method.
  66. topLabel.setBounds(0, 10, 450, 30);
  67. playerLabel.setBounds(20 + COLUMNS * SQUARE_SIZE, 100, 140, 30);
  68. resetButton.setBounds(20 + COLUMNS * SQUARE_SIZE, 140, 140, 40);
  69. gameBoard.setBounds(10, 80, COLUMNS * SQUARE_SIZE, ROWS * SQUARE_SIZE);
  70. gameStatus.setBounds(10, 90 + ROWS * SQUARE_SIZE, COLUMNS * SQUARE_SIZE, 30);
  71.  
  72. // Start the game
  73. newGame();
  74. }
  75.  
  76. /* newGame method: reinitialize variables and interface components */
  77. public void newGame() {
  78. gameBoard.clearBoard();
  79. player = BLACK;
  80. opponent = WHITE;
  81. playerLabel.setText((player == BLACK ? "Black" : "White") + "'s Turn");
  82. gameStatus.setText("Game Status");
  83. }
  84.  
  85. /* changePlayer method: called after a valid move by either player. */
  86. public void changePlayer() {
  87. char swap;
  88. swap = player;
  89. player = opponent;
  90. opponent = swap;
  91. if (player == BLACK)
  92. playerLabel.setText("Black's Turn");
  93. else playerLabel.setText("White's Turn");
  94. if(gameBoard.anyLegalMove()==false){
  95. JOptionPane.showMessageDialog (this, "No legal moves");
  96. swap = player;
  97. player = opponent;
  98. opponent = swap;
  99. if (player == BLACK)
  100. playerLabel.setText("Black's Turn");
  101. else playerLabel.setText("White's Turn");
  102. }
  103. // TO DO:
  104. // check if game is over, and start new game
  105. // Otherwise, allow the next turn by swapping values of player and opponent variables
  106. // if there is no legal move for the new player, that player must pass a turn.
  107. // Update the interface to show which player's turn it is.
  108.  
  109. }
  110.  
  111. /* isGameOver method: returns whether game is over */
  112. public boolean isGameOver() {
  113. // PROJECT 3 TO DO: count the pieces of each color on the board to determine if the game is over
  114. // Two conditions stop the game:
  115. // A player loses if there are no pieces of his color.
  116. // When the board is full, the player with the most pieces wins.
  117. // When the game is over, display a popup dialog indicating who won and why,
  118. // and return after the popup dialog is dismissed.
  119. return false;
  120. }
  121.  
  122. /* actionPerformed method is called whenever the user clicks a button. */
  123. public void actionPerformed(ActionEvent e) {
  124. // Use a separate branch to perform the action for each button
  125. if (e.getActionCommand().equals("New Game")) {
  126. int response = JOptionPane.showConfirmDialog(this, "Do you want to end this game?");
  127. if (response == JOptionPane.YES_OPTION) {
  128. newGame();
  129. gameBoard.repaint();
  130. }
  131. }
  132. }
  133.  
  134. // inner class to represent game board
  135. public class Board extends JPanel implements MouseListener {
  136.  
  137. // variables to represent status of the game
  138. char[][] board; // each board location is one of
  139. // EMPTY, BLACK, WHITE, ILLEGAL
  140. private int rows; // dimensions of board
  141. private int columns; // initialized by constructor method
  142. private int blackPieces = 2; // number of black pieces on board
  143. private int whitePieces = 2; // number of white pieces on board
  144.  
  145. // variables to control visible interface
  146. private int squareSize; // size of each square in pixels
  147. private int panelLength, panelWidth;
  148. private Font boardFont;
  149.  
  150. public Board() {
  151. // Constructor: create a board using default rows and columns
  152. rows = ROWS;
  153. columns = COLUMNS;
  154. squareSize = SQUARE_SIZE;
  155. panelLength = rows * squareSize;
  156. panelWidth = columns * squareSize;
  157. // dimensions of the board array are 2 greater than the actual board
  158. // to simplify checking possible actions for squares on the border
  159. board = new char[rows + 2][columns + 2];
  160. clearBoard();
  161. setBackground(Color.lightGray);
  162. addMouseListener(this); // listen for mouse clicks within the board panel
  163. } // end constructor
  164.  
  165. /* Methods to update and access the board */
  166.  
  167. /* clearBoard method */
  168. public void clearBoard() {
  169. // TO DO: initialize all cells of the board array to EMPTY,
  170. // and then place the 4 initial pieces to start of game.
  171. for (int i = 0; i < board.length; i++) {
  172. for (int j = 0; j < board.length; j++) {
  173. board[i][j] = EMPTY;
  174. }
  175. }
  176. board[4][4] = WHITE;
  177. board[4][5] = BLACK;
  178. board[5][4] = BLACK;
  179. board[5][5] = WHITE;
  180. board[6][5] = WHITE;
  181. }
  182.  
  183. /* isLegalMove method: return true if the current player can move at
  184. * the square given by (row, col)
  185. */
  186. public boolean isLegalMove(int row, int col) {
  187. // TO DO: the target square must be empty.
  188. if (board[row][col] == EMPTY) {
  189.  
  190. // check each neighboring square, including diagonals
  191. for (int dy = -1; dy <= 1; dy++) { // dy is change in y direction
  192. for (int dx = -1; dx <= 1; dx++) { // dx is change in x direction
  193. if (dy != 0 || dx != 0) { // do not consider current square
  194. // TO DO: check if board[row+dy][col+dx] has opponent's color
  195. // and then check for a line of opponent's pieces
  196. // followed by one of the player's pieces
  197. if (board[row + dy][col + dx] == opponent) {
  198.  
  199. int x = col + dx, y = row + dy;
  200. while (board[y][x] == opponent) {
  201. y = y + dy;
  202. x = x + dx;
  203. }
  204. if (board[y][x] == player) {
  205. return true;
  206. }
  207. }
  208.  
  209. }
  210. }
  211.  
  212. }
  213. }
  214. return false;
  215. }
  216.  
  217.  
  218. /* doMove method: place the current player's color at (row, col),
  219. * and flip the opponent's pieces in one or more directions that
  220. * should be reversed.
  221. * pre-condition: the current player has a legal move at (row, col)
  222. */
  223. public void doMove(int row, int col) {
  224. // TO DO: use nested loops to check all 8 neighboring sqaures
  225. // as in isLegalMove method
  226. if (isLegalMove(row, col) == true) {
  227. board[row][col] = player;
  228. for (int dy = -1; dy <= 1; dy++) {
  229. for (int dx = -1; dx <= 1; dx++) {
  230. if (dy != 0 || dx != 0) {
  231.  
  232. if (board[row + dy][col + dx] == opponent) {
  233.  
  234. int x = col + dx, y = row + dy;
  235. while (board[y][x] == opponent) {
  236.  
  237. System.out.println(x + " " + y + " " + board[y][x]);
  238. y = y + dy;
  239. x = x + dx;
  240. }
  241. if (board[y][x] == player) {
  242. while (y != row || x != col) {
  243. y = y - dy;
  244. x = x - dx;
  245. board[y][x] = player;
  246. System.out.println(x + " " + y);
  247. }
  248. }
  249.  
  250. }
  251. }
  252. }
  253. }
  254. }
  255. changePlayer();
  256. }
  257.  
  258. /* anyLegalMove method: returns true if there is any legal move
  259. * for the current player
  260. */
  261. public boolean anyLegalMove() {
  262. for (int i = 1; i < rows; i++) {
  263. for (int j = 1 ; j < columns; j++) {
  264. if (isLegalMove(i,j)==true)
  265. return true;
  266. }
  267. }
  268. // TO DO: check each square on board
  269. // until finding a square with a legal move
  270. return false;
  271. }
  272.  
  273. /* countPieces method: counts pieces of each color on board,
  274. * updating the instance variables blackPieces and whitePieces.
  275. * This will be called by isGameOver to determine if one of the players
  276. * has won the game.
  277. */
  278. public void countPieces() {
  279. // PROJECT 3 TO DO: check each square on board
  280. // updating counters whenever a BLACK or WHITE piece is found
  281. }
  282.  
  283. /* doComputerTurn: optional method to make a move automatically
  284. * for the current player (implements a simple AI for one player)
  285. */
  286. public void doComputerTurn() {
  287. // PROJECT 3 TO DO:
  288. }
  289.  
  290. public void paintComponent(Graphics g) {
  291. super.paintComponent(g); // handles fill with background color
  292.  
  293. /* Draw the board */
  294. g.setFont(boardFont);
  295. for (int row = 1; row <= rows; row++) {
  296. for (int col = 1; col <= columns; col++) {
  297. // First, draw a square around the cell
  298. g.setColor(Color.BLACK);
  299. g.drawRect((col - 1) * squareSize, (row - 1) * squareSize,
  300. squareSize, squareSize);
  301.  
  302. // Draw colored pieces on a non-empty square
  303. if (board[row][col] != EMPTY) {
  304. drawPiece(g, board[row][col], row, col);
  305. }
  306. }
  307. }
  308. } // end paintComponent()
  309.  
  310. /**
  311. * Draw a piece in the square at (row,col). The color is specified by
  312. * the piece parameter, which should be either BLACK or WHITE.
  313. */
  314. private void drawPiece(Graphics g, char piece, int row, int col) {
  315. if (piece == WHITE) {
  316. g.setColor(Color.WHITE);
  317. } else if (piece == BLACK) {
  318. g.setColor(Color.BLACK);
  319. } else if (piece == ILLEGAL) {
  320. g.setColor(Color.RED);
  321. } else {
  322. return; // unknown piece color
  323. }
  324. g.fillOval(2 + squareSize * (col - 1), 2 + squareSize * (row - 1),
  325. squareSize - 4, squareSize - 4);
  326. }
  327.  
  328. /* doClickSquare method: performs an action when the mouse is clicked
  329. * within the square located by (row, col) in the board array.
  330. */
  331. public void doClickSquare(int row, int col) {
  332. // DIAGNOSTIC CONSOLE OUTPUT: show click locations
  333. System.out.println("doClick at row=" + row + ", col=" + col);
  334. // TO DO: check if move is legal.
  335. if (isLegalMove(row, col) == false) {
  336. JOptionPane.showMessageDialog(this, "Illegal move");
  337. } else {
  338. doMove(row, col);
  339. }
  340. // Either make the move and change players,
  341. // or display an error dialog message if the move is not legal.
  342.  
  343. repaint(); // refreshes board display after changing the board
  344. }
  345.  
  346. /* methods to implement MouseListener interface */
  347. public void mouseClicked(MouseEvent evt) {
  348. // Respond to a user click on the board.
  349. // Find the row and column that the user clicked
  350. int col = evt.getX() / squareSize;
  351. int row = evt.getY() / squareSize;
  352. System.out.println("mouseClicked at (" + evt.getX() + "," + evt.getY() + ")");
  353. if (col < 0 || col >= columns || row < 0 || row >= rows) {
  354. JOptionPane.showMessageDialog(this, "Error: click out of bounds"
  355. + "row=" + row + ", column=" + col);
  356. } else // add one to coordinates, because row 0 and column 0 are not used.
  357. {
  358. doClickSquare(row + 1, col + 1);
  359. }
  360. }
  361.  
  362. // other methods required by MouseListener interface
  363. public void mousePressed(MouseEvent evt) {
  364. }
  365.  
  366. public void mouseReleased(MouseEvent evt) {
  367. }
  368.  
  369. public void mouseEntered(MouseEvent evt) {
  370. }
  371.  
  372. public void mouseExited(MouseEvent evt) {
  373. }
  374.  
  375. // methods used by layout manager
  376. public Dimension getPreferredSize() {
  377. // Specify desired size for this component.
  378. return new Dimension(panelWidth, panelLength);
  379. }
  380.  
  381. public Dimension getMinimumSize() {
  382. return new Dimension(panelWidth, panelLength);
  383. }
  384.  
  385. public Dimension getMaximumSize() {
  386. return new Dimension(panelWidth, panelLength);
  387. }
  388.  
  389. } // end Board inner class
  390.  
  391. } // end OthelloApplet class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement