我正在进行2人迷宫赛跑比赛,而且我遇到了键盘事件的麻烦。如果两个玩家同时击中一个键,则只有玩家1移动,因为我的代码首先测试了玩家1的事件。有没有办法在python和pygame中同时检查两个事件?这是我的player1课程的一部分:
class Player( pygame.sprite.Sprite ):
def __init__( self ):
super( Player, self ).__init__()
self.size = self.w,self.h = 75,75
self.image = pygame.Surface( ( self.size ) )
self.image.fill( white )
self.rect = self.image.get_rect()
self.move_y = 0
self.move_x = 0
self.speed = 5
self.player = True
self.alive = True
self.level = None
def update( self, collidable = pygame.sprite.Group(), event = None ):
self.rect.x += self.move_x
self.rect.y += self.move_y
if not ( event == None ):
if ( event.type == pygame.KEYDOWN ):
if ( event.key == pygame.K_LEFT ):
self.move_y = 0
self.move_x = -self.speed
if ( event.key == pygame.K_RIGHT ):
self.move_y = 0
self.move_x = self.speed
if ( event.key == pygame.K_UP ):
self.move_x = 0
self.move_y = -self.speed
if ( event.key == pygame.K_DOWN ):
self.move_x = 0
self.move_y = self.speed
对于代码块感到抱歉,但您必须了解它的工作原理。我有一个几乎相同的玩家2类,但有不同的键盘控制(WASD而不是箭头键)。
我定义了我的player1和player2类:
player_object_list = pygame.sprite.Group()
p1 = Player()
p1.set_position( 40, 725 )
p1.set_image(deadpool_icon)
p2 = Player2()
p2.set_position( 525, 725 )
p2.set_image(girl_bow)
然后我更新并绘制它们:
p1.update( current_level.object_list, event )
p2.update( current_level.object_list, event )
event = None
player_object_list.draw( window )
总结:使用此代码,键盘控制的移动工作正常,但它不会检查两个玩家'同时键盘事件,所以如果两个键同时按下一个键,只有player1检测到该事件,因为它在播放器2之前更新:
p1.update( current_level.object_list, event )
p2.update( current_level.object_list, event )
提前致谢,
德里克
答案 0 :(得分:0)
记住我的评论,让我们来解决问题。首先,我想让你的代码更加通用,也许更容易看到:使用查找表进行移动翻译。
move_translate = {
pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: (1, 0),
pygame.K_UP: (0, -1),
pygame.K_DOWN: (0, 1)
}
if event is not None:
if event.type == pygame.KEYDOWN:
if event.key in move_translate:
# dictionary.get() will improve this,
# if you want to advance that far in Python syntax
self.move_x, self.move_y = move_translate[event.key]
self.move_x *= self.speed
self.move_y *= self.speed
# Here, you have to retire the event you just processed.
# Then pass out of the first check for no event.
# Check for another in the event queue, for player 2.
# After this check, you can update the display.
这会让您走向解决方案吗?根据您正在使用的队列和交互,您可以将事件检查放入一个循环中,以处理此时间内的所有事件。