Open tteuru09 opened 6 months ago
public void randomlyPlaceShips() {
List<Ship> ships = this.fleet.getShips();
List<List<Tile>> map = this.playerMap.getMap();
Random random = new Random();
for (Ship ship : ships) {
System.out.println(ship.getName());
boolean canPlaceShip = false;
while (!canPlaceShip) {
int x = random.nextInt(10);
int y = random.nextInt(10);
List<String> directions = new ArrayList<>(Arrays.asList("avant", "arriere", "haut", "bas"));
while (!directions.isEmpty() && !canPlaceShip) {
int id_dir = random.nextInt(directions.size());
String direction = directions.remove(id_dir);
canPlaceShip = tryPlaceShip(ship, map, x, y, direction);
if (canPlaceShip) {
System.out.println("Le navire a été placé avec succès à la position : " + x + "," + y + " et à la direction : " +
direction);
} else {
System.out.println("Impossible de placer le navire à la position : " + x + "," + y + " et à la direction : " +
direction);
if (directions.isEmpty()) {
System.out.println("Changement de position x et y...");
}
}
}
}
}
this.playerMap.setMap(map);
}
private boolean tryPlaceShip(Ship ship, List<List<Tile>> map, int x, int y, String direction) {
int shipLength = ship.getLength();
int shipId = ship.getId();
switch (direction) {
case "avant":
return placeShipHorizontally(shipLength, shipId, map, x, y, 1);
case "arriere":
return placeShipHorizontally(shipLength, shipId, map, x, y, -1);
case "haut":
return placeShipVertically(shipLength, shipId, map, x, y, -1);
case "bas":
return placeShipVertically(shipLength, shipId, map, x, y, 1);
default:
return false;
}
}
private boolean placeShipHorizontally(int length, int shipId, List<List<Tile>> map, int x, int y, int direction) {
for (int i = 0; i < length; i++) {
int newY = y + i * direction;
if (newY < 0 || newY >= 10 || map.get(x).get(newY).getId_ship() != -1) {
return false;
}
}
for (int i = 0; i < length; i++) {
int newY = y + i * direction;
map.get(x).get(newY).setId_ship(shipId);
}
return true;
}
private boolean placeShipVertically(int length, int shipId, List<List<Tile>> map, int x, int y, int direction) {
for (int i = 0; i < length; i++) {
int newX = x + i * direction;
if (newX < 0 || newX >= 10 || map.get(newX).get(y).getId_ship() != -1) {
return false;
}
}
for (int i = 0; i < length; i++) {
int newX = x + i * direction;
map.get(newX).get(y).setId_ship(shipId);
}
return true;
}
Update the function that auto place the ships :