To aid in some mental rehabilitation after a nasty hip accident I decided to try and teach myself to program in Python. So I've just started getting my head around defining functions and classes.
I have a basic enemy class that allows me to create an object like this.
enemy01=Enemy("Goblin",10,100,2,5,1,2)
To get the enemy name I can use
foe=enemy01.get_enemyName()
My problem is I want to use a list of enemies which I append as they get killed off and the variable 'foe' to refer to whatever enemy is in play.
So I tried creating a list of the enemy objects, like
currentEnemy=[enemy01, enemy02, enemy03]
and do
foe=currentEnemy.....
But I cant work out how to attach the .get_enemyName()
I was trying things like this to concatenate it
foe=(currentEnemy, ".get_enemyName()")
But nothing I am trying is working when I type 'print(foe)' which is what would be in the main body of code.
I have tried searching online and here but it's really hard as a beginner to put it into words what I am trying to do. Maybe i'm just going about it the wrong way to start with.
I hope I'm making sense and thanks for reading :) Simon
-
Welcome to StackOverflow! Happy to hear that programming can help you in your healing process! Could you show us the code you wrote by editing and adding it to your question? Also please take the time to read about minimal verifiable example stackoverflow.com/help/mcveOlivier Melançon– Olivier Melançon2018年02月17日 14:17:06 +00:00Commented Feb 17, 2018 at 14:17
3 Answers 3
You seem to conflate the list of all enemies and a variable referring to a particular one.
Here's what you could do:
enemies = [enemy01, enemy02, enemy03]
for currentEnemy in enemies:
eName = currentEnemy.get_enemyName()
print('The current enemy is', eName)
Later on you would probably decide that creating individual enemies is too tedious and use another loop for that:
# create three identical goblins
enemies = [Enemy("Goblin",10,100,2,5,1,2) for _ in range(3)]
2 Comments
If your class :
class Enemy:
def __init__(self,name):
self.name=name
def get_enemyName(self,):
return self.name
and you have initialised currentEnemy as :
enemy01=Enemy('Goblin')
enemy02=Enemy('Rhino')
enemy03=Enemy('DR.Octopus')
currentEnemy=[enemy01, enemy02, enemy03]
And you want to get list of all enemy names into a list foe. Then try :
foe=[x.get_enemyName() for x in currentEnemy]
print foe
i.e. list comprehensions
i= foe.index('Rhino') #find index of Rhino
del[currentEnemy[i]] #let's kill Rhino
print 'current enemies at play {}'.format([x.get_enemyName() for x in currentEnemy])
Comments
Sorry - real silly error on my part. I just missed the list index.
I sorted it
enemylist = [enemy01, enemy02, enemy03]
currentEnemy=enemylist[0]
foe=currentEnemy.get_enemyName()
print(foe)