| It's boring to always use the same Life pattern. This version
allows us to click on any cell in the Life array to change
its color. We do this by adding implements
MouseListener to our MyCanvas class.
MyCanvas also gains an init method
for attaching the listener.
When we implement something, we commit to supplying all its methods. There are several mouse-does-something methods that we have to supply, but the ones we don't care about don't have to do anything. The one we do care about, mousePressed, just does some arithmetic to figure out which cell was clicked, and toggles the value of that cell. |
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*; // needed for ActionListener
public class Life extends Applet
{
static int boardSize = 10;
Cell [][] board;
Cell [][] nextBoard;
Button goButton;
MyCanvas canvas;
SeparateSubTask subtask;
boolean running = false;
/**
* Creates an empty (all cells dead) playing board of the given boardSize.
*/
static Cell[][] emptyBoard (int boardSize)
{
Cell[][] result = new Cell[boardSize][boardSize];
for (int i = 0; i limit) continue;
if (jj <0 || jj> limit) continue;
if (board[ii][jj].getAlive ()) count++;
}
return count;
}
}