Python Forum
How to put my game loop into a function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to put my game loop into a function?
#10
I think the main problems is due to scope, reinitialization, and event loop structure. So here's to get your "hold key to start game" idea working:

First of all, avoid using too many global variables. Use a Game class to encapsulate the state and logic. Globals will always give you trouble as the program grows.

Now, keep the main loop separate by using this structure:

def main():
    global running

    while running:
        keys = pygame.key.get_pressed()

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

        if keys[pygame.K_f]:  # When F is held
            game_loop()

        screen.fill(BLACK)
        font = pygame.font.Font(None, 40)
        message = font.render("Hold 'F' to Start", True, WHITE)
        screen.blit(message, (WIDTH//2 - message.get_width()//2, HEIGHT//2))
        pygame.display.flip()
        clock.tick(60)
Then call main() at the bottom of your script:

if __name__ == "__main__":
    main()
    pygame.quit()
Reply


Messages In This Thread
RE: How to put my game loop into a function? - by RogereK - May-23-2025, 12:35 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  I want to add a bullet function to my game. how would i go about it? Iyjja 5 3,082 Jan-09-2024, 05:42 PM
Last Post: Iyjja
  If 2nd input in the game is correct, replace with 1st input and loop the game tylerdurdane 11 6,928 Jul-17-2022, 04:55 AM
Last Post: deanhystad
  [PyGame] Problem With Entering Game Loop ElevenDecember 3 4,258 Jan-19-2020, 08:25 AM
Last Post: michael1789
  [Tkinter] Loop help in game Kgranulo1 1 4,153 Feb-28-2017, 08:02 AM
Last Post: wavic

Forum Jump:

User Panel Messages

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