import java.applet.*;
import java.awt.*;
//this graphs on the complex number plane - the imaginary part is y, the real part is x

//each pixel corresponds to a complex number c.

//for each c, compute the sequence of complex numbers w(0), w(1), .... w(10), 
// defined recursively by w(0)=0 and w(n+1)= f(w(n)) = w(n)^2 +c
// but stop if |w(n)| > 2

//when finished looping, colour the pixel in this way:
//If w(10) <= 2, colour c white.
//else if n is even, colour c another colour
//else if n is odd, pick another colour

public class Mandelbrot extends Applet
{
    public void paint (Graphics g)
    {
	//x goes from -2 to 1 in this function
	//y goes from -1 to 1 in this function
	double x = -2;
	double y = -1;

	while (x < 1)
	{
	    while (y < 1)
	    {
		//set up the point x, y to do the calculation
		double creal = x;
		double cimagine = y;
		double wreal = 0;
		double wimagine = 0;
		int i = 0;

		//the part before <=2 is the absolute value of pt w
		while ((Math.sqrt ((wreal * wreal) + (wimagine * wimagine))) <= 2 && i < 10)
		{ //What follows is the repeated function for the Mandlebrot set.
		    //We are calculating it from one point x,y
		    //it takes a loop to arrive at the value for a point
		    double r = wreal;
		    double m = wimagine;
		    wreal = r * r - m * m + creal;
		    wimagine = 2 * r * m + cimagine;
		    i++;
		}

		//now that we've arrived at the value for x, y
		//based on what we've got, make an if to colour the screen one of three colours
		if ((Math.sqrt ((wreal * wreal) + (wimagine * wimagine))) <= 2) //again the absolute value of point w
		    g.setColor (Color.yellow);
		else if ((i + 1) % 2 == 0)
		    g.setColor (Color.orange);
		else
		    g.setColor (Color.red);

		//there is some adjustment 300* +600 to expand it out to appear on the screen.
		//the range of the function is -2 to +1, and -1 to +1, but for small increments (0.005).
		//to see them we need to "blow it up"
		g.drawOval ((int) (300 * creal + 600), (int) (300 * cimagine + 300), 1, 1);

		//move over a tiny bit to the next part.
		y += 0.005;

	    }
	    //reset y and move x down.
	    //draws the next line over.
	    y = -1;
	    x += 0.003;
	}
    }
}
