Pygame Button Press Detection: Single Press Event Handling
You can detect if a button is pressed in Pygame using the 'pygame.KEYDOWN' event. Here's an example of how you can detect if a specific button, such as the spacebar, is pressed only once:
import pygame
pygame.init()
# Set up the screen
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Button Press Detection')
# Set up variables
button_pressed = False
# Game loop
running = True
while running:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Check for key press events
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not button_pressed:
# Spacebar is pressed for the first time
print('Spacebar pressed!')
button_pressed = True
# Clear the screen
screen.fill((0, 0, 0))
# Update the display
pygame.display.flip()
# Quit the game
pygame.quit()
In this example, the variable 'button_pressed' is initially set to False. When the spacebar is pressed for the first time, the message 'Spacebar pressed!' will be printed, and the 'button_pressed' variable will be set to True to prevent multiple detection of the button press.
Note that this example only detects the spacebar press. If you want to detect other buttons, you can refer to the Pygame documentation for the list of key constants: https://www.pygame.org/docs/ref/key.html
原文地址: https://www.cveoy.top/t/topic/o9uT 著作权归作者所有。请勿转载和采集!