Control 是状态机类,main函数是游戏的主循环,setup_states函数设置游戏启动时运行的状态。
class Control():
def __init__(self):
self.screen = pg.display.get_surface()
self.done = False
self.clock = pg.time.Clock()
self.fps = 60
self.current_time = 0.0
self.keys = pg.key.get_pressed()
self.state_dict = {}
self.state_name = None
self.state = None
def setup_states(self, state_dict, start_state):
self.state_dict = state_dict
self.state_name = start_state
self.state = self.state_dict[self.state_name]
def main(self):
while not self.done:
self.event_loop()
self.update()
pg.display.update()
self.clock.tick(self.fps)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
event_loop函数负责监听输入(键盘输入和退出按钮),slef.keys 保存键盘输入。
update函数会检测状态的done值,调用状态的更新函数。如果检测到当前状态结束,就调用flip_state函数进行旧状态的清理操作,并转换到下一个状态。
def update(self):
self.current_time = pg.time.get_ticks(http://www.amjmh.com/v/)
if self.state.done:
self.flip_state()
self.state.update(self.screen, self.keys, self.current_time)
def flip_state(self):
previous, self.state_name = self.state_name, self.state.next
persist = self.state.cleanup()
self.state = self.state_dict[self.state_name]
self.state.startup(self.current_time, persist)
def event_loop(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.done = True
elif event.type == pg.KEYDOWN:
self.keys = pg.key.get_pressed()
elif event.type == pg.KEYUP:
self.keys = pg.key.get_pressed()