summaryrefslogtreecommitdiff
path: root/src/ch/epfl/maze/physical/zoo/Mouse.java
blob: 1b22c66056db7c44c3f9e92f07d2df6a520579ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ch.epfl.maze.physical.zoo;

import ch.epfl.maze.physical.Animal;
import ch.epfl.maze.physical.ProbabilisticAnimal;
import ch.epfl.maze.util.Direction;
import ch.epfl.maze.util.Vector2D;

import java.util.ArrayList;
import java.util.List;

/**
 * Mouse A.I. that remembers only the previous choice it has made.
 *
 * @author Pacien TRAN-GIRARD
 */

public class Mouse extends ProbabilisticAnimal {

    private Direction previousChoice;

    /**
     * Constructs a mouse with a starting position.
     *
     * @param position Starting position of the mouse in the labyrinth
     */

    public Mouse(Vector2D position) {
        super(position);
        this.previousChoice = Direction.NONE;
    }

    /**
     * Excludes the origin direction for choices.
     *
     * @param choices An array of choices
     * @return An array of smart choices
     */

    private Direction[] excludeOrigin(Direction[] choices) {
        List<Direction> smartChoices = new ArrayList<>(choices.length - 1); // max size, excluding origin

        for (Direction dir : choices)
            if (!dir.isOpposite(this.previousChoice))
                smartChoices.add(dir);

        return smartChoices.toArray(new Direction[smartChoices.size()]);
    }

    /**
     * Moves according to an improved version of a <i>random walk</i> : the
     * mouse does not directly retrace its steps.
     */

    @Override
    public Direction move(Direction[] choices) {
        Direction[] smartChoices = choices.length > 1 ? this.excludeOrigin(choices) : choices;
        Direction dir = super.move(smartChoices);
        this.previousChoice = dir;
        return dir;
    }

    @Override
    public Animal copy() {
        return new Mouse(this.getPosition());
    }
}