Recitation Topic: Life


Date: 11/11/2005

    Today you will write a multi-threaded applet. One thread will listen to the mouse, and an additonal thread, every quarter second, will decide what to draw to the screen, and then draw it.

    Here's an example of a Life applet.

    There's a 100x100 grid that the Life applet creates. Each cell in the Life applet decides whether it is alive or not at each time step. It does so by looking at whether its neighbors are alive.

    The local rules can be simple or complex. In the applet above a cell will be alive at the next time step if 1) it's currently alive and its number of living neighbors is between 2 and 4 OR 2) it's currently dead and its number of living neighbors is betweem 1 and 3.

    To use a thread, you must make a class Runnable by having it implement the Runnable interface.

    Include a reference to a Thread object as a member variable of your class. During init() instantiate your Thread object with the new operator, and passing to the Thread constructor the this pointer.

    For example:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    	
    public class Life extends JApplet implements MouseListener, MouseMotionListener, Runnable
    {
       private Thread myThread;
       private boolean thread_running;
       
       public void init()
       {
          myThread = new Thread( this );
          addMouseListener( this );
          addMouseMotionListener( this );
          
          thread_running = true;
          myThread.start();
       }
       
       public void destroy()
       {
       	thread_running = false;
       	myThread = null;
       }
       
       public void paint( Graphics g )
       {
       	//paint the grid
       }
       
       public void run()
       {
          while ( thread_running )
          {
             try
             {
                myThread.sleep( 250 );
             }
             catch ( InterruptedException e )
             {}
    
             //DO SOMETHING HERE
          }
       
       }
       
       
       public void mouseClicked( MouseEvent e )
       {}
       
       public void mouseEntered( MouseEvent e )
       {}
       
       public void mouseExited( MouseEvent e )
       {}
       
       public void mousePressed( MouseEvent e )
       {}
       
       public void mouseReleased( MouseEvent e )
       {}
       
       public void mouseDragged( MouseEvent e )
       {}
       
       public void mouseMoved( MouseEvent e )
       {}
       
    }