import java.applet.*;
import java.awt.*;
import java.util.*;


/**
 * Project #1
 * 6.837- Fall 98
 * Stephen Smyth
 * 
 * @author Stephen Smyth
 * @version 1.0
 */

public class Project1 extends Applet{
  Playfield playfield;
  Sprite sprite1, sprite2;
  Raster bgnd;                             // background raster
  Image bgndImg, sprite1Img, sprite2Img;;
  Image output;
  int hotSprite, hotSpritex, hotSpritey;   // vars for sprite selection & movement

  public void init() {
    hotSprite = -1;      // initialize to no Sprite selected
    
    // read in images
    bgndImg = this.getImage(this.getDocumentBase(),this.getParameter("background"));
    sprite1Img = this.getImage(this.getDocumentBase(),this.getParameter("sprite1"));
    sprite2Img = this.getImage(this.getDocumentBase(),this.getParameter("sprite2"));
    
    //images stored in objects
    bgnd = new Raster(bgndImg);
    sprite1 = new Sprite(sprite1Img);
    sprite2 = new Sprite(sprite2Img);
    playfield = new Playfield(bgnd.toImage(),2);
    
    // initial position of sprite #2
    sprite2.x = 200;
    sprite2.y = 100;
    
    // sprites added to playfield
    playfield.addSprite(0,sprite1);
    playfield.addSprite(1,sprite2);

    renderPlayfield();
  }
  
  // computes new image of playfield after movement of sprite     
  public void updatePlayfield(int spriteIndex, int xOrig, int yOrig) {
    playfield.reDraw(spriteIndex, xOrig, yOrig);
    output = playfield.toImage();
    repaint();
  }
  
  // computes initial image of playfield
  public void renderPlayfield() {
    playfield.Draw();
    output = playfield.toImage();
    repaint();
  }
             
  public void paint(Graphics g) {
    g.drawImage(output, 0, 0,  this);
  }

  public void update(Graphics g) {
    paint(g);
  }

  // event-handling methods

  public boolean mouseDown(Event e, int x, int y) {
    hotSprite = playfield.isSprite(x, y);
    if (hotSprite >= 0) {
      showStatus("sprite");
      hotSpritex = x - playfield.sprite[hotSprite].x;
      hotSpritey = y - playfield.sprite[hotSprite].y;
    }
    else if (hotSprite == -2)
      showStatus("thin air");
    else showStatus("no sprite");
    return true;
  }

  public boolean mouseUp(Event e, int x, int y) {
    hotSprite = -1;
    return true;
  }

  public boolean mouseDrag(Event e, int x, int y) {
    if ((x >= 0) && (x < playfield.getWidth()) &&
        (y >= 0) && (y < playfield.getHeight())) {
      if (hotSprite >= 0) {
        int xOrig = playfield.sprite[hotSprite].x;
        int yOrig = playfield.sprite[hotSprite].y;
        playfield.sprite[hotSprite].x = x - hotSpritex;
        playfield.sprite[hotSprite].y = y - hotSpritey;
        updatePlayfield(hotSprite, xOrig, yOrig);
      }
    }
    return true;
  }
}
















