From 1f75f7bf30400bc0f14fb345b6996477126fd8c8 Mon Sep 17 00:00:00 2001 From: Tamino Mueller Date: Tue, 8 Oct 2024 20:49:19 +0200 Subject: [PATCH] Task 8 --- .../game/server/ServerGameLogic.java | 42 ++++++++++++++++++- 1 file changed, 41 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..1980d29 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 @@ -140,10 +140,19 @@ public class ServerGameLogic implements ClientInterpreter { */ @Override public void received(MapMessage msg, int from) { + List ships = msg.getShips(); if (state != ServerState.SET_UP) LOGGER.log(Level.ERROR, "playerReady not allowed in {0}", state); //NON-NLS else - playerReady(getPlayerById(from), 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,35 @@ public class ServerGameLogic implements ClientInterpreter { } } } + + private boolean isInBounds(Battleship ship){ + return ship.getMinX() >= 0 && ship.getMaxX() < config.getMapWidth() && + ship.getMinY() >= 0 && ship.getMaxY() < config.getMapHeight(); + } + + + + 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; + } + + }