gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:02 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com