73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
from random import choice, randrange
|
||
|
||
from coords import Coords
|
||
|
||
|
||
def maze_gen(row=4, col=4):
|
||
"""генератор карты
|
||
взял с коментария
|
||
https://stepik.org/lesson/502494/step/3?discussion=6527620&unit=494196
|
||
"""
|
||
row = max(2 * row + 1, 3)
|
||
col = max(2 * col + 1, 3)
|
||
maze = [[2] * col]
|
||
maze.extend([[2] + [1] * (col - 2) + [2] for _ in range(row - 2)])
|
||
maze.append(maze[0])
|
||
|
||
curr = (randrange(1, len(maze) - 1, 2), randrange(1, len(maze[0]) - 1, 2))
|
||
path = [curr]
|
||
maze[curr[0]][curr[1]] = 0
|
||
|
||
while path:
|
||
nexts = [
|
||
(r1, c1, r2, c2)
|
||
for r, c in zip((1, 0, -1, 0), (0, 1, 0, -1))
|
||
if (
|
||
(r1 := curr[0] + r) is None
|
||
or (c1 := curr[1] + c) is None
|
||
or (r2 := curr[0] + 2 * r) is None
|
||
or (c2 := curr[1] + 2 * c) is None
|
||
or 1 == maze[r1][c1] == maze[r2][c2]
|
||
)
|
||
]
|
||
if nexts:
|
||
r1, c1, r2, c2 = choice(nexts)
|
||
maze[r1][c1] = maze[r2][c2] = 0
|
||
path.append((r2, c2))
|
||
else:
|
||
curr = path.pop()
|
||
|
||
upd = {
|
||
("22", "20"): (None, "00"),
|
||
("02", "22"): ("00", None),
|
||
("11101", "00101", "11111", "10100", "10111"): (
|
||
None,
|
||
None,
|
||
None,
|
||
"10001",
|
||
None,
|
||
),
|
||
("10111", "10100", "11111", "00101", "11101"): (
|
||
None,
|
||
"10001",
|
||
None,
|
||
None,
|
||
None,
|
||
),
|
||
}
|
||
for pattern, replacement in upd.items():
|
||
for i in range(len(maze) - len(pattern) + 1):
|
||
for j in range(len(maze[0]) - len(pattern[0]) + 1):
|
||
if all(
|
||
maze[i + k][j : j + len(v)] == list(map(int, v))
|
||
for k, v in enumerate(pattern)
|
||
):
|
||
for k, v in filter(lambda x: x[1], enumerate(replacement)):
|
||
maze[i + k][j : j + len(v)] = list(map(int, v))
|
||
|
||
return maze
|
||
|
||
|
||
def get_maze_sz(maze: list[list[int]]) -> Coords:
|
||
return Coords(len(maze[0]), len(maze))
|