From 86e79f0a49e894817ffb3f90e3bcac52a3b80f68 Mon Sep 17 00:00:00 2001 From: Lorenz Hohmann Date: Sat, 15 Jan 2022 13:39:41 +0100 Subject: [PATCH] Implemented test if ship is already on position in shipSet --- .../de/tims/fleetstorm/matchfield/Matchfield.java | 7 ++++++- .../matchfield/MatchfieldPositioningTest.java | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java index bfc29fc..f9fcd5e 100644 --- a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java +++ b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java @@ -79,7 +79,12 @@ public class Matchfield { public boolean setShip(Coordinate coordinate, int length, int direction) { for (int i = 0; i < length; i++) { - this.getField(coordinate).setState(Coordinate.SHIP); + + Coordinate field = this.getField(coordinate); + if (field.getState() == Coordinate.SHIP) + return false; + + field.setState(Coordinate.SHIP); if (direction == 0) coordinate = this.getRight(coordinate); if (direction == 1) diff --git a/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldPositioningTest.java b/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldPositioningTest.java index 2fb254a..6ad6bb7 100644 --- a/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldPositioningTest.java +++ b/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldPositioningTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertTrue; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -69,4 +70,16 @@ class MatchfieldPositioningTest { Arguments.of("valid ship position from 8:0, length 5, direction 1", 10, new Coordinate(9, 0), 1, 5, true)); } + + @Test + void testShipPositionAlreadySetWithShip() { + Matchfield matchfield = new Matchfield(10); + matchfield.createMatchfield(); + + matchfield.setShip(new Coordinate(0, 0), 5, 1); + assertFalse(matchfield.setShip(new Coordinate(0, 1), 5, 1)); + + assertTrue(matchfield.setShip(new Coordinate(1, 1), 4, 0)); + assertFalse(matchfield.setShip(new Coordinate(4, 1), 2, 1)); + } }