我花了一段时间尝试用python制作同心正方形

2024-06-23 18:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Python3和while语句为同心正方形编写一个代码,但没有完全正确。帮点忙?谢谢好的,这是我的尝试:

import turtle

t = turtle.Turtle()

x=0
y=0
z=0
a=-0
b=0
c=-0
d=0
e=0


while x < 100:
  t.pendown()
  x=x-10
  y=y+10
  t.goto(x,y)
  z=z-10
  a=a-10
  t.goto(z,a)
  b=b+10
  c=c-10
  t.goto(b,c)
  d=d+10
  e=e+10
  t.goto(d,e)
  t.setposition(x,y)
  
  
turtle.done()

我想用一段时间,所以是的。。。谢谢


Tags: 代码import语句python3turtledonewhilegoto
3条回答

您需要使用penup和pendown停止并开始绘制轨迹

import turtle

t = turtle.Turtle()

x=0
y=0
z=0
a=-0
b=0
c=-0
d=0
e=0


while x < 100:
    t.penup()
    x=x-10
    y=y+10
    t.goto(x,y)
    t.pendown()
    z=z-10
    a=a-10
    t.goto(z,a)
    b=b+10
    c=c-10
    t.goto(b,c)
    d=d+10
    e=e+10
    t.goto(d,e)
    t.setposition(x,y)

turtle.done()

也许是一种更干净的方式:

import turtle

squares = 5 # Choose how many squares
scale = 20 # Chose the scale of the squares

t = turtle.Turtle()
for i in range(squares+1):
    for _ in range(4):
        t.pendown()
        t.forward(scale*i)
        t.right(90)
    t.penup()
    t.setpos(t.xcor()-scale/2,t.ycor()+scale/2)

turtle.done()

输出:

turtle-graphics

就快到了,只需添加一个笔画:

while x < 100:
   t.penup()         # <- penup here
   x=x-10
   y=y+10
   t.goto(x,y)
   z=z-10
   a=a-10
   t.pendown()       # <- pendown here
   t.goto(z,a)
   b=b+10
   c=c-10
   t.goto(b,c)
   d=d+10
   e=e+10
   t.goto(d,e)
   t.setposition(x,y)
  
  
   turtle.done()

相关问题 更多 >

    热门问题