summaryrefslogtreecommitdiff
path: root/src/ch/epfl/maze/simulation/DaedalusSimulation.java
blob: 8b60b5717d46e41e4ef04e6679439f65501a97fc (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package ch.epfl.maze.simulation;

import ch.epfl.maze.graphics.Animation;
import ch.epfl.maze.physical.*;
import ch.epfl.maze.util.Action;
import ch.epfl.maze.util.Direction;
import ch.epfl.maze.util.Vector2D;

import java.util.*;

/**
 * Simulation of a predation environment. Handles the next moves of every
 * predator and prey in a Daedalus, as well as the animation by notifying
 * changes to it. The simulation finishes when every prey has been caught.
 */

public final class DaedalusSimulation implements Simulation {

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

    /* simulation components */
    private Daedalus mDaedalus;
    private Map<Integer, List<Prey>> mArrivalTimes;
    private int mStepCounter;

    /* collision check variables */
    private Map<Prey, List<Vector2D>> mPreyMoves;
    private Map<Predator, List<Vector2D>> mPredatorMoves;

    /**
     * Constructs a simulation with a {@code Daedalus} to simulate.
     *
     * @param daedalus The daedalus to simulate
     */

    public DaedalusSimulation(Daedalus daedalus) {
        mDaedalus = daedalus;
        mArrivalTimes = new TreeMap<Integer, List<Prey>>(Collections.reverseOrder());
        mStepCounter = 0;
        mPreyMoves = new HashMap<Prey, List<Vector2D>>();
        mPredatorMoves = new HashMap<Predator, List<Vector2D>>();
    }

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

        // clears moves maps
        mPreyMoves.clear();
        mPredatorMoves.clear();

        // increments counter
        mStepCounter++;

        // if counter exceeded the limit, it considers preys safe
        if (mStepCounter > COUNTER_LIMIT) {
            List<Prey> preys = mDaedalus.getPreys();
            List<Prey> safePreys = new LinkedList<Prey>();
            for (Prey prey : preys) {
                mDaedalus.removePrey(prey);
                safePreys.add(prey);
            }

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

        // asks predators and preys to move
        movePredators(listener);
        movePreys(listener);

        // checks collisions
        checkCollisions(listener);

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

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

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

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

    @Override
    public Map<Integer, List<Animal>> getArrivalTimes() {
        TreeMap<Integer, List<Animal>> arrivalTimes = new TreeMap<Integer, List<Animal>>();
        for (Map.Entry<Integer, List<Prey>> entry : mArrivalTimes.entrySet()) {
            int time = entry.getKey();
            List<Animal> animals = new ArrayList<Animal>(entry.getValue());
            arrivalTimes.put(time, animals);
        }

        return arrivalTimes;
    }

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

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

        return recordTable;
    }

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

    @Override
    public void stop() {
        List<Prey> forgottenPreys = new LinkedList<Prey>();
        for (Prey prey : mDaedalus.getPreys()) {
            forgottenPreys.add(prey);
            mDaedalus.removePrey(prey);
        }
        mArrivalTimes.put(Integer.MIN_VALUE, forgottenPreys);
    }

    /**
     * Moves the predators in the daedalus.
     *
     * @param listener The listener to which the function will notify the changes
     *                 (can be null)
     */

    private void movePredators(Animation listener) {
        List<Predator> predators = mDaedalus.getPredators();
        for (int i = 0; i < predators.size(); i++) {
            Predator predator = predators.get(i);
            Vector2D position = predator.getPosition();
            Vector2D newPosition = position;
            Direction[] choices = mDaedalus.getChoices(position);

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

            // if predator could move
            Action action;
            if (choice != null) {
                newPosition = position.addDirectionTo(choice);

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

                if (mDaedalus.isFree(x, y)) {
                    action = new Action(choice, true);
                } else {
                    newPosition = position;
                    action = new Action(choice, false);
                    choice = Direction.NONE;
                }

                if (listener != null) {
                    // asks animation to draw corresponding action
                    listener.update(predator, i, action);
                }

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

            // records position changes to handle collisions
            List<Vector2D> moves = new ArrayList<Vector2D>();
            moves.add(position);
            moves.add(newPosition);
            mPredatorMoves.put(predator, moves);
        }
    }

    /**
     * Moves the preys in the daedalus.
     *
     * @param listener The listener to which the function will notify the changes
     *                 (can be null)
     */

    private void movePreys(Animation listener) {
        List<Prey> preys = mDaedalus.getPreys();
        Action action;
        Direction choice;
        for (int i = 0; i < preys.size(); i++) {
            Prey prey = preys.get(i);
            Vector2D position = prey.getPosition();
            Vector2D newPosition = position;
            Direction[] choices = mDaedalus.getChoices(position);

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

            // if prey could move
            if (choice != null) {
                newPosition = position.addDirectionTo(choice);

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

                if (mDaedalus.isFree(x, y)) {
                    action = new Action(choice, true);
                } else {
                    newPosition = position;
                    action = new Action(choice, false);
                    choice = Direction.NONE;
                }

                if (listener != null) {
                    // draws animation
                    listener.update(prey, i + mDaedalus.getPredators().size(), action);
                }
                prey.update(choice);
            } else {
                if (listener != null) {
                    action = new Action(Direction.NONE, false);
                    listener.update(prey, i + mDaedalus.getPredators().size(), action);
                }
            }

            // records position changes to handle collisions
            List<Vector2D> moves = new ArrayList<Vector2D>();
            moves.add(position);
            moves.add(newPosition);
            mPreyMoves.put(prey, moves);
        }
    }

    /**
     * Checks collisions between predators and preys in {@codeO(n*m)}. A collision
     * occurs if two animals land on the same tile, or when they run into each
     * other.
     * <p>
     * A special case is handled when animals run into each other. The animation
     * is notified that an animal dies between two squares.
     *
     * @param listener The listener to which the function will notify the changes
     *                 (can be null)
     */

    private void checkCollisions(Animation listener) {
        List<Predator> predators = mDaedalus.getPredators();
        List<Prey> preys = mDaedalus.getPreys();

        for (int i = 0; i < predators.size(); ++i) {
            Predator a = predators.get(i);
            List<Vector2D> aChanges = mPredatorMoves.get(a);
            for (int j = 0; j < preys.size(); ++j) {
                Prey b = preys.get(j);
                List<Vector2D> bChanges = mPreyMoves.get(b);

                // position changes for animal a
                Vector2D aOld = aChanges.get(0);
                Vector2D aNew = aChanges.get(1);
                // position changes for animal b
                Vector2D bOld = bChanges.get(0);
                Vector2D bNew = bChanges.get(1);

                // if (a.new == b.new) or (a.old == b.new and b.old == a.new)
                boolean diesInBetween = aOld.equals(bNew) && bOld.equals(aNew);
                boolean diesInPlace = aNew.equals(bNew);

                if (diesInPlace || diesInBetween) {
                    if (mDaedalus.hasPrey(b)) {
                        mDaedalus.removePrey(b);

                        // records survival time
                        if (mArrivalTimes.get(mStepCounter) == null) {
                            mArrivalTimes.put(mStepCounter, new LinkedList<Prey>());
                        }
                        mArrivalTimes.get(mStepCounter).add(b);

                        // asks animation to interrupt movement if it dies
                        // moving
                        if (listener != null && diesInBetween) {
                            listener.updateDying(j + predators.size());
                        }
                    }
                }
            }
        }
    }
}