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 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) {}
     }
   }
  
  /**
   * Paints a background, then paints other things on top of it.
   */
  public void update(Graphics g) {
    background(g);
    paint(g);
  }
  
  /**
   * Repaints the canvas based on information that it gets from the model.
   */
  public void paint(Graphics g) {
    // Draw new ball
    g.setColor(Color.red);
    g.fillOval(model.xPosition, model.yPosition, model.BALL_SIZE, model.BALL_SIZE);
    // 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);
  }
  
  /**
   * Paints a background on the given Graphics.
   */
   void background(Graphics g) {
       int width = getSize().width;
       int height = getSize().height;
       int squareSize = 2 * model.BALL_SIZE;
       
       g.setColor(Color.blue);
       g.fillRect(0, 0, width, height);
       g.setColor(Color.green);
       for (int x = 0; x < width; x += 2 * squareSize) {
           for (int y = 0; y < height; y += 2 * squareSize) {
               g.fillRect(x, y, squareSize, squareSize);
               g.fillRect(x + squareSize, y + squareSize, squareSize, squareSize);
           }
       }
   }
}
