import java.awt.*;
import java.awt.image.*;
import java.util.*;

/*
	This is the class that contains all of the Sprites.
*/

class Playfield extends Raster {
    boolean redisplay = true;

/*
	In C++, vectors are truly dynamic, somewhat of a "linked, blocked list",
which allows relatively quick lookups, yet dynamic growth.  In C++, the vector
doesn't try to re-allocate itself.  I'm not sure of the implementation here, but
I assume that vector[0] is always the first and vector[1] is always the second.
This probably will cause some problems in the future.
*/

    Vector spriteList = new Vector();   

    int originalImage[]; // Used to pigeonhole the original image
    ///////////////////////// Constructors //////////////////////

    /**
     *  This constructor, which takes no arguments,
     *  allows for future extension.
     */
    public Playfield()
    {
    }

    /**
     *  This constructor creates an uninitialized
     *  Raster Object of a given size (w x h).
     */
    public Playfield(int w, int h)
    {
	super(w,h);
    }

    /**
     *  This constructor creates an Playfield initialized
     *  with the contents of an image.
     */
    public Playfield(Image img)
    {
	super(img);
        originalImage = new int[pixel.length];
	System.arraycopy(pixel, 0,originalImage,0,pixel.length);
    }

    ////////////////////////// Methods //////////////////////////

    public void addSprite(Sprite newone)
    {
	spriteList.addElement(newone);
    }

    public void removeSprite(Sprite destroy)
    {
	spriteList.removeElement(destroy);
    }

/*
	This is supposedly a performance hack to make sure that the Playfield
doesn't redraw itself when nothing has happened.  This comes from my experience
with GLUT (OpenGL Utilities), where the use is very similar.  Actually, GLUT is
cool, because it will call your paint() equivalent on a vertical refresh.  With 
double buffering, you just glXSwapBuffers() and you're off!
*/
    public void postRedisplay()
    {
		redisplay = true;
    }

/*
	Pass on a query event to all of the sprites.  This is a single return,
purposefully, so that the item you click on (the one that's immediately visible)
is returned.
*/
	public Sprite query(int x, int y)
    {
		for (int z = spriteList.size()-1; z >= 0; --z)
		{
			if (((Sprite)spriteList.elementAt(z)).query(x,y))
				return (Sprite)spriteList.elementAt(z);
		}
		return null;
	}

    public void update()
    {
	if (redisplay = true)
	{
	    System.arraycopy(originalImage, 0,pixel,0,pixel.length);
	
		for (int x = 0; x < spriteList.size(); ++x)
		{
			((Sprite)spriteList.elementAt(x)).Draw(this);
		}
		redisplay = false;
	}
   }
   
}
