多个按键按Pygam

2024-09-28 19:02:39 发布

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

我想做一个游戏,如果有一个会射击的小机器人。问题是只有当它不动的时候,当我向左或向右移动的时候,或者当我跳的时候它才不动。当我按下其他键时,有什么方法可以让我的barspace键工作吗?我试图把另一个if key语句放在一个已经存在但不起作用的key语句中,我的意思是:

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

我把我的github放在这里,这样你就可以运行这个程序了。谢谢你的帮助,很抱歉我的代码乱七八糟。你知道吗

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


Tags: andkeypyrightfalsetrueif语句
1条回答
网友
1楼 · 发布于 2024-09-28 19:02:39

if keys [py.K_SPACE] and shootloop == 0:语句不应位于elif keys[py.K_LEFT] and man.x >= 0:子句内,否则只能在按左箭头键时进行拍摄。你知道吗

而且,在你的回购中

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:

这意味着只有在既不按K_LEFT也不按K_RIGHT时才会执行,因为这些语句的顺序是相同的ifelif。你知道吗

这个版本适合我:

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

相关问题 更多 >