尝试调用方法时,我收到了名称错误

时间:2019-11-23 23:18:09

标签: python class pygame

我具有以下功能,用于控制敌人的产卵及其行为。最后,我使用相同的构造函数创建了多个敌人。但是,当在主循环中调用这些对象的方法时,会得到一个name error

我的功能:

#cretating and manipulating enemies
def enemy_actions(enemies):

    free_lanes = 0
    free_lane_positions = []
    new_enemies_lanes = []

    #going through all lanes
    for i in lanes:
        lane_taken = i[1]   

        if not lane_taken:
            #counting how many free lanes there are
            free_lanes = free_lanes + 1
            #adding free lane position to a list
            free_lane_positions.append(i[0])

    #if atleast 2 lanes are free then we randomly select how many new enemies we will add
    if free_lanes > 1:
        #randomly selecting how many enemies will be added
        number_of_enemies = random.randint(1,3)

    #repeating action for the number of enemies required
    for i in range(number_of_enemies):
        #randomly selecting lanes for enemies
        lane_x = random.choice(free_lane_positions)

        #adding it to the list of taken lanes
        new_enemies_lanes.append(lane_x)

        #removing taken up lane from list of free lanes
        free_lane_positions.remove(lane_x)

        #marking lane_x as taken in lanes
        for i in lanes:
            if i[0] == lane_x:
                i.remove(False)
                i.append(True)

    #(self, place, x, y, length, width, path, speed):
    #building enemy 
    for i in new_enemies_lanes:
        Enemy = enemy(screen, i, enemy_y_start, 60, 60, enemy_path, random.randint(3,8))
        enemies.append(Enemy)

    #debugging
    print(enemies)

这是游戏的主要循环,我在其中调用方法Enemy.load()

#main loop
while not done:

        #checking for game events
        for event in pygame.event.get():

                #quitting game when window is closed
                if event.type == pygame.QUIT:
                        done = True

        #detecting key presses
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_a]:Player.move_left()
        if pressed[pygame.K_d]:Player.move_right()

        #checking for crushing
        crush_detected = crush_detection() 
        if crush_detected:
            game_over()

        #clear display
        screen.fill(0)

        #drawing the background
        screen.blit(background_image, [0, 0])

        #drawing the enemy
        for i in enemies:
            Enemy.load()

        #loading the player
        Player.load()

        #update display
        pygame.display.flip() 

        #controls FPS
        clock.tick(60)

还有我收到的错误:

Traceback (most recent call last):
  File "Pygame.py", line 234, in <module>
    Enemy.load()

可能有一个简单的解决方法,但是我还没有弄清楚。请告诉我是否需要更多代码。

谢谢!

1 个答案:

答案 0 :(得分:2)

您正在使用变量enemies而不是i遍历Enemy

for i in enemies:
    Enemy.load()

通常,您需要类似的东西:

for enemy in enemies:
    enemy.Load()

那样,您实际上是在当前迭代的对象上调用该方法。