我无法让播放器跳起来,甚至认为代码与工作示例非常相似

时间:2019-05-03 23:34:36

标签: python python-3.x pygame

我一直在学习如何使用pygame,并遇到了一个使角色跳跃的教程。代码并不完全相同,但是我不明白为什么它不起作用。

我想知道为什么他要问的话,为什么他会首先计算跳跃次数False

if not (p1jump):
    if keys[pygame.K_SPACE]:
        p1jump = True

这使我感到困惑,因为p1jump最初是假的。因此,您基本上是在问:如果p1jump为true,并且按了SPACE,则将p1jump设置为true。

这是整个班级,以防万一:

class Player1():
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.height = 25
        self.width = 25
        self.speed = 5
    def draw(self,r,g,b):
        pygame.draw.rect(win,(r,g,b),(self.x,self.y, self.width ,self.height))
    def movement(self):
        p1jump = False
        jumpcount = False
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and self.x > self.speed:
            self.x -= self.speed
        elif keys[pygame.K_d] and self.x < (w - self.width):
            self.x += self.speed

        if not(p1jump):
            if keys[pygame.K_SPACE]:
                p1jump = True
        else:
            if jumpcount >= -10:
                self.y -= (jumpcount **2) *0.5
                jumpcount = 1

            else:
                p1jump = False
                jumpcount = 10

此外,如果你们有更好的编码跳转的方法,请告诉我!谢谢!

2 个答案:

答案 0 :(得分:1)

您的第一个代码段正确。但是,在方法movement中,每次调用时都要将p1jump设置为False。我猜想您希望它一直True直到玩家着陆。因此,请改为将该变量作为属性。

class Player:

    def __init__(self,x,y):
        # ... stuff
        self.jump = False

    def movement(self):
        # ... stuff

        if not self.jump and keys[pygame.K_SPACE]:
            self.jump = True
        else:
            if jumpcount >= -10:
                self.y -= (jumpcount **2) *0.5
                jumpcount = 1
            else:
                self.jump = False
                jumpcount = 10

答案 1 :(得分:0)

  

因此,您基本上是在问:如果p1jump为true,并且按下了SPACE,   然后将p1jump设置为true。

不完全是,如果p1jump为not (p1jump):,则TrueFalsenot是Python中的逆运算符。

如果您更清楚

if not (p1jump)可以重写为if p1jump == False

我希望有帮助。