如何在放置战舰时使随机放置的战舰不重叠?(这是一个关于IT技术的提问标题)

3

我正在电脑上制作战舰游戏,并想知道如何在随机放置船只时避免它们重叠。

我的代码目前看起来是这样的:

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();
            for (int i = 0; i < 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));
                    for (int j = 0; j < ship[i].size; j++) {
                        grid[x][y + j] = i + 1;
                    }
                }
                if (way == 1) {
                    int x = (int) (Math.random() * (7 - ship[i].size));
                    int y = (int) (Math.random() * 7);
                    for (int j = 0; j < ship[i].size; j++) {
                        grid[x + j][y] = i + 1;
                    }
                }
            }
        }
        public int[][] getGrid() {
            return grid;
        }
    }
}`

现在的问题是,有时候当它放置船只时,会把一艘船部分地放在另一艘船上面,这是不应该发生的。


在设置之前,你只需检查网格值是否为0;否则重新计算船的位置并重试。 - Uwe Allner
2个回答

3
我会使用以下算法:
  1. 对于每个船的大小,在网格中存储可能的位置列表。
  2. 从此列表中随机选择一个位置。
  3. 对于每个船的大小,遍历其列表并删除(或使其无效)重叠的位置。
这样,随着游戏板变得更加拥挤,你就不太可能陷入寻找有效位置的困境。

0
也许在将船放置在网格上之前(在grid[x][y + j] = i + 1;之前),可以添加一个验证,以查看该空间是否已被占用。如果是这样,请重新开始放置。也许通过添加像isPlaced这样的布尔值,并将您的代码嵌入while循环中:
boolean isPlaced = false;

while (!isPlaced) {
  ...
  isPlaced = true;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接