Search code examples
pythonpython-3.xtimepygameframe-rate

Setting a fixed FPS on a Python 3 game


I'm currently making a game using PyGame (Python 3), and I'm looking for a way to make the game run at a fixed FPS.

Most of the game is located inside a giant while loop, where the user input is taken, sprites are rendered, etc. every tick. My problem is that running the game on a slow computer is fine, but running it on a fast one makes the game way too fast. I can, of course, add a time.sleep() command at the end of the loop, but then the game will run too slow on slow computers.

Is there a way to make the loop take a specified amount of time to run through? Thanks in advance.


Solution

  • Use the clock module in pygame.

    clock = pygame.time.Clock()
    

    Then in your main loop call this once per frame:

    clock.tick(30) # Now your game will be capped at 30 fps
    

    To read more about the clock module here is the documentation: http://www.pygame.org/docs/ref/time.html