Python龟程序没有正确绘制多边形

时间:2018-02-12 18:50:10

标签: python-3.x turtle-graphics

当我使用海龟工具运行程序时,它只会形成一条水平线并且不会形成完整的形状。我不确定为什么会这样。我已经制作了一个可以绘制预定形状的工作程序,例如正方形。我已经测试了我的计算,我相信我的for循环是正确的。我只是做了一些愚蠢的语法错误吗?

# polygon program

# get inputs
side_count = int(input( "How many sides does the polygon have?" ))
side_length = int(input( "How long is each side?" ))

# compute side angle
shape_angle = (side_count - 2) * 180

# import turtle modules
from turtle import *

# measure angles in
degrees()

# drawing speed
speed( 6 )

# square specs
color( 'green' )
width( 3 )
setheading( 0 )

# forloop to draw the polygon
for side in range ( side_count ):
    forward ( side_length ) 
    left ( shape_angle )

# all done drawing
done()

2 个答案:

答案 0 :(得分:0)

首先,首先导入所有模块,直到你必须使用它才是必要的,但这是一个好习惯。 shape_angle也是整个形状的总和。 为了使它工作,您将拥有原始代码:

shape_angle = (side_count - 2) * 180

然后将其放在括号中并将其除以side_count以找到单个角度,结果:

shape_angle = ((side_count - 2) * 180) / side_count

还要摆脱degrees

import turtle as *
side_count = int(input( "How many sides does the polygon have?" ))
side_length = int(input( "How long is each side?" ))
shape_angle = ((side_count - 2) * 180) / side_count
speed( 6 )
color( 'green' )
width( 3 )
setheading( 0 )
for side in range ( side_count ):
    forward ( side_length ) 
    left ( shape_angle )
done()

`

答案 1 :(得分:0)

虽然我同意@TudorPopescu认为这一行是你的主要问题:

shape_angle = (side_count - 2) * 180

该解决方案对我不起作用,所以我建议更简单的开始:

shape_angle = 360 / side_count

您的代码使用上述修复和样式更改进行了重新设计:

# polygon program

# import turtle modules
from turtle import *

# get inputs
side_count = int(input("How many sides does the polygon have? "))
side_length = int(input("How long is each side? "))

# compute side angle
shape_angle = 360 / side_count

# measure angles in
degrees()  # the default

# drawing speed
speed('normal')  # the default

# square specs
color('green')
width(3)
setheading(0)  # the default initial heading

# for loop to draw the polygon
for side in range(side_count):
    forward(side_length)
    left(shape_angle)

# all done drawing
done()