Help with 2D implementing array.

I'm working with inheritance right now, which I'm having no problem with.
I have this vector of strings (basically a 2D array of char's).

The exact middle is where the shark is and the character of the shark
changes based on where the other fish are.

For example
.....
.....
^.l..
.....
.....

The arrows are where the fish are and since the fish is to the left. The shark becomes a 'l'

.>...
.....
..u..
.....
.....

The arrows are where the fish are and since the fish is up. The shark becomes a 'u'

The code I had to do this correctly is this:

void Shark::point(std::vector<std::string>& map){

if (map[0][0] != '.' || map[1][0] != '.' || map[2][0] != '.' || map[3][0] != '.' || map[4][0] != '.' || map[1][1] != '.' || map[2][1] != '.' || map[3][1] != '.'){
ProtoFish::m_direction = Direction::left;
}
if (map[0][1] != '.' || map[0][2] != '.' || map[0][3] != '.' || map[1][2] != '.'){
ProtoFish::m_direction = Direction::up;
}
if (map[4][1] != '.' || map[4][2] != '.' || map[4][3] != '.' || map[3][2] != '.'){
ProtoFish::m_direction = Direction::down;
}
if (map[0][4] != '.' || map[1][4] != '.' || map[2][4] != '.' || map[3][4] != '.' || map[4][4] != '.' || map[1][3] != '.' || map[2][3] != '.' || map[3][3] != '.'){
ProtoFish::m_direction = Direction::right;
}
}

I am basically just checking if the fish are in this map:
//"luuur"
//"llurr"
//"ll.rr"
//"lldrr"
//"ldddr"

where if the '.' char doesn't exist that's where a fish is, so the Shark should point in that direction.


The problem occurs where there are multiple fish.

">....",
"..>..",
"..*..",
".>...",
"..^>.",

I understand what I'm supposed to do, but I have no idea of how to do it, or how to even get started. The goal is just to get the Shark facing the same direction of the nearest fish. So basically the arrow "closest" to the middle.
Can someone help me out to get started with this?
Maybe like a separate function that calculates the distance of each element from the center?



Last edited on
What program are you trying to implement?
I believe I know what you want to do. To find the distance of the fish, you'd need to calculate the distance. So the fish below for example has a distance of 2, since it has 1 less x and y value. 1 + 1 = 2 distance. The fish above is set on the same x, thus 1 + 0, it has a distance of 1. You could keep the current co-ordinates of the fish and replace them should another fish be closer. Once you've done this, just do what you're doing at the moment for a single fish, except using the co-ordinates of the fish and shark. If you want to get into 2d graphics, I'd recommend you have a look at a graphics library like SDL or SFML.
Last edited on
Topic archived. No new replies allowed.