Y.D
Y.D

Reputation: 43

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

Upvotes: 1

Views: 798

Answers (1)

Stuart
Stuart

Reputation: 9858

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([tr.window_width(), tr.window_height()]) - 20

(I'm not sure why it is necessary to reduce the dimension by about 20 pixels, but if I don't do this then the shape is drawn slightly outside the visible area.)

The circumradius is the radius of the circle that passes through all the points of the polygon and the apothem is the distance from the center to the midpoint of a side. For a polygon with odd numbers of sides to just fit the screen, the circumradius needs to be half the height of the screen; for a polygon with even numbers of sides to just fit the screen, the apothem + circumradius should equal the height of the screen.

Reversing the formulae for the circumradius and apothem, we can determine the maximum side length given the height. Also note that 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([tr.window_width(), tr.window_height()]) - 20

    # Determine max side length
    a = math.pi / sides
    if sides % 2:  # odd number of sides 
        size = min_dimension * 2 * math.sin(a) / (1 + math.cos(a)) 
    else:          # even number
        size = min_dimension * math.tan(a)

    # Start near the bottom of the screen
    penup()
    right(90)
    forward(min_dimension / 2)
    right(90)
    forward(size / 2)
    left(180)
    pendown()
    
    # Draw polygon
    for _ in range(sides):
        forward(size)
        left(angle)
    done()   

Upvotes: 1

Related Questions