I'm currently tasked with making a battleships game for college. So for, I've managed to get the ships down within the confines of the grid. My only problem now is validating the ship layout with regards to the ships colliding with other ships. I've read around, and presumably the best course of action is a two pass connected component algorithm, but I'm not entirely sure how I would go about implementing that.
This is what I currently have within my PlaceShips method:
public void placeShips(){
for(int iter = 0; iter < 5; iter++){
size = shipSizes[iter];
rotation = randNum.nextInt(2)+1;
while(!valid){
rows = randNum.nextInt(10)+1;
cols = randNum.nextInt(10)+1;
if(rotation ==1){
if (cols > mGame.getmColumns()- size){
valid = false;
}
else{
//assumed that the connected component algorithm needs to go here
valid = true;
}
}
else if(rotation == 2){
if (rows > mGame.getmRows() - size){
valid = false;
}
else{
//assumed that the connected component algorithm needs to go here
valid = true;
}
}
}
valid = false;
//Draw ships
for(int i = 0; i < size; i++){
if(rotation == 1){
gridPos[cols-1][rows-1] = 1;
cols = cols + 1;
}
else if(rotation == 2){
gridPos[cols-1][rows-1] = 1;
rows = rows + 1;
}
}
}
}
}