-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmazesolver.d
More file actions
471 lines (335 loc) · 8.18 KB
/
mazesolver.d
File metadata and controls
471 lines (335 loc) · 8.18 KB
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
import std.conv;
import std.stdio;
import std.math;
import std.datetime;
import std.datetime.stopwatch : StopWatch;
import core.time;
import std.algorithm;
import std.traits;
import gui;
import heap.binary;
import heap.pairing;
class MazeSolver {
public Gui gui;
@property Coord2D startCoord() {
return maze.start;
}
@property Coord2D startCoord(Coord2D c) {
return maze.start = c;
}
@property Coord2D endCoord() {
return maze.end;
}
@property Coord2D endCoord(Coord2D c) {
return maze.end = c;
}
void stop() {
wantStop = true;
}
void run() {
StopWatch timer;
Duration dur;
real dursec;
wantStop = false;
initMaze();
timer.start();
solveMaze();
timer.stop();
dur = cast(Duration)timer.peek;
dursec = dur.total!"hnsecs" / cast(real)(seconds(1).total!"hnsecs");
if (wantStop)
gui.displayMessage("Stopped after " ~ to!string(dursec) ~ " seconds", 0);
else
gui.displayMessage("Done in " ~ to!string(dursec) ~ " seconds", 0);
/* One last screen update. */
gui.updateDisplay(true, false);
}
private void tracePath() {
Coord2D here;
here = maze.end;
gui.pixelPath(here);
while (here != maze.start) {
here = maze.grid[here.y][here.x].prev;
gui.pixelPath(here);
}
}
private bool dirIsDiagonal(Coord2DDir dir) {
final switch (dir) {
case Coord2DDir.NORTHEAST:
case Coord2DDir.NORTHWEST:
case Coord2DDir.SOUTHWEST:
case Coord2DDir.SOUTHEAST:
return true;
case Coord2DDir.EAST:
case Coord2DDir.NORTH:
case Coord2DDir.WEST:
case Coord2DDir.SOUTH:
return false;
}
}
private Coord2D move(Coord2D coord, Coord2DDir dir) {
final switch (dir) {
case Coord2DDir.EAST:
coord.x++;
break;
case Coord2DDir.NORTHEAST:
coord.x++;
coord.y--;
break;
case Coord2DDir.NORTH:
coord.y--;
break;
case Coord2DDir.NORTHWEST:
coord.x--;
coord.y--;
break;
case Coord2DDir.WEST:
coord.x--;
break;
case Coord2DDir.SOUTHWEST:
coord.x--;
coord.y++;
break;
case Coord2DDir.SOUTH:
coord.y++;
break;
case Coord2DDir.SOUTHEAST:
coord.x++;
coord.y++;
break;
}
return coord;
}
private bool canMove(Coord2D coord, Coord2DDir dir) {
/* The coordinates are unsigned and may wrap. */
static assert(isUnsigned!(typeof(coord.x)));
static assert(isUnsigned!(typeof(coord.y)));
Coord2D c = move(coord, dir);
/* Since the coordinate wrap instead of going negative, the
* test is simpler. */
if (c.y >= maze.grid.length)
return false;
if (c.x >= maze.grid[c.y].length)
return false;
if (maze.grid[c.y][c.x].isWall)
return false;
/* This test actually work for all 8 directions. */
if (maze.grid[c.y][coord.x].isWall ||
maze.grid[coord.y][c.x].isWall)
return false;
return true;
}
/* Insert the neighbor cell in the heap if needed. */
private void addNeighbor(Coord2D me, Coord2D other, HeapCoord2D pending, uint dist) {
const Node* nme = &maze.grid[me.y][me.x];
Node* nother = &maze.grid[other.y][other.x];
if (nother.dist <= nme.dist + dist)
return;
assert(nother.state != NodeVisitState.VISITED, "Node already visited");
nother.dist = nme.dist + dist;
nother.prev = me;
if (nother.state == NodeVisitState.UNVISITED) {
nother.addtime = maze.time++;
nother.state = NodeVisitState.PENDING;
pending.insert(other);
gui.pixelPending(other);
} else {
pending.update(other);
}
}
private void solveMaze() {
bool cmpcoord(Coord2D a, Coord2D b) {
Node na, nb;
na = maze.grid[a.y][a.x];
nb = maze.grid[b.y][b.x];
if (na.dist + na.heuristic != nb.dist + nb.heuristic)
return na.dist + na.heuristic > nb.dist + nb.heuristic;
return na.addtime < nb.addtime;
}
alias BinaryHeapCoord2D = BinaryHeap!(Coord2D, cmpcoord);
alias PairingHeapCoord2D = PairingHeap!(Coord2D, cmpcoord);
bool solved = false;
HeapCoord2D pending = new PairingHeapCoord2D();
pending.insert(maze.start);
maze.grid[maze.start.y][maze.start.x].dist = 0;
maze.grid[maze.start.y][maze.start.x].state = NodeVisitState.PENDING;
while (!pending.empty && !wantStop) {
Coord2D me = pending.removeAny();
if (me == maze.end) {
solved = true;
break;
}
maze.grid[me.y][me.x].state = NodeVisitState.VISITED;
foreach (dir; Coord2DDir.min .. Coord2DDir.max + 1) {
Coord2DDir d = cast(Coord2DDir)dir;
Coord2D other;
if (!canMove(me, d))
continue;
other = move(me, d);
// sqrt(2) is 1.4142135623
if (dirIsDiagonal(d))
addNeighbor(me, other, pending, 14);
else
addNeighbor(me, other, pending, 10);
}
gui.pixelVisited(me);
gui.handlePendingEvents();
gui.updateDisplay();
}
if (solved)
tracePath();
}
private uint distance(Coord2D a, Coord2D b) {
uint dx = abs(cast(int)a.x - cast(int)b.x);
uint dy = abs(cast(int)a.y - cast(int)b.y);
return 14 * min(dx, dy) + 10 * (max(dx, dy) - min(dx, dy));
}
private void initMaze() {
Color cs, ce;
Coord2D size;
cs = gui.pixelColor(maze.start);
ce = gui.pixelColor(maze.end);
assert(cs == ce, "Pixels are not the same color");
size = gui.imageSize();
maze.grid.length = size.y;
foreach (y; 0 .. size.y) {
maze.grid[y].length = size.x;
foreach (x; 0 .. size.x) {
Coord2D c = Coord2D(x, y);
maze.grid[y][x].isWall = (gui.pixelColor(c) != cs);
maze.grid[y][x].heuristic = distance(c, maze.end);
}
}
}
private alias HeapCoord2D = Heap!Coord2D;
private enum NodeVisitState : ubyte {
UNVISITED,
PENDING,
VISITED
}
private enum Coord2DDir {
EAST, NORTHEAST, NORTH, NORTHWEST, WEST, SOUTHWEST, SOUTH, SOUTHEAST
}
private struct Node {
bool isWall;
Coord2D prev;
uint dist = uint.max;
uint heuristic;
NodeVisitState state = NodeVisitState.UNVISITED;
uint addtime;
}
private struct Maze {
Node[][] grid;
Coord2D start;
Coord2D end;
uint time;
}
private Maze maze;
private bool wantStop;
}
class MainCoordinator : GuiCallbacks {
public MazeSolver solver;
public Gui gui;
/* GUI Callbacks */
void startCoord(Coord2D coord) {
string msg;
hasStart = true;
solver.startCoord = coord;
msg = "Start: " ~ to!string(coord.x);
msg ~= ", " ~ to!string(coord.y);
gui.displayMessage(msg);
gui.updateDisplay(true);
}
void endCoord(Coord2D coord) {
string msg;
hasEnd = true;
solver.endCoord = coord;
msg = "Destination: " ~ to!string(coord.x);
msg ~= ", " ~ to!string(coord.y);
gui.displayMessage(msg);
gui.updateDisplay(true);
}
void start() {
if (!hasStart || !hasEnd || running) {
help();
return;
}
wantStart = true;
}
void stop() {
solver.stop();
}
void quit() {
solver.stop();
wantQuit = true;
}
void unhandledKey() {
help();
}
private void help() {
if (disabled) {
if (running)
gui.displayMessage("Press ESC to stop or Q to quit");
else
gui.displayMessage("Press Q to quit");
} else {
if (!hasStart)
gui.displayMessage("Press S");
else if (!hasEnd)
gui.displayMessage("Press E");
else
gui.displayMessage("Press SPACE or ENTER");
}
gui.updateDisplay(true);
}
/* Only public method of MainCoordinator */
int run(string[] args) {
string filename;
if (args.length < 2) {
stderr.writefln("usage: %s image", args[0]);
return 1;
}
filename = args[1];
gui.windowTitle = "Maze Solver";
gui.loadImage(filename);
gui.start();
while (!wantStart && !wantQuit) {
gui.updateDisplay(true);
gui.handleOneEventWait();
}
if (wantQuit)
return 0;
gui.disable();
running = true;
disabled = true;
gui.displayMessage("Searching...");
gui.updateDisplay(true);
solver.run();
running = false;
gui.handlePendingEventsWait();
gui.finish();
return 0;
}
private bool hasStart;
private bool hasEnd;
private bool wantStart;
private bool wantQuit;
private bool running;
private bool disabled;
}
int main(string[] args) {
SDLGui gui;
MazeSolver solver;
MainCoordinator coordinator;
/* Instanciate the components. */
gui = new SDLGui();
solver = new MazeSolver();
coordinator = new MainCoordinator();
/* Connect the components. */
solver.gui = gui;
coordinator.solver = solver;
coordinator.gui = gui;
gui.callbacks = coordinator;
/* Run the main components. */
return coordinator.run(args);
}