from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
我不明白这部分代码。
if abs(pos()) < 1:
这是什么意思?
此代码用红线绘制一颗星并用黄色填充。
abs(pos()) < 1
语句用于在执行while
语句的每次迭代后将当前海龟位置与原始起始海龟位置进行比较。如果海龟位置距离小于 1 个单位,则 while
语句终止,并执行 end_fill()
语句以完成黄色填充。
注释掉
if
语句并观察会发生什么,同时在 abs(pos())<1
表达式中尝试不同的数字,包括 10、20、30 等,看看效果。
abs(pos())
表示绝对位置。 if abs(pos())<1:
表示您回到起点。希望它能让你澄清。
另一种选择是使用“if t.heading() == 0:”。 如果我的理解不是太错误的话 当 'turtle.heading == 0' 时,乌龟面向 '东方', 它开始绘制的方向。 这对我迄今为止尝试过的所有角度都有效。
使用 'if abs(pos()) < 1:' ... I can only draw images at the origin (0,0). (Maybe there's a way to draw images at other locations using 'if abs(pos()) < 1:' but I haven't figured out how.)
使用 'if t.heading() == 0:'
我可以在屏幕上的任何地方绘制图像。
import turtle
wn = turtle.Screen()
wn.title("Drawing Geometric Shapes")
t = turtle.Turtle()
t.color('red', 'yellow')
t.speed(0)
#========================================
def star(x, y, length, angle):
# Draw star
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
while True:
t.forward(length)
t.left(angle)
if t.heading() == 0: #===============
break
t.end_fill()
# Move pen off-screen
t.penup()
t.goto(-500, 0)
#========================================
# ( x, y, length, angle)
star(-270, 180, 100, 120)
star( 190, 200, 100, 160)
star(-270, -220, 100, 100)
star( 190, -190, 100, 170)
star(-160, 0, 350, 178)
#========================================