diff --git a/src/main/java/nl/tudelft/jpacman/board/Direction.java b/src/main/java/nl/tudelft/jpacman/board/Direction.java index 2fb31fa9f..cdc85adae 100644 --- a/src/main/java/nl/tudelft/jpacman/board/Direction.java +++ b/src/main/java/nl/tudelft/jpacman/board/Direction.java @@ -3,7 +3,7 @@ /** * An enumeration of possible directions on a two-dimensional square grid. * - * @author Jeroen Roosen + * @author Jeroen Roosen */ public enum Direction { @@ -69,4 +69,22 @@ public int getDeltaX() { public int getDeltaY() { return deltaY; } + + /** + * @return The direction that is opposite to this direction. + */ + public Direction opposite() { + switch (this) { + case NORTH: + return SOUTH; + case SOUTH: + return NORTH; + case WEST: + return EAST; + case EAST: + return WEST; + default: + throw new IllegalStateException("Received an unknown enum value."); + } + } } diff --git a/src/main/java/nl/tudelft/jpacman/npc/ghost/Clyde.java b/src/main/java/nl/tudelft/jpacman/npc/ghost/Clyde.java index dab74c0eb..a21c67ebe 100644 --- a/src/main/java/nl/tudelft/jpacman/npc/ghost/Clyde.java +++ b/src/main/java/nl/tudelft/jpacman/npc/ghost/Clyde.java @@ -1,6 +1,5 @@ package nl.tudelft.jpacman.npc.ghost; -import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -57,18 +56,6 @@ public class Clyde extends Ghost { */ private static final int MOVE_INTERVAL = 250; - /** - * A map of opposite directions. - */ - private static final Map OPPOSITES = new EnumMap<>(Direction.class); - - static { - OPPOSITES.put(Direction.NORTH, Direction.SOUTH); - OPPOSITES.put(Direction.SOUTH, Direction.NORTH); - OPPOSITES.put(Direction.WEST, Direction.EAST); - OPPOSITES.put(Direction.EAST, Direction.WEST); - } - /** * Creates a new "Clyde", a.k.a. "Pokey". * @@ -105,7 +92,7 @@ public Optional nextAiMove() { if (path != null && !path.isEmpty()) { Direction direction = path.get(0); if (path.size() <= SHYNESS) { - return Optional.ofNullable(OPPOSITES.get(direction)); + return Optional.of(direction.opposite()); } return Optional.of(direction); } diff --git a/src/test/java/nl/tudelft/jpacman/board/DirectionTest.java b/src/test/java/nl/tudelft/jpacman/board/DirectionTest.java index ed066f25a..9559ed9ea 100644 --- a/src/test/java/nl/tudelft/jpacman/board/DirectionTest.java +++ b/src/test/java/nl/tudelft/jpacman/board/DirectionTest.java @@ -19,4 +19,20 @@ void testNorth() { Direction north = Direction.valueOf("NORTH"); assertThat(north.getDeltaY()).isEqualTo(-1); } + + /** + * The correct opposite is returned. + */ + @Test + void testOpposite() { + assertThat(Direction.NORTH.opposite()).isEqualTo(Direction.SOUTH); + } + + /** + * The opposite of the opposite is the original. + */ + @Test + void testOppositeTwice() { + assertThat(Direction.WEST.opposite().opposite()).isEqualTo(Direction.WEST); + } }