尝试调用方法时收到名称错误 [英] I received a name error when trying to call a method
问题描述
我具有以下功能,用于控制敌人的产卵及其行为.最后,我使用相同的构造函数创建了多个敌人.但是,当在主循环中调用这些对象的方法时,会出现 name error
.
I have the following function which controls the spawning of the enemies and what they do. At the end of it I create multiple enemies using the same constructor. However, when in the main loop I call the method of those objects I get a 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()
.
And here is the main game loop where I call the method 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()
可能有一个简单的解决方法,但是我还没有弄清楚.请告诉我是否需要更多代码.
There is probably an easy fix however I haven't figured it out. Please tell me if more code is required.
谢谢!
推荐答案
您正在使用变量 i
-不是 Enemy
敌人>:
You're iterating over enemies
with the variable i
- not Enemy
:
for i in enemies:
Enemy.load()
通常,您会想要类似的东西:
Usually you'd want something like:
for enemy in enemies:
enemy.Load()
那样,您实际上是在当前迭代的对象上调用该方法.
That way you're actually invoking the method on the object of your current iteration.
这篇关于尝试调用方法时收到名称错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!