To avoid the hardware-dependence of frame-based movement you can force pygame to calculate time-based movement. Please note that we still speak of the illusion of movement, because all what pygame does is blitting blobs (surfaces) to different positions - but in a more reliable way !
Time-based movement does not mean that your pygame program will run on crappy computers as smooth as on fast machines - pygame can not (yet) do that! Time-based movement just means that independent of the speed of the computer, in the source code example below the ball will always take the same amount of time to cross the screen. On fast machines, the movement will appear very smooth, while on slow machines the movement will appear bumpy.
The secret to time-based movement is to let pygame calculate how much time was passed since the last cycle of the mainloop (to be exact: since the last call of the clock.tick command). Pygame provide this information in milliseconds. In the source code example below I convert this value into seconds 1). This time value is multiplied to the speed vector:
#calculate new center of ball (time-based) ballx += dx * seconds # float, since seconds passed since last frame is a decimal value bally += dy * seconds
Note that the value of seconds will be something like 0.05 seconds per frame 2) so you need rather high dx and dy values to see any movement at all. In this example dx and dy speed values are set at 60 pixel per second.
In this pygame example, the whole background is blitted onto the screen each cycle (frame) of the mainloop. This will overwrite all old images of the ball surface. On top of the fresh background, the ball is blitted each frame. While this method of cleaning the whole screen allow you care-free programming, very big pygame windows (screen resolution) or slow computers will show a drop in the frame-rate. The next chapters will show you more time- and memory-efficient methods of cleaning only those parts of the screen that need cleaning. This is called dirty rects cleaning.
To run this example you need:
|006_time_based_movement.py||pygame|| Download the whole Archive with all files from Github:
View/Edit/Download the file directly in Github: https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/006_time_based_movement.py
click reload in your browser if you see no code here: