java - 放置战列舰时如何使随机放置的船只不与任何船只重叠

标签 java algorithm dictionary random

我在电脑上制作游戏战舰,想知道如何让随机放置的战舰不相互重叠。 我的代码现在看起来像这样:

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

现在的问题是,有时当它放置船只时,它会将一艘船部分地放在另一艘船上,而这是不可能的。

最佳答案

我会使用如下算法:

  1. 对于每种船舶尺寸,在网格中存储可能位置的列表。
  2. 从此列表中随机选择一个位置。
  3. 针对每种船舶尺寸浏览每个列表,移除(或使)重叠部分。

这样,当您的棋盘变得越来越拥挤时,您就不太可能在尝试获得有效位置时陷入困境。

关于java - 放置战列舰时如何使随机放置的船只不与任何船只重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799940/

相关文章:

c++ - 如何在 C++ 容器中向左移动元素(以实现删除)?

algorithm - 使用回溯的近似字符串匹配

python - 数据帧 : change value in column when value in another column is in dict

java - 在 Java Applet 中导入图像

java - Hibernate 自定义类型定义

algorithm - 这个序列是递增的还是递减的?

python - 如何在变量之后命名 Python 字典?

python - dict理解中的多个键值对

java - 任何人都有 AppScale 的经验?

java - 东方数据库。设置 ConflictStrategy 抛出异常