Python 的新功能:使用循环的 Turtle 25 方格棋盘

New to Python: Turtle 25 squares checkerboard using loops

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 的棋盘?

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

您希望该代码 运行 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)。因为你后面的 goto 使用这些值,所以如果你将它们设置为 0 以外的任何值,你的代码将会中断。你的行 x = x+50 也忽略了 width 的值,即使行turtle draws 使用它。同样,如果您将它设置为 50 以外的任何值,这将会中断。

我简化了您的 "square" 函数,使其只绘制一个正方形。然后我添加了一个单独的函数,其中包含一个调用 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()