Ejemplo n.º 1
0
  /**
   * Add a random ship of a given length to one side of the board. The new ship cannot intersect any
   * existing ships.
   *
   * @param length
   * @param squares
   * @param random
   */
  private void addRandomShip(BattleShip ship, boolean leftSide, Random random) {
    boolean vertical = random.nextBoolean();
    int length = ship.getLength();
    GridSquare[][] squares = leftSide ? leftSquares : rightSquares;
    if (leftSide) leftShips.add(ship);
    else rightShips.add(ship);

    while (true) {
      int xpos = random.nextInt(vertical ? width : width - length);
      int ypos = random.nextInt(vertical ? height - length : height);
      // now, check whether this ship intersects any others
      if (vertical) {
        for (int i = 0; i != length; ++i)
          if (!(squares[xpos][ypos + i] instanceof EmptySquare)) continue;

        // if we get here, then there is no intersection.

        for (int i = 0; i != length; ++i)
          if (i == 0)
            squares[xpos][ypos + i] = new ShipSquare(ShipSquare.Type.VERTICAL_TOP_END, ship);
          else if (i == (length - 1))
            squares[xpos][ypos + i] = new ShipSquare(ShipSquare.Type.VERTICAL_BOTTOM_END, ship);
          else squares[xpos][ypos + i] = new ShipSquare(ShipSquare.Type.VERTICAL_MIDDLE, ship);

        // done
        return;
      } else {
        for (int i = 0; i != length; ++i)
          if (!(squares[xpos + i][ypos] instanceof EmptySquare)) continue;

        // if we get here, then there is no intersection.

        for (int i = 0; i != length; ++i)
          if (i == 0)
            squares[xpos + i][ypos] = new ShipSquare(ShipSquare.Type.HORIZONTAL_LEFT_END, ship);
          else if (i == (length - 1))
            squares[xpos + i][ypos] = new ShipSquare(ShipSquare.Type.HORIZONTAL_RIGHT_END, ship);
          else squares[xpos + i][ypos] = new ShipSquare(ShipSquare.Type.HORIZONTAL_MIDDLE, ship);

        // done
        return;
      }
    }
  }
Ejemplo n.º 2
0
 /**
  * Check whether player won or not.
  *
  * @return
  */
 public boolean didPlayerWin() {
   for (BattleShip ship : rightShips) if (!ship.isDestroyed()) return false;
   return true;
 }
Ejemplo n.º 3
0
 /**
  * Check whether computer won or not.
  *
  * @return
  */
 public boolean didComputerWin() {
   for (BattleShip ship : leftShips) if (!ship.isDestroyed()) return false;
   return true;
 }