-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.py
2374 lines (1945 loc) · 77.5 KB
/
main.py
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import random
import time
import gc
import os
import asyncio
import shutil
import warnings
from asyncio import to_thread
from datetime import datetime
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor
from asyncio import Semaphore
from functools import partial
import numpy as np
import numba as nb
from scipy.spatial import Voronoi
from skimage.morphology import skeletonize, binary_erosion
from noise import snoise2
from scipy.ndimage import label, binary_dilation
from scipy.signal import convolve2d
from skimage.morphology import thin, disk
from PIL import Image
import requests
from tqdm import tqdm
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.animation import FuncAnimation, FFMpegWriter
from matplotlib.lines import Line2D
from matplotlib.patheffects import withStroke
from matplotlib.patches import Patch, Circle, Rectangle
from heapq import heappush, heappop
from PIL import Image
warnings.filterwarnings("ignore", message=".*tight_layout.*")
# Add this line to switch to a non-interactive backend
plt.switch_backend("Agg")
# Define the URL for the Montserrat font (Regular weight)
font_url = "https://github.com/JulietaUla/Montserrat/raw/master/fonts/ttf/Montserrat-Regular.ttf"
font_filename = "Montserrat-Regular.ttf"
font_path = os.path.join("fonts", font_filename)
# Create a fonts directory if it doesn't exist
os.makedirs("fonts", exist_ok=True)
os.nice(22) # Increase the niceness value to lower the priority
# Function to download the font
def download_font(url, path):
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
with open(path, "wb") as f:
f.write(response.content)
# Download the font if it doesn't exist locally or is corrupted
try:
if not os.path.isfile(font_path) or os.path.getsize(font_path) == 0:
print("Downloading Montserrat font...")
download_font(font_url, font_path)
print("Font downloaded.")
except requests.exceptions.RequestException as e:
print(f"Error downloading the font: {e}")
raise
# Verify that the font is a valid TrueType font
try:
font_manager.fontManager.addfont(font_path)
plt.rcParams["font.family"] = "Montserrat"
print("Font loaded and set.")
except RuntimeError as e:
print(f"Error loading font: {e}")
raise
# Constants for integer coordinate encoding
BITS_PER_COORDINATE = int(math.floor(math.log2((1 << 63) - 1) / 2))
# Constants for float coordinate encoding
BITS_PER_FLOAT_SIGNIFICAND = 24
BITS_PER_FLOAT_EXPONENT = BITS_PER_COORDINATE - 1 + BITS_PER_FLOAT_SIGNIFICAND
MOST_FLOAT_COORDINATE = (1 - (1 / (1 << BITS_PER_FLOAT_SIGNIFICAND))) * (
1 << (BITS_PER_FLOAT_EXPONENT - 1)
)
LEAST_FLOAT_COORDINATE = -MOST_FLOAT_COORDINATE
class PriorityQueue:
def __init__(self, items=None, priorities=None):
if items is None:
items = []
if priorities is None:
priorities = []
self.items = items
self.priorities = priorities
self.size = len(items)
self.capacity = len(items)
def is_empty(self):
return self.size == 0
def pop(self):
if self.is_empty():
raise EmptyQueueError()
min_item = self.items[0]
self.size -= 1
if self.size > 0:
last_item = self.items[self.size]
self.items[0] = last_item
self.priorities[0] = self.priorities[self.size]
self._heapify(0)
return min_item
def insert(self, item, priority):
if self.size >= self.capacity:
self._grow()
if self.size < len(self.items):
self.items[self.size] = item
self.priorities[self.size] = priority
else:
self.items.append(item)
self.priorities.append(priority)
self._improve_key(self.size)
self.size += 1
def _grow(self):
new_size = self.new_capacity(self.capacity)
self.capacity = new_size
self.items.extend([None] * (new_size - len(self.items)))
self.priorities.extend([float("inf")] * (new_size - len(self.priorities)))
@staticmethod
def new_capacity(current_capacity):
return current_capacity + (current_capacity >> 1)
def _heapify(self, i):
smallest = i
l = 2 * i + 1 # noqa: E741
r = 2 * i + 2
if l < self.size and self.priorities[l] < self.priorities[smallest]:
smallest = l
if r < self.size and self.priorities[r] < self.priorities[smallest]:
smallest = r
if smallest != i:
self.items[i], self.items[smallest] = self.items[smallest], self.items[i]
self.priorities[i], self.priorities[smallest] = (
self.priorities[smallest],
self.priorities[i],
)
self._heapify(smallest)
def _improve_key(self, i):
while i > 0 and self.priorities[(i - 1) // 2] > self.priorities[i]:
parent = (i - 1) // 2
self.items[i], self.items[parent] = self.items[parent], self.items[i]
self.priorities[i], self.priorities[parent] = (
self.priorities[parent],
self.priorities[i],
)
i = parent
class EmptyQueueError(Exception):
"""Raised when an operation depends on a non-empty queue."""
pass
@nb.jit
def encode_integer_coordinates(x, y):
return (x & ((1 << BITS_PER_COORDINATE) - 1)) | (y << BITS_PER_COORDINATE)
@nb.jit
def decode_integer_coordinates(value):
mask = (1 << BITS_PER_COORDINATE) - 1
x = value & mask
y = value >> BITS_PER_COORDINATE
return x, y
@nb.jit
def float_to_int(f):
significand, exponent = math.frexp(f)
significand = int(significand * (1 << BITS_PER_FLOAT_SIGNIFICAND))
exponent = exponent + BITS_PER_FLOAT_SIGNIFICAND - 1
result = (significand & ((1 << BITS_PER_FLOAT_SIGNIFICAND) - 1)) | (
exponent << BITS_PER_FLOAT_SIGNIFICAND
)
return result if f >= 0 else -result
@nb.jit
def int_to_float(i):
v = abs(i)
significand = v & ((1 << BITS_PER_FLOAT_SIGNIFICAND) - 1)
exponent = v >> BITS_PER_FLOAT_SIGNIFICAND
return math.ldexp(
significand / (1 << BITS_PER_FLOAT_SIGNIFICAND),
exponent - BITS_PER_FLOAT_SIGNIFICAND + 1,
) * (1 if i >= 0 else -1)
@nb.jit
def encode_float_coordinates(x, y):
x_int = float_to_int(x)
y_int = float_to_int(y)
return encode_integer_coordinates(x_int, y_int)
@nb.jit
def decode_float_coordinates(value):
x_int, y_int = decode_integer_coordinates(value)
x = int_to_float(x_int)
y = int_to_float(y_int)
return x, y
@nb.jit
def make_row_major_indexer(width, node_width=1, node_height=1):
def indexer(x, y):
return (y // node_height) * width + (x // node_width)
return indexer
@nb.jit
def make_column_major_indexer(height, node_width=1, node_height=1):
def indexer(x, y):
return (x // node_width) * height + (y // node_height)
return indexer
@nb.jit
def make_4_directions_enumerator(
node_width=1, node_height=1, min_x=0, min_y=0, max_x=None, max_y=None
):
max_x = max_x if max_x is not None else np.inf
max_y = max_y if max_y is not None else np.inf
def enumerator(x, y, func):
for dx, dy in [
(0, -node_height),
(0, node_height),
(-node_width, 0),
(node_width, 0),
]:
next_x = x + dx
next_y = y + dy
if min_x <= next_x < max_x and min_y <= next_y < max_y:
func(next_x, next_y)
return enumerator
@nb.jit
def make_8_directions_enumerator(
node_width=1, node_height=1, min_x=0, min_y=0, max_x=None, max_y=None
):
max_x = max_x if max_x is not None else np.inf
max_y = max_y if max_y is not None else np.inf
def enumerator(x, y, func):
for dx, dy in [
(node_width, 0),
(node_width, -node_height),
(0, -node_height),
(-node_width, -node_height),
(-node_width, 0),
(-node_width, node_height),
(0, node_height),
(node_width, node_height),
]:
next_x = x + dx
next_y = y + dy
if min_x <= next_x < max_x and min_y <= next_y < max_y:
func(next_x, next_y)
return enumerator
@nb.jit
def make_manhattan_distance_heuristic(scale_factor=1.0):
def heuristic(x1, y1, x2, y2):
return scale_factor * (abs(x1 - x2) + abs(y1 - y2))
return heuristic
@nb.jit
def make_octile_distance_heuristic(scale_factor=1.0):
sqrt2 = math.sqrt(2)
def heuristic(x1, y1, x2, y2):
return scale_factor * (
min(abs(x1 - x2), abs(y1 - y2)) * sqrt2 + abs(abs(x1 - x2) - abs(y1 - y2))
)
return heuristic
@nb.jit
def make_euclidean_distance_heuristic(scale_factor=1.0):
def heuristic(x1, y1, x2, y2):
return scale_factor * math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
return heuristic
def define_path_finder(
name,
world_size,
frontier_size=500,
coordinate_type="float",
coordinate_encoder=encode_float_coordinates,
coordinate_decoder=decode_float_coordinates,
indexer=None,
goal_reached_p=None,
neighbor_enumerator=None,
exact_cost=None,
heuristic_cost=None,
max_movement_cost=float("inf"),
path_initiator=lambda length: None,
path_processor=lambda x, y: None,
path_finalizer=lambda: True,
):
@nb.jit
def path_finder_core(
start_x, start_y, goal_x, goal_y, cost_so_far, came_from, path
):
frontier = [] # We'll use a list as a simple priority queue
heappush(frontier, (0.0, coordinate_encoder(start_x, start_y)))
start_index = indexer(start_x, start_y)
goal_index = indexer(goal_x, goal_y)
cost_so_far[start_index] = 0.0
while frontier:
_, current = heappop(frontier)
current_x, current_y = coordinate_decoder(current)
current_index = indexer(current_x, current_y)
if goal_reached_p(current_x, current_y, goal_x, goal_y):
break
def process_neighbor(next_x, next_y):
next_index = indexer(next_x, next_y)
new_cost = cost_so_far[current_index] + exact_cost(
current_x, current_y, next_x, next_y
)
if new_cost < max_movement_cost and (
math.isnan(cost_so_far[next_index])
or new_cost < cost_so_far[next_index]
):
cost_so_far[next_index] = new_cost
came_from[next_index] = current
priority = new_cost + heuristic_cost(next_x, next_y, goal_x, goal_y)
heappush(frontier, (priority, coordinate_encoder(next_x, next_y)))
neighbor_enumerator(current_x, current_y, process_neighbor)
if math.isnan(cost_so_far[goal_index]):
return 0 # Path not found
length = 0
current = goal_index
while current != start_index:
path[length] = current
length += 1
current_x, current_y = coordinate_decoder(came_from[current])
current = indexer(current_x, current_y)
path[length] = start_index
length += 1
return length
def path_finder(start_x, start_y, goal_x, goal_y, **params):
cost_so_far = np.full(world_size, np.nan)
came_from = np.full(world_size, -1, dtype=np.int64)
path = np.full(world_size, -1, dtype=np.int64)
length = path_finder_core(
start_x, start_y, goal_x, goal_y, cost_so_far, came_from, path
)
if length == 0:
return None
path_initiator(length)
for i in range(length - 1, -1, -1):
path_x, path_y = coordinate_decoder(path[i])
path_processor(path_x, path_y)
return path_finalizer()
path_finder.__name__ = name
return path_finder
@nb.jit
def is_maze_solvable(maze, start, goal, max_iterations=100000):
queue = [(start[0], start[1])]
visited = set([(start[0], start[1])])
iterations = 0
while queue and iterations < max_iterations:
iterations += 1
x, y = queue.pop(0)
if (x, y) == goal:
return True
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
nx, ny = x + dx, y + dy
if (
0 <= nx < maze.shape[1]
and 0 <= ny < maze.shape[0]
and maze[ny, nx] == 0
and (nx, ny) not in visited
):
queue.append((nx, ny))
visited.add((nx, ny))
return False
@nb.jit(nopython=True)
def create_dla_maze(width, height):
maze = np.zeros((height, width), dtype=np.int32)
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
num_seeds = np.random.randint(
max(3, min(width, height) // 20), max(10, min(width, height) // 5)
)
seed_positions = np.random.randint(
1, min(width - 1, height - 1), size=(num_seeds, 2)
)
# Use a loop instead of advanced indexing
for i in range(num_seeds):
y, x = seed_positions[i]
maze[y, x] = 1
num_particles = np.random.randint(width * height // 16, width * height // 8)
directions = np.array([(0, 1), (1, 0), (0, -1), (-1, 0)])
for _ in range(num_particles):
x, y = np.random.randint(1, width - 1), np.random.randint(1, height - 1)
steps = 0
max_steps = np.random.randint(100, 1000)
while maze[y, x] == 0 and steps < max_steps:
dx, dy = directions[np.random.randint(4)]
nx, ny = x + dx, y + dy
if 0 <= nx < width and 0 <= ny < height:
if maze[ny, nx] == 1:
maze[y, x] = 1
break
x, y = nx, ny
steps += 1
# Ensure connectivity
for y in range(1, height - 1):
for x in range(1, width - 1):
if maze[y, x] == 1 and np.random.random() < 0.1:
maze[y, x] = 0
return maze
def create_game_of_life_maze(width, height):
p_alive = random.uniform(0.3, 0.7)
maze = np.random.choice([0, 1], size=(height, width), p=[1 - p_alive, p_alive])
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
generations = random.randint(3, 10)
for _ in range(generations):
new_maze = maze.copy()
for y in range(1, height - 1):
for x in range(1, width - 1):
neighbors = maze[y - 1 : y + 2, x - 1 : x + 2].sum() - maze[y, x]
if maze[y, x] == 1:
if neighbors < 2 or neighbors > 3:
new_maze[y, x] = 0
else:
if neighbors == 3:
new_maze[y, x] = 1
maze = new_maze
return maze.astype(np.int32)
def create_one_dim_automata_maze(width, height):
maze = np.zeros((height, width), dtype=np.int32)
maze[0] = np.random.choice([0, 1], size=width)
maze[0, 0] = maze[0, -1] = 1
rule_number = random.randint(0, 255)
rule = np.zeros((2, 2, 2), dtype=np.int32)
for i in range(8):
rule[i // 4, (i % 4) // 2, i % 2] = (rule_number >> i) & 1
for y in range(1, height):
for x in range(width):
left = maze[y - 1, (x - 1) % width]
center = maze[y - 1, x]
right = maze[y - 1, (x + 1) % width]
maze[y, x] = rule[left, center, right]
maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
@nb.jit
def create_langtons_ant_maze(width, height):
maze = np.zeros((height, width), dtype=np.int32)
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
ant_x, ant_y = random.randint(1, width - 2), random.randint(1, height - 2)
ant_direction = random.randint(0, 3)
steps = random.randint(width * height // 4, width * height)
for _ in range(steps):
maze[ant_y, ant_x] = 1 - maze[ant_y, ant_x]
if maze[ant_y, ant_x] == 1:
ant_direction = (ant_direction + 1) % 4
else:
ant_direction = (ant_direction - 1) % 4
if ant_direction == 0:
ant_y = max(1, ant_y - 1)
elif ant_direction == 1:
ant_x = min(width - 2, ant_x + 1)
elif ant_direction == 2:
ant_y = min(height - 2, ant_y + 1)
else:
ant_x = max(1, ant_x - 1)
return maze
def create_voronoi_maze(width, height):
num_points = np.random.randint(max(width, height) // 3, max(width, height) // 2)
points = np.random.rand(num_points, 2) * [width, height]
vor = Voronoi(points)
maze = np.ones((height, width), dtype=np.int32)
maze = draw_lines(maze, vor.vertices, vor.ridge_vertices)
# Apply erosion to create wider passages
maze = binary_erosion(maze, np.ones((3, 3)))
# Skeletonize to thin the passages
maze = skeletonize(1 - maze).astype(np.int32)
maze = 1 - maze
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
@nb.jit
def recursive_divide(maze, x, y, w, h, min_size=4):
if w <= min_size or h <= min_size:
return
# Randomly decide whether to divide horizontally or vertically
if w > h:
divide_horizontally = np.random.random() < 0.8
else:
divide_horizontally = np.random.random() < 0.2
if divide_horizontally:
divide_at = np.random.randint(y + 1, y + h - 1)
maze[divide_at, x : x + w] = 1
opening = np.random.randint(x, x + w)
maze[divide_at, opening] = 0
recursive_divide(maze, x, y, w, divide_at - y, min_size)
recursive_divide(maze, x, divide_at + 1, w, y + h - divide_at - 1, min_size)
else:
divide_at = np.random.randint(x + 1, x + w - 1)
maze[y : y + h, divide_at] = 1
opening = np.random.randint(y, y + h)
maze[opening, divide_at] = 0
recursive_divide(maze, x, y, divide_at - x, h, min_size)
recursive_divide(maze, divide_at + 1, y, x + w - divide_at - 1, h, min_size)
def create_fractal_maze(width, height, min_size=4):
maze = np.zeros((height, width), dtype=np.int32)
recursive_divide(maze, 0, 0, width, height, min_size)
return maze
def create_maze_from_image(width, height):
image_path = "" # Enter file path here
# Load and resize the image
img = Image.open(image_path).convert("L")
img = img.resize((width, height))
# Convert to numpy array and threshold
maze = np.array(img)
maze = (maze > 128).astype(int)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
@nb.jit(nopython=True)
def get_valid_tiles(maze, x, y, width, height, tiles):
valid = np.ones(3, dtype=np.bool_)
for dx, dy, direction in [(0, -1, 0), (1, 0, 1), (0, 1, 2), (-1, 0, 3)]:
nx, ny = x + dx, y + dy
if 0 <= nx < width and 0 <= ny < height:
maze_value = maze[ny, nx]
if 0 <= maze_value < 3:
valid &= tiles[maze_value][direction]
else:
valid &= False
return np.where(valid)[0]
@nb.jit(nopython=True)
def create_wave_function_collapse_maze_core(width, height, tiles, max_iterations):
maze = np.full((height, width), -1, dtype=np.int32)
stack = [(np.random.randint(1, width - 2), np.random.randint(1, height - 2))]
iterations = 0
while stack and iterations < max_iterations:
idx = np.random.randint(0, len(stack))
x, y = stack[idx]
stack.pop(idx)
if maze[y, x] == -1:
valid_tiles = get_valid_tiles(maze, x, y, width, height, tiles)
if len(valid_tiles) > 0:
maze[y, x] = np.random.choice(valid_tiles)
for dx, dy in [(0, -1), (1, 0), (0, 1), (-1, 0)]:
nx, ny = x + dx, y + dy
if (
0 < nx < width - 1
and 0 < ny < height - 1
and maze[ny, nx] == -1
):
stack.append((nx, ny))
iterations += 1
return maze
def create_wave_function_collapse_maze(width, height, timeout=30):
tiles = np.array(
[
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], # Empty
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], # Wall
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], # Special
],
dtype=np.bool_,
)
start_time = time.time()
max_iterations = width * height * 10 # Adjust this factor as needed
maze = create_wave_function_collapse_maze_core(width, height, tiles, max_iterations)
# Fill any remaining -1 cells with random valid tiles
for y in range(height):
for x in range(width):
if maze[y, x] == -1:
valid_tiles = get_valid_tiles(maze, x, y, width, height, tiles)
maze[y, x] = (
np.random.choice(valid_tiles) if len(valid_tiles) > 0 else 0
)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
elapsed_time = time.time() - start_time
if elapsed_time > timeout:
print(
f"Warning: Wave Function Collapse maze generation exceeded timeout ({elapsed_time:.2f}s > {timeout}s)"
)
return maze
def create_growing_tree_maze(width, height):
maze = np.ones((height, width), dtype=np.int32)
stack = [(1, 1)]
maze[1, 1] = 0
directions = np.array([(0, -1), (1, 0), (0, 1), (-1, 0)])
while stack:
if np.random.random() < 0.5:
current = stack.pop(np.random.randint(0, len(stack)))
else:
current = stack.pop()
x, y = current
np.random.shuffle(directions) # This is now using numpy's shuffle
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 < nx < width - 1 and 0 < ny < height - 1 and maze[ny, nx] == 1:
maze[ny, nx] = 0
stack.append((nx, ny))
return maze
def generate_terrain(width, height, scale, octaves, persistence, lacunarity):
terrain = np.zeros((height, width), dtype=np.float32)
for y in range(height):
for x in range(width):
terrain[y, x] = snoise2(
x * scale,
y * scale,
octaves=octaves,
persistence=persistence,
lacunarity=lacunarity,
)
return terrain
def create_terrain_based_maze(width, height):
scale = np.random.uniform(0.05, 0.1)
octaves = np.random.randint(4, 6)
persistence = np.random.uniform(0.5, 0.7)
lacunarity = np.random.uniform(2.0, 2.5)
terrain = generate_terrain(width, height, scale, octaves, persistence, lacunarity)
terrain = (terrain - terrain.min()) / (terrain.max() - terrain.min())
maze = (terrain > np.percentile(terrain, 60)).astype(np.int32)
# Apply erosion to create wider passages
maze = binary_erosion(maze, np.ones((3, 3)))
# Skeletonize to thin the passages
maze = skeletonize(1 - maze).astype(np.int32)
maze = 1 - maze
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def create_musicalized_maze(width, height):
frequencies = np.linspace(1, 10, num=width)
time = np.linspace(0, 10, num=height)
t, f = np.meshgrid(time, frequencies)
harmonic1 = np.sin(2 * np.pi * f * t)
harmonic2 = np.sin(3 * np.pi * f * t)
harmonic3 = np.sin(5 * np.pi * f * t)
combined = (
np.random.random() * harmonic1
+ np.random.random() * harmonic2
+ np.random.random() * harmonic3
)
combined = (combined - combined.min()) / (combined.max() - combined.min())
threshold = np.random.uniform(0.3, 0.7)
maze = (combined > threshold).astype(np.int32)
# Apply binary dilation to create thicker walls
structure = np.ones((3, 3), dtype=np.int32)
maze = binary_dilation(maze, structure=structure).astype(np.int32)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def create_quantum_inspired_maze(width, height):
x = np.linspace(-5, 5, width)
y = np.linspace(-5, 5, height)
xx, yy = np.meshgrid(x, y)
psi1 = np.exp(-(xx**2 + yy**2) / 2) * np.exp(1j * (xx + yy))
psi2 = np.exp(-((xx - 2) ** 2 + (yy - 2) ** 2) / 2) * np.exp(1j * (xx - yy))
psi3 = np.exp(-((xx + 2) ** 2 + (yy + 2) ** 2) / 2) * np.exp(1j * (xx * yy))
psi_combined = psi1 + psi2 + psi3
prob_density = np.abs(psi_combined) ** 2
prob_density = (prob_density - prob_density.min()) / (
prob_density.max() - prob_density.min()
)
maze = (prob_density > np.percentile(prob_density, 70)).astype(np.int32)
# Apply erosion to create wider passages
maze = binary_erosion(maze, np.ones((3, 3)))
# Skeletonize to thin the passages
maze = skeletonize(1 - maze).astype(np.int32)
maze = 1 - maze
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def create_artistic_maze(width, height):
canvas = np.zeros((height, width), dtype=np.int32)
def add_brush_strokes(canvas, width, height):
for _ in range(np.random.randint(5, 15)):
x, y = np.random.randint(0, width - 1), np.random.randint(0, height - 1)
max_length = max(10, min(width, height) // 2)
length = np.random.randint(10, max_length)
angle = np.random.uniform(0, 2 * np.pi)
dx, dy = length * np.cos(angle), length * np.sin(angle)
rr, cc = np.linspace(x, x + dx, num=100), np.linspace(y, y + dy, num=100)
rr = np.clip(rr.astype(np.int32), 0, width - 1)
cc = np.clip(cc.astype(np.int32), 0, height - 1)
canvas[cc, rr] = 1
return canvas
canvas = add_brush_strokes(canvas, width, height)
# Add random "splatters"
for _ in range(np.random.randint(3, 8)):
x, y = np.random.randint(0, width - 1), np.random.randint(0, height - 1)
radius = np.random.randint(5, min(20, min(width, height) // 4))
splatter = disk(radius)
x_start, y_start = max(0, x - radius), max(0, y - radius)
x_end, y_end = min(width, x + radius + 1), min(height, y + radius + 1)
canvas_section = canvas[y_start:y_end, x_start:x_end]
splatter_section = splatter[: y_end - y_start, : x_end - x_start]
canvas_section[splatter_section > 0] = 1
# Apply binary dilation to create thicker strokes
structure = np.ones((3, 3), dtype=np.int32)
canvas = binary_dilation(canvas, structure=structure).astype(np.int32)
# Thin the result to create maze-like structures
maze = thin(canvas).astype(np.int32)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def custom_rule(neighborhood):
center = neighborhood[1, 1]
neighbors_sum = np.sum(neighborhood) - center
if center == 1:
return 1 if neighbors_sum in [2, 3, 4] else 0
else:
return 1 if neighbors_sum in [3, 4, 5] else 0
def create_cellular_automaton_maze(width, height):
maze = np.random.choice([0, 1], size=(height, width), p=[0.6, 0.4])
for _ in range(np.random.randint(3, 7)):
new_maze = np.zeros_like(maze)
for i in range(1, height - 1):
for j in range(1, width - 1):
neighborhood = maze[i - 1 : i + 2, j - 1 : j + 2]
new_maze[i, j] = custom_rule(neighborhood)
maze = new_maze
# Apply convolution to smooth the maze
kernel = np.ones((3, 3)) / 9
maze = convolve2d(maze, kernel, mode="same", boundary="wrap")
maze = (maze > 0.5).astype(np.int32)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def create_fourier_maze_core(width, height):
noise = np.random.rand(height, width)
fft_noise = np.fft.fft2(noise)
center_y, center_x = height // 2, width // 2
y, x = np.ogrid[-center_y : height - center_y, -center_x : width - center_x]
min_dim = min(width, height)
low_freq = (x * x + y * y <= (min_dim // 8) ** 2).astype(np.float32)
mid_freq = (
(x * x + y * y <= (min_dim // 4) ** 2) & (x * x + y * y > (min_dim // 8) ** 2)
).astype(np.float32)
high_freq = (
(x * x + y * y <= (min_dim // 2) ** 2) & (x * x + y * y > (min_dim // 4) ** 2)
).astype(np.float32)
mask = 0.6 * low_freq + 0.3 * mid_freq + 0.1 * high_freq
filtered_fft = fft_noise * mask
maze = np.real(np.fft.ifft2(filtered_fft))
return maze
def create_fourier_maze(width, height):
maze = create_fourier_maze_core(width, height)
maze = (maze > np.percentile(maze, 60)).astype(np.int32)
# Apply erosion to create wider passages
maze = binary_erosion(maze, np.ones((3, 3)))
# Skeletonize to thin the passages
maze = skeletonize(1 - maze).astype(np.int32)
maze = 1 - maze
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
@nb.jit(nopython=True)
def convolve2d_numba(A, kernel):
h, w = A.shape
kh, kw = kernel.shape
padh, padw = kh // 2, kw // 2
result = np.zeros_like(A)
for i in range(h):
for j in range(w):
for ki in range(kh):
for kj in range(kw):
ii = (i - padh + ki) % h
jj = (j - padw + kj) % w
result[i, j] += A[ii, jj] * kernel[ki, kj]
return result
@nb.jit(nopython=True)
def reaction_diffusion_step(A, B, DA, DB, f, k, laplacian_kernel):
A_lap = convolve2d_numba(A, laplacian_kernel)
B_lap = convolve2d_numba(B, laplacian_kernel)
A += DA * A_lap - A * B**2 + f * (1 - A)
B += DB * B_lap + A * B**2 - (k + f) * B
return np.clip(A, 0, 1), np.clip(B, 0, 1)
@nb.jit(nopython=True)
def create_reaction_diffusion_maze_core(width, height, num_iterations):
A = np.random.rand(height, width)
B = np.random.rand(height, width)
laplacian_kernel = np.array([[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]])
DA, DB = 0.16, 0.08
f, k = 0.035, 0.065
for _ in range(num_iterations):
A, B = reaction_diffusion_step(A, B, DA, DB, f, k, laplacian_kernel)
return A
def create_reaction_diffusion_maze(width, height):
A = create_reaction_diffusion_maze_core(width, height, 20)
maze = (A - A.min()) / (A.max() - A.min())
maze = (maze > np.random.uniform(0.4, 0.6)).astype(np.int32)
# Apply binary dilation to create thicker walls
structure = np.ones((3, 3), dtype=np.int32)
maze = binary_dilation(maze, structure=structure).astype(np.int32)
# Ensure borders are walls
maze[0, :] = maze[-1, :] = maze[:, 0] = maze[:, -1] = 1
return maze
def make_maze_based_on_custom_map_image(width, height):
# Hardcoded path to the custom map image
image_path = "path/to/your/custom_map_image.png"
# Load the image and convert it to grayscale
img = Image.open(image_path).convert('L')
# Convert the image to a numpy array
img_array = np.array(img)
# Threshold the image to create a binary maze
# You can adjust the threshold value (128) to fine-tune the maze generation
binary_maze = (img_array > 128).astype(np.uint8) * 255
# Convert back to an image for resizing
binary_img = Image.fromarray(binary_maze, mode='L')
# Resize the binary image to match the desired maze dimensions
# Use nearest neighbor interpolation to preserve sharp edges
resized_img = binary_img.resize((width, height), Image.NEAREST)