龟图:重复正方形

问题描述 投票:0回答:2

我正在尝试创建一个循环,它接受用户的输入并绘制多个正方形,但它会增加每个循环的正方形的大小,但是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()
python python-3.x turtle-graphics
2个回答
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()

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

© www.soinside.com 2019 - 2024. All rights reserved.