Создание обратного отсчета в Pygame: несколько методов и примеры кода

Обратный отсчет необходим во многих играх и приложениях для создания ожиданий и механики, основанной на времени. В этой статье блога мы рассмотрим различные методы реализации обратного отсчета в Pygame, популярной библиотеке Python для разработки игр. Мы предоставим примеры кода для каждого метода, что позволит вам выбрать тот, который лучше всего соответствует вашим потребностям. Давайте погрузимся!

Метод 1: Часы Pygame
Часы Pygame — это встроенная функция, обеспечивающая простой и эффективный способ обработки операций, связанных со временем, включая обратный отсчет.

import pygame
import sys
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Countdown using Pygame Clock")
# Set initial countdown value
countdown_value = 10
# Create a Pygame Clock object
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    # Clear the screen
    window.fill((255, 255, 255))
    # Draw the countdown value on the screen
    font = pygame.font.Font(None, 100)
    text = font.render(str(countdown_value), True, (0, 0, 0))
    text_rect = text.get_rect(center=(window_width // 2, window_height // 2))
    window.blit(text, text_rect)
    # Decrement the countdown value
    countdown_value -= 1
    # Check if the countdown has reached zero
    if countdown_value <= 0:
        # Perform countdown completion actions here
        pass
    # Update the screen
    pygame.display.flip()
    # Set the frames per second (FPS)
    clock.tick(1)  # 1 FPS, i.e., one second per frame

Метод 2: собственный класс таймера.
Если вы предпочитаете более настраиваемый подход, вы можете создать собственный класс таймера, который инкапсулирует функциональность обратного отсчета.

import pygame
import sys
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Countdown using Custom Timer Class")
class Timer:
    def __init__(self, duration):
        self.duration = duration
        self.start_time = pygame.time.get_ticks()
    def update(self):
        elapsed_time = pygame.time.get_ticks() - self.start_time
        remaining_time = max(0, self.duration - elapsed_time)
        return remaining_time
# Set initial countdown value
countdown_value = 10
# Create a Timer object
timer = Timer(countdown_value * 1000)  # Convert seconds to milliseconds
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    # Clear the screen
    window.fill((255, 255, 255))
    # Draw the countdown value on the screen
    font = pygame.font.Font(None, 100)
    text = font.render(str(timer.update() // 1000), True, (0, 0, 0))
    text_rect = text.get_rect(center=(window_width // 2, window_height // 2))
    window.blit(text, text_rect)
    # Check if the countdown has reached zero
    if timer.update() <= 0:
        # Perform countdown completion actions here
        pass
    # Update the screen
    pygame.display.flip()
Method 3: Threaded Countdown
If you want the countdown to run independently of the game loop, you can use threads to achieve that.
```python
import pygame
import sys
import threading

pygame.init()

# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Threaded Countdown in Pygame")

# Set initial countdown value
countdown_value = 10

def countdown():
    global countdown_value

    while countdown_value > 0:
        countdown_value -= 1
        pygame.time.wait(1000)  # Wait for 1 second

# Create and start the countdown thread
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Clear the screen
    window.fill((255, 255, 255))

    # Draw the countdown value on the screen
    font = pygame.font.Font(None, 100)
    text = font.render(str(countdown_value), True, (0, 0, 0))
    text_rect = text.get_rect(center=(window_width // 2, window_height // 2))
    window.blit(text, text_rect)

    # Check if the countdown has reached zero
    if countdown_value <= 0:
        # Perform countdown completion actions here
        pass

    # Update the screen
    pygame.display.flip()

    # Set the frames per second (FPS)
    pygame.time.Clock().tick(30)  # Adjust the FPS as needed

В этой статье мы рассмотрели несколько методов создания обратного отсчета в Pygame. Мы рассмотрели Pygame Clock, собственный класс Timer и многопоточный подход. Каждый метод имеет свои преимущества, что позволяет вам выбрать тот, который лучше всего подходит для вашего конкретного случая использования. Внедрив обратный отсчет, вы можете добавить механику, основанную на времени, и сделать свои проекты Pygame более интересными и интерактивными.