gpt4 book ai didi

python - 我在尝试调用方法时收到名称错误

转载 作者:行者123 更新时间:2023-12-01 00:20:12 25 4
gpt4 key购买 nike

我有以下函数来控制敌人的生成及其行为。最后,我使用相同的构造函数创建了多个敌人。但是,当在主循环中调用这些对象的方法时,我收到名称错误

我的功能:

#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()

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

谢谢!

最佳答案

您正在使用变量 i 迭代 enemies - 而不是 Enemy:

for i in enemies:
Enemy.load()

通常你会想要这样的东西:

for enemy in enemies:
enemy.Load()

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

关于python - 我在尝试调用方法时收到名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59013177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com