From af28ea8e341701e1c68ba88541fd934ec15c97ec Mon Sep 17 00:00:00 2001 From: Lorenz Hohmann Date: Thu, 3 Feb 2022 08:32:14 +0100 Subject: [PATCH] Improved random ship positioning --- .../de/tims/fleetstorm/matchfield/Matchfield.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java index 77ee171..54eb146 100644 --- a/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java +++ b/src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java @@ -137,12 +137,21 @@ public class Matchfield { 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); + int randomX = 0, randomY = 0; + + if (randomDirection == 0) { + randomX = random.nextInt(this.size - length); + randomY = random.nextInt(this.size); + } else if (randomDirection == 1) { + randomX = random.nextInt(this.size); + randomY = random.nextInt(this.size - length); + } + + origin = new Coordinate(randomX, randomY); + if (this.isFreePosition(origin, length, randomDirection)) { success = this.setShip(new Coordinate(randomX, randomY), length, randomDirection); }