One Byte Wealth

Wednesday, October 26, 2005

Regular Polygon

When all edges of polygon are having same lengths and meeting at same interior angle, that is being known as regular polygon. Radius and number of vertices(edges) are the known factors based on which the polygon is constrcuted.

First interior angle is calculated by:
angle = 2*math.pi/vertices

Now allocate each point by formula

>>> for i in range(0,vertices):
. . . X = math.cos(angle*i)*radius
. . . Y = math.sin(angle*i)*radius

Following image shows the simple polygon drawn on my screen



By adding code for GUI and lines between the allocated points of polygon, final program will be as following,

from Tkinter import *
import math

# Known Polygon Params
# Outer dia, Center point and vertices
OuterDia = 200
Cpx = 200
Cpy = 150
vertices = 6

# First point
fromX = Cpx + OuterDia/2
fromY = Cpy

# Calculate angle between edges
angle = 2*math.pi/vertices

root = Tk()
root.title("Polygon")
canvas = Canvas(width=400,height=300,background =‘white‘)

# Core logic goes here
# I made changes to draw lines
# rather than finding points

for i in range(0,vertices+1):
toX = math.cos(angle*i)*OuterDia/2 + Cpx
toY = math.sin(angle*i)*OuterDia/2 + Cpy
canvas.create_line(toX,toY,fromX,fromY,fill=‘brown‘)
fromX = toX
fromY = toY
canvas.pack()
mainloop()

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home