java - How to make the random placing of ships not overlap any ships when placing in battleships -


im making game battleships on computer , wonder how can make ships not overlap each other when randomly placing them. code right looks this:

public class battleshipsetup {      public static class boat {         int size;     }     public static class aircraftcarrier extends boat {         public aircraftcarrier() {             size = 5;         }     }     public static class battleship extends boat {         public battleship() {             size = 4;         }     }     public static class destroyer extends boat {         public destroyer() {             size = 3;         }     }     public static class submarine extends boat {         public submarine() {             size = 3;         }     }     public static class patrolship extends boat {         public patrolship() {             size = 2;         }     }     public static class gridsetup {         int[][] grid = {{0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0},                 {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0},                 {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}};         public void setgrid() {             boat[] ship;             ship = new boat[5];             ship[0] = new aircraftcarrier();             ship[1] = new battleship();             ship[2] = new destroyer();             ship[3] = new submarine();             ship[4] = new patrolship();             (int = 0; < 5; i++) {                 int way = (int) (math.random() * 2);                 if (way == 0) {                     int x = (int) (math.random() * 7);                     int y = (int) (math.random() * (7 - ship[i].size));                     (int j = 0; j < ship[i].size; j++) {                         grid[x][y + j] = + 1;                     }                 }                 if (way == 1) {                     int x = (int) (math.random() * (7 - ship[i].size));                     int y = (int) (math.random() * 7);                     (int j = 0; j < ship[i].size; j++) {                         grid[x + j][y] = + 1;                     }                 }             }         }         public int[][] getgrid() {             return grid;         }     } }` 

the thing when places ships puts 1 ship partially on 1 , not supossed possible.

i use algorithm like:

  1. for each ship size, store list of possible locations in grid.
  2. pick random location list.
  3. go through each list each ship size, removing (or invalidating) overlaps.

this way, less self stuck trying valid location board gets more crowded.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -