第一段代码来自我的文件“othello_game_logic.py”它是我用来为奥赛罗游戏创建游戏逻辑的模块。我目前的目标是使用我已经创建的逻辑为othello游戏创建一个图形用户界面(gui)。 这个类GameState代表整个othello游戏。
class GameState: # represents a game of Othello
board = [] #represents the board, is a two-dimensional list.
def __init__(self):
self._player_turn = 'BLACK' #keeps track of whos turn it is
def __init__(self):
self._valid_move = True #keeps track of whether or not a move is valid
columns = 4 #columms and rows for the board
rows = 4
下一部分来自一个新模块,我将在其中编写图形用户界面。我是用tkinter做的。
class OthelloGui: # as of now almost everything for the GUI is represented inside of this class.
def __init__(self):
def _run_othello(self):
'''runs the game of othello'''
a = othello_game_logic.GameState() # creates an instance of the GameState class from the other file
a.create_board(a.columns, a.rows) #creates the board, a 2-dimensional list
print(a._valid_move)
print(a._player_turn)
它生成并显示错误消息,指出a._valid_move
和a._player_turn
不存在。但它确实识别a.columns
等全局属性。这是为什么?
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Python34\ics32\project 5\othello_gui.py", line 112, in _canvas_resized
self._run_othello()
File "C:\Python34\ics32\project 5\othello_gui.py", line 40, in _run_othello
print(a._valid_move)
AttributeError: 'GameState' object has no attribute '_valid_move'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Python34\ics32\project 5\othello_gui.py", line 112, in _canvas_resized
self._run_othello()
File "C:\Python34\ics32\project 5\othello_gui.py", line 40, in _run_othello
print(a._valid_move)
AttributeError: 'GameState' object has no attribute '_valid_move'
答案 0 :(得分:2)
欢迎来到SO。您的问题属于“为什么这段代码不起作用?”的类别。这是Help Center section on Asking "What topics can I ask here?"
中涵盖的内容寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为,特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用。请参阅:How to create a Minimal, Complete, and Verifiable example。
特别要阅读"How to create a Minimal, Complete, and Verifiable example"上的部分。
在你的帖子中,我推断你要么是编程新手,要么是Python新手,你可以自己做几件事来回答你的问题:
__init__()
做了什么以及如何正确使用它。pdb
是一个简单的调试器,它允许您逐行遍历代码,设置断点,查询参数和变量,并在当前范围内执行任意代码以测试行为。通过删除额外的__init__
:
>>> class GameState:
>>> board = []
>>> def __init__(self):
>>> self._player_turn = 'BLACK'
>>> self._valid_move = True
>>> columns = 4
>>> rows = 4
>>> def create_board(self, c, r):
>>> pass
>>>
>>> class OthelloGui:
>>> def __init__(self):
>>> pass
>>> def _create_circles(self, board):
>>> pass
>>> def run_othello(self):
>>> '''runs the game of othello'''
>>> a = GameState()
>>> a.create_board(a.columns, a.rows)
>>> print(a._valid_move)
>>> print a._player_turn
>>> self._create_circles(a.board)
>>>
>>> b = OthelloGui()
>>> b.run_othello()
True
BLACK
注意我还向阅读我帖子的人添加了额外的信息,例如所有方法的定义,以便对我的代码实际执行的内容产生较少的疑问。希望这有助于您在编码冒险中获得好运,并请下次尝试提高您在SO上发布的问题的质量,并且您将得到更积极的回复。