随机战舰布置方法

时间:2013-02-23 19:27:19

标签: java random

我正在开发一种方法,随机将船只放置在 10x10 网格上,用于战舰。 它有时会起作用,但有时它会在没有放置船的情况下永远运行,即使它有一个可以清楚放置船只的地方。

我觉得它与随机数生成有关。

这是我的代码:

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);
        }
      }
    }
  }

1 个答案:

答案 0 :(得分:3)

  • overlap设置为false
  • while循环开始。
  • 找到重叠,overlap设置为true
  • 循环重启。
  • overlap仍为true
  • 循环永不退出。

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