首页 > 解决方案 > TypeError: run() missing 1 required positional argument: 'self' (Space Invaders Bullet issue)

问题描述

我正在创建一个类似游戏的太空入侵者,其中有一艘宇宙飞船(人类一侧)向上向外星人发射子弹。

我试图从我的主循环中调用我的子弹类中的 run() 函数。每次我得到这个错误:(TypeError:run()缺少1个必需的位置参数:'self')。但是当我调用 human.run() 时,它工作得非常好(而且它与 alien.run() 一起工作得很好,但那是断章取义的)

这是我调用 run 函数的主循环:

while not gameExit:

    gameDisplay.fill(black)
    human.run()

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                bullet = Bullet
                bulletslist.append(bullet)

    for bullet in bulletslist:
        bullet.run()

    pygame.display.update()
    clock.tick(60)

这是我的子弹课

class Bullet:

    speed = 80
    image = pygame.image.load('bullet.png')

    def __init__(self):
        self.x = human.x
        self.y = human.y

    def run(self):
        gameDisplay.blit(Bullet.image, (self.x, self.y))
        self.y -= Bullet.speed
        if self.y < display_height:
            bulletslist.remove(bullet)

这是我的人类课程,基本上我希望子弹与人类共享相同的 x,y 坐标。注意:我在这里使用类变量只是因为有 1 个对象是人类飞船。

class Human:

    y = display_height * 0.8
    x = display_width * 0.45
    width = 120
    speed = 0
    image = pygame.image.load('human.png')

    def run(self):
        global gameExit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    if Human.x > 0:
                        Human.speed = -8
                    else:
                        Human.speed = 0
                elif event.key == pygame.K_RIGHT:
                    if Human.x < display_width - Human.width:
                        Human.speed = 8
                    else:
                        Human.speed = 0
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                        Human.speed = 0
        gameDisplay.blit(Human.image, (Human.x, Human.y))
        Human.x += Human.speed

human = Human()

标签: pythonpygamegame-loop

解决方案


推荐阅读