Using a variable for an instance

This is kind of hard to explain, but I'm working on a game project and hit a brick wall. I have six instances of an enemy class randomly placed on a grid(array)and need a way to determine which one the player attacks. It should be easier to understand from the snippet bellow what I'm trying to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string name;

....

else if (i == Harry.m_posR && j == Harry.m_posC)
{
	name = "Harry";
	pDamage = Harry.attack(player.m_AC, player.m_HP);
}
else if(i == Al.m_posR && j == Al.m_posC)
{
 	name = "Al";
	pDamage = Al.attack(player.m_AC, player.m_HP);
}

player.attacked(pDamage);

if(abs(i - player.m_posR) <= 1 && abs(j - player.m_posC) <= 1)
{
	eDamage = player.attack(name.m_AC, name.m_HP);
}

name.attacked(eDamage);


Obviously using a string variable doesn't work like I intended in lines 20 and 23. I could use a bunch of if/else if statements, like I did to determine which enemy is attacking, but that gets long and it would be better to just reuse what I already did. If anyone has any ideas it would help me out greatly.
Thanks in advance, Kirk
Looks like you're trying to use a pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// string name;  <- no need for the name
Enemy* target = nullptr;  // <- assuming Al, Harry, etc are of 'Enemy' type
   // this creates a pointer to a Enemy, and initializes it to point to nothing (null)

...

else if (i == Harry.m_posR && j == Harry.m_posC)
    target = &Harry;  // point to Harry if he's the target
else if(i == Al.m_posR && j == Al.m_posC)
    target = &Al;  // or Al if he's the target


if(target != nullptr)  // if any target was selected
{
    pDamage = target->attack(player.m_AC, player.m_HP);
    player.attacked(pDamage);

    if(abs(i - player.m_posR) <= 1 && abs(j - player.m_posC) <= 1)
    {
        eDamage = player.attack( target->m_AC, target->m_HP);
        target->attacked(eDamage);
    }
}



Pointers are not objects themselves, but give you a way to refer to (or "point to") existing objets. In this case, 'target' refers/points to one of your existing enemies (Al, Harry, etc). Once you make target point to one of those enemies, you can then "dereference it" with the -> operator to interact with your pointer as if it were the actual object.
Hi Disch,

I wasn't trying to use a pointer, but I had a feeling that's where the solution was. I have a hard time with pointers, even though I understand the concept it's the implementation that tends to confuse me for some reason. Part of the confusion comes from the dereferencing (* vs ->). You forced me to look closer at it and I have a better understanding now. nullptr is also new to me and I like what I've read on it so far. I've picked up a couple other tidbits of info looking into why your solution works also so I can't thank you enough.

Kirk
Topic archived. No new replies allowed.