I've been making a game using PyGame/Python, and recently I've run into something strange: I'm unable to use pygame.Event.key outside of an if event.type == pygame.locals.KEYDOWN block.
Here's the relevant section of the code. This throws no errors and reacts to events as expected:
import pygame
import pygame.locals
import sys
import time
WINDOW = pygame.display.set_mode((500,500))
pygame.init()
pygame.display.set_caption("The Game of Awesomeness")
def update_screen():
#Code to update screen
pass
while True:
for event in pygame.event.get():
if event.type == pygame.locals.KEYDOWN:
if event.key == pygame.locals.K_q:
pygame.quit()
sys.exit()
elif event.key == pygame.locals.K_w:
pass
elif event.key == pygame.locals.K_d:
pass
elif event.key == pygame.locals.K_s:
pass
elif event.key == pygame.locals.K_a:
pass
update_screen()
time.sleep(0.1)
But if I simply comment out the line if event.type == pygame.locals.KEYDOWN, it doesn't work:
import pygame
import pygame.locals
import sys
import time
WINDOW = pygame.display.set_mode((500,500))
pygame.init()
pygame.display.set_caption("The Game of Awesomeness")
def update_screen():
#Code to update screen
pass
while True:
for event in pygame.event.get():
#if event.type == pygame.locals.KEYDOWN:
if event.key == pygame.locals.K_q:
pygame.quit()
sys.exit()
elif event.key == pygame.locals.K_w:
pass
elif event.key == pygame.locals.K_d:
pass
elif event.key == pygame.locals.K_s:
pass
elif event.key == pygame.locals.K_a:
pass
update_screen()
time.sleep(0.1)
With the if statement commented out I get the following error the first time any event occurs:
Traceback (most recent call last):
File "C:/Users/Username/Desktop/program.py", line 18, in <module>
if event.key == pygame.locals.K_q:
AttributeError: 'Event' object has no attribute 'key'
The only difference between the two programs is that the first one has the statement if event.type == pygame.locals.KEYDOWN, and the second one does not. Note that the code within the if statement in the working program does run when it should, meaning the if event.key == pygame.locals.K_keyname statements all run without throwing errors. Based on the error it seems that pygame.Event.key can only be referenced within an if event.type == pygame.locals.KEYDOWN block.
Why is pygame.Event.key behaving this way?
Aucun commentaire:
Enregistrer un commentaire