我在Python中为每个顶点生成随机坐标,如下所示:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-primary" id="btnsubmit" name="btnsubmit" value="Change Password" />
<input type="button" class="btn btn-warning" id="btnCancel" name="btnCancel" value="Cancel" />
</div>
我需要使用这些顶点创建一个闭合的多边形。有人可以给我一个建议吗?
答案 0 :(得分:2)
如果您不想要交叉点,实现此目的的一种方法是在一些旋转规则后订购您的坐标对。在上面的示例中,我首先定义一个中心点(这里只是所有x值和y值的平均值),然后计算每个坐标对与该中心点定义的角度。正如JRG已经说过的那样,你通过将第一个点附加到你的点序列来得到一个闭合的多边形:
import numpy as np
from matplotlib import pyplot as plt
def draw_polygon(ax, n):
x = np.random.randint(0,50,n)
y = np.random.randint(0,50,n)
##computing the (or a) 'center point' of the polygon
center_point = [np.sum(x)/n, np.sum(y)/n]
angles = np.arctan2(x-center_point[0],y-center_point[1])
##sorting the points:
sort_tups = sorted([(i,j,k) for i,j,k in zip(x,y,angles)], key = lambda t: t[2])
##making sure that there are no duplicates:
if len(sort_tups) != len(set(sort_tups)):
raise Exception('two equal coordinates -- exiting')
x,y,angles = zip(*sort_tups)
x = list(x)
y = list(y)
##appending first coordinate values to lists:
x.append(x[0])
y.append(y[0])
ax.plot(x,y, label = '{}'.format(n))
if __name__ == '__main__':
fig,ax = plt.subplots()
for n in range(3,11,2):
draw_polygon(ax,n)
ax.legend()
plt.show()
答案 1 :(得分:0)
给定n,只生成n-1个随机顶点,最后在列表中添加第一个元素作为获取闭合多边形的第n个元素。
NOTE
:您需要特殊处理新生成的顶点尚未出现在列表中
查找顶点是否形成真正的多边形,可在文章
下找到import random
n = 10
V = []
V = range(n-1) #vertices
random.seed(1)
points = []
for i in V:
x = random.randint(0,50)
y = random.randint(0,50)
points.append((x,y))
points.append(points[0])
print(points)
示例运行
======== RESTART: C:/polygon.py ========
[(8, 36), (48, 4), (16, 7), (31, 48), (28, 30), (41, 24), (50, 13), (6, 31), (1, 24), (8, 36)]