
李兴球Python牵引憨憨的小海龟
"""
牵引憨憨的小海龟.py
"""
import turtle # 导入海龟模块
def mouse_position(screen):
"""获取鼠标指针的坐标"""
root = screen._root # 获取根窗口对象
cv = screen._canvas # 获取画布
x = root.winfo_pointerx() # 鼠标指针相对于计算机屏幕的x坐标
y = root.winfo_pointery() # 鼠标指针相对于计算机屏幕的y坐标
rx = cv.winfo_rootx() # 画布到计算机屏幕最左边距离
ry = cv.winfo_rooty() # 画布到计算机屏幕最上边距离
x = x - rx - 2 # 画布边框宽度是2,所以要减去2
y = y - ry - 2
x = x - screen.window_width() //2 # 转换成在海龟画图坐标系中x坐标
y = screen.window_height() //2 - y # 转换成在海龟画图坐标系中y坐标
return x,y
screen = turtle.Screen() # 新建屏幕对象
t = turtle.Turtle('turtle') # 新建海龟对象
t.shapesize(5)
t.speed(0) # 设定海龟速度为最大
t.penup() # 抬笔
t.color('blue') # 设为蓝色的
while True:
x,y = mouse_position(screen) # 获取鼠标指针
if t.distance(x,y) > 50: # 如果海龟到x,y距离大于50
angle = t.towards(x,y) # 算出到x,y的朝向角度
t.setheading(angle) # 把angle设为海龟的方向
t.fd(5) # 前进5个单位
screen.update() # 刷新屏幕显示
发表评论