/////////////////////
// Sidney Chang    //
// 6.837 Project 1 //
// TA: Jacob F11   //
// 9/28/98         //
/////////////////////

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Project1 extends Applet implements Runnable {

  public static final int SPACE_BAR = 32;
  public static final int LEFT = 1006;
  public static final int RIGHT = 1007;
  public static final int COLLECT = 12000;

  //  Image output;

  Playfield playfield;        
  Viking v;
  Snake s;

  Thread animator;
  int delay;

  public void init() {
    String frameRate = getParameter("fps");
    int fps = (frameRate != null) ? Integer.parseInt(frameRate) : 10;
    delay = (fps > 0) ? (1000 / fps) : 100;

    String fieldFile = getParameter("field");
    playfield = new Playfield(getImage(getDocumentBase(), fieldFile),2);
    String vikingFile = getParameter("viking_image");
    v = new Viking(getImage(getDocumentBase(), vikingFile),200,100);
    playfield.addSprite(v);
    String snakeFile = getParameter("snake_image");
    s = new Snake(getImage(getDocumentBase(), snakeFile),50,200);
    playfield.addSprite(s);
  }

  public void start() {
    animator = new Thread(this);
    animator.start();
  }

  public void run() {
    long currentTime;
    long lastCollect = System.currentTimeMillis();

    while (Thread.currentThread() == animator) {
      
      currentTime = System.currentTimeMillis();

      if (currentTime > (lastCollect + COLLECT)) {
	System.gc();
	lastCollect = currentTime;
      }

      repaint();             // frames are advanced in AnimatedSprite.Draw()
      currentTime += delay; 

      // Delay for a while
      try {
	Thread.sleep(Math.max(0, currentTime - System.currentTimeMillis()));
      } catch (InterruptedException e) {
	break;
      }
    }
  }

  public void paint(Graphics g) {
    if (v.collidesWith(s) || s.collidesWith(v)) {
      v.setState(6); // collision state
      s.setState(6);
    }
    playfield.Draw();
    Image output = playfield.toImage();
    g.drawImage(output, 0, 0, null);
  }
  
  public void update(Graphics g) {
    paint(g);
  }
  
  public boolean mouseUp(Event e, int x, int y) {  // 1.0 event model

    if (v.isSprite(x,y) || s.isSprite(x,y))
      showStatus("Hit Sprite!");
    else
      showStatus("Missed Sprite!");

    return true;
  }

  public boolean keyUp(Event e, int key) { // 1.0 event model

    switch (key) {

    case (SPACE_BAR): {
      if (v.state == 0)
	v.setState(3); 	       // jump right if walking right
      else if (v.state == 1)   // jump left if walking left
	v.setState(2);
      else                     // jump right all other times 
	v.setState(3); 
      break;
    }
    case (LEFT): {
      if (v.state == 1)
	v.setState(5);
      else
	v.setState(1);
      break;
    }
    case (RIGHT):
      if (v.state == 0)
	v.setState(5);
      else
	v.setState(0);
      break;
    }

    return true;
  }

}



