/
generaterb.py
72 lines (58 loc) · 2.81 KB
/
generaterb.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
from mazegenerator import MazeGenerator
import time
import random
import pngfunctions
from typing import Tuple
class GenerateRB(MazeGenerator):
def __init__(self, size):
super().__init__(size)
self.name = "RB"
self.directory = self.directory = "mazes/" + self.name + "-" + str(self.size) + "x" + str(self.size) + "-" + hex(random.randint(0, 500))
def maze_generator_factory(self, size: int):
return GenerateRB(size)
def save_history(self, history_log):
frame = 0
for action in history_log:
action: Tuple
if action[0] == "bridge":
self.maze.draw.point(action[1], (0, 0, 255))
if frame + 1 < len(history_log):
self.maze.draw.point(history_log[frame + 1][1], (0, 0, 255))
if action[0] == "pop":
self.maze.draw.point(action[1], (0, 0, 255))
if frame - 1 > 0:
self.maze.draw.point(history_log[frame - 1][1], (255, 255, 255))
if frame - 2 >= 0 and history_log[frame - 1][0] == "bridge":
self.maze.draw.point(history_log[frame - 2][1], (255, 255, 255))
pngfunctions.save_frame(self.maze.image, self.directory, frame)
frame += 1
def generate(self, history_log=None, save_png=True):
start_time = time.time()
the_stack = [(1, 1)]
self.matrix[1][1].visited = True
while the_stack: # while there are things left on the stack
x, y = the_stack.pop()
if history_log is not None:
history_log.append(("pop", (x, y)))
# add every non-visited neighbor to a pool
pool = []
if y - 2 > 0 and not self.matrix[x][y - 2].visited: # check north
pool.append((x, y - 2))
if y + 2 < len(self.matrix) and not self.matrix[x][y + 2].visited: # check south
pool.append((x, y + 2))
if x - 2 > 0 and not self.matrix[x - 2][y].visited: # check east
pool.append((x - 2, y))
if x + 2 < len(self.matrix) and not self.matrix[x + 2][y].visited: # check west
pool.append((x + 2, y))
if len(pool) > 0: # pick a random neighbor from the pool and connect it to the current node
the_stack.append((x, y))
next_node = random.choice(pool)
self.maze.connect(self.matrix[x][y], self.matrix[next_node[0]][next_node[1]], history_log)
self.matrix[next_node[0]][next_node[1]].visited = True
the_stack.append(next_node)
self.duration = time.time() - start_time
if history_log is not None:
history_log.append(("pop", (1, 1)))
self.save_history(history_log)
if save_png:
self.save_png()