龟图:重复正方形

时间:2018-02-28 21:23:50

标签: python python-3.x turtle-graphics

我正在尝试创建一个循环,它接受用户的输入并绘制多个正方形,但它会增加每个循环的正方形的大小,但是2个边保持连接。我将包含图片以便更好地解释。

enter image description here

    import turtle

squares = 1
while squares >= 1:
    squares = int(input('How many squares would you like drawn?:'))
    if squares == 0:
        print("You must have at-least 1 square.")
        squares = int(input('How many squares would you like drawn?:'))
    else:
        for count in range(squares):
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)


turtle.done()

2 个答案:

答案 0 :(得分:0)

输入请求和绘图逻辑应该分开 这是一种方法,在增加边长后,在每个回合开始时返回乌龟。

import turtle

num_squares = 3
t = turtle.Turtle()
t.pendown()
side = side_unit = 30

while True:
    try:
        num_squares = int(input('input the number of squares'))
    except ValueError:
        print("please enter an integer")
    if num_squares > 3:
        break

for sq in range(1, num_squares + 1):
    t.left(90)
    t.forward(side)
    t.left(90)
    t.forward(side)
    t.left(90)
    t.forward(side)
    t.left(90)
    side = side_unit + 3 * sq  # increase the size of the side

    t.goto(0,0)                # return to base

turtle.done()

答案 1 :(得分:0)

在等待@ ReblochonMasque的解决方案完成 绘图 100平方时,有足够的时间来实施基于的替代,更快的解决方案的 冲压

首先要注意的是,在提供的说明中,它描绘了绘制100个方格以在图中创建设计,但该图形由不到50个方格组成。它也以一些非整体的方式缩放,使其看起来具有不同的线条厚度。

让我们专注于问题的范围,而不是示例。 OP的最小值为1平方,所以我保留了它。这种解决方案也自然倾向于将正方形置于窗口中心:

from turtle import Turtle, Screen

DELTA = 3
MINIMUM = DELTA * 2
CURSOR_SIZE = 20

num_squares = -1

while num_squares < 1:
    try:
        num_squares = int(input('Input the number of squares: '))
    except ValueError:
        print("please enter an integer.")

    if num_squares < 1:
        print("You must have at least 1 square.")

screen = Screen()
turtle = Turtle("square", visible=False)
turtle.fillcolor("white")

for size in range(((num_squares - 1) * DELTA) + MINIMUM, MINIMUM - 1, -DELTA):
    turtle.goto(turtle.xcor() + DELTA/2, turtle.ycor() - DELTA/2)
    turtle.shapesize(size / CURSOR_SIZE)
    turtle.stamp()

screen.exitonclick()

这显然不是OP所寻求的那种解决方案,但也许下次这样的问题出现时,它可能是OP至少会考虑的问题。

enter image description here