From 293b24a88f941934d1ab832f1cc80c74183f0327 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Mon, 23 Nov 2015 21:22:35 +0100 Subject: Fix Monkey undefined behaviour in special cases --- src/ch/epfl/maze/physical/zoo/Monkey.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'src/ch/epfl/maze/physical/zoo') diff --git a/src/ch/epfl/maze/physical/zoo/Monkey.java b/src/ch/epfl/maze/physical/zoo/Monkey.java index 8aea75d..a29b7d4 100644 --- a/src/ch/epfl/maze/physical/zoo/Monkey.java +++ b/src/ch/epfl/maze/physical/zoo/Monkey.java @@ -37,9 +37,6 @@ public class Monkey extends Animal { */ private Direction followLeft(Direction[] choices) { - if (choices.length == 0) return Direction.NONE; - if (choices.length == 1) return choices[0]; - List choiceList = new ArrayList<>(Arrays.asList(choices)); Direction dir = this.currentDirection.rotateLeft(); while (!choiceList.contains(dir)) dir = dir.rotateRight(); @@ -47,13 +44,27 @@ public class Monkey extends Animal { return dir; } + /** + * Determines the strategy to follow depending on special cases. + * + * @param choices An array of possible directions + * @return The Direction to take + */ + private Direction findDirection(Direction[] choices) { + if (choices.length == 0) return Direction.NONE; + if (this.currentDirection == Direction.NONE) return choices[0]; + if (choices.length == 1) return choices[0]; + if (choices.length > 3) return choices[0]; + return this.followLeft(choices); + } + /** * Moves according to the relative left wall that the monkey has to follow. */ @Override public Direction move(Direction[] choices) { - this.currentDirection = this.followLeft(choices); + this.currentDirection = this.findDirection(choices); return this.currentDirection; } -- cgit v1.2.3