diff --git a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java index cca91c9..1a4d4b8 100644 --- a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java +++ b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java @@ -110,4 +110,22 @@ public class Matchfield { return shipCounter == 0; } + public boolean isFreePosition(Coordinate next, int length, int direction) { + + for (int i = 0; i < length; i++) { + + if (this.getState(next.getX(), next.getY()) != Coordinate.EMPTY) + return false; + + if (direction == 0) { + + next = new Coordinate(next.getX() + i, next.getY()); + } else if (direction == 1) { + next = new Coordinate(next.getX(), next.getY() + i); + } + } + + return true; + } + } diff --git a/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java b/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java index 665f367..565cd98 100644 --- a/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java +++ b/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java @@ -130,4 +130,14 @@ class MatchfieldShipTest { boolean calulatedResult = matchfield.areAllShipsHit(); assertFalse(calulatedResult); } + + @Test + void testMatchfieldIsFreePositionWithNonFreeField() { + Matchfield matchfield = new Matchfield(10); + matchfield.createMatchfield(); + matchfield.setState(new Coordinate(0, 0), Coordinate.SHIP); + + boolean calculatedResult = matchfield.isFreePosition(new Coordinate(0, 0), 2, 1); + assertFalse(calculatedResult); + } }