我正在计算机上制作游戏战舰,并想知道如何随机放置它们时船只不会相互重叠。 我的代码现在看起来像这样:
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 :(得分:3)
我会使用像:
这样的算法通过这种方式,当您的电路板变得更拥挤时,您不太可能因为尝试获得有效位置而陷入困境。
答案 1 :(得分:0)
也许在将船放在网格上之前(isPlaced
之前)添加验证,以查看是否已经占用了空间。如果是,请重新开始放置。也许通过添加类似boolean isPlaced = false;
while (!isPlaced) {
...
isPlaced = true;
}
的布尔值并将代码嵌入到while循环中,如:
<receiver android:name=".ReceiverName" >
<intent-filter >
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>