我想用PyCharm和PyQt5制作一个Gomoku游戏
我在game.py中编写游戏逻辑,在window.py中编写游戏图形界面
在game.py中,我定义g_map
来保存数据。在window.py中,我导入game
来绘制棋子
但是,我无法对错误进行纠正:
AttributeError: 'GomokuWindow' object has no attribute 'g'
game.py
class Gomoku:
def __init__(self):
self.g_map=[[0 for y in range(15)] for x in range(15) ]# current chess board if 0 None if 1 white,if 2 black
self.cur_step=0 # current step
window.py
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QPen, QColor ,QPainter
from PyQt5.QtWidgets import QMainWindow
#######################################################################
from game import Gomoku # here i import Gomoku class
#######################################################################
class GomokuWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
########################################################################
self.g = Gomoku() # I Create member variables || i need Gomoku().g_map
########################################################################
def init_ui(self):
self.setObjectName('Main Window')
self.setWindowTitle("五子棋")
self.setFixedSize(650,650)
self.setStyleSheet("QMainWindow{background-color:green}")
self.show()
def paintEvent(self,e):
qp = QPainter()
qp.begin(self)
self.draw_map(qp)
self.draw_pieces(qp)
qp.end()
def draw_map(self,qp):
qp.setPen(QPen(Qt.black, 2, Qt.SolidLine))
for x in range(15):
qp.drawLine(40*(x+1),40,40*(x+1),600)
for y in range(15):
qp.drawLine(40,40*(y+1),600,40*(y+1))
#######################################################################
in this method i use self.g.g_map
#######################################################################
def draw_pieces(self,qp):
# i try this:
# g_map = Gomoku().g_map || its ok
qp.setPen(QPen(QColor(0,0,0),1,Qt.SolidLine))
qp.setBrush(QColor(0,0,0))
for x in range(15):
for y in range(15):
#######################################################################
if self.g.g_map[x][y] == 1: here
#######################################################################
qp.drawEllipse(QPoint(40*(x+1)),40*(y+1),15,15)
qp.setPen(QPen(QColor(255, 255, 255), 1, Qt.SolidLine))
qp.setBrush(QColor(255, 255, 255))
for x in range(15):
for y in range(15):
if self.g.g_map[x][y] == 2:
qp.drawEllipse(QPoint(40 * (y + 1)), 40 * (y + 1), 15, 15)
请说:
"D:\Program Files (x86)\Python38-64\python.exe" D:/pychram/五子棋/main.py
Traceback (most recent call last):
File "D:\pychram\������\window.py", line 30, in paintEvent
self.draw_pieces(qp)
File "D:\pychram\������\window.py", line 54, in draw_pieces
if self.g.g_map[x][y] == 1:
AttributeError: 'GomokuWindow' object has no attribute 'g'
Process finished with exit code -1073740791 (0xC0000409)
我试图在{
似乎在self.g初始化之前,paintEvent方法调用draw\u pieces方法
尝试将self.g初始化移动到init函数的开头,如下所示:
相关问题 更多 >
编程相关推荐