2
votes

In pygame I wish to have a scrolling background so that the player can move around a large area, I have done this rather easily, but the game runs very slowly.

some of my code: http://pastebin.com/1EzDV7mc

what am I doing inefficiently? how can I make it run faster?

2

2 Answers

2
votes

See A Newbie Guide to PyGame

In particular:

  1. Use surface.convert()

  2. Ideally use dirty rect animation, only updating the parts of the screen that have changed, not the entire view. That said I have previously used whole screen updates with PyGame (which is what you need to do for a game where the whole screen is constantly scrolling), and it's not that bad on a modern computer as long as you don't have too many objects.

Not mentioned in that guide:

  1. you are aiming for 60fps with clock.tick(60), aim lower, 30fps is fine and won't hose the CPU as much

  2. If you need to do full screen updates for scrolling, then either a) don't use many objects or b) stop using PyGame and switch to OpenGL

  3. why are you blitting images using their mid points, rather than their top left point? A mistake?

  4. It is more usual to store size attributes as seperate width and height attribute, not as a list you have to index. This makes your code much clearer.

0
votes

Adding to what junichiro said, I did find a website giving the information he said plus some.

https://www.pygame.org/docs/tut/newbieguide.html

I'm not calling you a newbie, even I learned quite a bit from this website, and I've been using pygame for 6 years.

Also, surface.convert() only works with non-transparent images. Use surface.convert_alpha(), which works with everything. I usually create a function so I don't have to type the entire thing every time I want to load an image. Feel free to use the following 2 lines of code:

def loadify(imgname):
    return pygame.image.load(imgname).convert_alpha()

This increased the fps of my game from 18 to 30 fps.

Good luck!