From 29f7ebc26f765da449aed07adc2854c95d453f44 Mon Sep 17 00:00:00 2001 From: Thoumi Ngonga Brice Date: Mon, 6 Feb 2023 21:25:53 +0100 Subject: [PATCH] Update Implementation Methode AIGridGUI --- src/main/java/BattleShip/AIGridGUI.java | 61 ++++++++++++++++++++++ target/classes/BattleShip/AIGridGUI.class | Bin 2331 -> 2901 bytes 2 files changed, 61 insertions(+) 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 a21b7becd014c42309c30f774136d8ffce22a165..e603c494a8fd0bf61d7e252dc389dea1f4b294da 100644 GIT binary patch delta 858 zcmZuuTTc^F5dMbUZDm(( zaJ?g5Kn2AcQA?D>7#~c~#24d>FZvtwjYM&}Mc~1loSE;;eCL}va|Uw0=E@)cymdiy2W#Z{gv}xl|df4<8&X=DL%5dVGg7dgQ5JI|1aIspN z*`|d<-l|}$-e?y4QjPR0xQI3UDkl1kNRuAPF>!-7=s+!LUA&Il^kVvBM6|8Y?U%(LC4=A=aFY1evfl}&3 z8TF!^ECgs6l{AVfdW~v&kDWAy8v24-`o^&zsH2~#$1n?&^S{r)gL^zVftf3C9}ghW z7&h85F*OB@U^F!`Mh}@sHhRP;gX>gd4Bp4w&l6^>f;hu^q7zv}%$r8RZ*)5mqiJm5 Li%*%8foFdKR1Vu@ delta 301 zcmcaAHd~16)W2Q(7#J9A876Mz5@DI_%Q}~jHzhSKu{5W|DZeNswP^ASRu48-4Np(a zu*rICCX?&fG$tQnv)8Qz>SAK30+K=u{0xi?5Pmg~U&BxfBpDb)8N`4jBSRfS{bW6M zTf+u0pMgP@K@BXg&tL$i8=-U)g9Dgv%pe7(n_h=m2uGfNK6TXfSjF?PUh3X6Rz*2AK?G r^#H{f!K_{&i;1BRC@jRl^dG2!g`I($kr62Qi$NWzrXMK7#4rH>@Axw#