import java.awt.*;
import java.awt.event.*;
import java.applet.*;
 
public class sierpinski extends Applet implements Runnable
{ 
  int pontosX[] = {200, 50, 350};
  int pontosY[] = {50, 310, 310};
  int npontos = 3, estado;
  int x0, x1, x2, y0, y1, y2;
  Thread proc;
  boolean start = false, loop = false;
  
  public void init()
  { 
    Panel botoes = new Panel();
    Button botao_start = new Button("Start");
    Button botao_stop = new Button("Stop");
    Button botao_loop = new Button("Loop");
    sierpinski.ButtonHandler bh = new sierpinski.ButtonHandler();
    botao_start.addActionListener(bh);
    botao_stop.addActionListener(bh);
    botao_loop.addActionListener(bh);
    botoes.add(botao_start);
    botoes.add(botao_stop);
    botoes.add(botao_loop);
    add("South", botoes);
    setSize(400,400);
  }
 
  public void start()
  {
    proc = new Thread(this);
    if((start == true) || (loop == true))
      proc.start();
  }

  public void stop()
  {
    proc.stop();
  }

  public void run()  
  {
    estado = 0;
    pontosX[0] = 200;
    pontosX[1] = 50;
    pontosX[2] = 350;
    pontosY[0] = 50;
    pontosY[1] = 310;
    pontosY[2] = 310;
    repaint();
    while(estado < 5)
    {  
      try
      {
        Thread.sleep(750);
      }
      catch(InterruptedException e) {}
      x0 = pontosX[0];
      x1 = pontosX[1];
      x2 = pontosX[2];
      y0 = pontosY[0];
      y1 = pontosY[1];
      y2 = pontosY[2];
      pontosX[0] = ((x0 - x1) / 2) + x1;
      pontosX[1] = ((x2 - x0) / 2) + x0;
      pontosX[2] = ((x2 - x1) / 2) + x1;
      pontosY[0] = ((y1 - y0) / 2) + y0;
      pontosY[1] = ((y2 - y0) / 2) + y0;
      pontosY[2] = y1;
      repaint();
      estado++;
      if((loop == true) && (estado > 4))
      {
        estado = 0; 
        pontosX[0] = 200;
        pontosX[1] = 50;
        pontosX[2] = 350;
        pontosY[0] = 50;
        pontosY[1] = 310;
        pontosY[2] = 310;
      }
    }
  } 

  public void update(Graphics g)
  {
    paint(g);
  }

  public void paint(Graphics g)
  {
    if(estado == 0)
      g.setColor(Color.red);
    else if(estado == 1)
      g.setColor(Color.blue);
    else if(estado == 2)
      g.setColor(Color.cyan);
    else if(estado == 3)
      g.setColor(Color.green);
    else if(estado == 4)
      g.setColor(Color.yellow);
    System.out.println(estado);
    if(estado < 5)
      g.fillPolygon(pontosX, pontosY, npontos);
  }  


  class ButtonHandler implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
      String s = e.getActionCommand();
      if(s == "Start")
      {
        start = true;
        start();
      }
      else if(s == "Stop")
      {
        stop();
        loop = false;
      }
      else if(s == "Loop")
      {
        loop = true;
        start(); 
      }
    }
  }   
}
