import java.awt.*;
/**
 * This class runs in a separate (animation) thread and controls all the
 * painting.
 */
class View extends Canvas implements Runnable {
   Controller controller;
   Model model;
   Dimension size = getSize();
   int oldX, oldY;
   int delay = 1000;
   int stepNumber = 0;
   boolean alive, okToRun;
   
   /**
    * Sets up an (almost) infinite loop to do the animation, and every
    * delay milliseconds asks the model to update itself, then draws the
    * result.
    */
   public void run() {
     // "alive" will be true until the Applet is destroyed
     while(alive) {
       // "okToRun" will be true if the Applet is started and not stopped
       if(okToRun) {
         model.makeOneStep();
         repaint(); // Note: uses Graphics for this Canvas, not for the Applet
       }
       // Control the speed of execution
       try { Thread.sleep(delay); }
       catch(InterruptedException e) {}
     }
   }
  
  /**
   * The default update(Graphics g) method erases the canvas before calling
   * paint, and this results in flicker. We override update to avoid this
   * flicker; but that means that our paint(Graphics g) method must itself
   * erase the bit of canvas that the ball was just in, or it will leave
   * a trail.
   */
  public void update(Graphics g) {
    paint(g);
  }
  
  /**
   * Repaints the canvas based on information that it gets from the model.
   */
  public void paint(Graphics g) {
    // Erase previous ball (since update() no longer does this)
    g.setColor(Color.white);
    g.fillRect(oldX, oldY, model.BALL_SIZE, model.BALL_SIZE);
    // Draw new ball and remember its position
    g.setColor(Color.red);
    g.fillOval(model.xPosition, model.yPosition, model.BALL_SIZE, model.BALL_SIZE);
    oldX = model.xPosition;
    oldY = model.yPosition;
    // Display steps and position in the status line;
    // this is a good place to put debugging information.
    if(++stepNumber % 10 == 0)
      controller.showStatus("Step " + stepNumber + ", x = " + model.xPosition +
                            ", y = " + model.yPosition);
  }
}

