turtle朝向鼠标指针向前进

"""
通过鼠标指针牵引小海龟前进.
原理:通过获取screen的canvas,对<Motion>鼠标移动事件进行绑定.
由于turtle的坐标系的不同,所以要进行坐标转换.
更好的转换方法可查阅turtle.py源代码文件,可以通过输入关键字
def onclick之类的,顺藤摸瓜,就能找到更好的转换方法.

"""

import math
from turtle import *

screen = Screen()
screen.setup(480,360)
screen.delay(0)

萍乡 = Turtle(shape='turtle')
萍乡.penup()
萍乡.pencolor("blue")
萍乡.fillcolor("blue")
萍乡.pensize(2)

def follow_mouse(event):
    """本函数让小海龟面朝鼠标指针移动"""
    x = event.x - 240              # 转换成海龟坐标系中的x坐标
    y = 180 - event.y              # 转换成海龟坐标系中的y坐标
    dy = y - 萍乡.ycor()
    dx = x - 萍乡.xcor()
    angle = math.degrees(math.atan2(dy,dx))
    萍乡.setheading(angle)
    if 萍乡.distance(x,y)>50:萍乡.fd(10)
    s = "鼠标指针坐标:" + str(x) + "," + str(y) + "方向:" + str(angle)
    screen.title(s)

You must log in to read the rest of this article. Please log in or register as a user.