Python 游戏中的飞船在额外按键时不移动
我根据一本叫做Python速成课程的书创建了这个外星人入侵游戏。现在出现的问题是,一旦我按下另一个键,我创建的船就会卡住 我尝试过对代码进行一些修改,但效果不太好,所以我提供了我以前的代码,希望有人能帮助我Python 游戏中的飞船在额外按键时不移动,python,pygame,Python,Pygame,我根据一本叫做Python速成课程的书创建了这个外星人入侵游戏。现在出现的问题是,一旦我按下另一个键,我创建的船就会卡住 我尝试过对代码进行一些修改,但效果不太好,所以我提供了我以前的代码,希望有人能帮助我 import sys import pygame def check_keydown_events(event,ship): """it will respond to the keypresses""" if event.key == pygame.K_RIGHT: #
import sys
import pygame
def check_keydown_events(event,ship):
"""it will respond to the keypresses"""
if event.key == pygame.K_RIGHT: # detects if the key pressed is the right key
# will move the ship to right
ship.moving_right = True # used for modifying the value rathr than changing the ships position we change it directlty to true
elif event.key == pygame.K_LEFT:
ship.moving_left = True
def check_keyup_events(event,ship):
"""it will respond to the key release"""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ship):
"""it will respond to keypress and mouse events."""
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN: #detects wheteher a key is pressed or not
check_keydown_events(event,ship)
elif event.type==pygame.KEYUP: #new block to rsspond to the keyup event when the user releases the key
check_keydown_events(event,ship)
#it will move the ship to right
def update_screen(ai_settings,screen,ship):
"""basic use was to refactor the basic developed code once again"""
"""updates images on the screen and flips to a new screen."""
#redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_color)
ship.blitme()
#make the most recently drawn screen visible
pygame.display.flip()
目前没有错误消息出现,只是在我按下另一个键后,飞船没有移动 修复检查密钥更新\u事件的问题
。缩进应与check\u keydown\u事件的缩进相同
check\u keydown\u事件
被调用两次(在pygame.keydown
和pygame.keydup
的情况下),但从不调用check\u keydown\u事件
def check_keydown_事件(事件,发货):
如果event.key==pygame.K_RIGHT:
ship.moving_right=真
elif event.key==pygame.K_左:
ship.moving_left=真
def check_keyup_事件(事件,发货):
如果event.key==pygame.K_RIGHT:
ship.moving_right=错误
elif event.key==pygame.K_左:
ship.moving_left=错误
def检查_事件(发货):
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
检查按键关闭事件(事件,发货)
elif event.type==pygame.KEYUP:
检查加密事件(事件,发货)
可使用以下方法简化代码:
def检查事件(发货):
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
sys.exit()
keys=pygame.key.get_pressed();
ship.moving_right=键[pygame.K_right]
ship.moving_left=键[pygame.K_left]
当事件由或elif event.type==pygame.KEYUP:check\u keydown\u事件(事件,ship)处理时,将评估由pygame.key.get\u pressed()返回的状态我不认为您的def check\u keyup\u事件
应该在check\u keydown\u事件中
谢谢您的帮助。问题解决了。