The state machine code implementation

Because the purpose of this article is the game interface state machine, so a state_demo.py wrote a special file, so that we can more easily see the code.

Game startup code
begins to initialize pygame, and set the screen size is c.SCREEN_SIZE (800, 600). All constants are stored in a separate constants.py in.

import os
import pygame as pg
import constants as c

pg.init ()
pg.event.set_allowed ([pg.KEYDOWN, pg.KEYUP, pg.QUIT])
pg.display.set_caption (c.ORIGINAL_CAPTION)
SCREEN = pg.display.set_mode (c.SCREEN_SIZE)
SCREEN_RECT = SCREEN .get_rect ()
1
2
3
4
5
6
7
8
9
load_all_gfx function to find all the pictures in line with the suffix specified directory, use pg.image.load function to load, save in the graphics set in.
GFX save all the pictures resources / graphics directory found, it will be used when acquiring a variety of graphics behind.

def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', '.jpg', '.bmp', '.gif')):
graphics = {}
for pic in os.listdir(directory):
name, ext = os.path.splitext(pic)
if ext.lower() in accept:
img = pg.image.load(os.path.join(directory, pic))
if img.get_alpha():
img = img.convert_alpha()
else:
img = img.convert()
img.set_colorkey(colorkey)
graphics[name] = img
return graphics

= Load_all_gfx the GFX (the os.path.join ( "Resources", "Graphics"))
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
The following is the demo function entry, create a save all state state_dict set, the function call setup_states initial state is provided MAIN_MENU.

if __name__=='__main__':
game = Control()
state_dict = {c.MAIN_MENU: Menu(),
c.LOAD_SCREEN: LoadScreen(http://www.amjmh.com/v/BIBRGZ_558768/),
c.LEVEL: Level(),
c.GAME_OVER: GameOver(),
c.TIME_OUT: TimeOut()}
game.setup_states(state_dict, c.MAIN_MENU)
game.main()

Guess you like

Origin www.cnblogs.com/ly570/p/11535803.html