From fae747e504ca40dcc5375a19513a6db9d04dcf86 Mon Sep 17 00:00:00 2001 From: Simon Wilkening Date: Sat, 12 Oct 2024 15:51:44 +0200 Subject: [PATCH] Server site map loading validation --- .../game/server/ServerGameLogic.java | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/Projekte/battleship/model/src/main/java/pp/battleship/game/server/ServerGameLogic.java b/Projekte/battleship/model/src/main/java/pp/battleship/game/server/ServerGameLogic.java index a5987fa..9cbd3ff 100644 --- a/Projekte/battleship/model/src/main/java/pp/battleship/game/server/ServerGameLogic.java +++ b/Projekte/battleship/model/src/main/java/pp/battleship/game/server/ServerGameLogic.java @@ -142,8 +142,15 @@ public class ServerGameLogic implements ClientInterpreter { public void received(MapMessage msg, int from) { if (state != ServerState.SET_UP) LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS - else - playerReady(getPlayerById(from), msg.getShips()); + + List ships = msg.getShips(); + + if (!shipsValidation(ships)){ + LOGGER.log(Level.ERROR, "ship placement by player {0} is Invalid", from); + send(getPlayerById(from),null); + return; + } + playerReady(getPlayerById(from), msg.getShips()); } /** @@ -217,4 +224,41 @@ public class ServerGameLogic implements ClientInterpreter { } } } -} + + /* Tests if any ship in the list occupies the space of another ship and marks occupied points in the Map. + * @param ships list of ships to validate + * @return {@code true} if all ships positions are valid, {@code false} otherwise + */ + + private boolean shipsValidation(List ships) { + + Set occupied = new HashSet<>(); + + for (Battleship ship : ships) { + if (!onMap(ship)){ + return false; + } + for (int x = ship.getMinX(); x <= ship.getMaxX(); x++) { + for (int y = ship.getMinY(); y <= ship.getMaxY(); y++) { + IntPoint point = new IntPoint(x,y); + if (!occupied.add(point)){ + return false; + + } + + } + } + } + return true; + } + + /* Tests if a given ship is positioned inside of Map constrains + * @param ship the ship to validate + * @return {@code true} if a ship is not violating constrains, {@code false} otherwise + */ + + private boolean onMap(Battleship ship){ + return ship.getMinX() >= 0 && ship.getMaxX() < config.getMapWidth() && + ship.getMinY() >= 0 && ship.getMaxY() < config.getMapHeight(); + } +} \ No newline at end of file