diff --git a/src/main/java/BattleShip/AIGridGUI.java b/src/main/java/BattleShip/AIGridGUI.java index b017b6c..0bfc9f9 100644 --- a/src/main/java/BattleShip/AIGridGUI.java +++ b/src/main/java/BattleShip/AIGridGUI.java @@ -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; + } + } diff --git a/target/classes/BattleShip/AIGridGUI.class b/target/classes/BattleShip/AIGridGUI.class index a21b7be..e603c49 100644 Binary files a/target/classes/BattleShip/AIGridGUI.class and b/target/classes/BattleShip/AIGridGUI.class differ