[파이썬] pygame 타이머 및 시간 관리

pygame_logo

Introduction

Pygame is a popular library in Python for creating games and multimedia applications. It provides various functionalities for game development, including graphics rendering, audio playback, and event handling. In this blog post, we will explore how to use pygame to create timers and manage time in our games or applications.

Setting up Pygame

Before we dive into timers and time management, let’s make sure we have pygame installed on our machine. You can install pygame by running the following command:

pip install pygame

Once installed, we can import the pygame module in our Python script.

import pygame

Pygame Clock

One of the main features of pygame for managing time is the pygame.Clock class. This class provides a convenient way to control the frame rate of our game and measure elapsed time.

Let’s start by creating an instance of the Clock class.

import pygame

# Initialize pygame
pygame.init()

# Create a clock object
clock = pygame.time.Clock()

To control the frame rate of our game, we can use the tick() method of the Clock class. This method limits the frame rate to a specific number of frames per second (FPS).

# Set the desired FPS
FPS = 60

# Game loop
while True:
    # Limit the frame rate
    clock.tick(FPS)

    # Game logic and rendering
    # ...

By calling clock.tick(FPS) at the beginning of each iteration of the game loop, we ensure that our game runs at a consistent frame rate.

Using pygame.time

Apart from the Clock class, pygame also provides the pygame.time module, which contains functions for managing time in our game.

One useful function is pygame.time.get_ticks(), which returns the number of milliseconds since pygame was initialized or the last time pygame.time.set_timer() was called.

# Main game loop
while True:
    # Get the current time
    current_time = pygame.time.get_ticks()

    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Set a timer for 1 second
                pygame.time.set_timer(pygame.USEREVENT, 1000)

        if event.type == pygame.USEREVENT:
            # Timer event handler
            print("1 second has passed")

    # Game logic and rendering
    # ...

In the example above, we set a timer for 1 second when the spacebar (pygame.K_SPACE) is pressed. When the timer expires, pygame generates a pygame.USEREVENT event, which we can handle in our game loop.

Conclusion

In this blog post, we explored how to use pygame for creating timers and managing time in our games or applications. With the pygame.Clock class and the functions in pygame.time, we have the necessary tools to control the frame rate and measure elapsed time in our pygame projects.

By effectively managing time, we can create smooth animations, synchronize game events, and provide an immersive gameplay experience for our users.

Happy coding with Pygame!