海龟快跑,turtle碰撞检测示例

"""
   海龟快跑!
   turtle碰撞检测示例。
   本程序主要演示如何对两只海龟进行碰撞检测。
"""
from turtle import Turtle, Screen

screen = Screen()

screen.screensize(250, 250)      # 调整画布尺寸
screen.bgcolor("black")
screen.title("海龟快跑,turtle碰撞检测示例")
screen.delay(0)

player = Turtle("turtle")
player.color("blue")
player.penup()
player.setposition(250, 250)

catcher = Turtle("turtle")
catcher.color("red")
catcher.penup()
catcher.setposition(-250, -250)

def k1():
    player.forward(10)

def k2():
    player.left(10)

def k3():
    player.right(10)

def k4():
    player.backward(10)

def close_window():
    screen.bye()

def is_collided_with(a, b):
    """两只海龟的水平和垂直距离都小于10,则认为它们发生了碰撞"""
    
    return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10

def catch_player():
    """去“抓“玩家,每隔10毫秒重设方向。"""
    catcher.setheading(catcher.towards(player))
    catcher.forward(min(catcher.distance(player), 1))

    if is_collided_with(catcher, player):
        print('追到你了!(发生了碰撞)')
        close_window()
    else:
        screen.ontimer(catch_player, 10)

screen.onkey(k1, "Up")    # 按上移方向箭头调用k1函数
screen.onkey(k2, "Left")  # 按下移方向箭头调用k2函数
screen.onkey(k3, "Right") # 按右移方向箭头调用k3函数
screen.onkey(k4, "Down")  # 按左移方向箭头调用k4函数

screen.listen()           # 监听键盘按键

catch_player()

screen.mainloop()