summaryrefslogtreecommitdiff
path: root/src/ch/epfl/maze/simulation/MazeSimulation.java
blob: 02883530dddd5431f26a78764e8b75468692ca12 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package ch.epfl.maze.simulation;

import ch.epfl.maze.graphics.Animation;
import ch.epfl.maze.physical.Animal;
import ch.epfl.maze.physical.Maze;
import ch.epfl.maze.physical.World;
import ch.epfl.maze.util.Action;
import ch.epfl.maze.util.Direction;
import ch.epfl.maze.util.Vector2D;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Simulation of a maze solver. Handles the next move of each animal, as well as
 * the animation by notifying the changes to it. The simulation finishes when
 * every animal has found the exit.
 *
 * @author EPFL
 */
public final class MazeSimulation implements Simulation {

    /* limit to the step counter, over which the animals are considered lost */
    public static final int COUNTER_LIMIT = 10000;

    /* simulation components */
    private Maze mMaze;
    private Map<Integer, List<Animal>> mArrivalTimes;
    private int mStepCounter;

    /**
     * Constructs a simulation with a {@code Maze} to simulate.
     *
     * @param maze The maze to simulate
     */
    public MazeSimulation(Maze maze) {
        mMaze = maze;
        mArrivalTimes = new TreeMap<Integer, List<Animal>>();
        mStepCounter = 0;
    }

    @Override
    public void move(Animation listener) {
        if (isOver()) {
            return;
        }

        // increments counter
        mStepCounter++;

        // if counter exceeded limit, it considers animals lost
        if (mStepCounter > COUNTER_LIMIT) {
            List<Animal> animals = mMaze.getAnimals();
            List<Animal> lostAnimals = new LinkedList<Animal>();
            for (Animal animal : animals) {
                mMaze.removeAnimal(animal);
                lostAnimals.add(animal);
            }

            mArrivalTimes.put(Integer.MAX_VALUE, lostAnimals); // infinite
            return;
        }

        // asks animals to move
        moveAnimals(listener);

        // notifies animation that all the changes are done
        if (listener != null) {
            listener.doneUpdating();
        }
    }

    @Override
    public boolean isOver() {
        return mMaze.isSolved();
    }

    @Override
    public World getWorld() {
        return mMaze;
    }

    @Override
    public int getSteps() {
        return mStepCounter;
    }

    public Map<Integer, List<Animal>> getArrivalTimes() {
        return new TreeMap<Integer, List<Animal>>(mArrivalTimes);
    }

    public String getRecordTable() {
        String recordTable = "";
        int position = 1;
        for (Map.Entry<Integer, List<Animal>> entry : mArrivalTimes.entrySet()) {
            // only returns the 10 first
            if (position > 10) {
                return recordTable;
            }

            for (Animal animal : entry.getValue()) {
                if (entry.getKey() == Integer.MAX_VALUE) {
                    recordTable += "-- ";
                    recordTable += animal.getClass().getSimpleName();
                    recordTable += " - never finished\n";
                } else {
                    recordTable += position + ". ";
                    recordTable += animal.getClass().getSimpleName();
                    recordTable += " - " + entry.getKey() + " steps\n";
                }
            }
            position += entry.getValue().size();
        }

        return recordTable;
    }

    @Override
    public void restart() {
        mMaze.reset();
        mArrivalTimes.clear();
        mStepCounter = 0;
    }

    @Override
    public void stop() {
        List<Animal> forgottenAnimals = new LinkedList<Animal>();
        for (Animal animal : mMaze.getAnimals()) {
            forgottenAnimals.add(animal);
            mMaze.removeAnimal(animal);
        }
        mArrivalTimes.put(Integer.MAX_VALUE, forgottenAnimals);
    }

    /**
     * Moves the animals in the maze.
     *
     * @param listener The listener to which the function will notify the changes
     *                 (can be null)
     */
    private void moveAnimals(Animation listener) {
        List<Animal> animals = mMaze.getAnimals();
        for (int i = 0; i < animals.size(); i++) {
            Animal animal = animals.get(i);
            Vector2D position = animal.getPosition();
            Direction[] choices = mMaze.getChoices(position);

            // tries to make animal move
            Direction choice;
            try {
                choice = animal.move(choices);
                if (!animal.getPosition().equals(position)) {
                    System.err.println("Error : Animal position changed while choosing direction.");
                    System.err.println("\tDid you call setPosition(Vector2D) or update(Direction) ?\n");
                    animal.setPosition(position);
                    choice = null;
                }
            } catch (Exception E) {
                System.err.print("Exception occurred while moving animals: ");
                E.printStackTrace();
                choice = null;
            }

            // if animal could move
            if (choice != null) {
                Vector2D futurePosition = animal.getPosition();
                futurePosition = futurePosition.addDirectionTo(choice);

                int x = futurePosition.getX();
                int y = futurePosition.getY();


                if (mMaze.isFree(x, y)) {
                    // asks animation to draw the action of the animal
                    if (listener != null) {
                        Action action = new Action(choice, true);
                        listener.update(animal, i, action);
                    }

                    // if at the end of the maze
                    if (mMaze.getTile(x, y) == World.EXIT) {
                        mMaze.removeAnimal(animal);

                        // records arrival time
                        if (mArrivalTimes.get(mStepCounter) == null) {
                            mArrivalTimes.put(mStepCounter, new LinkedList<Animal>());
                        }
                        mArrivalTimes.get(mStepCounter).add(animal);
                    } else {
                        animal.update(choice);
                    }
                } else if (listener != null) {
                    // asks animation to draw an interrupted movement
                    Action action = new Action(choice, false);
                    listener.update(animal, i, action);
                }

            } else if (listener != null) {
                // asks animation to draw a confused animal
                Action action = new Action(Direction.NONE, false);
                listener.update(animal, i, action);
            }
        }
    }

}