/** 
 * A grid of references to objects.  This is handy for block graphics
 * style games where we want to record which spaces on the display are
 * occupied by which objects.
 *
 * @author Jim Grundy
 * @version $Revision: 1.1 $ */

import java.awt.Color;

public class ObjectField
{
    private PlayingField field;      // Visiual display for the objects.
    private FieldObject[][] members; // Record of which objects own spaces.

    /** 
     * Create an object field to display colored objects on a 
     * PlayingField. */
    public ObjectField(PlayingField field) 
    {
	Assert.check(field != null, "The field is null!");
		     
	this.field = field;
	members = new FieldObject[field.getWidth()][field.getHeight()];
	for(int col=0; col<field.getWidth(); col=col+1){
	    for(int row=0; row<field.getHeight(); row=row+1){
		/* INVARIANT: all c < col & r < row, 
		   members[c][r] = null */
		members[col][row]=null;
	    }
	}
    }

    /** The width of the object field. */
    public int getWidth() 
    {
	return field.getWidth();
    }

    /** The height of the object field. */
    public int getHeight() 
    {
	return field.getHeight();
    }

    /**
     * Set a particular tile to be occupied by an object - 
     * or to the null object reference to vacate the tile. */
    public void setObject(int col, int row, FieldObject obj)
    {
	Assert.check((0 <= col) && (col < getWidth()) &&
		     (0 <= row) && (row < getHeight()),
		     "Can't set object ("+col+","+row+"):off the field.");
	members[col][row] = obj;
	if (obj != null) {
	    field.setTile(col,row,obj.getColor());
	} else {
	    field.setTile(col,row,field.getBackground());
	}
    }

    /** Get a reference to the object occuping a given tile. */
    public FieldObject getObject(int col, int row)
    {
	Assert.check((0 <= col) && (col < getWidth()) &&
		     (0 <= row) && (row < getHeight()),
		     "Can't set object ("+col+","+row+"):off the field.");
	return members[col][row];
    }

    /** 
     * Update the graphical depiction of the object field so that each tile 
     * has the colour of the object it currently contains. */
    public void repaint () 
    {
	field.repaint();
    }

    /** Get a textual version of a picture of the object field. */
    public String toString()
    {
	String picture = new String();
	
	for(int row=getHeight()-1; row>=0; row=row-1) {
	    picture = picture + '|';
	    for(int col=0; col<getWidth(); col=col+1) {
		/* INVARIANT:
		 *   picture is a textual representation of that portion of
		 *   the field extending from the top-left corner and down 
		 *   to just before (col,row)."  */
		if (members[col][row] == null) {
		    picture = picture + ' ';
		} else {
		    picture = picture + members[col][row].getLetter();
		}
	    }
	    picture = picture + "|\n";
	}
	return picture;
    }
}


