绘制同心正方形

时间:2016-12-12 16:54:13

标签: python turtle-graphics

在阅读本书时,#34;如何思考...",我坚持练习4.9.2。

问题是:"写一个程序来绘制它。假设最里面的正方形是每边20个单位,并且每个连续的正方形每边比其内部的正方形大20个单位"

enter image description here

以下代码表示我到目前为止的距离:

import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()

def draw_square(t,size):
    for i in range(4):
        tess.forward(size)
        tess.left(90)

size = 20
for j in range(3):
   tess.pensize(3)
   draw_square(tess,size)
   size = size + 20
   tess.penup()
   tess.goto(-20, -20)
   tess.pendown()

wn.mainloop()

有人可以这么善良并告诉我正确的方向吗?

谢谢!

斯文

6 个答案:

答案 0 :(得分:1)

问题在于:

tess.goto(-20, -20)

你有两个问题。首先,如果每个方格大于20个单位,并且您将每个方格偏移(-20, -20),则所有方格将共享一个角。相反,您希望将方块的角部偏移(-10, -10),以便内部方块在所有侧面上偏移10个单位。

第二个问题是.goto(x, y)设置绝对位置,而不是偏移量。要移动到偏移量,您需要根据偏移量计算新的绝对位置:

tess.goto(tess.xcor()-10, tess.ycor()-10)

或者

tess.goto(tess.pos() + (-10, -10))

答案 1 :(得分:0)

有时当你被卡住时,使用乌龟图形的好方法是在广场之外思考。如果我们将期望的结果视为严重绘制的同心圆,则问题将减少为:

from turtle import Turtle, Screen

HYPOTENUSE = (2 ** 0.5) / 2

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

tess = Turtle()
tess.pencolor("red")
tess.setheading(45)
tess.width(3)

for radius in range(20, 20 * 5 + 1, 20):
    tess.penup()
    tess.goto(radius/2, -radius/2)
    tess.pendown()
    tess.circle(radius * HYPOTENUSE, steps=4)

screen.exitonclick()

<强>输出

enter image description here

答案 2 :(得分:0)

import turtle
def drawSquare (t, size):
    for i in range (4):
        t.forward(size)
        t.left(90)

def main():
    wn = turtle.Screen()
    wn.bgcolor('black')
    pat = turtle.Turtle()
    pat.pensize(2)
    pat.speed(10)
    pat.color('blue')
    space = -10

    for i in range(20, 105, 20):
        drawSquare(pat,i)
        pat.up()
        pat.goto(space, space)
        pat.down()
        space = space - 10
    wn.exitonclick()
main()

答案 3 :(得分:0)

import turtle
def draw_sqr(name,size):
    for i in range(4):
        name.forward(size)
        name.left(90)
    name.penup()
    name.backward(10)
    name.right(90)
    name.forward(10)
    name.left(90)
    name.pendown()

window = turtle.Screen()
window.bgcolor('lightgreen')
window.title("conc_sqr")

x = turtle.Turtle()
x.color('hotpink')
x.pensize(3)

for i in range(5):
    draw_sqr(x,20 + 20*i)

window.mainloop()

答案 4 :(得分:0)

exit

答案 5 :(得分:0)

    import turtle 

    def drawsquare(t,sz): #(turtle, size)
        for i in range(4):
            t.fd(sz)
            t.right(90)
        
    def main():
        wn = turtle.Screen()
        your_turtle = turtle.Turtle()
        your_turtle.pensize(3)
        wn.bgcolor("light green")
        your_turtle.pencolor("hot pink")
        
        for i in range(1,6):
            drawsquare(your_turtle,20*i)
            your_turtle.up()
            your_turtle.left(135)
            your_turtle.fd(14.142) #the distance between each square
            your_turtle.right(135)
            your_turtle.down()
        
    main()
    wn.exitonclick()
相关问题