// Michael Tartaglia
// GenDriver: Evolutionary algorithm that displays what happens to a small,
//     closed community.



import java.awt.Graphics;
import java.awt.Font;
import java.applet.Applet;
import java.awt.*;

public class GenDriver extends Applet {
	private int w = 750, h = 390,	// WIDTH AND HEIGHT OF DISPLAY
		mu, ge, pe, counter = 0;	// MUTATION, GENES, PEOPLE #S
	private boolean um, uf;			// USE MUTATION AND USE FITNESS BOOLEANS
	private Image canvas;			// BUFFER
	private Graphics painting;
	private Population group;		// GROUP OF INDIVIDUALS
	private String[] s = new String[20];


	public GenDriver() {}

	public void init() {
	 uf = toBool(getParameter("usef"));	// use fitness
	 um = toBool(getParameter("usem"));	// use mutation
	 mu = toInt(getParameter("mutx"));	// mutation factor
	 ge = toInt(getParameter("gen"));	// # of genes
	 pe = toInt(getParameter("pop"));	// # of people
	 group = new Population(pe,ge,um,uf,mu);
	 canvas = this.createImage(w,h);
	 painting = canvas.getGraphics();
	}
	public void update(Graphics g) {paint(g);}


	// CONVERTING STRING TO BOOLEAN (FOR APPLET PARAM'S SAKE)
	private boolean toBool(String str) {
		if (str.toUpperCase().equals("TRUE")) return true;
		else return false;
	}

	// CONVERTING STRING TO INTEGER (FOR APPLET PARAM'S SAKE)
	private int toInt(String str) {
		return Integer.parseInt(str);
	}

	// CONVERTING TO STRING FROM BOOLEAN
	private String fromBool(boolean b) {
		if (b) return "yes";
		else return "no";
	}


	public void genImage() {
	 counter++;		// INCREASE GENERATION 3
	 painting.setColor(Color.white);	// SET COLORS
	 painting.fillRect(0,0,w,h);		// CLEAR CANVAS
	 painting.setColor(Color.black);

	 // WRITE VARIOUS HEADERS
	 painting.setFont(new Font("Arial", Font.BOLD+Font.ITALIC, 22));
	 painting.drawString("Evolving Population",1,20);

	 painting.setFont(new Font("Arial", Font.BOLD, 10));
	 painting.drawString("by Michael Tartaglia",3,35);

	 painting.setFont(new Font("Arial", Font.PLAIN, 12));
	  if (um) painting.drawString("Mutation factor: "
		+(mu)+"%",275,32);
	  else painting.drawString("Using Mutation: "
		+fromBool(um),275,33);
	 painting.drawString("Using Fitness: "+fromBool(uf),275,17);
	 painting.drawString("Population: "+pe,410,17);
	 painting.drawString("Gene Size: "+ge,410,32);
	 painting.drawString("Years passed: "+(double)(counter*250.45)/10,545,17);
	 painting.drawString("Generation #: "+counter,545,32);

	 // DRAW THE CURRENT GENERATION
	 painting.setFont(new Font("Courier", Font.BOLD, 11));
	 s = group.getGeneration();
	 for (int i = 0; i < s.length; i++)
		painting.drawString(s[i], 1, 50+(i*14));
	 group.setGeneration();
	}


	public void paint(Graphics g) {
	 genImage();		// GENERATE IMAGE
	 g.drawImage(canvas,0,0,this);	// DRAW IMAGE
	 try {Thread.sleep(500);}			// WAIT ...
	 catch (InterruptedException x) {}
	 repaint();			// & LOOP PROCESS
	}
}
