简体   繁体   English

用海龟图形绘制多边形

[英]Drawing polygon with turtle graphics

I am trying to draw a polygon in python using the turtle library.我正在尝试使用turtle库在 python 中绘制一个多边形。 I want to set the size to fit the screen size but I don't know how.我想设置大小以适合屏幕大小,但我不知道如何。 For now I tried two ways and it does work but I want that no matter the size the polygon fits in the screen.现在我尝试了两种方法,它确实有效,但我希望无论多边形适合屏幕的大小如何。 For example if I put size = 50 and n = 100 it will not show in the screen.例如,如果我设置 size = 50 和 n = 100,它就不会显示在屏幕上。

from turtle import * 
def main():
    sides = int(input('Enter the number of sides of a polygon: '))
    angle = 360/sides
    size = 500/sides
# =============================================================================
#     if sides <= 20:
#         size = 50
#     else: 
#         size= 10
# =============================================================================
    for i in range(sides):
        forward(size)
        left(angle)
        i += 1
    hideturtle()
    done()   
main()

If I understand correctly, you are asking how to choose a size (side length) such that the shape fills but does not exceed the screen.如果我理解正确,您会问如何选择size (边长)以使形状填充但不超过屏幕。 First, we need to check the height or width of the screen (whichever is smaller):首先,我们需要检查屏幕的高度或宽度(以较小者为准):

min_dimension = min(screensize())  # by default, 300 pixels

The circumradius is the radius of the circle that passes through all the points of the polygon .外接半径通过多边形所有点的半径。 For the polygon to fit in the screen, the circumradius should be equal to min_dimension .为了使多边形适合屏幕, min_dimension半径应等于min_dimension Reversing the formula for the circumradius we can write a function to determine the appropriate side length:反转圆周半径公式,我们可以编写一个函数来确定合适的边长:

def side_length(circumradius, number_of_sides):
    return circumradius * 2 * math.sin(math.pi / number_of_sides)

To fill the screen we should start drawing near the bottom of the screen rather than in the center.为了填满屏幕,我们应该开始在屏幕底部附近而不是在中心绘制。

def main():
    sides = int(input('Enter the number of sides of a polygon: '))
    angle = 360/sides
    min_dimension = min(screensize())
    size = side_length(min_dimension, sides)
    right(90 + angle / 2)
    
    # Start from near the bottom of the screen
    penup()
    forward(min_dimension)
    left(90 + angle / 2)
    pendown()

    # Draw polygon
    for _ in range(sides):
        forward(size)
        left(angle)
    hideturtle()
    done()   

(Technically, this makes the shape slightly smaller than the screen, especially for low numbers of sides. The apothem should be used instead of the circumradius.) (从技术上讲,这使得形状比屏幕略小,特别是对于边数较少的情况。应该使用国题而不是圆周率。)

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

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