<p>当我运行程序时,我希望它运行<code>start_game(self)</code>。为此,必须运行构造函数。否则,对象就不存在,因此它们的方法就无法运行。到目前为止,很清楚。基本上,我很难正确地“开始”这个过程</p>
<pre><code>from Surface import Surface
from Pellet import Pellet
from Pacman import Pacman
from Ghost import Ghost
from Timer import Timer
class Controls:
def __init__(self):
global the_surface
the_surface = Surface(self)
the_pellets = []
for y in range(0, 8):
for x in range(0, 14):
pellet = Pellet(x, y)
the_pellets.append(pellet)
global the_pacman
the_pacman = Pacman(the_pellets)
the_ghosts = []
for ghost in range(0, 3):
the_ghosts.append(Ghost())
global the_timer
the_timer = Timer(self, 200)
# [...]
def start_game(self):
self.__init_game_objects()
Timer.start(the_timer)
return
def tick_timer(self):
Pacman.move(the_pacman)
return
# http://stackoverflow.com/a/419185
if __name__ == '__main__':
# need to run start_game()
</code></pre>
<p>我尝试过的(以下所有内容都在<code>if __name__ [...]</code>行之后,每个项目符号代表一次尝试。)</p>
<p><strong>第一次尝试:</strong></p>
<pre><code>the_controls = Controls()
the_controls.start_game(the_controls)
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 53, in Controls
the_controls = Controls()
NameError: name 'Controls' is not defined
</code></pre>
<p><strong>第二次尝试:</strong></p>
<pre><code>__init__('Controls')
self.start_game(self)
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 54, in Controls
self.start_game(self)
NameError: name 'self' is not defined
</code></pre>
<p><strong>第三次尝试(由@TigerhawkT3建议)</strong></p>
<pre><code>the_controls = Controls()
the_controls.start_game()
Traceback (most recent call last):
File "Controls.py", line 8, in <module>
class Controls:
File "Controls.py", line 53, in Controls
the_controls = Controls()
NameError: name 'Controls' is not defined
</code></pre>