From 1a2bd513943c409c0976ce90d08fa28737a9e264 Mon Sep 17 00:00:00 2001 From: Max Wenzel Date: Wed, 12 Jan 2022 11:14:41 +0100 Subject: [PATCH] choosenField returns only Fields with state != shot --- .../java/de/tims/fleetstorm/ai/Logic.java | 19 +++++++++++++-- .../java/de/tims/fleetstorm/ai/LogicTest.java | 23 +++++++++++++++++-- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/tims/fleetstorm/ai/Logic.java b/src/main/java/de/tims/fleetstorm/ai/Logic.java index 359fcbd..d918ed5 100644 --- a/src/main/java/de/tims/fleetstorm/ai/Logic.java +++ b/src/main/java/de/tims/fleetstorm/ai/Logic.java @@ -1,9 +1,24 @@ package de.tims.fleetstorm.ai; +import java.util.ArrayList; +import java.util.Random; + +import de.tims.fleetstorm.matchfield.Matchfield; + public class Logic { - public int[] chooseField() { - return new int[] {}; + public int[] chooseField(Matchfield matchfield) { + ArrayList possibleFields = new ArrayList(); + for (int x = 0; x < Math.sqrt(matchfield.getSize()); x++) { + for (int y = 0; y < Math.sqrt(matchfield.getSize()); y++) { + if (matchfield.getState(x, y) == Matchfield.EMPTY || matchfield.getState(x, y) == Matchfield.SHIP) { + possibleFields.add(new int[] { x, y }); + } + } + } + Random randy = new Random(); + + return possibleFields.get(randy.nextInt(possibleFields.size() - 1)); } } diff --git a/src/test/java/de/tims/fleetstorm/ai/LogicTest.java b/src/test/java/de/tims/fleetstorm/ai/LogicTest.java index 76fe7f2..d8ebcf5 100644 --- a/src/test/java/de/tims/fleetstorm/ai/LogicTest.java +++ b/src/test/java/de/tims/fleetstorm/ai/LogicTest.java @@ -1,16 +1,35 @@ package de.tims.fleetstorm.ai; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; +import de.tims.fleetstorm.matchfield.Matchfield; + class LogicTest { Logic logic = new Logic(); + int size = 3; + private Matchfield matchfield = new Matchfield(size); @Test - void testFielIsNotNull() { - int[] calcResult = logic.chooseField(); + void testFieldIsNotNull() { + int[] calcResult = logic.chooseField(matchfield); assertNotNull(calcResult); } + @Test + void testChoosenFieldHasNotStateShot() { + matchfield.createMatchfield(); + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + // matchfield.setState(x, y, Matchfield.SHOT); + } + } + // matchfield.setState(0, 0, Matchfield.EMPTY); + + int[] choosenField = logic.chooseField(matchfield); + int calcState = matchfield.getState(choosenField[0], choosenField[1]); + assertNotEquals(calcState, Matchfield.SHOT); + } }