使用PythonTurtle 绘制小飞侠
在这篇文章中,我们将使用Python的Turtle模块创建Fidget Spinner。这是一个类似于画板的Python功能,它可以让我们命令Turtle在上面画个不停我们可以使用像turtle.forward()和turtle.right()这样的函数,可以让Turtle四处移动。
让我们看看逐步实现的情况:
第1步:绘制小飞侠
在这段代码中,我们将初始化小飞侠的状态,以顺时针和逆时针方向旋转的角度,并制作小飞侠所需的彩色图形。
# initial state of spinner is null (stable)
state= {'turn':0 }
# Draw fidget spinner
def spin():
clear()
# Angle of fidget spinner
angle = state['turn']/10
right(angle)
# move the turtle forward by specified
# distance
forward(100)
# draw a dot with diameter 120 using colour
# red
dot(120, 'red')
# move the turtle backward by specified
# distance
back(100)
"second dot"
right(120)
forward(100)
dot(120, 'blue')
back(100)
"third dot"
right(120)
forward(100)
dot(120, 'green')
back(100)
right(120)
update()
输出:
第2步:为小飞侠制作动画。
在这一步中,我们将调用一个函数animate(),它将通过查看状态是否大于0来使小飞侠旋转起来,然后从它的减少中减去1,并再次调用旋转函数。之后,安装了一个定时器,它将在20毫秒后再次调用animate函数。
# Animate fidget spinner
def animate():
if state['turn'] > 0:
state['turn'] -= 1
spin()
ontimer(animate, 20)
第3步:移动小飞侠,设置窗口,并追踪小飞侠回到其原始位置
在这里,我们将定义 “轻弹 “函数,该函数将移动小飞侠,将其状态增加到40,我们还将设置一个窗口及其背景颜色,我们将使用一个跟踪器,在完成旋转后将小飞侠带回其初始状态,之后,我们将定义小飞侠的宽度和颜色,最后,我们将定义移动小飞侠的键。
# Flick fidget spinner
def flick():
# acceleration of spinner
state['turn'] += 40
# setup window screen
setup(600, 400, 370, 0)
bgcolor("black")
tracer(False)
'''tracer brings back the fidget spinner into its initial state
after completing the rotation'''
# wing of fidget spinner
width(60)
color("orange")
# keyboard key for the rotation of spinner
onkey(flick, 'space')
listen()
animate()
done()
下面是完整的实施方案:。
# import object from module turtle
from turtle import *
# initial state of spinner is null (stable)
state= {'turn':0 }
# Draw fidget spinner
def spin():
clear()
# Angle of fidget spinner
angle = state['turn']/10
# To rotate in clock wise we use right
# for Anticlockwise rotation we use left
right(angle)
# move the turtle forward by specified distance
forward(100)
# draw a dot with diameter 120 using colour red
dot(120, 'red')
# move the turtle backward by specified distance
back(100)
"second dot"
right(120)
forward(100)
dot(120, 'blue')
back(100)
"third dot"
right(120)
forward(100)
dot(120, 'green')
back(100)
right(120)
update()
# Animate fidget spinner
def animate():
if state['turn']>0:
state['turn']-=1
spin()
ontimer(animate, 20)
# Flick fidget spinner
def flick():
state['turn']+=40 #acceleration of spinner
# setup window screen
setup(600, 400, 370, 0)
bgcolor("black")
tracer(False)
# wing of fidget spinner
width(60)
color("orange")
# keyboard key for the rotation of spinner
onkey(flick,'space')
listen()
animate()
done()
输出: