大家好(第一次在这里发帖,希望我没有犯什么错误)...
我正在尝试使用Python随机生成一组具有3到2l条边的凸多边形,以使每个多边形的每条边都与l个预定线之一平行。如果有人知道如何做到这一点(无论是使用计算几何包,如CGAL或Shapely还是不使用它们),那就太棒了。
我从一个包含2l个角度的列表开始(每条线的方向以及每条线+ pi的方向用于平行边)。对于我制作的每个多边形,我随机选择3到2l个角度,并按升序排列,以确保每个角度与前一个角度相差不超过pi,以确保角度能够定义一个多边形。然而,在此之后,我无法确保我生成的多边形仍然是凸多边形,并且只包含与我选择的线平行的边。我的代码目前看起来像这样:
def generate(l, n, w, h):
"""Generate n polygons with sides parallel to
at most l vectors in a w x h plane."""
L = []
polygons = []
while len(L) < 2*l:
i = random.uniform(0, math.pi)
if i != math.pi and not i in L:
L.append(i)
L.append(i+math.pi)
L.sort()
while len(polygons) < n:
Lp = list(L)
rm = random.randint(0, 2*l-3)
#Filter out rm lines, if possible
for i in range(rm):
i = random.randint(0, len(Lp)-1)
for j in range(i, len(Lp)) + range(0, i):
nxt = Lp[(j+1)%len(Lp)]
prv = Lp[(j-1)%len(Lp)]
if prv < nxt < prv+math.pi or nxt < (prv+math.pi)%(2*math.pi)-1e-14 < prv:
del Lp[j]
break
# Choose a "center point, then generate a polygon consisting of points
# a fixed distance away in the direction perpendicular to each angle.
# This does not work however; resulting polygons may have sides not
# parallel to one of the original lines.
cx, cy = random.uniform(-w/2,w/2), random.uniform(-h/2,h/2)
points = []
r = random.uniform(10,100)
for theta in Lp:
# New point is r away from "center" in direction
# perpendicular to theta
x = cx + r * math.sin(theta)
y = cy - r * math.cos(theta)
points.append(polygon.Vector(x,y))
polygons.append(polygon.Polygon(points))
return polygons