海龟快跑,turtle碰撞检测小游戏

海龟快跑,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()

 

如需要查看完整源代码,请

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

李兴球

李兴球的博客是Python创意编程原创博客