Objects, lists and my old brain

To help in some mental rehabilitation after an unpleasant disaster, I decided to try to learn how to program in Python. So I just started to come up with functions and classes.

I have a main class of enemies that allows me to create such an object.

enemy01=Enemy("Goblin",10,100,2,5,1,2)

To get the name of the enemy, I can use

foe=enemy01.get_enemyName()

My problem is that I want to use the list of enemies that I add when they are killed, and the “against” variable refers to the fact that the enemy is in the game.

So, I tried to create a list of enemy objects, for example

currentEnemy=[enemy01, enemy02, enemy03]

and do

foe=currentEnemy.....

But I can’t figure out how to attach .get_enemyName()

I tried things like this to tie it

foe=(currentEnemy, ".get_enemyName()")

But nothing that I try works when I print "print (foe)", which will be in the main body of the code.

, , , , . , .

, :)

+4
3

, , .

:

enemies = [enemy01, enemy02, enemy03]
for currentEnemy in enemies:
   eName = currentEnemy.get_enemyName()
   print('The current enemy is', eName)

, , , :

# create three identical goblins
enemies = [Enemy("Goblin",10,100,2,5,1,2) for _ in range(3)]
+2

:

class Enemy:
    def __init__(self,name):
        self.name=name
    def get_enemyName(self,):
        return self.name

currentEnemy :

enemy01=Enemy('Goblin')
enemy02=Enemy('Rhino')
enemy03=Enemy('DR.Octopus')

currentEnemy=[enemy01, enemy02, enemy03]

foe. :

foe=[x.get_enemyName() for x in currentEnemy]

print foe

.

i= foe.index('Rhino') #find index of Rhino

del[currentEnemy[i]]  #let kill Rhino

print 'current enemies at play {}'.format([x.get_enemyName() for x in currentEnemy])
+2

Sorry - a real stupid mistake on my part. I just skipped the list index.

I sorted it

enemylist = [enemy01, enemy02, enemy03]

currentEnemy=enemylist[0]

foe=currentEnemy.get_enemyName()

print(foe)

+1
source

Source: https://habr.com/ru/post/1693773/


All Articles