在本文中,我们将使用 Python 乌龟模块来创建 Fidget Spinner。它是一个类似于画板的 Python 功能,可以让我们命令乌龟在上面画来画去!我们可以使用 turtle.forward() 和 turtle.right() 等函数来移动乌龟。
让我们来看看如何逐步实现:
步骤 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 来为小飞虫旋转器设置动画,然后从 0 开始递减 1,并再次调用 spin 函数。之后,我们会安装一个计时器,在 20 毫秒后再次调用 animate 函数。
# Animate fidget spinner
def animate():
if state['turn'] > 0:
state['turn'] -= 1
spin()
ontimer(animate, 20)
步骤 3:移动小飞虫,设置窗口,并将小飞虫追踪回原位
在这里,我们将定义闪烁函数(flick function),通过将小飞虫的状态增加到 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()