/** Tile models a single tile in the magic square game
 */
public class Tile {

  // A tile knows its value.
  private String value; // numeral from 1..nxn

  // A tile knows its left, right, top, bottom neighbour, respectively
  private Tile[] neighbour = new Tile[4]; // left, right, top, bottom

  /** constructor: create a tile with value v.
   */
  public Tile(String v) {
    value= v;
  }

  /** setNeighbours: set neighbours to l, r, t, b, respectively
   */
  public void setNeighbours(Tile l, Tile r, Tile t, Tile b) {
    neighbour[0]= l;
    neighbour[1] = r;
    neighbour[2]= t;
    neighbour[3]= b;
  }

  /** getValue: return value.
   */
  public String getValue() {
    return value;
  }

  /** setValue: set value to v.
   */
  public void setValue(String v) {
    value= v;
  }

  /** toString: print this tile's value.
   */
  public String toString(){
    return value;
  }
  
  /** swapValue: swap this Tile's value with otherTile's value.
   */
  private void swapValue(Tile otherTile) {
    String tmpValue= value;
    value= otherTile.value;
    otherTile.value= tmpValue;
  }

  /** swap: If a neighbouring tile has value n, swap my value
   *  with it and return that neighbour.  Otherwise, return 
   *  this tile.
   */
  public Tile swap(String n) {
    for (int i= 0; i != 4; i++) {
      if (neighbour[i] != null && neighbour[i].value.equals(n)) {
	swapValue(neighbour[i]);
	return neighbour[i];
      }
    }
    return this;
  }
}

