【问题标题】:Pygame - 2 keys stops jetPygame - 2键停止喷射
【发布时间】:2020-06-18 20:15:33
【问题描述】:

大家好,我对 python 和一般编程还是很陌生。我开始使用 pygame 制作自己的游戏,但我遇到了问题。我正在创建一个陈词滥调的游戏,其中一艘船射杀了一群外星人。

我让我的船移动了,但是例如:

当我按右键然后按左键使它们同时按下,然后释放右船停止,这是由于pygame.keyup导致increment = 0释放右键时。 但是我知道如何修复它,这样我就可以控制飞船而不会时不时停下来,因为按键之间的快速切换。

我正在寻找一种方法,当我按下一个键时,它会忽略前一个键的键位,但是当我不按下任何按钮时,船就会停止

我的代码:

import sys
import pygame

pygame.init()

# Setting up a window
screen = pygame.display.set_mode((1200,800))
screen_rect = screen.get_rect()


# Caption
pygame.display.set_caption("space shooter".title())


# Setting up the icon
icon = pygame.image.load("undertake.png").convert_alpha()
pygame.display.set_icon(icon)


# Identifying a Background
bg = pygame.image.load("bg.png").convert_alpha()


# Adding the jet
jet = pygame.image.load("jet.png").convert_alpha()
jet_rect = jet.get_rect()
jet_rect.centerx = screen_rect.centerx
jet_rect.bottom = screen_rect.bottom
jet_xincrement=0


# Moving the jet
def move_jet(x):
    jet_rect.centerx += x


# Adding Boundaries
def boundaries():
    if jet_rect.left >= 1200:
        jet_rect.right = 0
    elif jet_rect.right <= 0:
        jet_rect.left = 1200


# Game Loop
while True:
    screen.blit(bg,(0,0))
    screen.blit(jet,jet_rect)

    # EVENTS
    for event in pygame.event.get():
        # Quitting
        if event.type == pygame.QUIT:
            sys.exit()

        # Key Strokes
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                jet_xincrement = 3
            elif event.key == pygame.K_LEFT:
                jet_xincrement = -3

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


    boundaries()
    move_jet(jet_xincrement)



    pygame.display.flip()

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    不用监听按键事件,只需用pygame.key.get_pressed()检查按键的当前状态。

    把你的事件循环改成这样。

        ...
    
        # EVENTS
        for event in pygame.event.get():
            # Quitting
            if event.type == pygame.QUIT:
                sys.exit()
    
        pressed = pygame.key.get_pressed()
        jet_xincrement = 0
        if pressed[pygame.K_RIGHT]: jet_xincrement += 3
        if pressed[pygame.K_LEFT]: jet_xincrement -= 3
    
        boundaries()
        move_jet(jet_xincrement)
    
        pygame.display.flip()
    

    【讨论】:

    • 天哪,我听说 python 社区非常支持我,我很高兴能成为其中的一员。我希望我能成为专家,帮助像你一样的人!非常感谢!你成就了我的一天
    • @HamzaEyad 没问题。另一个例子,见this question,它处理相同的主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多