Reputation: 4149
I am implementing a random mouse algorithm to explore the maze. The algorithm after a while gets stuck in an infinite loop. I debugged it and it seems to get stuck going back and forth between a passage way.
Please take a look at my algorithm implementation.
Here is my code: The directions are relative to the robot.
public boolean drive2Exit() throws Exception {
Turn[] turn = {Turn.LEFT, Turn.RIGHT};
while (!robot.isAtGoal() && robot.getBatteryLevel() != 0) {
if (robot.distanceToObstacle(Direction.FORWARD) != 0) {
try {
robot.move(1);
} catch (Exception e) {
}
} else {
int index = randomGenerator.nextInt(turn.length);
try {
robot.rotate(turn[index]);
} catch (Exception e) {
}
}
}
if (robot.isAtGoal())
return true;
return false;
}
Upvotes: 0
Views: 552
Reputation: 34638
Suppose you have a T-shaped passage:
┌───────┐
│ │
└──┐ ┌──┘
Your mouse comes into it, sees a wall, and turns into one of the sides of the T.
┌───────┐
│ ┌> │
└──┐ ┌──┘
Then it hits the wall at the end of that side. It turns - no matter whether left or right. Still sees a wall. So it turns again - until it finally turns backwards. So far so good.
┌───────┐
│ <-│
└──┐ ┌──┘
But then, since it doesn't see a wall, it will always go forward, up until the other side of the T. And the same will happen, over and over.
┌───────┐
│-> │
└──┐ ┌──┘
Your program does not make any option that will cause it to decide to turn back into the leg of the T, because when he gets there, there is no obstacle in front of it, so why should it turn?
┌───────┐
│ ↴ │ ** This option doesn't exist **
└──┐ ┌──┘
Upvotes: 3