我正在电脑上制作战舰游戏,并想知道如何在随机放置船只时避免它们重叠。
我的代码目前看起来是这样的:
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;
}
}
}`
现在的问题是,有时候当它放置船只时,会把一艘船部分地放在另一艘船上面,这是不应该发生的。