Search code examples
pythonpygamefullscreen

Switching to Pygame Fullscreen Mode working only one time


I'm new to the pygame.FULLSCREEN mode, and I need your help. I'm writing a small game, in which the player is supposed to be able to switch between normal mode and full screen mode.

When I run my program is that the window opens, and when I click on the maximize button I get into full screen mode. When I press escape, I get back to normal mode. Everything's working fine so far.

But when I click the maximize button a second time the window is maximized, however, I do not get into full screen mode. Also, the part of the window that pygame uses remains normal size.

Here's my code:

import pygame

pygame.init()

width = 500
height = 500

info = pygame.display.Info()
screen_width = info.current_w
screen_height = info.current_h

window = pygame.display.set_mode((width, height), pygame.RESIZABLE)

fullscreen = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.VIDEORESIZE:
            window = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)
            fullscreen = True

        keys = pygame.key.get_pressed()

        if keys[pygame.K_ESCAPE] and fullscreen:
            window = pygame.display.set_mode((width, height), pygame.RESIZABLE)
            fullscreen = False

    window.fill((255, 255, 255))
    pygame.display.update()

Thanks in advance!


Solution

  • The pygame.VIDEORESIZE is executed every time when the window is resized. Hence even if the window is changed to a smaller size, then pygame.VIDEORESIZE occurs. Get the new size of the window by event.set and create a new pygame.FULLSCREEN or pygame.FULLSCREEN display dependent on the current state of fullscreen. But set fullscreen by a key, for instance f. pygame.event.post() a new pygame.event.Event() with the proper arguments:

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
    
            elif event.type == pygame.VIDEORESIZE:
                type = pygame.FULLSCREEN if fullscreen else pygame.RESIZABLE
                window = pygame.display.set_mode(event.size, type)
    
            elif event.type == pygame.KEYDOWN:
                if not fullscreen and event.key == pygame.K_f:
                    fullscreen = True
                    pygame.event.post(pygame.event.Event(pygame.VIDEORESIZE, size = (screen_width, screen_height)))
                if fullscreen and event.key == pygame.K_ESCAPE:
                    fullscreen = False
                    pygame.event.post(pygame.event.Event(pygame.VIDEORESIZE, size = (width, height)))
    
        window.fill((255, 255, 255))
        pygame.display.update()