Reputation: 142
I have created two classes named Point
and Triangle
and I have a function pts_polygone
that gives me the list of points in a polygon.
For example PolyPts = pts_polygone(Point(0., 0.), 9, 4)
gives me a polygon of 9 points, centered in O(0, 0)
and of radius 4.
I'm trying to triangulate this polygon, but first I have to extract the list of triangles, and I'm almost there but one is missing, here is what I have:
def tri_polygone(PolyPts):
O = Point(0., 0.)
TriLst = []
for i in range(len(PolyPts)-1):
P2 = PolyPts[i]
P3 = PolyPts[i+1]
TriLst.append(Triangle(O, P2, P3))
return TriLst
The last triangle is missing, to make it a 'circle' if you get what I mean. I know there's something wrong with my dimensions in the list I create, it is of len 8 instead of 9, but I can't figure out how to fix it.
Upvotes: 2
Views: 175
Reputation: 2513
The last triangle should consist of the first point, the last point in PolyPts
and the origin, right? So you can do the following:
def tri_polygone(PolyPts):
O = Point(0.,0.)
TriLst = []
for i in range(len(PolyPts)):
P2 = PolyPts[i]
P3 = PolyPts[i-1]
TriLst.append(Triangle(O,P2,P3))
return TriLst
That way you append 9 points, origin, current point i
and the point behind i
. Python has the nice feature that you can pass negative indices to lists, which means you read the array starting from the end, i.e. PolyPts[-1]
is the last point, PolyPts[-2]
is the second last point and so on.
Upvotes: 1
Reputation: 19403
You are looping "around" the polygon on couples of points. The first with second, second with third, etc... For this, you are rightfully looping on range(len(PolyPts)-1)
. But that means that you never get to the last point inside the loop. Because you are going "around" the polygon, the last point should couple with the first, so just add this line after the loop:
TriList.append(Triangle(O, P3, PolyPts[0]))
Upvotes: 0