I'm currently programming a BattleShip game in Java, I randomly generate x, then y for the first cell of the ship,
public class Cell implements Comparable<Cell> {
private final int x;
private final int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
Cell(int xc, int yc) {
x = xc;
y = yc;
}
public Cell continueWithDirection(Direction d) {
switch (d) {
case ROW -> {
return new Cell(x + 1, y);
}
case COLUMN -> {
return new Cell(x, y + 1);
}
}
;
return new Cell(x, y);
}
}
//file 2
import java.util.Random;
public enum Direction {
ROW,
COLUMN;
private static final Random randomizer=new Random();
static Direction random(){
boolean b = randomizer.nextBoolean();
if (b) {
return Direction.ROW;
} else {
return Direction.COLUMN;
}
}
}
Cell[] cells = new Cell[size];
cells[0] = new Cell(randomizer.nextInt(getAreaWidth() - size + 1), randomizer.nextInt(getAreaHeight() - size + 1));
for (int i = 1; i < cells.length; i++) {
cells[i] = cells[i - 1].continueWithDirection(getDirection());
}
return cells;
and then choose a random direction (either up or right) for the other 2 cells of the ship the first cell is placed from 0 to bound-shipSize + 1
x and y bound, so I guarantee that all ships will be placed in the border area, but how do I implement random coordinate generation without repeating the same x and y together. I thought to randomly generate only the first ship, then just randomly go in some direction from the ship and put a new ship, but even so I have to store an array of all ships, and detect collisions. How can I better implement this algorithm
Aucun commentaire:
Enregistrer un commentaire