From 2dd70c10b53631cdc02a1270d0e50240a96548d4 Mon Sep 17 00:00:00 2001 From: Yvonne Schmidt Date: Mon, 7 Oct 2024 01:23:52 +0200 Subject: [PATCH] Server checks imported map for invalid placements --- .../game/server/ServerGameLogic.java | 46 ++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) 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..4a6642d 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 @@ -134,6 +134,7 @@ public class ServerGameLogic implements ClientInterpreter { /** * Handles the reception of a MapMessage. + * Also tests valid ship placement on the Map. * * @param msg the received MapMessage * @param from the ID of the sender client @@ -142,7 +143,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 + + List ships = msg.getShips(); + + if (!shipsValid(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 +226,39 @@ public class ServerGameLogic implements ClientInterpreter { } } } + /* Tests if a given ship is positioned inside of Map constrains + * + */ + + private boolean isInBounds(Battleship ship){ + return ship.getMinX() >= 0 && ship.getMaxX() < config.getMapWidth() && + ship.getMinY() >= 0 && ship.getMaxY() < config.getMapHeight(); + } + + + /* Tests if a ship occupies the space of another ship and marks occupied points in the Map. + * + */ + private boolean shipsValid(List ships) { + + Set occupied = new HashSet<>(); + + for (Battleship ship : ships) { + if (!isInBounds(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; + } + }