问题
I'm making a little Mario for my school's Computer Club. (well, as part of a team.) Anyway, I'm having some trouble with the "keyup/keydown" commands. Here's my code:
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 1280, 1000
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]
# 3 - Load images
player = pygame.image.load("images/totallynotgodzilla.png")
# 3.1 - Load Audio
music = pygame.mixer.Sound("audio/skyrim.wav")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, playerpos)
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
Basically, the problem is that when I press a key down, it waits for the keyup command to happen before moving again. So basically I have to rapidly press down the buttons to move.
I deleted some of the code, so if something is missing, let me know and I'll tell you whether or not I have it.
回答1:
Indenting problem. You need to test your key states in you main game loop not in your event loop. You need to UNINDENT your keystate test one level.
while 1:
# do init stuff
screen.fill(0)
# .... (all main loop init stuff here)
for event in pygame.event.get():
# test events, set key states
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
# .... (all event stuff)
# Indent moves back to main game loop
# test key states here...
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
# .... (and so on)
来源:https://stackoverflow.com/questions/26811132/pygame-keyup-keydown