Frank Zhou
Frank Zhou

Reputation: 31

How to close the pygame window without using quit()/sys.exit() so that I don't quit the loop outside of the game?

I am creating a chat system and want to insert a game made with Pygame. In the state_machine file of the chat system, I set a state of the client as S_GAMING. When the client type "game" in the S_LOGGEDIN state, the state will be changed into S_GAMING and when the game is over, the user can quit the game either by clicking the "x" button or by waiting for 3 seconds.

I have some trouble closing the game window without exiting the chat system.

when I used pygame.quit(), the window will froze. When I tried pygame.quit() and sys.exit() or quit(), I exited the chat system as well.

This is a part of the game.py file:

run = True

gameOver = False

timer = 0

while run:

   clock.tick(27)   

   #check events
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           run = False

   if not gameOver:

       drawWindow()
       for each in barriers:
           if each.isHit:
               gameOver = True
   else:
       if timer < 81:
           win.blit(game_over,(0,0))
           timer +=1 
           pygame.display.update() 
       else:
           run = False

pygame.display.quit()

pygame.quit()

This is a part of the chat_state_machine file:

elif self.state == S_GAMING:

    import game

    self.state = S_LOGGEDIN

I know this is a specific question and I can provide more code if the above is not clear. Hopefully, I can get an answer. I am all ears.

Upvotes: 3

Views: 779

Answers (1)

ScriptLine Studios
ScriptLine Studios

Reputation: 11

Here is a simple solution: Once you exit pygame the code should throw an exception, in that case you can switch run to False and start a new loop

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
run = True

while run:
   try:
      screen.fill((0,0,0))

      for event in pygame.event.get():
          if event.type == pygame.QUIT:
              pygame.quit()

      clock.tick(120)
      pygame.display.update()
   except:
      run = False

while not run:
  #Your other code here
  pass

Upvotes: 1

Related Questions