方中有方中有方

1 投票
3 回答
62 浏览
提问于 2025-04-13 15:28

这是我目前尝试过的。我不知道怎么把这些方块居中,这样它们就不会重叠在一起。

import turtle

def square(t, sz):
    for i in range(4):
        t.color("hotpink")
        t.forward(sz)
        t.left(90)

wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.pensize(3)
size = 10

for _ in range(5):
    square(alex, size)
    alex.penup()
    alex.right(90) 
    alex.left(90)
    alex.pendown()
    size += 20

3 个回答

0

这个代码应该能解决问题:

def draw_square(t, size):
    t.penup()
    t.goto(-size / 2, -size / 2)
    t.pendown()
    for _ in range(4):
        t.forward(size)
        t.left(90)

wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.pensize(3)


size = 100 
step = 20

for _ in range(5):
    draw_square(alex, size)
    size -= step

wn.mainloop()

0

好的,这个问题挺有意思的,让你思考怎么解决它。

你现在的代码是从每个正方形的左下角开始画的。

当然,你可以考虑在每次循环时,根据正方形的大小来调整起始位置。

但其实有个更简单的方法,就是把所有东西都放在正方形里面。

如果你想让正方形是同心的,可以修改正方形的函数,让它假设起始位置和结束位置都是中心点。

这样的话,在循环中只需要调用 t.square 就行了,因为正方形的函数自己会处理起始和结束的位置。

基本上,我们首先需要把笔抬起来,从中心移动到一个角落,然后画出四条边,最后再回到中心。

import turtle
def square(t, sz):
    # assume we start at the center of the square facing upwards,
    # so we first move to the top left corner and face downwards

    t.penup()
    t.forward(sz / 2) 
    t.left(90)
    t.forward(sz / 2)
    t.left(90)
    t.pendown()
    # here we are at the top left corner looking down

    # we draw a square
    for i in range(4):
        t.color("hotpink")
        t.forward(sz)
        t.left(90)
        
    # now we are back to the top left corner looking down,
    # we need move back to the center and looking up
    # so we leave the turtle prepared for the next square

    t.penup()
    t.right(90)
    t.backward(sz/2)
    t.right(90)
    t.backward(sz/2)
    t.pendown()
    
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.pensize(3)
size = 10

for _ in range(5):
    square(alex, size)
    size += 20

这个例子很好地说明了,最开始看起来很难的问题,如果每次循环都从已知的条件开始,并确保系统在结束时回到相同的状态,其实可以很简单地解决。

0

另一种方法是使用印章而不是绘图,这样可以自然地在当前热点周围绘制正方形,省去了将小海龟移动到正方形中心的麻烦:

from turtle import Screen, Turtle

CURSOR_SIZE = 20

screen = Screen()
screen.bgcolor('lightgreen')

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.color('hotpink', screen.bgcolor())

for size in range(90, 0, -20):
    turtle.shapesize(size / CURSOR_SIZE, outline=3)
    turtle.stamp()

screen.exitonclick()

撰写回答