-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathProgram.cs
622 lines (563 loc) · 17.2 KB
/
Program.cs
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//#define MazeGenertorLoop // uncomment to run the generator in a loop
//#define DebugRandomMazeGeneration // uncomment me to watch the maze being built node-by-node
//#define UsePrims // uncomment me to use an alternate algorithm for maze generation
using System;
using System.Collections.Generic;
using System.Text;
using Towel.DataStructures;
class Program
{
static void Main()
{
if (OperatingSystem.IsWindows())
{
Console.WindowHeight = 32;
}
const int rows = 8;
const int columns = 20;
static Maze.Tile[,] GenerateMaze() =>
#if UsePrims
Maze.GeneratePrims(rows, columns);
#else
Maze.Generate(rows, columns);
#endif
#if MazeGenertorLoop
while (true)
{
Maze.Tile[,] maze = GenerateMaze();
Console.Clear();
Console.WriteLine(Maze.Render(maze));
Console.WriteLine("Press Enter To Continue...");
Console.ReadLine();
}
#else
Console.CursorVisible = true;
Maze.Tile[,] maze = GenerateMaze();
Console.Clear();
Console.WriteLine(Maze.Render(maze));
Console.WriteLine();
Console.WriteLine("Maze");
Console.WriteLine("Solve the maze by using the arrow keys.");
Console.WriteLine("Press escape to quit.");
int row = 0;
int column = 0;
while (row != rows - 1 || column != columns - 1)
{
Console.SetCursorPosition(column * 3 + 1, row * 3 + 1);
switch (Console.ReadKey().Key)
{
case ConsoleKey.UpArrow:
if (maze[row, column].HasFlag(Maze.Tile.Up))
row--;
break;
case ConsoleKey.DownArrow:
if (maze[row, column].HasFlag(Maze.Tile.Down))
row++;
break;
case ConsoleKey.LeftArrow:
if (maze[row, column].HasFlag(Maze.Tile.Left))
column--;
break;
case ConsoleKey.RightArrow:
if (maze[row, column].HasFlag(Maze.Tile.Right))
column++;
break;
case ConsoleKey.Escape:
Console.Clear();
Console.Write("MMaze was closed.");
return;
}
}
Console.Clear();
Console.Write("You Win.");
#endif
}
}
public static class Maze
{
[Flags]
public enum Tile
{
Null = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
Start = 16,
End = 32,
}
#region Algorithm 1
internal class Node
{
internal int Row;
internal int Column;
internal bool UpExplored;
internal bool DownExplored;
internal bool LeftExplored;
internal bool RightExplored;
}
public static Tile[,] Generate(
int rows, int columns,
int? start_row = null, int? start_column = null,
int? end_row = null, int? end_column = null)
{
// parameter defaults
start_row ??= 0;
start_column ??= 0;
end_row ??= rows - 1;
end_column ??= columns - 1;
#region Exceptions
if (rows <= 1)
throw new ArgumentOutOfRangeException(nameof(rows));
if (columns <= 1)
throw new ArgumentOutOfRangeException(nameof(columns));
if (start_row < 0 || rows < start_row)
throw new ArgumentOutOfRangeException(nameof(start_row));
if (end_row < 0 || rows < end_row || start_row == end_row)
throw new ArgumentOutOfRangeException(nameof(end_row));
if (start_column < 0 || columns < start_column)
throw new ArgumentOutOfRangeException(nameof(start_column));
if (end_column < 0 || columns < end_column || start_column == end_column)
throw new ArgumentOutOfRangeException(nameof(end_column));
#endregion
Tile[,] maze = new Tile[rows, columns];
var directionBuffer = new (int Row, int Column)[4];
maze[start_row.Value, start_column.Value] = Tile.Start;
maze[end_row.Value, end_column.Value] = Tile.End;
// generate a valid path (so the maze is guaranteed to be solve-able)
{
var stack = new Stack<Node>();
stack.Push(new Node()
{
Row = start_row.Value,
Column = start_column.Value,
});
#region Optimizations
// optimizations to prevent the algorithm from exploring unnecessary isolations
// that will never reach the end of the maze. these currently depend on using the
// default start/end locations, but they could be improved to help with custom
// locations too. I am just lazy and didn't care enough to make a more general
// purpose algorithm...
bool DefaultLocations() =>
start_row is 0 && start_column is 0 &&
end_row == rows - 1 && end_column == columns - 1;
bool UpOptimization(int column) => !(DefaultLocations() && column == columns - 1 || column is 0);
bool LeftOptimization(int row) => !(DefaultLocations() && row == rows - 1 || row is 0);
#endregion
static bool NullOrEnd(Tile tile) => tile is Tile.Null || tile is Tile.End;
bool MoveRandom()
{
Node node = stack.Peek();
int i = 0;
// populate possible moves
if (node.Row != rows - 1 && NullOrEnd(maze[node.Row + 1, node.Column]) && !node.DownExplored)
directionBuffer[i++] = (node.Row + 1, node.Column);
if (node.Row != 0 && NullOrEnd(maze[node.Row - 1, node.Column]) && !node.UpExplored && UpOptimization(node.Column))
directionBuffer[i++] = (node.Row - 1, node.Column);
if (node.Column != 0 && NullOrEnd(maze[node.Row, node.Column - 1]) && !node.LeftExplored && LeftOptimization(node.Row))
directionBuffer[i++] = (node.Row, node.Column - 1);
if (node.Column != columns - 1 && NullOrEnd(maze[node.Row, node.Column + 1]) && !node.RightExplored)
directionBuffer[i++] = (node.Row, node.Column + 1);
// if no possibilities return false
if (i is 0)
{
return false;
}
// get a random move from the possibilities
var move = directionBuffer[Random.Shared.Next(0, i)];
// mark the move as explored
if (move.Row == node.Row + 1)
{
node.DownExplored = true;
maze[node.Row, node.Column] |= Tile.Down;
maze[move.Row, move.Column] |= Tile.Up;
}
if (move.Row == node.Row - 1)
{
node.UpExplored = true;
maze[node.Row, node.Column] |= Tile.Up;
maze[move.Row, move.Column] |= Tile.Down;
}
if (move.Column == node.Column - 1)
{
node.LeftExplored = true;
maze[node.Row, node.Column] |= Tile.Left;
maze[move.Row, move.Column] |= Tile.Right;
}
if (move.Column == node.Column + 1)
{
node.RightExplored = true;
maze[node.Row, node.Column] |= Tile.Right;
maze[move.Row, move.Column] |= Tile.Left;
}
stack.Push(new Node()
{
Row = move.Row,
Column = move.Column,
});
// return the move
return true;
}
while (stack.Peek().Row != end_row || stack.Peek().Column != end_column)
{
if (!MoveRandom())
{
Node move = stack.Pop();
maze[move.Row, move.Column] = Tile.Null;
Node parent = stack.Peek();
if (move.Row == parent.Row - 1) maze[parent.Row, parent.Column] &= ~Tile.Up;
if (move.Row == parent.Row + 1) maze[parent.Row, parent.Column] &= ~Tile.Down;
if (move.Column == parent.Column + 1) maze[parent.Row, parent.Column] &= ~Tile.Right;
if (move.Column == parent.Column - 1) maze[parent.Row, parent.Column] &= ~Tile.Left;
}
#if DebugRandomMazeGeneration
Console.Clear();
Console.WriteLine(Render(maze));
Console.WriteLine("Press Enter To Continue...");
Console.ReadLine();
#endif
}
}
// Generate invalid paths (to fill in the rest of the maze)
{
var stack = new Stack<Node>();
var invalidPath = new HashSet<(int Row, int Column)>();
var previousMoves = new Stack<Tile>();
int CountNulls()
{
int count = 0;
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
if (maze[row, column] is Tile.Null)
count++;
return count;
}
(int Row, int Column)? GetRandomNull(int? nullCount = null)
{
int nullCountInt = nullCount ?? CountNulls();
// if no Tile.Null's, return null
if (nullCountInt <= 0) return null;
// nulls exist, get a random one
int index = Random.Shared.Next(0, nullCountInt + 1);
(int, int) @null = default;
for (int row = 0; row < rows && index > 0; row++)
for (int column = 0; column < columns && index > 0; column++)
if (maze[row, column] is Tile.Null && --index is 0)
@null = (row, column);
return @null;
}
bool MoveRandom()
{
Node node = stack.Peek();
int i = 0;
if (node.Row != rows - 1 && !invalidPath.Contains((node.Row + 1, node.Column)) && !node.DownExplored)
directionBuffer[i++] = (node.Row + 1, node.Column);
if (node.Row != 0 && !invalidPath.Contains((node.Row - 1, node.Column)) && !node.UpExplored)
directionBuffer[i++] = (node.Row - 1, node.Column);
if (node.Column != 0 && !invalidPath.Contains((node.Row, node.Column - 1)) && !node.LeftExplored)
directionBuffer[i++] = (node.Row, node.Column - 1);
if (node.Column != columns - 1 && !invalidPath.Contains((node.Row, node.Column + 1)) && !node.RightExplored)
directionBuffer[i++] = (node.Row, node.Column + 1);
if (i is 0)
return false;
var move = directionBuffer[Random.Shared.Next(0, i)];
if (move.Row == node.Row + 1)
{
node.DownExplored = true;
maze[node.Row, node.Column] |= Tile.Down;
maze[move.Row, move.Column] |= Tile.Up;
previousMoves.Push(Tile.Up);
}
if (move.Row == node.Row - 1)
{
node.UpExplored = true;
maze[node.Row, node.Column] |= Tile.Up;
maze[move.Row, move.Column] |= Tile.Down;
previousMoves.Push(Tile.Down);
}
if (move.Column == node.Column - 1)
{
node.LeftExplored = true;
maze[node.Row, node.Column] |= Tile.Left;
maze[move.Row, move.Column] |= Tile.Right;
previousMoves.Push(Tile.Right);
}
if (move.Column == node.Column + 1)
{
node.RightExplored = true;
maze[node.Row, node.Column] |= Tile.Right;
maze[move.Row, move.Column] |= Tile.Left;
previousMoves.Push(Tile.Left);
}
stack.Push(new Node()
{
Row = move.Row,
Column = move.Column,
});
invalidPath.Add((node.Row, node.Column));
return true;
}
(int Row, int Column)? nullStart;
while ((nullStart = GetRandomNull()).HasValue)
{
stack.Clear();
invalidPath.Clear();
stack.Push(new Node()
{
Row = nullStart.Value.Row,
Column = nullStart.Value.Column,
});
invalidPath.Add((nullStart.Value.Row, nullStart.Value.Column));
previousMoves.Clear();
previousMoves.Push(Tile.Null);
while (maze[stack.Peek().Row, stack.Peek().Column] == previousMoves.Peek())
{
if (!MoveRandom())
{
Node move = stack.Pop();
Node parent = stack.Peek();
previousMoves.Pop();
if (move.Row == parent.Row - 1)
{
maze[move.Row, move.Column] &= ~Tile.Down;
maze[parent.Row, parent.Column] &= ~Tile.Up;
}
if (move.Row == parent.Row + 1)
{
maze[move.Row, move.Column] &= ~Tile.Up;
maze[parent.Row, parent.Column] &= ~Tile.Down;
}
if (move.Column == parent.Column + 1)
{
maze[move.Row, move.Column] &= ~Tile.Left;
maze[parent.Row, parent.Column] &= ~Tile.Right;
}
if (move.Column == parent.Column - 1)
{
maze[move.Row, move.Column] &= ~Tile.Right;
maze[parent.Row, parent.Column] &= ~Tile.Left;
}
}
#if DebugRandomMazeGeneration
Console.Clear();
Console.WriteLine(Render(maze));
Console.WriteLine("Press Enter To Continue...");
Console.ReadLine();
#endif
}
}
}
return maze;
}
#endregion
#region Algorithm 2 (Prims)
public class Graph
{
public class Node
{
public int OwnIndex { get; }
public List<int> Connections { get; }
public List<double> Costs { get; }
public void Add(int other, double cost)
{
Connections.Add(other);
Costs.Add(cost);
}
public Node(int ownIndex)
{
OwnIndex = ownIndex;
Connections = new List<int>();
Costs = new List<double>();
}
}
public Node[] Nodes { get; }
public Graph(Node[] nodes)
{
Nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
}
public static Maze.Tile[,] ConvertToGrid(Graph graph, int rows, int columns, Func<int, int, int> index, int start_row, int start_column, int end_row, int end_column)
{
var tiles = new Maze.Tile[rows, columns];
foreach (var node in graph.Nodes)
{
if (node == null)
continue;
(int, int) Unpack(int i) => (i % rows, i / rows);
var (row, col) = Unpack(node.OwnIndex);
// directional
if (node.Connections.Contains(index(row - 1, col)))
{
tiles[row, col] |= Maze.Tile.Up;
tiles[row - 1, col] |= Maze.Tile.Down;
}
if (node.Connections.Contains(index(row + 1, col)))
{
tiles[row, col] |= Maze.Tile.Down;
tiles[row + 1, col] |= Maze.Tile.Up;
}
if (node.Connections.Contains(index(row, col - 1)))
{
tiles[row, col] |= Maze.Tile.Left;
tiles[row, col - 1] |= Maze.Tile.Right;
}
if (node.Connections.Contains(index(row, col + 1)))
{
tiles[row, col] |= Maze.Tile.Right;
tiles[row, col + 1] |= Maze.Tile.Left;
}
// start/end
if (row == start_row && col == start_column)
{
tiles[row, col] |= Maze.Tile.Start;
}
if (row == end_row && col == end_column)
{
tiles[row, col] |= Maze.Tile.End;
}
}
return tiles;
}
}
public static Tile[,] GeneratePrims(
int rows, int columns,
int? start_row = null, int? start_column = null,
int? end_row = null, int? end_column = null)
{
start_row ??= 0;
start_column ??= 0;
end_row ??= rows - 1;
end_column ??= columns - 1;
var grid = new Graph.Node[rows * columns];
int Index(int row, int col) => row + rows * col;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
var n = new Graph.Node(Index(row, col));
if (row + 1 < rows)
{
n.Add(Index(row + 1, col), Random.Shared.NextDouble());
}
if (row - 1 >= 0)
{
n.Add(Index(row - 1, col), Random.Shared.NextDouble());
}
if (col + 1 < columns)
{
n.Add(Index(row, col + 1), Random.Shared.NextDouble());
}
if (col - 1 >= 0)
{
n.Add(Index(row, col - 1), Random.Shared.NextDouble());
}
grid[Index(row, col)] = n;
}
}
var graph = new Graph(grid);
#if DebugRandomMazeGeneration
Console.Clear();
Console.WriteLine(Maze.Render(Graph.ConvertToGrid(graph, rows, columns, Index, start_row.Value, start_column.Value, end_row.Value, end_column.Value)));
Console.WriteLine("Press Enter To Continue...");
Console.ReadLine();
var res = SimplePrims(graph, rows, columns, Index, start_row.Value, start_column.Value, end_row.Value, end_column.Value);
#else
var res = SimplePrims(graph);
#endif
return Graph.ConvertToGrid(res, rows, columns, Index, start_row.Value, start_column.Value, end_row.Value, end_column.Value);
}
private readonly struct TwoWayConnection : IComparable<TwoWayConnection>
{
public readonly int IndexA;
public readonly int IndexB;
public readonly double Cost;
public TwoWayConnection(int indexA, int indexB, double cost)
{
IndexA = indexA;
IndexB = indexB;
Cost = cost;
}
public int CompareTo(TwoWayConnection other) => other.Cost.CompareTo(Cost); // inversed because of how the heap works
}
public static Graph SimplePrims(Graph graph
#if DebugRandomMazeGeneration
, int rows, int columns, Func<int, int, int> index, int start_row, int start_column, int end_row, int end_column
#endif
)
{
var newGraph = new Graph(new Graph.Node[graph.Nodes.Length]);
var nodes = graph.Nodes;
var current = nodes[0];
newGraph.Nodes[0] = new Graph.Node(0);
var heap = HeapArray.New<TwoWayConnection>();
while (true)
{
for (int i = 0; i < current.Connections.Count; i++)
{
heap.Enqueue(new TwoWayConnection(current.OwnIndex, current.Connections[i], current.Costs[i]));
}
TwoWayConnection c;
do
{
if (heap.Count is 0)
{
return newGraph;
}
c = heap.Dequeue();
}
while (newGraph.Nodes[c.IndexB] != null);
newGraph.Nodes[c.IndexA].Add(c.IndexB, c.Cost);
newGraph.Nodes[c.IndexB] = new Graph.Node(c.IndexB);
current = graph.Nodes[c.IndexB];
newGraph.Nodes[c.IndexB].Add(c.IndexA, c.Cost);
#if DebugRandomMazeGeneration
Console.Clear();
Console.WriteLine(Maze.Render(Graph.ConvertToGrid(newGraph, rows, columns, index, start_row, start_column, end_row, end_column)));
Console.WriteLine("Press Enter To Continue...");
Console.ReadLine();
#endif
}
}
#endregion
public static string Render(Tile[,] maze)
{
static char Center(Tile tile) =>
tile.HasFlag(Tile.Start) ? 'S' :
tile.HasFlag(Tile.End) ? 'E' :
/* default */ ' ';
static char Side(Tile tile, Tile flag) =>
tile.HasFlag(flag) ? ' ' : '█';
static char[,] RenderTile(Tile tile) => new char[,]
{
{ '█', Side(tile, Tile.Up), '█' },
{ Side(tile, Tile.Left), Center(tile), Side(tile, Tile.Right) },
{ '█', Side(tile, Tile.Down), '█' },
};
int rows = maze.GetLength(0);
int columns = maze.GetLength(1);
char[,][,] rendered = new char[rows, columns][,];
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
rendered[row, column] = RenderTile(maze[row, column]);
}
}
int rowsX3 = rows * 3;
int columnsX3 = columns * 3;
StringBuilder stringBuilder = new();
for (int row = 0; row < rowsX3; row++)
{
for (int column = 0; column < columnsX3; column++)
{
int tileRow = row / 3;
int tileColumn = column / 3;
int renderRow = row % 3;
int renderColumn = column % 3;
stringBuilder.Append(rendered[tileRow, tileColumn][renderRow, renderColumn]);
}
stringBuilder.AppendLine();
}
string render = stringBuilder.ToString();
return render;
}
}