Control category

Control state machine type, main function is main loop of the game, when the state of running of the game starts setup_states setting function.

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 is
13 is
14
15
16
. 17
18 is
. 19
20 is
21 is
22 is
23 is
event_loop function is responsible for monitoring input (keyboard input and exit button), slef.keys save keyboard input.
done value update function detects the state, call state update function. If it detects the end of the current status, call flip_state function cleanup of the old state, and transition to the next 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()

Guess you like

Origin www.cnblogs.com/hyhy904/p/11535779.html