先定义一个State 基类, 按照上面说的状态需要的三个操作分别定义函数(startup, update, cleanup)。在 init 函数中定义了上面说的三个变量(next,persist,done),还有start_time 和 current_time 用于记录时间。
class State():
   def __init__(self):
       self.start_time = 0.0
       self.current_time = 0.0
       self.done = False
       self.next = None
       self.persist = {}
   @abstractmethod
   def startup(self, current_time, persist):
       '''abstract method'''
   def cleanup(self):
       self.done = False
       return self.persist
   @abstractmethod
   def update(sefl, surface, keys, current_time):
       '''abstract method'''
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
看一个状态类LoadScreen的具体实现,这个状态的显示效果如图3。
startup 函数保存了传入的persist,设置 next 为Level 状态类,start_time保存进入这个状态的开始时间。初始化一个Info类,这个就是专门用来显示界面信息的。
update 函数根据在这个状态已运行的时间(current_time - self.start_time),决定显示内容和是否结束状态(self.done = True)。
class LoadScreen(State):
   def __init__(self):
       State.__init__(self)
       self.time_list = [2400, 2600, 2635]
   def startup(self, current_time, persist):
       self.start_time = current_time
       self.persist = persist
       self.game_info = self.persist
       self.next = self.set_next_state(http://www.amjmh.com/v/BIBRGZ_558768/)
       info_state = self.set_info_state()
       self.overhead_info = Info(self.game_info, info_state)
   def set_next_state(self):
       return c.LEVEL
   def set_info_state(self):
       return c.LOAD_SCREEN
   def update(self, surface, keys, current_time):
       if (current_time - self.start_time) < self.time_list[0]:
           surface.fill(c.BLACK)
           self.overhead_info.update(self.game_info)
           self.overhead_info.draw(surface)
       elif (current_time - self.start_time) < self.time_list[1]:
           surface.fill(c.BLACK)
       elif (current_time - self.start_time) < self.time_list[2]:
           surface.fill((106, 150, 252))
       else:
           self.done = True