summaryrefslogtreecommitdiff
path: root/src/ch/epfl/maze/physical/zoo/Hamster.java
blob: 527e8ce742dad1a5d325c2620b9c252488fabf8d (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
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;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Hamster A.I. that remembers the previous choice it has made and the dead ends
 * it has already met.
 *
 * @author EPFL
 * @author Pacien TRAN-GIRARD
 */
public class Hamster extends ProbabilisticAnimal {

    private final List<Vector2D> deadPaths;

    /**
     * Constructs a hamster with a starting position.
     *
     * @param position Starting position of the hamster in the labyrinth
     */
    public Hamster(Vector2D position) {
        super(position);
        this.deadPaths = new ArrayList<>();
    }

    /**
     * Discard directions known to lead to dead ends.
     *
     * @param choices A set of choices
     * @return A set of smart choices
     */
    private Set<Direction> excludeDeadPaths(Set<Direction> choices) {
        return choices
                .stream()
                .filter(dir -> !this.deadPaths.contains(this.getPosition().addDirectionTo(dir)))
                .collect(Collectors.toSet());
    }

    /**
     * Moves without retracing directly its steps and by avoiding the dead-ends
     * it learns during its journey.
     */
    @Override
    public Direction move(Set<Direction> choices) {
        Set<Direction> smartChoices = this.excludeDeadPaths(choices);
        if (smartChoices.size() == 1) this.deadPaths.add(this.getPosition()); // dead end
        return super.move(smartChoices);
    }

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

}