Note that there are some explanatory texts on larger screens.

plurals
  1. POBattleship game - ships overlapping
    text
    copied!<p>I'm writing a simple battleship game in Java using the ACM library. After the game starts, ships are supposed to be put on the canvas at random locations but the problem is that the ships might cover each other and this is not allowed in the game. How can I avoid the ships being placed on top of each other?</p> <p>My code is:</p> <pre><code>private void putSmallShips() { for (int i = 0; i &lt; SMALL_SHIP_QUANTITY; i++){ smallShip = new GRect(SMALL_SHIP_WIDTH, SHIP_HEIGHT); int x = rgen.nextInt(10, 510); int y = rgen.nextInt(10, 510); while (true){ gobj = getElementAt(x, y); if (gobj == null) break; x = rgen.nextInt(10, 510); y = rgen.nextInt(10, 510); } smallShip.setLocation(x, y); add(smallShip); } } private void putMiddleShips() { for (int i = 0; i &lt; MIDDLE_SHIP_QUANTITY; i++){ middleShip = new GRect(MIDDLE_SHIP_WIDTH, SHIP_HEIGHT); int x = rgen.nextInt(10, 530); int y = rgen.nextInt(10, 530); while (true){ gobj = getElementAt(x, y); if (gobj == null) break; System.out.println("opa!"); x = rgen.nextInt(10, 530); y = rgen.nextInt(10, 530); } x = x + i * 10; y = y + i * 10; middleShip.setLocation(x, y); add(middleShip); } } private void putBigShips() { for (int i = 0; i &lt; BIG_SHIP_QUANTITY; i++){ bigShip = new GRect(BIG_SHIP_WIDTH, SHIP_HEIGHT); int x = rgen.nextInt(10, 550); int y = rgen.nextInt(10, 550); while (true){ gobj = getElementAt(x, y); if (gobj == null) break; x = rgen.nextInt(10, 550); y = rgen.nextInt(10, 550); } bigShip.setLocation(x, y); add(bigShip); } } </code></pre> <p>As you see I put a while loop inside the for loop, but it doesn't help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload