Mail Answering for https://otvet.mail.ru/question/238241687

Mail Answering for https://otvet.mail.ru/question/238241687

Chudo_Chudnoe
import pygame 
import sys 
 
# Константы для настройки графики 
CELL_SIZE = 40 
CELL_BORDER = 5 
BACKGROUND_COLOR = (30, 30, 30) 
ROBOT_COLOR = (70, 130, 180) 
VISITED_COLOR = (100, 100, 255) 
WALL_COLOR = (128, 128, 128) 
START_COLOR = (255, 165, 0) 
FINISH_COLOR = (255, 20, 147) 
FILL_COLOR = (200, 200, 200) 
START_POS = (0, 0) 
FINISH_POS = (9, 9) 
MAX_X, MAX_Y = 10, 10  # Размеры лабиринта 
 
def init_grid(): 
    MAX_X, MAX_Y = 10, 10  # Размеры лабиринта 
    grid = [[[True, True] for _ in range(MAX_Y)] for _ in range(MAX_X)] 
    visited = [[False] * MAX_Y for _ in range(MAX_X)]  # Для отслеживания посещенных клеток 
 
    # Сначала устанавливаем стены для всех клеток 
    for x in range(MAX_X): 
        for y in range(MAX_Y): 
            grid[x][y][0] = True  # Стена справа 
            grid[x][y][1] = True  # Стена снизу 
 
    # Определяем путь от начала до конца 
    # Путь идет с (0,0) до (0,9) вниз 
    for y in range(9): 
        grid[0][y][1] = False  # Убираем стену снизу 
 
    # Затем вправо до (9,9) 
    for x in range(9): 
        grid[x][9][0] = False  # Убираем стену справа 
 
    # Создаем тупики и дополнительные маршруты 
    grid[1][1][0] = False  # Тупиковый путь вправо на одну клетку 
    grid[1][2][0] = False 
    grid[1][3][0] = False 
    grid[1][4][0] = False 
    grid[1][5][0] = False 
    grid[1][6][0] = False 
    grid[2][6][1] = False  # Тупик вниз 
 
    grid[3][1][0] = False 
    grid[4][1][1] = False 
    grid[4][2][1] = False 
    grid[4][3][1] = False 
    grid[5][3][0] = False  # Тупик вправо 
 
    grid[8][8][1] = False  # Дополнительный тупик вниз в предпоследней клетке 
 
    return grid, visited 
 
def draw_grid(screen, grid, visited): 
    for x in range(MAX_X): 
        for y in range(MAX_Y): 
            rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE) 
            if visited[x][y]: 
                pygame.draw.rect(screen, VISITED_COLOR, rect)  # Рисуем посещенные клетки 
            elif (x, y) == START_POS or (x, y) == FINISH_POS: 
                pass  # Старт и финиш рисуются позже 
            else: 
                pygame.draw.rect(screen, FILL_COLOR, rect) 
            if grid[x][y][0] and x < MAX_X - 1:  # Стена справа 
                pygame.draw.line(screen, WALL_COLOR, (rect.right, rect.top), (rect.right, rect.bottom), CELL_BORDER) 
            if grid[x][y][1] and y < MAX_Y - 1:  # Стена снизу 
                pygame.draw.line(screen, WALL_COLOR, (rect.left, rect.bottom), (rect.right, rect.bottom), CELL_BORDER) 
    # Отдельная отрисовка старта и финиша 
    start_rect = pygame.Rect(START_POS[0] * CELL_SIZE, START_POS[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE) 
    finish_rect = pygame.Rect(FINISH_POS[0] * CELL_SIZE, FINISH_POS[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE) 
    pygame.draw.rect(screen, START_COLOR, start_rect) 
    pygame.draw.rect(screen, FINISH_COLOR, finish_rect) 
 
def can_move(grid, x, y, direction): 
    # Добавлена проверка стен по направлениям движения 
    if direction == 'UP' and y > 0: 
        return not grid[x][y-1][1] 
    if direction == 'DOWN' and y < MAX_Y - 1: 
        return not grid[x][y][1] 
    if direction == 'LEFT' and x > 0: 
        return not grid[x-1][y][0] 
    if direction == 'RIGHT' and x < MAX_X - 1: 
        return not grid[x][y][0] 
    return False 
 
def update_screen(screen, grid, visited, robot_position): 
    screen.fill(BACKGROUND_COLOR) 
    draw_grid(screen, grid, visited) 
    rect = pygame.Rect(robot_position[0] * CELL_SIZE, robot_position[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE) 
    pygame.draw.rect(screen, ROBOT_COLOR, rect)  # Робот всегда рисуется последним 
    pygame.display.flip() 
 
def main(): 
    pygame.init() 
    screen = pygame.display.set_mode((MAX_X * CELL_SIZE, MAX_Y * CELL_SIZE)) 
    pygame.display.set_caption("Лабиринт Робота") 
     
    grid, visited = init_grid() 
    robot_position = list(START_POS) 
 
    running = True 
    while running: 
        for event in pygame.event.get(): 
            if event.type is pygame.QUIT: 
                running = False 
            elif event.type == pygame.KEYDOWN: 
                new_position = list(robot_position) 
                if event.key == pygame.K_UP and can_move(grid, robot_position[0], robot_position[1], 'UP'): 
                    new_position[1] -= 1 
                elif event.key == pygame.K_DOWN and can_move(grid, robot_position[0], robot_position[1], 'DOWN'): 
                    new_position[1] += 1 
                elif event.key == pygame.K_LEFT and can_move(grid, robot_position[0], robot_position[1], 'LEFT'): 
                    new_position[0] -= 1 
                elif event.key == pygame.K_RIGHT and can_move(grid, robot_position[0], robot_position[1], 'RIGHT'): 
                    new_position[0] += 1 
                 
                if new_position != robot_position: 
                    robot_position[:] = new_position 
                    visited[robot_position[0]][robot_position[1]] = True  # Пометить клетку как посещенную 
 
        update_screen(screen, grid, visited, robot_position) 
        if robot_position == list(FINISH_POS): 
            print("Поздравляю! Ты достиг финиша.") 
            running = False 
 
    pygame.quit() 
    sys.exit() 
 
if __name__ == "__main__": 
    main() 


Report Page