【问题标题】:Drawing the turtle module绘制海龟模块
【发布时间】:2016-09-19 17:22:29
【问题描述】:
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()) &lt; 1:是什么意思?

【问题讨论】:

    标签: turtle-graphics


    【解决方案1】:

    这段代码用红线画了一个星星,用黄色填充。 abs(pos()) &lt; 1 语句用于在执行while 语句的每次迭代后将当前海龟位置与原始起始海龟位置进行比较。如果海龟位置距离小于 1 个单位,则while 语句终止并执行end_fill() 语句以完成黄色填充。

    注释掉if 语句并观察会发生什么,另外,在abs(pos())&lt;1 表达式中尝试不同的数字,包括10、20、30 等,看看效果。

    【讨论】:

      【解决方案2】:

      abs(pos()) 表示绝对位置。 if abs(pos())&lt;1: 表示您回到起点。希望它为您澄清。

      【讨论】:

        【解决方案3】:

        另一个选择是使用'if t.heading() == 0:'。 如果我的理解不是太不正确, 当“turtle.heading == 0”时,乌龟面向“东”, 它开始绘制的方向。 到目前为止,这适用于我尝试过的所有角度。

        使用 '如果 abs(pos())

        使用 '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)
        

        【讨论】:

          猜你喜欢
          • 2016-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-31
          相关资源
          最近更新 更多