我如何创建 Turtle 克隆并将它们附加到列表中?

How can i create Turtle clones and append them into a list?

我想编写一个程序,在 3 行中绘制 5 个正方形。每两个方块都是不同的颜色。

到目前为止我已经准备好了方块

sq1 = turtle.Turtle()
sq1.shape("square")
sq1.hideturtle()
sq1.color("red")
sq1.begin_fill()

sq2 = turtle.Turtle()
sq2.shape("square")
sq2.hideturtle()
sq2.color("black")
sq2.begin_fill()

正如您想象的那样,输入 15 clone.turtles 并为每个输入一个不同的位置将花费很长时间。我的目标是为此目的创建一个简单的列表。只是我不知道如何将所有不同的方块放入列表以及如何设法将它们移动到不同的位置。

for 循环中创建海龟,并在每次迭代中将海龟附加到列表中。

你可以定义一个函数:

import turtle

def draw_squares(rows, cols, x=0, y=0, size=20):
    colors = ['red', 'black']
    square = []
    for i in range(cols):
        for j in range(rows):
            t = turtle.Turtle('square')
            t.penup()
            t.shapesize(size / 20)
            t.goto(i * size + x, j * size + y)
            t.color(colors[(i + j) % 2])
            square.append(t)
    return squares

squares = draw_squares(3, 5, size=40)

输出:

其中 xy 是左下角正方形中心的坐标,size 是每个正方形的像素大小,rowscols 是棋盘中的行数和列数。

更新

根据评论中的要求,我们可以通过以下方式更改每个矩形之间的宽度、高度和间距:

import turtle

def draw_squares(rows, cols, x=-170, y=0, w=80, h=40, space=5):
    colors = ['red', 'black']
    square = []
    for i in range(cols):
        for j in range(rows):
            t = turtle.Turtle('square')
            t.penup()
            t.shapesize(h / 20, w / 20)
            t.goto(i * space + i * w + x,j * space + j * h + y)
            t.color('white', colors[(i + j) % 2])
            square.append(t)
    return squares

squares = draw_squares(3, 5)

输出:

其中 w 是宽度,h 是高度,space 是间距。

既然你提到了克隆海龟,让我们使用原型和海龟的clone()方法来做到这一点:

from turtle import Screen, Turtle

COLORS = ['black', 'red']

CURSOR_SIZE = 20

def draw_squares(rows, columns, height=45, width=85, border=5):
    prototype = Turtle('square', visible=False)
    prototype.shapesize(height / CURSOR_SIZE, width / CURSOR_SIZE, border)
    prototype.pencolor('white')
    prototype.penup()

    x = -width / 2 * (columns // 2 * 2 + columns % 2 - 1)  # center on widow
    y = -height / 2 * (rows // 2 * 2 + rows % 2 -1)

    squares = []

    for column in range(columns):
        for row in range(rows):
            square = prototype.clone()
            square.fillcolor(COLORS[(column + row) % len(COLORS)])
            square.goto(column * width + x, row * height + y)
            square.showturtle()
            squares.append(square)

    return squares

screen = Screen()

squares = draw_squares(3, 5)

screen.exitonclick()