-
Notifications
You must be signed in to change notification settings - Fork 10
/
Maze.razor
430 lines (396 loc) · 14.2 KB
/
Maze.razor
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
@page "/maze"
<div @onkeydown="@OnKeyDown" tabindex="0">
<h3>Maze</h3>
<div class="source-code-badge">
<a href="https://github.com/ZacharyPatten/dotnet-blazor-games/blob/main/dotnet-blazor-games/Pages/Maze.razor" alt="Go To Source Code">
<img title="Go To Source Code" alt="Go To Source Code" src="https://img.shields.io/badge/source-code-black?logo=github&style=flat">
</a>
</div>
<div class="row">
@((MarkupString)MazeRender)
</div>
<div class="row">
<div class="controls">
<button class="btn btn-primary" @onclick="() => { TryMove(Direction.Left); StateHasChanged(); }">←</button>
<button class="btn btn-primary" @onclick="() => { TryMove(Direction.Right); StateHasChanged(); }">→</button>
<button class="btn btn-primary" @onclick="() => { TryMove(Direction.Up); StateHasChanged(); }">↑</button>
<button class="btn btn-primary" @onclick="() => { TryMove(Direction.Down); StateHasChanged(); }">↓</button>
</div>
</div>
<div class="row controls">
<button class="btn btn-primary" @onclick="() => { Win = false; PlayerX = 0; PlayerY = 0; _currentMaze = Generate(10, 10); StateHasChanged(); }">New Maze</button>
</div>
<div class="row winmessage" style="display:@(Win ? "block" : "none")">
You Win! Press "New Maze" to play again.
</div>
<div class="alert alert-dismissible alert-secondary">
<strong>Rules:</strong>
You are the blue square, and always start in the top left. Nagivate the maze to make it to the end in the bottom right.
Keyboard inputs (←, →, ↑, ↓) are supported if you <i>click on the board</i>.
</div>
</div>
<style>
.player {
x: @(PlayerX * 3 + 1.2);
y: @(PlayerY * 3 + 1.2);
}
.controls {
margin-top: 1rem;
}
.controls button {
margin-right: .5rem;
margin-bottom: .5rem;
}
</style>
@code
{
bool Win = false;
Tile[,] _currentMaze;
Tile[,] CurrentMaze => _currentMaze ?? (_currentMaze = Generate(10, 10));
string MazeRender => RenderToSvg(CurrentMaze);
int PlayerX = 0;
int PlayerY = 0;
enum Direction
{
Up = 1,
Down = 2,
Left = 3,
Right = 4,
}
[Flags]
enum Tile
{
Null = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
Start = 16,
End = 32,
}
void OnKeyDown(KeyboardEventArgs e)
{
switch (e.Key)
{
case "ArrowLeft": TryMove(Direction.Left); break;
case "ArrowRight": TryMove(Direction.Right); break;
case "ArrowUp": TryMove(Direction.Up); break;
case "ArrowDown": TryMove(Direction.Down); break;
default: return;
}
StateHasChanged();
}
void TryMove(Direction direction)
{
if (!Win)
{
if (direction is Direction.Up && CurrentMaze[PlayerY, PlayerX].HasFlag(Tile.Up))
{
PlayerY--;
}
else if (direction is Direction.Down && CurrentMaze[PlayerY, PlayerX].HasFlag(Tile.Down))
{
PlayerY++;
}
else if (direction is Direction.Left && CurrentMaze[PlayerY, PlayerX].HasFlag(Tile.Left))
{
PlayerX--;
}
else if (direction is Direction.Right && CurrentMaze[PlayerY, PlayerX].HasFlag(Tile.Right))
{
PlayerX++;
}
if (PlayerX == CurrentMaze.GetLength(1) - 1 && PlayerY == CurrentMaze.GetLength(0) - 1)
{
Win = true;
}
}
}
#region Algorithm 1
class Node
{
internal int Row;
internal int Column;
internal bool UpExplored;
internal bool DownExplored;
internal bool LeftExplored;
internal bool RightExplored;
}
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];
Random random = new Random();
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 == 0 && start_column == 0 &&
end_row == rows - 1 && end_column == columns - 1;
bool UpOptimization(int column) => !(DefaultLocations() && column == columns - 1 || column == 0);
bool LeftOptimization(int row) => !(DefaultLocations() && row == rows - 1 || row == 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.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;
}
}
}
// Generate invalid paths (to fill in the rest of the maze)
{
var stack = new Stack<Node>();
var invalidPath = new HashSet<(int Row, int Column)>();
Tile previousMove;
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.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 == 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.Next(0, i)];
if (move.Row == node.Row + 1)
{
node.DownExplored = true;
maze[node.Row, node.Column] |= Tile.Down;
maze[move.Row, move.Column] |= previousMove = Tile.Up;
}
if (move.Row == node.Row - 1)
{
node.UpExplored = true;
maze[node.Row, node.Column] |= Tile.Up;
maze[move.Row, move.Column] |= previousMove = Tile.Down;
}
if (move.Column == node.Column - 1)
{
node.LeftExplored = true;
maze[node.Row, node.Column] |= Tile.Left;
maze[move.Row, move.Column] |= previousMove = Tile.Right;
}
if (move.Column == node.Column + 1)
{
node.RightExplored = true;
maze[node.Row, node.Column] |= Tile.Right;
maze[move.Row, move.Column] |= previousMove = 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));
previousMove = Tile.Null;
while (maze[stack.Peek().Row, stack.Peek().Column] == previousMove)
{
if (!MoveRandom())
{
Node move = stack.Pop();
Node parent = stack.Peek();
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;
}
}
}
}
}
return maze;
}
#endregion
string RenderToSvg(Tile[,] maze)
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
stringBuilder.AppendLine();
stringBuilder.AppendLine($@"<svg width=""60vmin"" height=""60vmin"" viewBox=""0 0 {maze.GetLength(0) * 3} {maze.GetLength(1) * 3}"" preserveAspectRatio=""xMinYMin meet"" xmlns=""http://www.w3.org/2000/svg"" xmlns:svg=""http://www.w3.org/2000/svg"">");
for (int i = 0; i < maze.GetLength(0); i++)
{
for (int j = 0; j < maze.GetLength(1); j++)
{
// corners
{
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""1"" x=""{i * 3 + 0}"" y=""{j * 3 + 0}""/>");
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""1"" x=""{i * 3 + 2}"" y=""{j * 3 + 0}""/>");
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""1"" x=""{i * 3 + 0}"" y=""{j * 3 + 2}""/>");
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""1"" x=""{i * 3 + 2}"" y=""{j * 3 + 2}""/>");
}
// sides
if (!maze[j, i].HasFlag(Tile.Up))
{
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""3"" height=""1"" x=""{i * 3 + 0}"" y=""{j * 3 + 0}""/>");
}
if (!maze[j, i].HasFlag(Tile.Down))
{
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""3"" height=""1"" x=""{i * 3 + 0}"" y=""{j * 3 + 2}""/>");
}
if (!maze[j, i].HasFlag(Tile.Left))
{
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""3"" x=""{i * 3 + 0}"" y=""{j * 3 + 0}""/>");
}
if (!maze[j, i].HasFlag(Tile.Right))
{
stringBuilder.AppendLine($@"{'\t'}<rect fill=""#24292e"" stroke=""#24292e"" stroke-width=""0"" width=""1"" height=""3"" x=""{i * 3 + 2}"" y=""{j * 3 + 0}""/>");
}
}
}
stringBuilder.AppendLine($@"{'\t'}<rect class=""start"" fill=""#bbb"" stroke=""#24292e"" stroke-width=""0"" width="".6"" height="".6"" x=""1.2"" y=""1.2""/>");
stringBuilder.AppendLine($@"{'\t'}<rect class=""end"" fill=""#999"" stroke=""#24292e"" stroke-width=""0"" width="".6"" height="".6"" x=""{maze.GetLength(0) * 3 - 1.8}"" y=""{maze.GetLength(1) * 3 - 1.8}""/>");
stringBuilder.AppendLine($@"{'\t'}<rect class=""player"" fill=""#7abafc"" stroke=""#24292e"" stroke-width=""0"" width="".6"" height="".6"" x=""2.2"" y=""2.2""/>");
stringBuilder.AppendLine($@"</svg>");
stringBuilder.AppendLine();
return stringBuilder.ToString();
}
}