pygame.key.get_pressed()
returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key
attribute of the pygame.event.Event
object:
while carryOn == True:
# [...]
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
my_sprite.update(50, 0)
if event.key == pygame.K_s:
my_sprite.update(-50, 0)
if event.key == pygame.K_d:
my_sprite.update(0, 50)
if event.key == pygame.K_a:
my_sprite.update(0, 50)
# [...]
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN
event occurs once every time a key is pressed. KEYUP
occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed()
returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key
attribute of the pygame.event.Event
object.
However, you must evaluate the keys in the application loop rather than the event loop:
while carryOn == True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
my_sprite.update(50, 0)
if keys[pygame.K_s]:
my_sprite.update(-50, 0)
if keys[pygame.K_d]:
my_sprite.update(0, 50)
if keys[pygame.K_a]:
my_sprite.update(0, 50)
# [...]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…