from tkinter import *
from random import randint

def key_player(event):
    global x
    global y
    if event.keycode == 87:
        print("W")
        if y > 0:
            y -= 1
            canv.move(id_rect_player, 0, -100)
        is_game_over()
    elif event.keycode == 65:
        print("A")
        if x > 0:
            x -= 1
            canv.move(id_rect_player, -100, 0)
        is_game_over()
    elif event.keycode == 83:
        print("S")
        if y < h-1:
            y += 1
            canv.move(id_rect_player, 0, 100)
        is_game_over()
    elif event.keycode == 68:
        print("D")
        if x < w-1:
            x += 1
            canv.move(id_rect_player, 100, 0)
        is_game_over()


W = Tk()
W.title("Существо в лабиринте: Возвращение")
canv = Canvas(W, width=1200, height=800, bg="black")
canv.pack()

x = 5
y = 2
X_ = 1
Y_ = 0
w = 12
h = 7

def is_game_over():
    if x == X_ and y == Y_:
        print("Игра завершена.")
        exit()

def bot_move():
    global X_
    global Y_
    n = randint(1, 5)
    if n == 1:
        X_ += 1
        if X_ >= w:
            X_ = w - 1
            bot_move()
        else:
            print("Бот пошёл")
            canv.move(id_rect_bot, 100, 0)

    elif n == 2:
        Y_ += 1
        if Y_ >= h:
            Y_ = h - 1
            bot_move()
        else:
            print("Бот пошёл")
            canv.move(id_rect_bot, 0, 100)

    elif n == 3:
        X_ -= 1
        if X_ < 0:
            X_ = 0
            bot_move()
        else:
            print("Бот пошёл")
            canv.move(id_rect_bot, -100, 0)

    elif n == 4:
        Y_ -= 1
        if Y_ < 0:
            Y_ = 0
            bot_move()
        else:
            print("Бот пошёл")
            canv.move(id_rect_bot, 0, -100)

    else:
        print("Бот остался на своём месте")

    W.after(randint(500, 2000), bot_move)
    is_game_over()

id_rect_bot = canv.create_rectangle(X_*100,Y_*100,(X_+1)*100, (Y_+1)*100, fill = "blue")
id_rect_player = canv.create_rectangle(x*100,y*100,(x+1)*100, (y+1)*100, fill = "red")

W.after( randint(200, 2000), bot_move)

W.bind('<KeyPress>', key_player)

W.mainloop()