所以我有这个函数中的代码问题没有识别我的UP,DOWN,LEFT和DOWN键的击键,我想知道为什么。似乎无法解决这个问题。我需要这个以某种方式工作,所以我可以在我编码的程序的另一部分中使用相同的代码。
def movementVariables():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
#testkey
#if event.key == K_SPACE:
if event.key == K_LEFT:
moveRight = False
moveLeft = True
if event.key == K_RIGHT:
moveRight = True
moveLeft = False
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == K_DOWN:
moveDown = True
moveUp = False
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT:
moveLeft = False
if event.key == K_RIGHT:
moveRight = False
if event.key == K_UP:
moveUp = False
if event.key == K_DOWN:
moveDown = False
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 400
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVE_SPEED = 0
levelOne = True
while levelOne == True:
if moveDown and player.bottom < WINDOW_HEIGHT:
player.top += MOVE_SPEED
if moveUp and player.top > 0:
player.top -= MOVE_SPEED
if moveLeft and player.left > 0:
player.left -= MOVE_SPEED
if moveRight and player.right < WINDOW_WIDTH:
player.right += MOVE_SPEED
我试图发布尽可能少的代码,所以我不会溢出无用的代码。如果您需要整个代码,只需输入。
答案 0 :(得分:3)
moveUp
,moveDown
等是函数movementVariables
中的局部变量,它们在函数期间分配,然后在完成时放弃。您需要明确使用外部范围变量:
def movementVariables():
global moveUp
global moveDown
global moveLeft
global moveRight
或者,更好的是,实际上return
并使用函数中的内容:
def movementVariables():
...
return movement