| We change the "Step" button into a "Stop/Go" button.
Besides just changing the label on the button, we also
need to create another thread. One thread will run the
Life game; the original thread will continue to listen
for button presses.
This isn't as difficult as it might seem. Our new class SeparateSubTask extends Thread goes into an infinite loop, executing the code to make one step, then sleeping for awhile. The code for the "Stop/Go" button either creates and starts this thread, or stops it, depending on whether the thread is currently running. |
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;
}
}