rendered paste bodypackage Battleship;
import java.util.ArrayList;
import Battleship.Ship.Direction;
public class Board {
public static final String COORD_STATE_BLANK = " . ";
public static final String COORD_STATE_SHIP = " | ";
public static final String COORD_STATE_MISS = " o ";
public static final String COORD_STATE_HIT = " x ";
public static final String COORD_STATE_SUNKEN = " X ";
private int mapWidth;
private int mapHeight;
private ArrayList<Ship> ships;
private String[][] board;
private Coordinate coord;
public Board(int x, int y) {
mapWidth = x;
mapHeight = y;
ships = new ArrayList<Ship>();
board = new String[x][y];
for (int i = 0; i < mapWidth; i++) {
for (int j = 0; j < mapHeight; j++) {
board[i][j] = COORD_STATE_BLANK;
}
}
}
public Board() {
}
public boolean placeShip(int x, int y, int length, Direction direction) {
if(coordinateOutOfBounds(new Coordinate(x,y)) == true) return false;
if(lengthOutOfBounds(x,y,length) == true) return false;
for (int i = 0; i < ships.size(); i++) {
if(ships.get(i).occupiesCoordinate(new Coordinate(x,y))) return false;
}
System.out.println("Ship placed at " + x + "," + y);
for (int i = 0; i < length; i++) {
if(direction == Direction.NORTH) {
x--;
} else if (direction == Direction.SOUTH) {
x++;
} else if (direction == Direction.EAST) {
y++;
} else if (direction == Direction.WEST) {
y--;
}
}
Ship ship = new Ship(direction, length, x, y);
ships.add(ship);
return true;
}
public boolean hit(int x, int y){
if(board[x][y] != COORD_STATE_BLANK)
return false;
for(Ship ship : ships)
if(ship.hit(x, y)){
if(ship.sunken()) {
for(Coordinate coordinate : ship.getCoordinates())
board[coordinate.getX()][coordinate.getY()] = COORD_STATE_SUNKEN;
} else {
board[x][y] = COORD_STATE_HIT;
return true;
}
}
board[x][y] = COORD_STATE_MISS;
return false;
}
public boolean lengthOutOfBounds(int x, int y, int length) {
for (int i = 0; i < ships.size(); i++) {
if(coordinateOutOfBounds(ships.get(i).getCoordinates().get(i)) == true) return true;
}
return false;
}
private boolean coordinateOutOfBounds(Coordinate coord) {
if(coord.getX() > mapWidth || coord.getY() > mapWidth) return true;
if(coord.getX() < 1 || coord.getY() < 1) return true;
return false;
}
public boolean allShipsSunken() {
for (int i = 0; i < ships.size(); i++) {
if(ships.get(i).sunken() == true) return true;
}
return false;
}
public int getHeight() {
return mapHeight;
}
public int getWidth() {
return mapWidth;
}
public String[][] getMap() {
return board;
}
public void setMapElement(String s, int y, int x) {
board[x][y] = " "+ s + " ";
}
public ArrayList<Ship> getShips() {
return ships;
}
}