|
|
@ -85,4 +85,65 @@ public class AIGridGUI extends JPanel { |
|
|
|
|
|
|
|
defaultBorder = buttons.get(0).getBorder(); |
|
|
|
} |
|
|
|
public void autoPlaceShips() { |
|
|
|
|
|
|
|
//If ships are to be placed automatically, randomly place each ship. |
|
|
|
|
|
|
|
for(Ship s : allShips) { |
|
|
|
int shipLength = s.getLength(); |
|
|
|
int clearSpace = 0; |
|
|
|
testLocations = new int[shipLength]; |
|
|
|
|
|
|
|
//Randomly select starting position to place ship and check if sufficient space to place ship. |
|
|
|
|
|
|
|
while(clearSpace < shipLength) { |
|
|
|
|
|
|
|
//Randomly choose whether to place ship vertically or horizontally and choose location of ship. |
|
|
|
|
|
|
|
boolean vert = new Random().nextBoolean(); |
|
|
|
int x; |
|
|
|
int y; |
|
|
|
|
|
|
|
if(vert) { |
|
|
|
|
|
|
|
x = (int) (Math.random() * (columns)); |
|
|
|
y = (int) (Math.random() * (rows - shipLength)); |
|
|
|
for(int i = 0; i < shipLength; i++) { |
|
|
|
testLocations[i] = x + (columns*(y+i)); |
|
|
|
} |
|
|
|
} else { |
|
|
|
x = (int) (Math.random() * (columns - shipLength)); |
|
|
|
y = (int) (Math.random() * (rows)); |
|
|
|
for(int i = 0; i < shipLength; i++) { |
|
|
|
testLocations[i] = x + i + (columns*y); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
//Check if the location is clear. |
|
|
|
|
|
|
|
clearSpace = 0; |
|
|
|
for(int i = 0; i < shipLength; i++) { |
|
|
|
if(buttons.get(testLocations[i]).getCellContents() == null) { |
|
|
|
clearSpace++; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
//Set the contents of the chosen cells to contain the ship. |
|
|
|
|
|
|
|
for(int i = 0; i < shipLength; i++) { |
|
|
|
buttons.get(testLocations[i]).setCellContents(s); |
|
|
|
} |
|
|
|
|
|
|
|
testLocations = null; |
|
|
|
} |
|
|
|
|
|
|
|
// |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
text = "Ready to start the game."; |
|
|
|
shipsPlaced = true; |
|
|
|
} |
|
|
|
|
|
|
|
} |