如何在游戏中使用2个控制器(Python)

2024-09-30 06:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我们想用Python创建一个有两个玩家和两个控制器的游戏(类似于街头斗士)。我们有一个问题,我们不知道如何分开两个控制器。你知道吗

当我们用一个控制器移动或攻击一个角色时,另一个角色也在移动。你知道吗

代码如下:

def usecontroller():   
    pygame.init()
    global instanceFenetrePause
    for i in range(0,pygame.joystick.get_count()):
        vr.listeJoysticks.append(pygame.joystick.Joystick(i))
        vr.listeJoysticks[-1].init() 

    while vr.loopGestionClavier :
        for event in pygame.event.get():
            if event.type == pygame.QUIT :
                instanceFenetrePause.affichage_fenetre()
            if vr.loopJeu :
                for x in range(0,len(vr.listeJoysticks)) :
                    if event.type == pygame.JOYBUTTONDOWN :
                        if event.button == 0 :
                            print ('command0')
                        if event.button == 1 :
                            print ('command1')
                        if event.button == 2 :
                            print ('command2')
                        if event.button == 3 :
                            print ('command3')
                        if event.button == 4 :
                            print ('command4')
                        if event.button == 5 :
                            print ('command5')
                        if event.button == 7 :
                            instanceFenetrePause.affichage_fenetre()

Tags: inevent角色forifinitrangebutton
1条回答
网友
1楼 · 发布于 2024-09-30 06:32:20

快速浏览documentation会发现,所有操纵杆事件都包含一个属性event.joy,该属性应该引用哪个操纵杆创建了事件。然后简单地使用if语句或其他一些控制逻辑来确定应该移动哪个字符。我对pygame不够熟悉,不知道event.joy的值是多少,但我怀疑它将是传递给pygame.joystick.Joystick的同一个数字索引。你知道吗

例如,使用上面的代码:

if event.type == pygame.JOYBUTTONDOWN :
    if event.button == 0 :
        if event.joy == 0:
            print('player 1, command0')
        elif event.joy == 1:
            print('player 2, command0')

    if event.button == 1 :
        if event.joy == 0:
            print('player 1, command1')
        elif event.joy == 1:
            print('player 2, command1')
        print ('command1')

当然,这可能需要修改以处理任意操纵杆索引,但想法是存在的。你知道吗

相关问题 更多 >

    热门问题