import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QPushButtonfrom PyQt5.QtGui import QPainter, QColor, QPenfrom PyQt5.QtCore import Qtclass ChessBoard(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 500, 500) self.setWindowTitle('五子棋对战') self.show() def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) # 绘制棋盘 for i in range(15): painter.drawLine(50, 50 + i * 30, 440, 50 + i * 30) painter.drawLine(50 + i * 30, 50, 50 + i * 30, 440) # 绘制落子标记 brush = QBrush(Qt.SolidPattern) brush.setColor(QColor(0, 0, 0)) painter.setBrush(brush) painter.drawEllipse(245, 245, 10, 10) def mousePressEvent(self, event): print('鼠标按下:', event.pos()) class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('五子棋对战') self.setGeometry(300, 300, 500, 500) # 水平布局 hbox = QHBoxLayout() self.setLayout(hbox) # 添加棋盘 chessboard = ChessBoard() hbox.addWidget(chessboard) # 添加按钮 vbox = QVBoxLayout() newgamebtn = QPushButton('新游戏') vbox.addWidget(newgamebtn) regretbtn = QPushButton('悔棋') vbox.addWidget(regretbtn) hbox.addLayout(vbox) self.show()if __name__ == '__main__': app = QApplication(sys.argv) mainwindow = MainWindow() sys.exit(app.exec_())
时间: 2024-02-15 13:27:53 浏览: 148
这是一段使用 PyQt5 模块实现的五子棋对战程序的代码。其中,ChessBoard 类是继承自 QWidget 的自定义组件,用于绘制棋盘和落子标记,并响应鼠标事件;MainWindow 类则是继承自 QWidget 的主窗口,包含一个 ChessBoard 组件和两个按钮。你可以在主窗口中点击按钮进行新游戏和悔棋操作,同时在 ChessBoard 组件中落子。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)