Как сделать "зрение" змейке на python для дальнейшего внедрение ИИ

MrSover

Новичок
Пользователь
Дек 29, 2020
1
0
1
Стоит задача сделать змейку, управляемую нейросетью, но я не знаю как создать "зрение" для змейки, чтобы она видела препятствия и еду с выходом данных о местоположении препятствий и еды в радиусе 5-ти клеток.

визуально выглядит так(это просто для наглядности, а выход должен быть в текстовом формате для работы с ним):

Безымянный.png

Источник:

Вот код змейки:
Python:
import pygame

from random import randrange

RES = 900
SIZE = 29
MARGIN = 1

x, y = randrange(SIZE+MARGIN, RES - SIZE, SIZE+MARGIN), randrange(SIZE+MARGIN, RES - SIZE, SIZE+MARGIN)
apple = randrange(SIZE+MARGIN, RES - SIZE, SIZE+MARGIN), randrange(SIZE+MARGIN, RES - SIZE, SIZE+MARGIN)
length = 1
snake = [(x, y)]
dx, dy = 0, 0
fps = 60
dirs = {'W': True, 'S': True, 'A': True, 'D': True, }
score = 0
speed_count, snake_speed = 0, 10
COUNT_BLOCKS = 30
FRAME_COLOR = (200, 200, 200)
WHITE = (250, 250, 250)
BLUE = (210, 250, 250)


pygame.init()
surface = pygame.display.set_mode([RES, RES])
clock = pygame.time.Clock()
font_score = pygame.font.SysFont('Arial', 24, bold=True)
font_end = pygame.font.SysFont('Arial', 66, bold=True)




while True:
    def close_game():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

    surface.fill(FRAME_COLOR)

    for row in range(COUNT_BLOCKS):
        for column in range(COUNT_BLOCKS):
            if (column+row)%2==0:
                color = BLUE
            else:
                color = WHITE
            pygame.draw.rect(surface,color,[(SIZE+MARGIN)*column,
                                            (SIZE+MARGIN)*row, SIZE ,SIZE])
    # drawing snake, apple
    [pygame.draw.rect(surface, pygame.Color('green'), (i, j, SIZE, SIZE)) for i, j in snake]
    pygame.draw.rect(surface, pygame.Color('red'), (*apple, SIZE, SIZE))
    # show score
    render_score = font_score.render(f'SCORE: {score}', 1, pygame.Color('orange'))
    surface.blit(render_score, (5, 5))
    # snake movement
    speed_count += 1
    if not speed_count % snake_speed:
        x += dx * (SIZE+MARGIN)
        y += dy * (SIZE+MARGIN)
        snake.append((x, y))
        snake = snake[-length:]
    # eating food
    if snake[-1] == apple:
        apple = randrange(0, RES - SIZE, SIZE+MARGIN), randrange(0, RES - SIZE, SIZE+MARGIN)
        length += 1
        score += 1
        #snake_speed -= 1
        #cancel speed increase
        snake_speed = max(snake_speed, 4)
    # game over
    if x < 0 or x > RES - (SIZE+MARGIN) or y < 0 or y > RES - (SIZE+MARGIN) or len(snake) != len(set(snake)):
        while True:
            render_end = font_end.render('GAME OVER', 1, pygame.Color('orange'))
            surface.blit(render_end, (RES // 2 - 200, RES // 3))
            pygame.display.flip()
            close_game()

    pygame.display.flip()
    clock.tick(fps)
    close_game()
    # controls
    key = pygame.key.get_pressed()
    if key[pygame.K_w]:
        if dirs['W']:
            dx, dy = 0, -1
            dirs = {'W': True, 'S': False, 'A': True, 'D': True, }
    elif key[pygame.K_s]:
        if dirs['S']:
            dx, dy = 0, 1
            dirs = {'W': False, 'S': True, 'A': True, 'D': True, }
    elif key[pygame.K_a]:
        if dirs['A']:
            dx, dy = -1, 0
            dirs = {'W': True, 'S': True, 'A': True, 'D': False, }
    elif key[pygame.K_d]:
        if dirs['D']:
            dx, dy = 1, 0
            dirs = {'W': True, 'S': True, 'A': False, 'D': True, }

Заранее спасибо!
 

Форум IT Специалистов