Pygame Tutorial (5): Monitoring Game Time

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...

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.timemodules 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.inithow many milliseconds have passed since the function was called. pygame.initThis 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.waitwith 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.Eventan object or an integer representing the event. An optional parameter loopscan 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 millisset 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.timeClasses are defined in the module Clockto 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 framerateparameters 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.tickmethod. The difference is that this method will use pygame.time.delaya 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.tickthe number of milliseconds between the last two calls.
get_raw_time() -> milliseconds Similar to pygame.time.Clock.get_timemethod, but this method does not include any time used in delaying the frame rate.
get_fps() -> float Calculate Clockthe frame rate of this object. pygame.time.Clock.tickCalculated by averaging the last ten calls to the method.

Example: Drawing performance comparison

This example is relatively simple and will pygame.time.Clock.get_timecompare the performance of pygame.draw.linefunctions and pygame.draw.aalinefunctions 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_fpsthe method because this method needs to calculate tickthe 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_timeto add the interval time of each frame to time_listit. 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.

lineFunction execution result:

line function execution result

aalineFunction execution result:

aaline function operation 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.

Guess you like

Origin blog.csdn.net/ZhouJinXuan24/article/details/128766602