How to Control Pygame Frame Rate with Time Clock

In this Pygame article we want to learn about How to Control Pygame Frame Rate with Time Clock, so first of all let’s talk about Pygame, Pygame is popular Python library for creating 2D games and multimedia applications. when you are building games, than there will be a key challenge on your way, and that is controlling the frame rate, if you have too loo frame rate, than your game maybe sluggish, if you have too high frame rate, than the game may consume too much CPU resources or lead to screen tearing. luckily Pygame provides builtin Time Clock object that can help you control the frame rate of your game

 

 

 

For using Pygame Time Clock, first you need to create a Clock object using Pygame.time.Clock() function. Clock object provides a tick() method that you can use to control the frame rate of your game, in this example we have imported Pygame library, after that we have initialized it and created a Clock object.

 

 

After that you have created Time Clock object, you can use its tick() method to control the frame rate of your game. tick() method takes an optional argument that specifies maximum frame rate you want to achieve in frames per second or we can say FPS.

 

 

For using Pygame Time Clock in a game loop, you can call tick() method at the end of each iteration of the loop to control the frame rate of your game. for example this is a simple game loop that uses Pygame Time Clock to control the frame rate.

 

 

 

This is a complete code for simple Ball Game, that we are controlling the frame rate in the game, so first this example code create the window, after that it generates a list of Ball objects and runs the game loop that updates and draws the ball on the screen.

in here Pygame Time Clock is used to control the frame of the game, and it runs at consistent speed.

 

 

 

Run the complete code and you will see a bouncing ball in the window the nice frame rate and speed, if you change the frame rate than the speed will also change.

How to Control Pygame Frame Rate with Time Clock
How to Control Pygame Frame Rate 

 

 

 

Learn More on Pygame

Leave a Comment