【发布时间】: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()
【问题讨论】: