In this chapter, you will learn how to monitor game time.
navigation
Previous Chapter: Image Transfer and Drawing Text
Next Chapter: Working hard to update...
Article directory
Monitoring time
In game programs, it is often necessary to perform different actions as time passes. For example: countdown, animation, limiting frame rate... This requires monitoring of game time.
Pygame uses pygame.time
modules to monitor time in milliseconds ( 1 1000 \frac{1}{1000}10001seconds) as the timing unit.
All functions in this module are shown in the following table (see official documentation for details ):
function definition | function effect |
---|---|
get_ticks() -> milliseconds |
Gets pygame.init how many milliseconds have passed since the function was called. pygame.init This function always returns when not called 0 . |
wait(milliseconds) -> time |
Pause the program for a certain period of time to make the program sleep. This function consumes less processor and has lower accuracy pygame.time.delay . Returns the actual number of milliseconds paused. |
delay(milliseconds) -> time |
Pause the program for a certain amount of time. This function uses the processor to control the time pygame.time.wait with high . Returns the actual number of milliseconds paused. |
set_timer(event, millis, loops=0) -> None |
Every certain milliseconds, a given event is created in the event queue. The event can be pygame.Event an object or an integer representing the event. An optional parameter loops can be used to specify the number of times to create, if the default value ( 0 ) is used, events will continue to be created until explicitly stopped. To stop the timer explicitly, call the function again with the same event parameters, but millis set to0 . |
game frame rate
The running speed of the game can be expressed by FPS (Frames Per Second, the number of frames refreshed per second). pygame.time
Classes are defined in the module Clock
to help track time and control the game frame rate.
All methods of this class are shown in the following table (see official documentation for details ):
method definition | Method function |
---|---|
tick(framerate=0) -> milliseconds |
This method should be called once per frame and it will calculate how many milliseconds have passed since the last call. If optional framerate parameters are passed in, this method will delay to limit the game's frame rate. For example, if called every frame Clock.tick(60) , this method will ensure that the game runs at no more than 60 fps. |
tick_busy_loop(framerate=0) -> milliseconds |
Similar to pygame.time.Clock.tick method. The difference is that this method will use pygame.time.delay a function to delay the time, so the accuracy is higher, but this will cause a lot of CPU consumption in a busy loop. |
get_time() -> milliseconds |
Get pygame.time.Clock.tick the number of milliseconds between the last two calls. |
get_raw_time() -> milliseconds |
Similar to pygame.time.Clock.get_time method, but this method does not include any time used in delaying the frame rate. |
get_fps() -> float |
Calculate Clock the frame rate of this object. pygame.time.Clock.tick Calculated by averaging the last ten calls to the method. |
Example: Drawing performance comparison
This example is relatively simple and will pygame.time.Clock.get_time
compare the performance of pygame.draw.line
functions and pygame.draw.aaline
functions by calling methods.
The complete code is as follows:
import sys
import pygame
class PerformanceComparsion:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Performance Comparsion')
self.clock = pygame.time.Clock()
self.time_list = []
def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print(1000 / (sum(self.time_list) / len(self.time_list)))
pygame.quit()
sys.exit()
self.screen.fill((255, 255, 255))
for i in range(100):
# 运行后记得切换函数
pygame.draw.line(self.screen, (0, 0, 0), (0, i * 5 + 5), (800, i * 5 + 5))
pygame.display.update()
self.clock.tick()
self.time_list.append(self.clock.get_time())
if __name__ == '__main__':
app = PerformanceComparsion()
app.run()
This example does not use get_fps
the method because this method needs to calculate tick
the average of the intervals between the first 10 method calls, and there will be errors in the calculation. This example will use the method directly get_time
to add the interval time of each frame to time_list
it. Calculate the average interval time at the end of the program, and then use 1000 interval time\frac{1000}{interval time}Intervals1000Get average fps.
Note:
1. Please remember to switch functions after running.
2. Do not run this program for a long time, otherwise a large number of numbers will accumulate in the list, and the amount of calculation will be huge.
line
Function execution result:
aaline
Function execution result:
Results vary by device.
Conclusion
The above is all the content of this chapter. In the next chapter, you will learn how to use Pygame sprites.