0

I am making a game using python and pygame. I had a problem a few days ago that I needed to give my games a functionality of being resized and maintain the aspect ratio. Also everything on the screen is resized proportionately. And luckily I got a quick solution to create two different pygame surfaces. One is the screen visible to the user and the other is to manage the blitting functionality. Actually, fake screen has everything blitted and then it itself is blitted to the main screen by using

main_screen.blit((pygame.transform.scale(fake_screen, main_screen.get_rect().size), [0, 0]).

The main problem is that now since the MOUSEBUTTONDOWN events are getting triggered on the main screen and not on fake screen, But the clicks are getting processed according to the fake screen. This means that when I click on a button after resizing, the button appears to be their but actually its at its respective position on the fake screen. This makes all the buttons loose their functionality after the VIDEORESIZE event. Can anyone help me out with this? I hope that I was able to explain.

Matiiss
  • 5,970
  • 2
  • 12
  • 29

2 Answers2

0

Easy answer: use the pygame.SCALED display flag.

It resizes the main screen for you and the mouse events too, without your program needing to know anything about it. Documented on this page: https://www.pygame.org/docs/ref/mixer.html

Using this means you wouldn’t need to use a fake screen at all, or do anything at all with scaling on your end.

DIY answer: If you still want to control the scaling yourself, you just have to scale the mouse events along with the screen. Like scale then the opposite way you scale the fake screen.

In your case it looks like that would involve dividing the mouse event x by the ratio between fakescreen width and screen width, and same with y (with heights ofc).

Starbuck5
  • 1,649
  • 2
  • 7
  • 13
  • Thank you for your answer. I like the method of not using a fake screen. However I have currently implemented my own trick and it works fine. But in my next game, I will definitely try to avoid fake screen. Thank you so much for your reply. – Ayushman Rajora Jun 28 '21 at 21:03
0

I got a very easy solution to this myself. I just after getting mouse x and y coordinates, changed them to proportionately corresponding points. With a simple math. I mean, if x coordinate is 15% of main screen width, then convert it to 15% of fake screen width. This way, the fake screen will get properly scaled coordinates. The mathematical equation can be as follows:-

    mouse_x = mouse_x/(xd/100)
    mouse_x *= 10
    mouse_y = mouse_y/(yd/100)
    mouse_y *= 6

Here xd and yd are width and height of the resizable main screen respectively. And 10 and 6 are 1% of 1000 and 600 which are the width and height of the fake screen. This solved my problem and game is now working perfectly. Thank You.