我在PyQt5中创建一个游戏,用户可以在网格内单击以形成正方形。如果用户选择形成正方形的四个网格空间,则角落用线连接。我的代码目前看起来像这样:
import sys
from PyQt5.QtGui import QPainter, QColo, QPen, QBrush
from PyQt5.QtCore import Qt, QRect, QPoint
from PyQt5.QtWidgets import QWidget, QApplication
CELL_COUNT = 8
CELL_SIZE = 50
GRID_ORIGINX = 150
GRID_ORIGINY = 150
W_WIDTH = 700
W_HEIGHT = 700
class TribeSquares(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, W_WIDTH, W_HEIGHT)
a = ''
self.__board = [[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a],[a,a,a,a,a,a,a,a]]
self.__row = None
self.__col = None
self.__clicked0 = []
self.show()
首先,我将(x,y)坐标转换为网格坐标。
def mousePressEvent(self, event):
self.__x = event.x()
self.__y = event.y()
self.__row = (event.y() - GRID_ORIGINY) // CELL_SIZE
self.__col = (event.x() - GRID_ORIGINX) // CELL_SIZE
row = self.__row
col = self.__col
self.update()
对于另一种方法,我想将(row,col)转换回(x,y)。我尝试颠倒过程,并按照这样做:
def cell2coord(self, row, col):
return ((row * CELL_SIZE) + GRID_ORIGINX, (col * CELL_SIZE) + GRID_ORIGINY)
接下来,在paintEvent中,我尝试调用我创建的方法。
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
for r in range(CELL_COUNT):
for c in range(CELL_COUNT):
qp.setPen(QPen(Qt.black, 1))
qp.drawRect(CELL_SIZE * c + GRID_ORIGINX, CELL_SIZE * r + GRID_ORIGINY, CELL_SIZE, CELL_SIZE)
if (r, c) in self.__clicked0:
qp.setPen(QPen(QColor(40, 85, 66), 1))
qp.setBrush(QColor(40, 85, 66))
qp.drawRect(CELL_SIZE * c + GRID_ORIGINX + 7.5, CELL_SIZE * r + GRID_ORIGINY + 7.5, 35, 35)
qp.setBrush(QColor(237, 237, 237))
elif (r, c) in self.__clicked1:
qp.setPen(QPen(QColor(231, 181, 71), 1))
qp.setBrush(QColor(231, 181, 71))
qp.drawRect(CELL_SIZE * c + GRID_ORIGINX + 7.5, CELL_SIZE * r + GRID_ORIGINY + 7.5, 35, 35)
qp.setBrush(QColor(237, 237, 237))
for (r, c) in self.__clicked0:
x,y = self.cell2coord(r,c)
x2,y2 = self.cell2coord(self.__row, self.__col)
if r == self.__row or c == self.__col:
qp.setPen(QPen(QColor(40, 85, 66), 5))
qp.drawLine(x, y, x2, y2)
for (r, c) in self.__clicked1:
if r == self.__row or c == self.__col:
qp.setPen(QPen(QColor(231, 181, 71), 5))
qp.drawLine(x, y, x2, y2)
qp.end()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = TribeSquares()
sys.exit(app.exec_())
但它没有用。线条没有显示在正确的位置,并连接用户点击网格中创建的方块。我该怎么办?
答案 0 :(得分:0)
正如您已经使用paintEvent
方法构建了要绘制的矩形,您可以执行此操作以获取QRect
,然后使用其center()
方法,然后获取其坐标
def cell2coord(self, row, col):
center_pos = QRect(CELL_SIZE * c + GRID_ORIGINX, CELL_SIZE * r + GRID_ORIGINY, CELL_SIZE, CELL_SIZE).center()
return center_pos.x(), center_pos.y()