【问题标题】:New to Python: Turtle 25 squares checkerboard using loopsPython 新手:使用循环的 Turtle 25 方格棋盘
【发布时间】:2017-10-16 18:57:20
【问题描述】:
def main():
    square(0,0,50,'red')


def square(x,y,width,color):  

    turtle.penup()  
    turtle.goto(0,0)  
    turtle.fillcolor(color)  
    turtle.pendown()  
    turtle.begin_fill()

    for number in range(5):
        for count in range(4):
            turtle.forward(width)
            turtle.left(90)
        turtle.end_fill()
        x = x+50
        turtle.goto(x,y)


    turtle.showturtle()

调用主函数

main()

这给了我一排 5 个正方形。我如何编写一个外循环来再画 4 个 这样 5 个正方形的行 - 一个 5 x 5 的棋盘?

【问题讨论】:

    标签: python turtle-graphics


    【解决方案1】:

    我将您的“正方形”功能简化为仅绘制一个正方形。然后我添加了一个单独的函数,其中包括一个调用 square 函数的嵌套循环。 尽量保持简单,每个功能只负责一项:

    import turtle
    
    def main():
        board(5, 5, 50)
        input("Hit enter to close")
    
    def square(x,y,width,color):
        turtle.penup()  
        turtle.fillcolor(color)  
        turtle.goto(x, y)
        turtle.pendown()
        turtle.begin_fill()
        for side in range(4):
            turtle.forward(width)
            turtle.left(90)
        turtle.end_fill()
    
    def board(rows, columns, square_width):
        turtle.showturtle()
        for row in range(rows):
            for column in range(columns):
                color = "red" if (row + column)%2 == 1 else "white"
                square(row*square_width, column*square_width, square_width, color)
        turtle.hideturtle()
    

    【讨论】:

      【解决方案2】:

      您已经有了绘制一排正方形的代码,这就是您现在拥有的循环。

      您希望该代码运行 5 次,因此只需将其包装在另一个循环中,并确保根据需要修改变量。类似这样的东西:

      for i in range(5):  
          for number in range(5):
              for count in range(4):
                  turtle.forward(width)
                  turtle.left(90)
              turtle.end_fill()
              x += width
              turtle.goto(x,y)
          x -= 5*width
          y += width
      

      还有一个关于样式的注释,square() 忽略了它的大部分参数。无论xy 的值如何,你都将你的乌龟硬编码到(0,0)。因为您以后的gotos 使用这些值,如果您将它们设置为0 以外的任何值,您的代码将中断。您的行x = x+50 也忽略width 的值,即使海龟绘制的行使用它。同样,如果您将其设置为 50 以外的任何值,则会中断。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-10
        • 1970-01-01
        • 2016-11-13
        • 2022-10-04
        • 1970-01-01
        • 2021-05-10
        • 1970-01-01
        • 2015-05-23
        相关资源
        最近更新 更多