使用Turtle库实现,鼠标左键绘制路径,用鼠标右键结束绘制,小海龟并沿路径移动
Turtle库是Python标准库的一部分,它提供了一种基于命令的图形绘制方式。Turtle模块通过一个“海龟”(Turtle)对象在屏幕上移动和绘制图形,支持诸如前进、后退、左转、右转等操作。此外,Turtle还支持设置颜色等功能。
现在,使用Turtle库实现,鼠标左键绘制路径,用鼠标右键结束绘制时,小海龟并沿路径移动。
源码如下:
# 鼠标左键绘制路径,用鼠标右键结束绘制时,小海龟并沿路径移动。
import turtle
import math
# 全局变量
screen = None
draw_turtle = None
move_turtle = None
path = []
def setup_screen():
global screen, draw_turtle, move_turtle
# 设置屏幕
screen = turtle.Screen()
screen.title("海龟跟随鼠标绘制路径")
screen.setup(width=800, height=600)
# 创建绘图海龟
draw_turtle = turtle.Turtle()
draw_turtle.hideturtle()
draw_turtle.speed(0)
# 创建移动海龟
move_turtle = turtle.Turtle()
move_turtle.shape('turtle')
move_turtle.color('red')
#move_turtle.penup()
#move_turtle.hideturtle()
def start_drawing(x, y):
global path
# 开始绘制路径
path = [(x, y)]
# 准备绘图海龟
draw_turtle.penup()
draw_turtle.goto(x, y)
draw_turtle.pendown()
def continue_drawing(x, y):
global path
# 继续绘制路径
draw_turtle.goto(x, y)
path.append((x, y))
def calculate_angle(index):
# 计算海龟前进角度
if index + 1 < len(path):
current = path[index]
next_point = path[index + 1]
dx = next_point[0] - current[0]
dy = next_point[1] - current[1]
return math.degrees(math.atan2(dy, dx))
return 0
def move_along_path(index=0):
# 沿路径移动
if index < len(path) - 1:
current = path[index]
next_point = path[index + 1]
# 计算距离和角度
distance = math.sqrt(
(next_point[0] - current[0])**2 +
(next_point[1] - current[1])**2
)
# 设置海龟朝向
angle = calculate_angle(index)
move_turtle.setheading(angle)
# 移动
move_turtle.goto(next_point[0], next_point[1])
# 递归移动到下一个点
screen.ontimer(
lambda: move_along_path(index + 1),
50 # 移动间隔时间
)
else:
# 路径结束
move_turtle.penup()
def finish_drawing(x, y):
# 显示并移动海龟
if len(path) > 1:
move_turtle.showturtle()
start_x, start_y = path[0]
move_turtle.goto(start_x, start_y)
move_turtle.pendown()
move_turtle.setheading(calculate_angle(0))
# 开始沿路径移动
move_along_path()
def main():
# 初始化屏幕和海龟
setup_screen()
# 绑定鼠标事件
screen.onscreenclick(start_drawing, 1) # 左键开始绘制
screen.onscreenclick(continue_drawing, 1) # 左键继续绘制
screen.onscreenclick(finish_drawing, 3) # 右键结束绘制
screen.listen()
# 启动主循环
turtle.done()
# 运行程序
if __name__ == "__main__":
main()