From 7830143d4b1660bfe633a641388ca503142b645f Mon Sep 17 00:00:00 2001 From: Lorenz Hohmann Date: Wed, 2 Feb 2022 16:14:26 +0100 Subject: [PATCH] Added isFreePosition() with first test case when position is filled --- .../tims/fleetstorm/matchfield/Matchfield.java | 18 ++++++++++++++++++ .../matchfield/MatchfieldShipTest.java | 10 ++++++++++ 2 files changed, 28 insertions(+) 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); + } }