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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
|
package ch.epfl.maze.graphics;
import ch.epfl.maze.physical.World;
import ch.epfl.maze.simulation.Simulation;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Handles the display of a {@code Simulation} on a window.
*
* @author EPFL
*/
public final class Display implements Runnable {
/* constants */
public static final Color BACKGROUND_COLOR = Color.GRAY;
public static final int SQUARE_SIZE = 42;
public static final int BUFFERS_NUMBER = 2;
public static final int MAX_SPEED = 32;
public static final int DEFAULT_SPEED = 2;
public static final int MIN_SPEED = 1;
public static final int ANIMATION_SLEEP = 10;
/* lock for mutual exclusion between human interactions and display */
private final Object mLock = new Object();
/* simulation and animation handlers */
private final Simulation mSimulation;
private final Animation mAnimation;
private volatile float mSpeed;
/* actual window frame and canvas */
private JFrame mFrame;
private JMenuBar mMenuBar;
private Canvas mCanvas;
/* drawing buffers */
private BufferStrategy mStrategy;
private Map<Integer, BufferedImage> mTiles;
/* control variables */
private boolean mRunning;
private boolean mPaused;
private boolean mShowGrid;
private boolean mDebug;
private boolean mFinished;
/**
* Constructs a {@code Display} that will display a simulation.
*
* @param simulation A {@code Simulation} to display
*/
public Display(Simulation simulation) {
// sanity check
if (simulation == null) {
throw new IllegalArgumentException("Simulation must be defined.");
}
if (simulation.getWorld() == null) {
throw new IllegalArgumentException("World in Simulation must be defined.");
}
// initiates instances
mSimulation = simulation;
mAnimation = new Animation(simulation.getWorld().getAnimals());
mSpeed = DEFAULT_SPEED;
// default control variables
mRunning = true;
mPaused = false;
mShowGrid = false;
mDebug = false;
mFinished = false;
// creates menu
createMenu();
// creates canvas
createCanvas();
// creates window
createWindow();
// sets canvas and menu on frame
mFrame.setJMenuBar(mMenuBar);
mFrame.add(mCanvas);
mFrame.pack();
mFrame.setLocationRelativeTo(null);
// creates buffer strategy
mCanvas.createBufferStrategy(BUFFERS_NUMBER);
mStrategy = mCanvas.getBufferStrategy();
// loads images of tiles
mTiles = new HashMap<Integer, BufferedImage>();
try {
mTiles.put(World.FREE, ImageIO.read(new File("img/tiles/free.png")));
mTiles.put(World.WALL, ImageIO.read(new File("img/tiles/wall.png")));
mTiles.put(World.START, ImageIO.read(new File("img/tiles/start.png")));
mTiles.put(World.EXIT, ImageIO.read(new File("img/tiles/exit.png")));
mTiles.put(World.NOTHING, ImageIO.read(new File("img/tiles/nothing.png")));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
mFrame.setVisible(true);
mainLoop();
mFrame.dispose();
}
/**
* Sets the debug control.
*
* @param debug The new debug value
*/
public void setDebug(boolean debug) {
mDebug = debug;
mShowGrid = debug;
createMenu();
mFrame.setJMenuBar(mMenuBar);
}
/**
* Creates frame window.
*/
private void createWindow() {
// actual window
mFrame = new JFrame("Maze solver simulation");
// redefines closing operation
mFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
mFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
synchronized (mLock) {
mRunning = false;
}
}
});
// sets up various options to make it look good
mFrame.setIgnoreRepaint(false);
mFrame.setBackground(BACKGROUND_COLOR);
mFrame.setFocusable(false);
mFrame.setFocusTraversalKeysEnabled(false);
mFrame.setResizable(false);
System.setProperty("sun.awt.noerasebackground", "true");
}
/**
* Creates canvas.
*/
private void createCanvas() {
// actual canvas
mCanvas = new Canvas();
// sets canvas size
int height = SQUARE_SIZE * mSimulation.getWorld().getHeight();
int width = SQUARE_SIZE * mSimulation.getWorld().getWidth();
mCanvas.setSize(width, height);
// sets up options to make it look good
mCanvas.setIgnoreRepaint(true);
mCanvas.setBackground(Color.BLACK);
mCanvas.setFocusable(true);
mCanvas.setFocusTraversalKeysEnabled(false);
}
/**
* Creates menu.
*/
private void createMenu() {
// creates menu bar
mMenuBar = new JMenuBar();
// creates "Maze" menu
JMenu menu = new JMenu("Simulation");
menu.setMnemonic(KeyEvent.VK_M);
menu.setToolTipText("Contains main manipulation options.");
mMenuBar.add(menu);
// creates menu items
// "Stop"
JMenuItem stopItem = new JMenuItem("Stop", KeyEvent.VK_S);
stopItem.setToolTipText("Stops simulation in its current state.");
stopItem.setAccelerator(KeyStroke.getKeyStroke("control W"));
stopItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
mSimulation.stop();
mAnimation.reset(null);
mPaused = false;
}
}
});
menu.add(stopItem);
// "Restart"
JMenuItem restart = new JMenuItem("Restart", KeyEvent.VK_R);
restart.setToolTipText("Restarts the simulation from the beginning.");
restart.setAccelerator(KeyStroke.getKeyStroke("control R"));
restart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
mSimulation.restart();
mAnimation.reset(mSimulation.getWorld().getAnimals());
mPaused = false;
mFinished = false;
}
}
});
menu.add(restart);
// ==========================================================
menu.addSeparator();
// "Pause"
final JMenuItem pauseItem = new JMenuItem(mDebug ? "Next step" :
(mPaused ? "Resume" : "Pause"), KeyEvent.VK_P);
pauseItem.setAccelerator(KeyStroke.getKeyStroke("SPACE"));
pauseItem.setToolTipText("Pauses simulation.");
pauseItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
if (mPaused) {
mPaused = false;
if (!mDebug) {
pauseItem.setText("Pause");
}
} else {
mPaused = true;
if (!mDebug) {
pauseItem.setText("Resume");
}
}
}
;
}
});
menu.add(pauseItem);
// "Debug mode"
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem("Debug mode");
debugItem.setState(mDebug);
debugItem.setMnemonic(KeyEvent.VK_M);
debugItem.setAccelerator(KeyStroke.getKeyStroke("alt G"));
debugItem.setToolTipText("Enters in debug mode, allowing to move animals step by step.");
menu.add(debugItem);
// ==========================================================
menu.addSeparator();
// "Accelerate"
final JMenuItem accelerateItem = new JMenuItem("Accelerate",
KeyEvent.VK_A);
// "Decelerate"
final JMenuItem decelerateItem = new JMenuItem("Decelerate",
KeyEvent.VK_D);
accelerateItem.setToolTipText("Increases simulation speed up to a maximum.");
decelerateItem.setToolTipText("Decreases simulation speed down to a minimum.");
accelerateItem.setAccelerator(KeyStroke.getKeyStroke('+'));
decelerateItem.setAccelerator(KeyStroke.getKeyStroke('-'));
accelerateItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
decelerateItem.setEnabled(true);
if (mSpeed < MAX_SPEED) {
mSpeed *= 2;
}
if (mSpeed == MAX_SPEED) {
accelerateItem.setEnabled(false);
}
}
}
});
decelerateItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
accelerateItem.setEnabled(true);
if (mSpeed > MIN_SPEED) {
mSpeed /= 2;
}
if (mSpeed == MIN_SPEED) {
decelerateItem.setEnabled(false);
}
}
}
});
menu.add(accelerateItem);
menu.add(decelerateItem);
// ==========================================================
menu.addSeparator();
// "Show grid"
final JCheckBoxMenuItem gridItem = new JCheckBoxMenuItem("Show grid");
gridItem.setState(mShowGrid);
gridItem.setMnemonic(KeyEvent.VK_G);
gridItem.setToolTipText("Criss-crosses the maze tiles.");
gridItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
mShowGrid = !mShowGrid;
gridItem.setState(mShowGrid);
}
}
});
debugItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
if (!mDebug) {
mDebug = true;
mShowGrid = true;
pauseItem.setText("Next Step");
} else {
mShowGrid = false;
mPaused = false;
mDebug = false;
pauseItem.setText("Pause");
}
gridItem.setState(mShowGrid);
}
}
});
menu.add(gridItem);
// "Exit"
JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_E);
exitItem.setToolTipText("Exits program.");
exitItem.setAccelerator(KeyStroke.getKeyStroke("ESCAPE"));
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (mLock) {
mRunning = false;
}
}
});
menu.add(exitItem);
}
/**
* Draws the labyrinth being simulated.
*
* @param g The graphics on which the labyrinth will be drawn
*/
private void drawLabyrinth(Graphics2D g) {
World world = mSimulation.getWorld();
BufferedImage tile;
for (int y = 0; y < world.getHeight(); y++) {
for (int x = 0; x < world.getWidth(); x++) {
// retrieves corresponding image
tile = mTiles.get(world.getTile(x, y));
if (tile == null) {
tile = mTiles.get(World.WALL);
}
int width = x * SQUARE_SIZE;
int height = y * SQUARE_SIZE;
g.drawImage(tile, width, height, mFrame);
if (mShowGrid) {
g.setColor(BACKGROUND_COLOR);
g.drawRect(width, height, SQUARE_SIZE, SQUARE_SIZE);
}
}
}
}
/**
* Draws the actual animation of the display.
*
* @param dt The elapsed time between two frames
* @param g The graphics on which the animation will be drawn
* @param width Width of graphics
* @param height Height of graphics
*/
private void drawAnimation(float dt, Graphics2D g, int width, int height) {
// clears background
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, width, height);
// paints maze
drawLabyrinth(g);
synchronized (mLock) {
// paints next animation frame
mAnimation.paint(dt, g, mFrame);
if (mAnimation.isDone()) {
// determines if maze is solved
if (!mFinished && mSimulation.isOver()) {
mFinished = true;
final String recordTable = mSimulation.getRecordTable();
// message dialog to invoke later, to prevent Display from
// crashing when a key is being held
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "Simulation is complete.\n\n" + recordTable);
}
});
mPaused = true;
} else {
if (mDebug) {
mPaused = true;
}
nextMove();
}
}
}
}
/**
* Controls the graphics environment for the animation of the display.
*
* @param dt The elapsed time between two frames
*/
private void animate(float dt) {
Graphics2D g = null;
try {
// retrieves Graphics2D from strategy
g = (Graphics2D) mStrategy.getDrawGraphics();
// sets options
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawAnimation(dt, g, mCanvas.getWidth(), mCanvas.getHeight());
} finally {
if (g != null) {
// to call at the end
g.dispose();
}
}
// displays the buffer
mStrategy.show();
}
/**
* Runs the animation main loop.
*/
private void mainLoop() {
long before = System.nanoTime();
while (mRunning) {
if (mPaused || mFinished) {
animate(0);
before = System.nanoTime();
} else {
long now = System.nanoTime();
float dt = (now - before) * 0.000000001f * mSpeed;
if (dt < 0.001f) {
dt = 0.001f;
}
animate(dt);
before = now;
}
try {
Thread.sleep(ANIMATION_SLEEP);
} catch (InterruptedException e) {
// do nothing
}
}
// paints a last frame
animate(0);
}
/**
* Computes the {@code Simulation}'s next move.
*/
private void nextMove() {
synchronized (mLock) {
if (mRunning) {
mSimulation.move(mAnimation);
}
}
}
}
|