向左或向右移动以快速导致img粘住

时间:2015-05-25 01:31:50

标签: python python-3.x pygame

我正在使用pygame在python 3中制作太空飞船入侵者游戏。我目前遇到麻烦太空船坚持让我双击左或右箭头键让它生效。这是我的代码:

import pygame

pygame.init()

display_width = 800
display_height = 600

black = (0, 0, 0)
white = (255, 255, 255)

#Window Size
gameDisplay = pygame.display.set_mode((display_width, display_height))
#Title Of Window
pygame.display.set_caption('A Bit Racey')
#FPS
clock = pygame.time.Clock()

spaceshipImg = pygame.image.load('SpaceShipSmall.png')

def spaceship(x,y):
    gameDisplay.blit(spaceshipImg, (x,y))

x = (display_width * 0.45)
y = (display_height * 0.8)

x_change  = 0

crashed = False

while not crashed:
    # this will listen for any event every fps
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            #change later
            crashed = True

        if event.type  == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    x += x_change

    gameDisplay.fill(white)
    spaceship(x,y)
    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

2 个答案:

答案 0 :(得分:1)

每次检测到pygame.KEYUP事件时,左箭头键或右箭头键重置x_change 。即使你按住,例如你的右箭头键一个左箭头按键可以停止你的宇宙飞船的移动

要解决此问题,您可以使用pygame.key.get_pressed()方法获取所有键盘按钮的状态此函数返回一个布尔值序列,由 pygames键常量值索引,表示键盘上每个键的状态。

因为每次事件发生都不需要调用pygame.key.get_pressed() ,更新后的主循环应如下所示:

while not crashed:
    # this will listen for any event every fps
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            #change later
            crashed = True
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    #get the state of all keyboard buttons
    pressedKeys = pygame.key.get_pressed()

    #change position if pygame.K_LEFT or pygame.K_RIGHT is pressed
    if pressedKeys[pygame.K_LEFT]:
        x += -5
    elif pressedKeys[pygame.K_RIGHT]:
        x += 5

    gameDisplay.fill(white)
    spaceship(x,y)
    pygame.display.update()

    clock.tick(60)

请注意 pygame.K_LEFT事件的优先级pygame.K_RIGHT事件更高。您可以使用两个单独的if来更改此行为。 非常感谢 @sloth 指出这一点!

#change position if either pygame.K_LEFT or pygame.K_RIGHT is pressed
if pressedKeys[pygame.K_LEFT]:
    x += -5
if pressedKeys[pygame.K_RIGHT]:
    x += 5

我希望这可以帮助你:)

答案 1 :(得分:0)

在x + = x_change之前添加以下语句:

print (event.type, event.key, x)

这会将事件数据和x位置打印到控制台。

再次尝试您的脚本,尝试按住左键3秒,然后释放,并重复右键。在按住键的同时查看是否看到多个keydown事件。我认为你应该只在发布时看到一个keyup事件。

相关问题