Surround

Member
Posts: 102
Joined: 2005.01
Post: #1
I cant wrap my small head around how to do this.

I want a tile to change its owner if it is surrounded by 3 more more tiles of a different owner.

Code:
[self ownerOfX:x+32 Y:y] ;
[self ownerOfX:x-32 Y:y] ;
[self ownerOfX:x Y:y+32] ;        
[self ownerOfX:x Y:y-32] ;


these return the owner of the tiles right, left, above, below respectivly
if three or more of these are the same number i want to change the current tile's
owner to that number. Basically if three of the above lines of code return the same number i want that number.
I might be being lame but yea... i cant figure it out.
Quote this message in a reply
Member
Posts: 208
Joined: 2005.04
Post: #2
Well, if you want to exploit Cocoa, you could create an NSNumber out of each returned value, then store each number in an NSCountedSet. Then check the count of each value in the counted set.
Quote this message in a reply
Member
Posts: 102
Joined: 2005.01
Post: #3
So much about cocoa i didnt know NSCountedSet eh? I should look at that, i was thinking about an array and then organize the array but i was too lazy Annoyed

Thank you. it works beautifulay.
I didnt even know that sets existed, now im like a kid with a bunch of new toys, i have to play with those WOO, thanks. I owe you a bottle of day old mayonaise.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #4
You could create a 4 element array, then go into a loop going from index 0 to 3, and each iteration compare it to the others, incrementing a counter each time. If the counter is large enough, you've got it. You can do something like this (I'm assuming these are stored as ints, though you can adapt it for other types).

Code:
int compare[4];
compare[0] = [self ownerOfX:x+32 Y:y];
compare[1] = [self ownerOfX:x-32 Y:y];
compare[2] = [self ownerOfX:x Y:y+32];              
compare[3] = [self ownerOfX:x Y:y-32];

int i, j, counter, newTile;
bool match = false;
for (i = 0; i < 4; ++i)
{
    for (j = 0; j < 4; ++j)
    {
        if (compare[i] == compare[j])
            ++counter;
    }
    if (counter >= 3)
    {
        match = true;
        newTile = compare[i];
        break;
    }
    counter = 0;
}
if (match)
{
    //do stuff with newTile being the new tile number
}

Edit: it looks like you found it out already, but it still might do you good to learn how to do these types of things without relying on built in types and functions. It will make you a better programmer in general.
Quote this message in a reply
Member
Posts: 102
Joined: 2005.01
Post: #5
That looks somewhat like my original code, the only difference is its a lot cleaner and probably works Annoyed
Quote this message in a reply
Post Reply