Coned_Stoding
Coned_Stoding

Reputation: 125

How to determine which instance of an object I'm dealing with?

I'm making a text based dungeon crawler type game. In this game I have an enemy class and a player class. If I instantiate several enemies and place them in a grid structure along with my player, how can I detect which instance of the enemy class the player has encountered so that I can pass the instance to various functions as a parameter. so for example:

    class Enemy:
        def __init__(self, name, x, y):
            self.name = name
            self.x = x
            self.y = y

    e = Enemy('goblin', 0, 0)
    e1 = Enemy('troll',0, 1)
    enemies = (e, e1)
    grid = [[' '] * 10 for i in range(10)]
    grid[e.x][e.y] = e.name
    grid[e1.x][e1.y] = e1.name

    someFucntion(player, enemy)

As you can see, for the function to have the enemy instance at this point, I would have to manually pass in the instance. But that would mean writing if elif statements galore to determine which instance it is. Which is obviously not efficient or good, considering I would like to have 20 + instances of enemy.

so is there a method or function that would allow me to detect/ get hold of the instance to pass around? Thanks in advance for your time and expertise. Hopefully this question isn't off topic or too vague.

Upvotes: 1

Views: 41

Answers (1)

Coned_Stoding
Coned_Stoding

Reputation: 125

well I did some messing around outside of my project on the online python tutor, I found that if i iterated over my list 'enemies' I could check their coordinates against the player's and and if they matched I could pass them on as a variable in this case 'currentEnemy' and it seems to work. Here's the code:

    class Player:
        def __init__(self, name, x, y):
            self.name = name
            self.x = x
            self.y = y

    class Enemy:
        def __init__(self, name, x, y):
            self.name = name
            self.x = x
            self.y = y

    def combat(player, enemy):
         print('%s dies.' % (enemy.name))


    p = Player('tom', 0, 1)
    e = Enemy('goblin', 0, 0)
    e1 = Enemy('troll', 0, 1)
    currentEnemy = ()
    enemies = (e, e1)
    grid = [[' '] * 10 for i in range(10)]

    grid[e.x][e.y] = e.name
    grid[e1.x][e1.y] = e1.name

    for i in enemies:
        if i.x == p.x and i.y == p.y:
        currentEnemy = i

    combat(p, currentEnemy)

Which left me with the output i expected, i.e 'troll dies'

Hope this is helpful to anyone else with this problem.

Upvotes: 1

Related Questions