A few months ago, I worked on a distributed multi-player Pong in python as part of a class project. I found that there wasn’t a whole lot of info on calculating the points that make up a regular polygon. So, using the indispensable Wolfram MathWorld reference, I wrote some code.
The purpose of this code is to construct a regular polygon with n sides (though it doesn’t really make sense with n < 3 sides). When given the number of sides and the length (in “units” of each side), the code will generate a sequence of points starting at the origin, and proceeding counter-clockwise around the polygon.
One of the most helpful quantities when constructing a regular polygon is the exterior angle.
import math def polygon(number_of_sides, side_length = 10): # the exterior angle is the difference in angle # between sides of the polygon and is the same # for every side of a simple polygon exterior_angle = 2. * math.pi / number_of_sides point = (0, 0) angle = 0. yield point for i in xrange(number_of_sides - 1): point = (point[0] + side_length * math.cos(angle), point[1] + side_length * math.sin(angle)) angle += exterior_angle yield point
To use this, just iterate over the result of the function:
for point in polygon(5): do_something(point)
or if you just want a list of points:
# use a list comprehension [pt for pt in polygon(4)] # which results in: [(0, 0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.000000000000002)]