【问题标题】:Turtle Graphics: Repeating Squares海龟图形:重复方块
【发布时间】:2018-02-28 21:23:49
【问题描述】:

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

    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()

【问题讨论】:

  • 您有问题吗?到目前为止,你只是给了我们你的家庭作业和一些代码,而没有解释问题是什么。
  • 问题是如何让它增加尺寸,同时保持正方形在同一条线上。到目前为止,我尝试过的每件事要么在另一个正方形之上构建一个正方形,要么它们就遍布整个地方。
  • 您似乎正在绘制相同大小的正方形 - 也许这不是一个好主意?但是 SO 不是来帮你完成作业的,请查看help center 中的材料。
  • 不要求任何人完成我的作业,这是我试图在书中完成的一个练习,以及其他练习,但是当我坚持这个练习时,我想也许有人可以提供帮助.如果您不确定如何操作,那没关系,也许其他人以前遇到过这个问题。

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


【解决方案1】:

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

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()

【讨论】:

  • 啊,这让我大吃一惊。当我试图回到起点时,我要么在彼此上直接绘制正方形,要么在前一个正方形上切开。无法弄清楚如何增加尺寸,非常感谢。
【解决方案2】:

在等待@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 至少会考虑的问题。

【讨论】:

  • 不错的莫尔效应@cdlane
猜你喜欢
  • 2018-05-30
  • 1970-01-01
  • 2017-12-05
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 2016-01-05
相关资源
最近更新 更多