绘制用到的参数我们存放在data.txt文件中,data.txt文件内容如下:
300,0,144,1,0,0
300,0,144,0,1,0
300,0,144,0,0,1
300,0,144,1,1,0
300,0,108,0,1,1
184,0,72,1,0,1
184,0,72,0,0,0
184,0,72,0,0,0
184,0,72,0,0,0
Python代码如下:
# data.txt中数据说明
# 0 路径前进像素数
# 1 转动方向,0左,1右
# 2 转动角度
# 3,4,5 绘制颜色的rgb值
import turtledef main():# 设置窗口信息turtle.title("数据驱动的动态路径绘制") # 窗口标题turtle.setup(800, 600, 0, 0) # 窗口的大小,坐标原点(0,0)表示窗口中心# 设置画笔pen = turtle.Turtle() # 建立画笔pen.color("red") # 画笔颜色的初始化设置为红色pen.width(5) # 画笔宽度pen.shape("turtle") # 画笔形状pen.speed(2) # 绘制速度# 读取文件result = []file = open("data.txt", "r")for line in file:result.append(list(map(float, line.split(","))))print(result)# 动态绘制for i in range(len(result)):pen.color(result[i][3], result[i][4], result[i][5])pen.fd(result[i][0])if result[i][1]:pen.rt(result[i][2])else:pen.lt(result[i][2])pen.goto(0, 0)if __name__ == "__main__":main()
运行结果如下: