import java.applet.Applet; import java.awt.Rectangle; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; /** This program will show many squares in an applet. Each time you click on * one, it will turn blue or red, to illustrate taking turns. */ public class MouseApplet4 extends Applet { private int [][] board; private int howMany; private Rectangle [][] box; private int row; private int col; private static final int EMPTY = 0; private static final int BLUE = 1; private static final int RED = 2; public void init() { board = new int [8][8]; howMany = 0; // When drawing the boundaries of the squares, j refers to the inner // loop which is the column number, which corresponds to x. And so // i corresponds to y. (At first this may seem backwards!) box = new Rectangle[8][8]; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) box[i][j] = new Rectangle(35*j,35*i,35,35); DetectInput listener = new DetectInput(); addMouseListener(listener); } class DetectInput implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); // set row and col based on x and y, and set 7 as their max so we don't // go off the board row = y / 35; col = x / 35; if (row > 7) row = 7; if (col > 7) col = 7; // Keep track of which box has been clicked. // If we take out the check for blank, then we'll be able to steal // the opponent's place. // We need checks for howMany > 1 to make sure the top left corner // isn't already colored in when we start. ++howMany; if (howMany % 2 == 1 && board[row][col] == EMPTY) board[row][col] = BLUE; else if (howMany % 2 == 0 && board[row][col] == EMPTY && howMany > 1) board[row][col] = RED; else if (howMany > 1) { // We chose a space that's already taken, disregard the fact the we // just moved by decrementing howMany. --howMany; } repaint(); } public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; int i, j; // make all boxes (blue or red) that have been clicked for (i = 0; i < 8; ++i) for (j = 0; j < 8; ++j) { if (board[i][j] == BLUE) { g2.setColor(Color.blue); g2.fill(box[i][j]); } else if (board[i][j] == RED && howMany > 1) { g2.setColor(Color.red); g2.fill(box[i][j]); } } // now, draw the board for (i = 0; i < 8; ++i) for (j = 0; j < 8; ++j) g2.draw(box[i][j]); } }