import java.awt.*;
import java.applet.Applet;

public class Ex4 extends Applet implements Runnable {
  Thread thread;
  Graphics gfxBuff;
  Image imgBuff;
  int startPos = 0, width = 300, pos, color[] = { 0, 0, 0 }, delay = 100;
  boolean forward = true, firstLap = true;
  
  public void init() {  // Initializes the Applet
    delay = Integer.parseInt(getParameter("Delay"));
    String param = getParameter("Color");
    if(param.equals("red"))
      color[0] = 1;
    else if(param.equals("green"))
      color[1] = 1;
    else if(param.equals("blue"))
      color[2] = 1;
  }

  public void start() { // Called when the Applet starts
    thread = new Thread(this);
    thread.start();
  }    

  public void stop() { // Called when the Applet stops
    thread.stop();
  }

  public void run() {   // The thread's code
    while(true) {
      try { thread.sleep(delay); } catch(InterruptedException e) { return; }
      repaint();
      startPos += forward ? 10 : -10;
      if(startPos >= width - 10 || startPos <= 0) {
	firstLap = false;
      	forward = !forward;
      }
    }
  }
  
  public void makeDblBuffer() { // Creates a buffer
    imgBuff = createImage(size().width, size().height);
    gfxBuff = imgBuff.getGraphics();
  }

  public void update(Graphics g) { // Overriden to not clear the surface
    paint(g);
  }

  public void paint(Graphics g) { 
    if(gfxBuff == null) // If no buffer exist, create one
      makeDblBuffer();
    gfxBuff.setColor(Color.darkGray);
    gfxBuff.fillRect(0, 0, size().width, size().height);
    for(int cnt=25;cnt >= 0;cnt--) {
      gfxBuff.setColor(new Color(10 * (25-cnt) * color[0],
				 10 * (25-cnt) * color[1],
				 10 * (25-cnt) * color[2]));
      pos = startPos + (forward ? -10 * cnt : 10 * cnt);
      if(pos < 0 && !firstLap)
	pos = -pos;
      else if(pos > width && !firstLap)
	pos = 2 * width - pos;

      gfxBuff.fillRect(pos, 20, 10, 10);
    }
    g.drawImage(imgBuff, 0, 0, this);
  }
}