绘制海龟模块
Drawing the turtle module
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())
表示绝对位置。 if abs(pos())<1:
表示你回到了起点。希望它能给你澄清。
这段代码用红线绘制了一颗星,并用黄色填充。 abs(pos()) < 1
语句用于在每次迭代 while
语句后将当前海龟位置与原始起始海龟位置进行比较。如果海龟位置距离小于 1 个单位,则 while
语句终止并执行 end_fill()
语句以完成黄色填充。
注释掉 if
语句并观察会发生什么,另外,在 abs(pos())<1
表达式中尝试使用不同的数字,包括 10、20、30 等以查看效果。
另一种选择是使用 'if t.heading() == 0:'。
如果我的理解不是太错误的话,
当 'turtle.heading == 0' 时,乌龟面向 'east',
它开始绘制的方向。
到目前为止,这对我尝试过的所有角度都有效。
正在使用 'if abs(pos()) < 1:' ...
我只能在原点 (0,0) 绘制图像。
(也许有一种方法可以在
使用 'if abs(pos()) < 1:' 的其他位置
但我还没有想出如何。)
使用'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):
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()
# ( x, y, length, angle)
star(-470, 300, 100, 120)
star( 360, 320, 100, 160)
star(-450, -340, 100, 100)
star( 360, -340, 100, 170)
star(-360, 0, 750, 178)
t.penup()
t.goto(-500, 0)
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())
表示绝对位置。 if abs(pos())<1:
表示你回到了起点。希望它能给你澄清。
这段代码用红线绘制了一颗星,并用黄色填充。 abs(pos()) < 1
语句用于在每次迭代 while
语句后将当前海龟位置与原始起始海龟位置进行比较。如果海龟位置距离小于 1 个单位,则 while
语句终止并执行 end_fill()
语句以完成黄色填充。
注释掉 if
语句并观察会发生什么,另外,在 abs(pos())<1
表达式中尝试使用不同的数字,包括 10、20、30 等以查看效果。
另一种选择是使用 'if t.heading() == 0:'。 如果我的理解不是太错误的话, 当 'turtle.heading == 0' 时,乌龟面向 'east', 它开始绘制的方向。 到目前为止,这对我尝试过的所有角度都有效。
正在使用 'if abs(pos()) < 1:' ... 我只能在原点 (0,0) 绘制图像。 (也许有一种方法可以在 使用 'if abs(pos()) < 1:' 的其他位置 但我还没有想出如何。)
使用'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):
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()
# ( x, y, length, angle)
star(-470, 300, 100, 120)
star( 360, 320, 100, 160)
star(-450, -340, 100, 100)
star( 360, -340, 100, 170)
star(-360, 0, 750, 178)
t.penup()
t.goto(-500, 0)