Why is this pygame program not working so when I hover over the computer screen it turns blue?

To use multithreading in PyGame, you’ve to consider 2 things:

  1. Process an event loop in the main thread

  2. Do all the drawing on and the update of the window in a single thread. If there is an “intro” thread and a “game” thread, then the “intro” thread has to terminate first, before the “game” thread can start.

In the main thread (program) you’ve to declare the threads and to initialize the control (state) variables. Start the “intro” thread immediately and run the event loop.
I recommend to implement at least the pygame.QUIT, which signals that the program has to be terminated (run = False).
Further it can be continuously checked if the mouse is in the start area (inStartRect = startRectArea.collidepoint(*pygame.mouse.get_pos())):

introThread = threading.Thread(target = introLoop)
gameThread = threading.Thread(target = gameLoop)

run = True
intro = True
inStartRect = False
startRectArea = pygame.Rect(279, 276, 220, 128) 

introThread.start()

while run:
    if intro:
        inStartRect = startRectArea.collidepoint(*pygame.mouse.get_pos())
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.MOUSEBUTTONDOWN and inStartRect:
            intro = False

In the intro thread the entire intro screen has to be drawn, including the background and the blue start area. If the intro is finished (the game is started), then at the end of the intro thread the main game loop is started:

def introLoop():

    i = 0
    while run and intro:
        clock.tick(8)

        filename = "introScreen/" + str(i) + ".gif"
        i = i+1 if i < 26 else 0

        introScreen = pygame.image.load(filename)
        introScreen = pygame.transform.scale(introScreen, (width, height))

        screen.blit(introScreen, (30, 30))
        if inStartRect:
            pygame.draw.rect(screen, blue, (279, 276, 220, 128), 0)
        pygame.display.flip()

    gameThread.start()

The game thread starts, when the intro thread terminates. So the game thread can do the drawing of the game scene:

def gameLoop(): 

    while run:
        clock.tick(60)

        screen.fill(red)

        # [...]

        pygame.display.flip()
        clock.tick(60)

Leave a Comment