局部变量' x'在赋值之前引用,但x = 0

时间:2015-12-17 10:56:19

标签: python pygame

我在pygame中制作游戏,但是当我为zombie类调用update()函数时 它说UnboundLocalError:局部变量' x'在分配之前引用 但是x是= 0,如果我从Zombie init函数调用update,它会说NameError:name' update'未定义

class Zombie:
    x = 0
    y = 0
    movX = 0

    def movStop(self):
        movX = 0

    def update(self):
        x += movX

    def movX(self):
        movX = -2

    def __init__(self, _x, _y):
        x, y = _x, _y
        image = pygame.image.load('zombie.png')
        win.blit(image, (x, y))

def main():
    # init window
    pygame.display.set_caption(title)
    pygame.init()
    clock = pygame.time.Clock()

    # game loop and user input
    isClosed = False
    while not isClosed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: # check if exit button is pressed
                isClosed = True
            # user input
            # render
            win.fill(green)
            zomb = Zombie(50,50)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    zomb.movX()
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    movStop()
            zomb.update()
            geWrite('health', 40, 20, 20)
            # redisplay
            pygame.display.update()
            clock.tick(120)
    pygame.quit()
    quit()

1 个答案:

答案 0 :(得分:1)

cd $GOPATH/src mkdir a b cat > a/a.go <<EOT package main import "C" //export a func a() { println("a") } func main() {} EOT cat > b/b.go <<EOT package main import "C" //export b func b() { println("b") } func main() {} EOT cat > test.c <<EOT #include "a.h" #include "b.h" int main(int argc, char *argv[]) { a(); b(); } EOT go build -buildmode=c-archive -o a.a a go build -buildmode=c-archive -o b.a b gcc test.c a.a b.a 是局部变量。您必须在类方法中使用xself.xself.y

你的课程看起来像这样

self.movX

我使用class Zombie: def __init__(self, x=0, y=0): self.mov_x = 0 self.image = pygame.image.load('zombie.png') self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y # or in one line # self.rect = self.image.get_rect(x=x, y=y) def draw(self, surface) surface.blit(self.image, self.rect) def movStop(self): self.mov_x = 0 def update(self): self.x += self.mov_x def movX(self): self.mov_x = -2 rect),因为它很有用 - 你可以获得pygame.Rect()rect.center和一些pygame类需要它来绘制元素 - 请参阅{{3} }。

您不能同时拥有变量rect.right和方法movX