[2] feat - загрузка лабиринта из файла
This commit is contained in:
parent
56ff7f317a
commit
735626045b
|
|
@ -13,9 +13,9 @@ class GridCell:
|
|||
def __init__(self, x, y):
|
||||
self._x = x
|
||||
self._y = y
|
||||
self._blocked = False # стена
|
||||
self._entry = False # старт
|
||||
self._exit_flag = False # выход
|
||||
self._blocked = False
|
||||
self._entry = False
|
||||
self._exit_flag = False
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
|
|
@ -114,3 +114,42 @@ class Labyrinth:
|
|||
if neighbour and neighbour.passable():
|
||||
neighbours.append(neighbour)
|
||||
return neighbours
|
||||
|
||||
|
||||
# ----------------------------- Загрузка лабиринта -----------------------------
|
||||
class LabyrinthBuilder:
|
||||
def build_from_file(self, filename):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class TxtLabyrinthBuilder(LabyrinthBuilder):
|
||||
def build_from_file(self, filename):
|
||||
with open(filename, 'r') as f:
|
||||
lines = [line.rstrip('\n') for line in f.readlines()]
|
||||
height = len(lines)
|
||||
width = max(len(line) for line in lines) if height > 0 else 0
|
||||
start_cnt = 0
|
||||
exit_cnt = 0
|
||||
lab = Labyrinth(width, height)
|
||||
|
||||
for y, line in enumerate(lines):
|
||||
for x, ch in enumerate(line):
|
||||
if ch == "#":
|
||||
lab.configure_cell(x, y, "wall")
|
||||
elif ch == "S":
|
||||
lab.configure_cell(x, y, "start")
|
||||
start_cnt += 1
|
||||
elif ch == "E":
|
||||
lab.configure_cell(x, y, "exit")
|
||||
exit_cnt += 1
|
||||
else:
|
||||
lab.configure_cell(x, y, 'path')
|
||||
if start_cnt != 1 or exit_cnt != 1:
|
||||
raise ValueError(f"Maze must have exactly one S and one E. Found S={start_cnt}, E={exit_cnt}")
|
||||
return lab
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
builder = TxtLabyrinthBuilder()
|
||||
maze = builder.build_from_file("maze/level1.txt")
|
||||
print(f"Maze loaded: {maze.width}x{maze.height}")
|
||||
Loading…
Reference in New Issue
Block a user