简体   繁体   中英

Drawing polygon with turtle graphics

I am trying to draw a polygon in python using the turtle library. 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.

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. 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 . 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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