简体   繁体   中英

Multiple Keys press Pygame

I'm trying to make a game were there is this little robot that shoots. The problem is that it shoots only when it's not moving, when I move left or right or when I jump it doesn't shoot. Is there something that I can do for let my barspace key works when I'm pressing the other keys? I tried to put another if key statement in a key statement that already exist but it doesn't work, like this I mean:

elif keys[py.K_LEFT] and man.x >= 0:
    man.x -= man.vel
    man.right = False
    man.left = True
    man.standing = False
    man.idlecount = 0
    man.direction = -1

    if keys [py.K_SPACE] and shootloop == 0:
        if man.left:
            facing = -1

        elif man.right:
            facing = 1

        if len(bullets) < 5:
            man.standing = True
            man.shooting = True
            bullets.append(bulletss(round(man.x + man.lenght//2), round(man.y + man.lenght//2), facing))

        shootloop = 1

I left my github here so you can run the program. Thank you for the help and sorry for my code that is a mess.

https://github.com/20nicolas/Game.git

The if keys [py.K_SPACE] and shootloop == 0: statement should not be inside of the elif keys[py.K_LEFT] and man.x >= 0: clause, otherwise you can only shoot when you press the left arrow key.

Also, in your repo it's actually,

if keys[py.K_RIGHT] and man.x <= 700:
    # ...
elif keys[py.K_LEFT] and man.x >= 0:
    # ...       
elif keys [py.K_SPACE] and shootloop == 0:

which means that it will only be executed when neither K_LEFT nor K_RIGHT are pressed, because these statements are in the same if ... elif sequence.

This version works for me:

elif keys[py.K_LEFT] and man.x >= 0:
    man.x -= man.vel
    man.right = False
    man.left = True
    man.standing = False
    man.idlecount = 0
    man.direction = -1
else:
    man.standing = True

if keys [py.K_SPACE] and shootloop == 0:
    if man.left:
        facing = -1

    elif man.right:
        facing = 1

    if len(bullets) < 5:
        man.standing = True
        man.shooting = True
        bullets.append(bulletss(round(man.x + man.lenght//2), round(man.y + man.lenght//2), 1))

    shootloop = 1
else:
    man.shooting = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM