用python的turtle作图(二)动画吃豆人

本文是用python的turtle作图的第二篇,通过这个例子可以了解动画的原理,用python自带的turtle库制作一些小动画。

1.问题描述

在上一篇“用python的turtle作图(一)静态图”我们介绍了,用python自带的turtle库,制作静态图。

本文将介绍用python自带的turtle库制作动画。

2.原理说明

动画的原理简单来说,就是利用视觉停留效应,每隔一定时间重新绘制图形。这里有三个关键点:

  • 擦除原来的图形

  • 重新绘制图形

  • 时间一般是二十四分之一秒之内

下面以吃豆人为例进行说明:

1、新建一个后缀是py的文件,用文本编辑器打开,导入turtle和time库:

import turtle as t
import time

2、程序运行的时候,设置画图窗口大小800*600,黑色:

t.screensize(800,600,'black')

3、定义一个画吃豆人、豆子的函数:

def draw_smile(loc):
    if(loc<200):
        t.color('yellow')
        t.penup()
        t.goto(300-loc,0)
        t.dot(30,'red')

    t.seth(0)
    t.goto(0,-100)
    t.begin_fill()
    t.circle(100)
    t.end_fill()

    if(loc<200):
        t.color('black')
        t.goto(87,-51)
        t.pendown()
        t.seth(60)
        t.begin_fill()
        t.circle(100,60)
        t.goto(0,0)
        t.end_fill()

4)擦除原理的图像,左移10个像素重新绘制吃豆人和豆子

for r in range(0,200,10):
    t.tracer(False)
    t.clear()
    draw_smile(r)
    time.sleep(1)
    t.hideturtle()
    t.tracer(True)

3.代码实现

完整的代码如下:

import turtle as t
import time
def draw_smile(loc):
    if(loc<200):
        t.color('yellow')
        t.penup()
        t.goto(300-loc,0)
        t.dot(30,'red')

    t.seth(0)
    t.goto(0,-100)
    t.begin_fill()
    t.circle(100)
    t.end_fill()

    if(loc<200):
        t.color('black')
        t.goto(87,-51)
        t.pendown()
        t.seth(60)
        t.begin_fill()
        t.circle(100,60)
        t.goto(0,0)
        t.end_fill()

t.tracer(False) 
t.screensize(800,600,'black')
t.color('yellow')
t.speed(1)

for r in range(0,200,10):
    t.tracer(False)
    t.clear()
    draw_smile(r)
    time.sleep(1)
    t.hideturtle()
    t.tracer(True)

t.clear()
t.tracer(0)
draw_smile(0)

程序运行效果如下:

3.总结

本着Talk is cheap. Show me the code原则,代码实现不做过多解释。

写起来,并不难,多试试就可以了。

本文从构思到完成,可谓是耗费了大量的心血。

如果您阅读本文后哪怕有一丢丢收获,请不要吝啬你手中关注点赞的权力,谢谢!

posted @ 2022-02-17 19:47  siwei718  阅读(1455)  评论(0编辑  收藏  举报