简体   繁体   English

使用Turtle绘制形状

[英]Drawing Shapes Using Turtle

I'm trying to use Python/Turtle to achieve a result like this: 我正在尝试使用Python / Turtle实现如下结果:

http://i.imgur.com/2eoAB.png http://i.imgur.com/2eoAB.png

I drew the squares uneven in paint but I mean for them to be even. 我画了油漆不均匀的正方形,但我的意思是使它们均匀。 The squares can be any shape as well depending on the user input (for ex. 5 for polygons). 取决于用户输入,正方形也可以是任何形状(例如,多边形为5)。

Here is my code so far: 到目前为止,这是我的代码:

import turtle
import time
import random

print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
    squares = int(num_str)

angle = 180 - 180*(squares-2)/squares

turtle.color(random.random(),random.random(), random.random())
turtle.begin_fill()

count = 0
x = -80
y = -80
turtle.setpos(x,y)
turtle.down()

while count < 8:
    x += 50
    y += 50
    turtle.goto(x,y)
    for i in range(squares):
        count += 1
        turtle.forward(20)
        turtle.left(angle)
        turtle.forward(20)      
        print (turtle.pos())

turtle.end_fill()

time.sleep(15)
turtle.bye()

And here is what I get: 这就是我得到的:

http://i.imgur.com/7hAje.png http://i.imgur.com/7hAje.png

The error I get is: How can I get it to print out 8 shapes total, instead of only 2, I though the loop would make it repeat 8 times because of the count += 1 < 8? 我得到的错误是:我怎么能打印出总共8个形状,而不是仅打印2个形状,尽管由于计数+ = 1 <8而使循环重复8次?

I thought the loop would change the position of x and y by adding 50, 50 each time and then I would tweak it to give the right coordinates to make the shape I want, but it won't even display all 8 yet? 我以为循环会通过每次加50、50来改变x和y的位置,然后我会对其进行调整以给出正确的坐标以形成所需的形状,但是它甚至不会显示全部8个?

I've spent a while reconfiguring the code but instead of doing trial and error forever, I figured maybe some help would work, thanks. 我花了一些时间重新配置代码,但我没有想过永远反复试验,而是想出了一些帮助,谢谢。

I am using Python 3.2.3 我正在使用Python 3.2.3

If you choose to display a shape with four sides, you're only going to draw two shapes. 如果选择显示具有四个边的形状,则只绘制两个形状。 This is because you're increasing your loop counter once per side for each shape . 这是因为您要为每种形状 每侧增加一次循环计数器。

This is not a good way to do loops, counters are rarely necessary, and when they are - use enumerate 这不是执行循环的好方法,很少需要使用计数器,如果需要,可以使用- enumerate

You want to try something like this. 您想尝试这样的事情。

numshapes = 8
for x in range(numshapes):
  x += 50
  y += 50
  turtle.goto(x,y)
  for i in range(squares):
      turtle.forward(20)
      turtle.left(angle)
      turtle.forward(20)      
      print (turtle.pos())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM