Get screen orientation with Python

1.3k Views Asked by At

I did a simple game using Python and Pygame.

The game works on both orientations (Portrait and Landscape) since that I play in the same orientation that I used to open the game.

If I rotate the device changing the orientation with the game running, everything appears at the wrong place.

The problem is that I don't know how to detect that the device was rotated to redraw the screen correctly.

Then, my question is:

How I can detect that the user rotated the device using only a Python or Pygame code?

IMPORTANT: Suggestions should not be related to any particular OS, because the same code must run on notebooks with touch screen (running Linux, Windows or OS X) and mobile devices (running Android or iOS).

OBSERVATION: I tried to create another screen to get its size and compare with the actual screen using pygame.display.set_mode() but this new screen returned the same size of the actual screen instead of have its width equals to actual screen height.

Thanks for your help.

1

There are 1 best solutions below

1
On

You have to set the RESIZABLE flag when you generate the display surface by set_mode(). When the logical display resolution changes, then you get a VIDEORESIZE event:

screen = pygame.set_mode((0, 0), pygame.FULLSCREEN | pygame.pygame.RESIZABLE)
width, height = screen.get_size()
while run:

    for event in pygame.event.get():
    
        if event.type == pygame.VIDEORESIZE:
             width, height = event.w, event.h