I'm working on a method that randomly places ships on a 10x10 grid for battleship. It works sometimes, but sometimes it will run forever without placing a ship, even if it comes up with a spot where a ship could clearly be placed.
I feel like it has something to do with the random number generation.
Here's my code:
public void placeAllShips() {
int dir = 0;
int xCoord = 0;
int yCoord = 0;
boolean flag;
boolean overlap;
for (int i=0; i<5; i++) {
flag = true;
overlap = false;
while (flag) {
xCoord = (int)(Math.random()*(10)); //get a random x coordinate
yCoord = (int)(Math.random()*(10)); //get a random y coordinate
dir = (int)(Math.random()*(2)); //get a random direction, 0 = horizontal, 1 = vertical
if ((cellArr[xCoord][yCoord].hasShip()==false)&&(((dir==0)&&((xCoord+i)<=9))||((dir==1)&&((yCoord+i)<=9)))) {
for (int j=0; j<i+1; j++) {
if ((dir==0)&&(cellArr[xCoord+j][yCoord].hasShip())) {
overlap = true;
}
else if ((dir==1)&&(cellArr[xCoord][yCoord+j].hasShip())) {
overlap = true;
}
}
if (overlap==false) {
flag = false;
}
}
System.out.print("A");
}
System.out.println(xCoord+":"+yCoord+":"+dir);
for (int k=0; k<i+1; k++) {
if (dir==0) {
cellArr[xCoord+k][yCoord].setHasShip(true);
}
else {
cellArr[xCoord][yCoord+k].setHasShip(true);
}
}
}
}