import pygame import random # Размеры окна WIDTH, HEIGHT = 800, 800 # Размеры ячейки CELL_SIZE = 20 # Количество ячеек ROWS, COLS = HEIGHT // CELL_SIZE, WIDTH // CELL_SIZE # Цвета WHITE = (255, 255, 255) GREEN = (0, 255, 0) # Инициализация Pygame pygame.init() WIN = pygame.display.set_mode((WIDTH, HEIGHT)) # Класс ячейки class Cell: def __init__(self, row, col): self.row = row self.col = col self.visited = False self.walls = {"top": True, "right": True, "bottom": True, "left": True} def draw(self): x, y = self.col * CELL_SIZE, self.row * CELL_SIZE if self.visited: pygame.draw.rect(WIN, GREEN, (x, y, CELL_SIZE, CELL_SIZE)) if self.walls["top"]: pygame.draw.line(WIN, WHITE, (x, y), (x + CELL_SIZE, y)) if self.walls["right"]: pygame.draw.line(WIN, WHITE, (x + CELL_SIZE, y), (x + CELL_SIZE, y + CELL_SIZE)) if self.walls["bottom"]: pygame.draw.line(WIN, WHITE, (x, y + CELL_SIZE), (x + CELL_SIZE, y + CELL_SIZE)) if self.walls["left"]: pygame.draw.line(WIN, WHITE, (x, y), (x, y + CELL_SIZE)) # Генерация сетки grid = [[Cell(i, j) for j in range(COLS)] for i in range(ROWS)] def main(): clock = pygame.time.Clock() running = True # Начальная ячейка start = grid[0][0] stack = [start] while running: clock.tick(60) # Обработка событий for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Генерация лабиринта if len(stack) > 0: current = stack[-1] current.visited = True neighbours = [] # Проверка соседей if current.row > 0 and not grid[current.row - 1][current.col].visited: neighbours.append(grid[current.row - 1][current.col]) if current.col < COLS - 1 and not grid[current.row][current.col + 1].visited: neighbours.append(grid[current.row][current.col + 1]) if current.row < ROWS - 1 and not grid[current.row + 1][current.col].visited: neighbours.append(grid[current.row + 1][current.col]) if current.col > 0 and not grid[current.row][current.col - 1].visited: neighbours.append(grid[current.row][current.col - 1]) if len(neighbours) > 0: next_cell = random.choice(neighbours) stack.append(next_cell) # Удаление стен if next_cell == grid[current.row - 1][current.col]: current.walls["top"] = False next_cell.walls["bottom"] = False elif next_cell == grid[current.row][current.col + 1]: current.walls["right"] = False next_cell.walls["left"] = False elif next_cell == grid[current.row + 1][current.col]: current.walls["bottom"] = False next_cell.walls["top"] = False elif next_cell == grid[current.row][current.col - 1]: current.walls["left"] = False next_cell.walls["right"] = False else: stack.pop() # Отрисовка сетки WIN.fill((0, 0, 0)) for row in grid: for cell in row: cell.draw() pygame.display.update() pygame.quit() if __name__ == "__main__": main()