summaryrefslogtreecommitdiff
path: root/src/ch/epfl/maze/physical/ProbabilisticAnimal.java
blob: e461e8c59781616602bf2bfc861b6d11f241ea92 (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
67
68
69
70
71
72
73
74
75
76
77
package ch.epfl.maze.physical;

import ch.epfl.maze.util.Direction;
import ch.epfl.maze.util.Vector2D;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * A probabilistic animal that uses a random component in its decision making process.
 *
 * @author Pacien TRAN-GIRARD
 */
abstract public class ProbabilisticAnimal extends Animal {

    public static final Random RANDOM_SOURCE = new Random();

    /**
     * Constructs a probabilistic animal with a starting position
     *
     * @param position Starting position of the probabilistic animal in the labyrinth
     */
    public ProbabilisticAnimal(Vector2D position) {
        super(position); // no pun intended
    }

    /**
     * Excludes the given direction from possible choices.
     *
     * @param choices   A set of choices
     * @param toExclude The Direction to exclude
     * @return A set of smart choices
     */
    protected Set<Direction> excludeDirection(Set<Direction> choices, Direction toExclude) {
        return choices
                .stream()
                .filter(dir -> dir != toExclude)
                .collect(Collectors.toSet());
    }

    /**
     * Excludes the origin direction from possible choices.
     *
     * @param choices A set of choices
     * @return A set of smart choices
     */
    protected Set<Direction> excludeOrigin(Set<Direction> choices) {
        return this.excludeDirection(choices, this.getDirection().reverse());
    }

    /**
     * Returns a random Direction from the given choices.
     *
     * @param choices A set of Direction
     * @return A random Direction taken from the given choices
     */
    protected Direction getRandomDirection(Set<Direction> choices) {
        List<Direction> choiceList = new ArrayList<>(choices);
        return choiceList.get(RANDOM_SOURCE.nextInt(choices.size()));
    }

    /**
     * Moves according to an improved version of a <i>random walk</i> : the
     * probabilistic animal does not directly retrace its steps if not forced.
     */
    @Override
    public Direction move(Set<Direction> choices) {
        if (choices.isEmpty()) return Direction.NONE;

        Set<Direction> smartChoices = choices.size() > 1 ? this.excludeOrigin(choices) : choices;
        return this.getRandomDirection(smartChoices);
    }

}