Reputation: 57
I have managed to create a way to access each enemy in a list and detect if its been hit... I think... Besides the problem. My problem is that every time I want to create more than one enemy I get the error "Enemy is not a callable object"
I honestly don't know whats going wrong here. Ive looked on other posts and one similar post shares something about "making sure I don't make my object = anything else". However my object isn't called anywhere else other than where it is being added to the list.
Outside the loop
Enemies = []
print("Enemies at start: ",len(Enemies))
It returns "0"
Creating the enemy inside the while loop
if len(Enemies) <= 5:
Enemies.append(Enemy(random.randint(0,500),-50,70,70))
#Spawns an enemy while the list is still less than 5 not really relevant and should be removed after code below is fixed.
print("Enemies at creation point: ",len(Enemies))
for Enemy in Enemies:
#Enemies.append(Enemy(random.randint(0,500),-50,70,70))
print("Created")
if Enemy.health <= 0:
Enemies.pop(Enemies.index(Enemy))
print("Destroyed")
else:
print("Skipping")
Error: 'Enemy' object is not callable
I expect the output to simply spawn these enemies on the screen at random positions. While 5 do not simultaneously exist. So at the start, it will not spawn anymore enemies. However when one is destroyed, a new one is spawned.
Upvotes: 1
Views: 46
Reputation: 142641
Your mistake is you use the same name for class definiton Enemy
and variable in for Enemy in Enemies
There is good rule in PEP 8 -- Style Guide for Python Code to use lowercase names for variables and camel case names (with first upper letter) for class names
So you should rather have
enemies = []
print("Enemies at start:", len(enemies))
if len(enemies) <= 5:
enemies.append(Enemy(random.randint(0,500),-50,70,70))
#Spawns an enemy while the list is still less than 5 not really relevant and should be removed after code below is fixed.
print("Enemies at creation point: ", len(enemies))
for enemy in enemies:
#enemies.append(Enemy(random.randint(0,500),-50,70,70))
print("Created")
if enemy.health <= 0:
enemies.pop(enemies.index(enemy))
print("Destroyed")
else:
print("Skipping")
As you can see I use Enemy
only in Enemy(random.randint(0,500),-50,70,70)
. In other places I use enemy
BTW: even editor in SO know this rule and it uses light blue color to show class Enemy
and make code more readable.
Upvotes: 2