package com.caplet.manna; import java.awt.*; /** * Does the evolution, and displays the results, in a separate thread than * the rest of the applet. One thread evolves both dishes, so their * generations will be exactly in synch.

* * When evolution is paused, the GAPainter thread still exists, but is * paused, waiting to be told to go. It starts paused. * * @author Mark S. Miller, markm@caplet.com * @author Terry Stanley, tstanley@cocoon.com */ public class GAPainter implements Runnable { private boolean amRunning = false; private GA[] myGAs; private Graphics[] theirGfxs; /** * Give it the array of GAs it should evolve. */ public GAPainter(GA[] gas) { myGAs = gas; Thread painter = new Thread(this); painter.setPriority(Thread.MIN_PRIORITY); painter.start(); } /** * This is the "main"-like method for a Thread. */ public void run() { while(true) { Thread.yield(); synchronized(this) { // must get the lock each time through the loop while(!amRunning) { try { this.wait(); } catch(InterruptedException e) { System.err.println("interrupted with " + e); } } step(20); } } } private synchronized void step(int matings) { for (int i = 0; i < matings; i++) { for (int j = 0; j < myGAs.length; j++) { myGAs[j].step(myGAs[j].getGraphics()); } } } /** * Let the evolution resume (or commence) */ public synchronized void go() { amRunning = true; this.notify(); } /** * Stop the world, I want to play god. */ public void pause() { amRunning = false; } /** * Add the same amount of manna at the same place in all GAs. */ public synchronized void addManna(int cx, int cy, int amount) { for (int i = 0; i < myGAs.length; i++) { myGAs[i].addManna(cx, cy, amount); } } }