Browse Source

Implemented method to random position ships on matchfield

fleetstorm
Lorenz Hohmann 2 years ago
parent
commit
3ff4b665f6
  1. 25
      src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java
  2. 8
      src/test/java/de/tims/fleetstorm/matchfield/MatchfieldShipTest.java

25
src/main/java/de/tims/fleetstorm/matchfield/Matchfield.java

@ -1,5 +1,7 @@
package de.tims.fleetstorm.matchfield; package de.tims.fleetstorm.matchfield;
import java.util.Random;
public class Matchfield { public class Matchfield {
private Coordinate[][] matchfield; private Coordinate[][] matchfield;
@ -127,4 +129,27 @@ public class Matchfield {
return true; 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;
}
} }

8
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, 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)); 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);
}
}
} }
Loading…
Cancel
Save