【发布时间】:2018-05-01 21:39:20
【问题描述】:
我正在尝试创建一个程序,用户可以在其中单击网格上的正方形并使用 PyQt5 (QPainter) 创建正方形,但我无法让程序识别何时何地画线。所有点击的点都存储在一个列表中。
clicked0 = [] #clicked points
distlist0 = [] # list of distances between 2 points
distdict0 {} = # dictionary to identify which two points go with each distance
#there are versions of these for both player 0 and player 1
这是我用来让程序识别和绘制正方形的代码:
for i in list(itertools.combinations(clicked0, 2)):
woo = list(chain.from_iterable(i))
dist = math.hypot(woo[2]-woo[0],woo[3]-woo[1])
distlist0.append(dist)
distdict0[str(dist)] = "("+str(woo[0])+","+str(woo[1])+"), ("+str(woo[2])+","+str(woo[3])+")"
listy = list(itertools.combinations(distlist0, 4))
for i in listy:
if i[0] == i[1] and i[0] == i[2] and i[0] == i[3]:
for item in i:
diction = list(chain.from_iterable(distdict0.get(str(item))))
diction = [int(diction[1]),int(diction[3]),int(diction[8]),int(diction[10])]
x,y = self.cell2coord(diction[0],diction[1]) #method to turn grid coords into x,y coords
x2,y2 = self.cell2coord(diction[2],diction[3])
qp.setPen(QPen(QColor(40, 85, 66), 5))
qp.drawLine(x, y, x2, y2)
这会导致 Python 最终变慢并崩溃,但这是视觉结果:
当可以从它们创建正方形时,这些线应该连接彩色网格空间(角)。我已经在这部分代码上工作了几个小时,但我不确定我可以做些什么来简化/纠正这个过程。
【问题讨论】:
-
你的意思是在同一条线上的任意两个正方形都应该连接起来,还是只有四个成对的正方形组成一个矩形?
-
@Nathan 只有四个成对的彩色方格。
-
为什么有 2 个用户问同一个问题? Given a list of coordinates, check whether any form a square
-
如果您与另一个问题中的人是同一个人。我建议关闭您的任何一个问题或合并它们。它将帮助未来的读者。
-
下次发布代码时。请务必发布我们可以在不添加任何内容的情况下运行的代码(请参阅Minimal, Complete, Verifiable Example)。在下面的答案中,帖子是完整的程序,省略了图形 I/O 和其他不必要的细节。
标签: python python-3.x pyqt5 qpainter