Windspar

Pygame Simple Infinite State Machine

Oct 16th, 2025 (edited)
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | Gaming | 0 0
  1. # This is a simple example.
  2. import pygame
  3.  
  4. class State:
  5.   def __init__(self, control):
  6.     self.control = control
  7.  
  8.   def on_draw(self, surface): pass
  9.   def on_event(self, event): pass
  10.   def on_update(self, delta): pass
  11.  
  12. class StateControl:
  13.   def __init__(self, caption, size, flags=0, fps=60):
  14.     pygame.display.set_caption(caption)
  15.     self.display = pygame.display.set_mode(size, flags)
  16.     self.rect = self.display.get_rect()
  17.     self.clock = pygame.time.Clock()
  18.     self.delta = 0
  19.     self.fps = fps
  20.     self.running = True
  21.  
  22.     self.current_state = None
  23.     self.next_state = None
  24.  
  25.   def main_loop(self):
  26.     while self.running:
  27.       if self.next_state:
  28.         self.current_state = self.next_state
  29.         self.next_state = None
  30.  
  31.       for event in pygame.event.get():
  32.         if event.type != pygame.QUIT:
  33.           self.current_state.on_event(event)
  34.         else:
  35.           self.running = False
  36.  
  37.       self.current_state.on_update(self.delta)
  38.       self.current_state.on_draw(self.display)
  39.       pygame.display.flip()
  40.       self.delta = self.clock.tick(self.fps) / 1000
  41.  
  42.   def run(self, state):
  43.     if state:
  44.       self.current_state = state
  45.       self.main_loop()
  46.  
  47. class RedState(State):
  48.   def __init__(self, control):
  49.     super().__init__(control)
  50.     self.background = 'firebrick'
  51.  
  52.   def on_draw(self, surface):
  53.     surface.fill(self.background)
  54.  
  55.   def on_event(self, event):
  56.     if event.type == pygame.KEYDOWN:
  57.       self.control.next_state = BlueState(self.control)
  58.  
  59. class BlueState(State):
  60.   def __init__(self, control):
  61.     super().__init__(control)
  62.     self.background = 'dodgerblue'
  63.  
  64.   def on_draw(self, surface):
  65.     surface.fill(self.background)
  66.  
  67.   def on_event(self, event):
  68.     if event.type == pygame.KEYDOWN:
  69.       self.control.next_state = RedState(self.control)
  70.  
  71. def main():
  72.   control = StateControl("Example Infinite State Machine", (800, 600))
  73.   control.run(RedState(control))
  74.  
  75. if __name__ == "__main__":
  76.   pygame.init()
  77.   main()
  78.   pygame.quit()
  79.  
Advertisement
Add Comment
Please, Sign In to add comment