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 a5987fa1..6a61cfd9 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 @@ -17,10 +17,14 @@ import pp.battleship.message.server.StartBattleMessage; import pp.battleship.model.Battleship; import pp.battleship.model.IntPoint; +import pp.battleship.model.Rotation; +import pp.util.Position; import java.lang.System.Logger; import java.lang.System.Logger.Level; +import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -142,10 +146,64 @@ public Player addPlayer(int id) { 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 if (checkMap(msg, from)) + LOGGER.log(Level.ERROR, "player submitted not allowed Map"); else playerReady(getPlayerById(from), msg.getShips()); } + /** + * Returns true if the map contains correct ship placement and is of the correct size + * + * @param msg the received MapMessage of the player + * @param from the ID of the Player + * @return a boolean based on if the transmitted map ist correct + */ + private boolean checkMap(MapMessage msg, int from) { + int mapWidth = getPlayerById(from).getMap().getWidth(); + int mapHeight = getPlayerById(from).getMap().getHeight(); + + if (mapHeight != 10 || mapWidth != 10) + return false; + + // check if ship is out of bounds + for (int i = 0; i < msg.getShips().size(); i++){ + Battleship battleship = msg.getShips().get(i); + if (battleship.getMaxX() >= mapWidth || battleship.getMinX() < 0 || battleship.getMaxY() >= mapHeight || battleship.getMinY() < 0) { + LOGGER.log(Level.ERROR, "Ship is out of bounds ({0})", battleship.toString()); + return false; + } + } + + // check if ships overlap + int[][] tempMap = new int[mapWidth][mapHeight]; + for (int[] row : tempMap) + Arrays.fill(row, 0); + msg.getShips().forEach(s -> { + int deltaX = s.getMaxX()-s.getMinX(); + int deltaY = s.getMaxY()-s.getMinY(); + int lastX = s.getX(); + int lastY = s.getY(); + tempMap[lastX][lastY] += 1; + for (int i = 0; i < deltaX-1; i++) + for (int j = 0; j < deltaY-1; j++) { + tempMap[lastX + (deltaX / Math.abs(deltaX))][lastY + (deltaY / Math.abs(deltaY))] += 1; + lastX = lastX + (deltaX / Math.abs(deltaX)); + lastY = lastY + (deltaY / Math.abs(deltaY)); + } + }); + for (int[] row : tempMap){ + for(int cell : row){ + if (cell > 1){ + LOGGER.log(Level.ERROR, "There are multiple ships on one position"); + return false; + } + } + } + + return true; + } + /** * Handles the reception of a ShootMessage. *