/**
   SummaryDescription. 
   
   /home1/ugrads/t172q/CS2013/BGServer/BGPlayer.java
   
   Created: Wed May 19 15:07:54 2004
   
   @author  Stuart MacGillivray #3148021 (email: <t172q@unb.ca>)
   
*/

public class BGPlayer 
{
  private static final int BOARDSIZE = 10;
  private static final int MAXSHIPS = 5;
  private BGCoord[][] field;
  private int numShips;
  private BGShip[] playerShips;

  public BGPlayer ()
  {
    field = new BGCoord[BOARDSIZE][BOARDSIZE];
    numShips = 0;
    playerShips = new BGShip[MAXSHIPS];
  }

  public void placeShip(int[][] coords) throws BGErrorException
  {
    if (numShips >= MAXSHIPS || !verifyLine(coords))
      throw new BGErrorException();
    int shipLength = coords.length;
    BGCoord[] location = new BGCoord[shipLength];
    
    for (int i = 0; i < shipLength; i++)
      location[i] = field[coords[i][0]][coords[i][1]];
    
    playerShips[numShips] = new BGShip(location, shipLength);
    
    for (int i = 0; i < shipLength; i++)
      {
	try
	  {
	    field[coords[i][0]][coords[i][1]].setContents(playerShips[numShips]);
	  }
	catch (BGErrorException e)
	  {
	    try
	      {
		for (int j = 0; j < i; j++)
		  field[coords[j][0]][coords[j][1]].setContents(null); // Cleanup after crash.
	      }
	    catch (BGErrorException f)
	      {
		throw e;
	      }
	    finally
	      {
		throw e;
	      }
	  }
      }
    
    numShips++;
  }

  public int fireAtLoc (int x, int y) throws BGErrorException
  {
    if (x < 0 || x > BOARDSIZE || y < 0 || y > BOARDSIZE)
      throw new BGErrorException();

    BGShip target = field[x][y].getContents();
    if (target != null)
      {
	try
	  {
	    target.hitShip(field[x][y]);
	  }
	catch (BGErrorException e)
	  {
	    throw e;
	  }
	if (target.isSunk())
	  return target.getLength();
	else
	  return 1;
      }
    return 0;
  }

  public boolean isDefeated()
  {
    for (int i = 0; i < numShips; i++)
      if (!playerShips[i].isSunk()) return false;
    return true;
  }

  public static boolean verifyLine (int[][] coords)
  {
    if (coords.length < 2 || coords.length > 5)
      return false;

    for (int i = 0; i < coords.length; i++)
      if (coords[i][0] >= BOARDSIZE || coords[i][0] < 0 || coords[i][1] >= BOARDSIZE ||
	  coords[i][1] < 0) return false;

    boolean possXLine = true;
    boolean possYLine = true;

    for (int i = 1; i < coords.length; i++)
      if (coords[i][0] != coords[0][0])
	possXLine = false;
    for (int i = 1; i < coords.length; i++)
      if (coords[i][1] != coords[0][1])
	possYLine = false;

    return (possXLine || possYLine);      
  }
  
}// BGPlayer
