-1

I'm working on a method that randomly places ships on a 10x10 grid for battleship. It works sometimes, but sometimes it will run forever without placing a ship, even if it comes up with a spot where a ship could clearly be placed.

I feel like it has something to do with the random number generation.

Here's my code:

public void placeAllShips() {
    int dir = 0;
    int xCoord = 0;
    int yCoord = 0;
    boolean flag;
    boolean overlap;
    for (int i=0; i<5; i++) {
      flag = true;
      overlap = false;
      while (flag) {
        xCoord = (int)(Math.random()*(10)); //get a random x coordinate
        yCoord = (int)(Math.random()*(10)); //get a random y coordinate
        dir = (int)(Math.random()*(2)); //get a random direction, 0 = horizontal, 1 = vertical
        if ((cellArr[xCoord][yCoord].hasShip()==false)&&(((dir==0)&&((xCoord+i)<=9))||((dir==1)&&((yCoord+i)<=9)))) {
          for (int j=0; j<i+1; j++) {
            if ((dir==0)&&(cellArr[xCoord+j][yCoord].hasShip())) {
              overlap = true;
            }
            else if ((dir==1)&&(cellArr[xCoord][yCoord+j].hasShip())) {
              overlap = true;
            }
          }
          if (overlap==false) {
            flag = false;
          }
        }
        System.out.print("A");
      }
      System.out.println(xCoord+":"+yCoord+":"+dir);
      for (int k=0; k<i+1; k++) {
        if (dir==0) {
          cellArr[xCoord+k][yCoord].setHasShip(true);
        }
        else {
          cellArr[xCoord][yCoord+k].setHasShip(true);
        }
      }
    }
  }
4

1 回答 1

3
  • overlap设置为false
  • while 循环开始。
  • 发现重叠,overlap设置为true
  • 循环重新开始。
  • overlap还在true
  • 循环永远不会退出。

因此,向下移动overlap = false;一行。

于 2013-02-23T19:33:18.023 回答