From 3ff4b665f600a6230696daa5ee9d0ceecf9d5c78 Mon Sep 17 00:00:00 2001 From: Lorenz Hohmann Date: Wed, 2 Feb 2022 16:53:42 +0100 Subject: [PATCH] Implemented method to random position ships on matchfield --- .../fleetstorm/matchfield/Matchfield.java | 25 +++++++++++++++++++ .../matchfield/MatchfieldShipTest.java | 8 ++++++ 2 files changed, 33 insertions(+) diff --git a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java index ade8efb..77ee171 100644 --- a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java +++ b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java @@ -1,5 +1,7 @@ package de.tims.fleetstorm.matchfield; +import java.util.Random; + public class Matchfield { private Coordinate[][] matchfield; @@ -127,4 +129,27 @@ public class Matchfield { return true; } + public boolean setShipOnRandomPosition(int length) { + boolean success = false; + Coordinate origin = null; + int randomDirection; + + do { + + Random random = new Random(); + int randomX = random.nextInt(this.size - length); + int randomY = random.nextInt(this.size - length); + origin = new Coordinate(randomX, randomY); + + randomDirection = random.nextInt(2); + + if (this.isFreePosition(origin, length, randomDirection)) { + success = this.setShip(new Coordinate(randomX, randomY), length, randomDirection); + } + + } while (!success); + + 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 b3f1205..d12852e 100644 --- a/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java +++ b/src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java @@ -152,4 +152,12 @@ class MatchfieldShipTest { Arguments.of("one of the coordinates is hit, others on free fields", new Coordinate(5, 5), 1, 3, new Coordinate[] { new Coordinate(5, 7), new Coordinate(5, 8), new Coordinate(5, 9) }, false)); } + + @Test + void testIfRandomShipPositioningIsWorking() { + for (int shipLength = 2; shipLength <= 5; shipLength++) { + boolean calculatedResult = matchfield.setShipOnRandomPosition(shipLength); + assertTrue(calculatedResult); + } + } }