Pygame Keyup / Keydown

时间:2014-11-07 22:25:34

标签: python pygame keydown keyup

我为我学校的电脑俱乐部制作了一个小马里奥。 (好吧,作为一个团队的一部分。) 无论如何,我在" keyup / keydown"上遇到了一些麻烦。命令。这是我的代码:

# 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

基本上,问题是当我按下一个键时,它会等待键盘命令发生再次移动之前。所以基本上我必须快速按下按钮才能移动。

我删除了一些代码,所以如果缺少某些内容,请告诉我,我是否会告诉您。

1 个答案:

答案 0 :(得分:3)

缩进问题。您需要在主游戏循环中测试关键状态,而不是在事件循环中。你需要在一个级别上解决你的keystate测试。

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)