Search code examples
arraysvectorcocos2d-iphone

cocos2dx : Change Array to Vector


I need to change Array to Vector as it is being depracted in cocos2dx. Earlier it was running but after deprecation its giving error. As I am quite new to cocos2dx I am not able to resolve this issue.

Here is my code:

int BaseScene::generateRandom()
{
//int  rn = arc4random()%6+1;
int  rn = rand() % 6 + 1;
Array * balls = (Array*)this->getChildren();

Array * ballsTypeLeft = Array::create();
//    if(balls->count() <= 7)
{
for (int j=0; j<balls->count(); j++)
{
Node * a = (Node*)balls->objectAtIndex(j);
if(a->getTag() >= Tag_Ball_Start)
{                
Ball * currentBall =  (Ball*)balls->objectAtIndex(j);
bool alreadyHas = false;
for(int k=0;k<ballsTypeLeft->count();k++)
{
if(strcmp(((String*)ballsTypeLeft->objectAtIndex(k))->getCString(), (String::createWithFormat("%d",currentBall->type))->getCString()) == 0)
{
alreadyHas = true;
}
}
if(alreadyHas)
{

}
else
{
ballsTypeLeft->addObject(String::createWithFormat("%d",currentBall->type));
}
}
}
}
//    CCLog("%d",ballsTypeLeft->count());
if(ballsTypeLeft->count() <=2)
{
// int tmp = arc4random()%ballsTypeLeft->count();
int tmp = rand() % ballsTypeLeft->count();
return ((String*)ballsTypeLeft->objectAtIndex(tmp))->intValue();
}
return rn;
}

How can I make this method working? Please convert this method using Vector. Thanks


Solution

  • To change cocos2d::Array to cocos2d::Vector, you must first understand it. cocos2d::Vector is implemented to mimick std::vector. std::vector is part of the STL in c++. cocos2d::Vector is built specifically to handle cocos2d::Ref. Whenever you add a Ref type to Vector it automatically retained and then released on cleanup.

    Now to change Array to Vector in your code:

    Store children this way:

    Vector <Node*> balls = this->getChildren();
    

    Access ball at index i this way:

    Ball* ball = (Ball*)balls.at (i);
    

    Add elements to vector this way:

    balls.pushBack (myNewBall);
    

    EDIT -

    From what I understand, you want to get a random ball from the scene/layer. You can perform this by simply returning the Ball object:

    Ball* BaseScene::generateRandom()
    {
        Vector <Node*> nodeList = this->getChildren();
    
        Vector <Ball*> ballList;
        for (int i = 0; i<nodeList.size(); i++)
        {
            if (ball->getTag() >= Tag_Ball_Start)
            {
                Ball * ball = (Ball*)nodeList.at(i);
                ballList.pushBack(ball);
            }
        }
    
        if (ballList.size() > 0)
        {
            return ballList[rand() % ballList.size()];
        }
    
        return nullptr;
    }
    

    If there is no ball it will return NULL which you can check when you call the function. The code you have linked below seems to make use of Arrays outside the function. You need to make the changes to accommodate that. I suggest studying the documentation for Vector.