Im creating a battleship game for a school project and ive tried for very long to place my ships randomly and not overlap with each other. Ive tried various booleans and if statements but it doesnt seem to work.Its something wrong with the if statement I think and I need more code there.
My ships prints out ok with the size but sometimes they overlap.
Id appreciate if someone could help me out !:D
public class Game {
private int row;
private int col;
private Ship[][] board;
private ArrayList<Ship> ships;
private int shotsFired;
private int hitCount;
private int shipsSunk;
private int placedShips;
private int shipNumber;
public Game() {
shotsFired = 0;
hitCount = 0;
shipsSunk = 0;
placedShips = 0;
shipNumber = 5;
ships = new ArrayList<>();
ships.add(new Battleship(5));
ships.add(new Fighter(4));
ships.add(new Destroyer(3));
ships.add(new Cruiser(2));
ships.add(new Submarine(1));
}
public void createBoard(Ship ship) {
row = 10;
col = row;
board = new Ship[row][col];
//creates the battle field, fills with empty ships
for (int i = 0; i < board.length; i++) {
Arrays.fill(board[i], null);
}
placeShips();
}
public void placeShips() {
int occupied = 0;
Random random = new Random();
for (int i = 0; i < ships.size(); i++) {
boolean direction = random.nextBoolean();
if (direction) {
int x = (int) (Math.random() * 10);
int y = (int) (Math.random() * (10 - ships.get(i).getSize()));
for (int j = 0; j < ships.get(i).getSize(); j++) {
if (board[x][y + j] == null) {
board[x][y + j] = ships.get(i);
}
}
}
else {
int x = (int) (Math.random() * (10 - ships.get(i).getSize()));
int y = (int) (Math.random() * 10);
for (int j = 0; j < ships.get(i).getSize(); j++) {
if (board[x + j][y] == null) {
board[x + j][y] = ships.get(i);
}
}
}
}
}