我在电脑上制作游戏战舰,想知道如何让随机放置的战舰不相互重叠。 我的代码现在看起来像这样:
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;
}
}
}`
现在的问题是,有时当它放置船只时,它会将一艘船部分地放在另一艘船上,而这是不可能的。
最佳答案
我会使用如下算法:
- 对于每种船舶尺寸,在网格中存储可能位置的列表。
- 从此列表中随机选择一个位置。
- 针对每种船舶尺寸浏览每个列表,移除(或使)重叠部分。
这样,当您的棋盘变得越来越拥挤时,您就不太可能在尝试获得有效位置时陷入困境。
关于java - 放置战列舰时如何使随机放置的船只不与任何船只重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799940/