Python Forum
[PyGame] Variables shared between game states, how to?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Variables shared between game states, how to?
#1
I've followed metulburr's tutorial: https://python-forum.io/Thread-PyGame-Cr...te-machine

Thanks for this BTW.

I'm able to code new states and switch between them at will, but I'm struggling with where in here to define variables that I want visible and changeable by all states(ie. location, money, etc)

I tried a global "location" variable, changed it in the starmap state ("print(location)" confirmed it) and flipped to planetscreen state, but "print(location)" there showed the original definition.

What would I put in here for shared variables and how would in refer to them in the state modules?

class Control:
    def __init__(self, **control_settings):
        self.__dict__.update(control_settings)
        self.done = False
        self.screen = pygame.display.set_mode(self.size)
        self.screen_rect = self.screen.get_rect()
        self.clock = pygame.time.Clock()
        self.state_dict = {
            'menu': Menu(self.screen_rect),
            'starmap': Starmap(self.screen_rect),
            'planetscreen': Planet_screen(self.screen_rect)
        }
    def setup_states(self, start_state):
        self.state_name = start_state
        self.state = self.state_dict[self.state_name]
    def flip_state(self):
        self.state.done = False
        previous,self.state_name = self.state_name, self.state.next
        self.state.cleanup()
        self.state = self.state_dict[self.state_name]
        self.state.startup()
        self.state.previous = previous
    def update(self, dt):
        if self.state.quit:
            self.done = True
        if self.state.done:
            self.flip_state()
        self.state.update(self.screen, dt)
    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            
            self.state.get_event(event)
    def main_game_loop(self):
        while not self.done:
            delta_time = self.clock.tick(self.fps)/1000.0
            self.event_loop()
            
            self.update(delta_time)
            pygame.display.update()
Reply


Messages In This Thread
Variables shared between game states, how to? - by michael1789 - Dec-09-2019, 12:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Best way to pass data to the few game states with the same superclass? Milosz 5 3,082 Oct-20-2021, 01:47 PM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020