TeslaItem::TeslaItem(const int id, const int friendId)
:MovingObstacle(id),
_friendId(friendId)
{
    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    
    this->initWithSpriteFrameName("teslaItem1.png");
    
    CCArray* animFrames = CCArray::createWithCapacity(10);
    
    char str[100] = {0};
    for (int i = 0; i < 30; ++i) {
        int animNumber = i < 15 ? i + 1 : 30 - i;
        sprintf(str, "teslaItem%d.png", animNumber);
        CCSpriteFrame* frame = cache->spriteFrameByName(str);
        animFrames->addObject(frame);
    }
    
    CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames);
    animation->setDelayPerUnit(1 / 30.0f);
    CCAnimate* animate = CCAnimate::create(animation);
    this->runAction(CCRepeatForever::create(animate));
}
Exemple #2
0
void Image::runFullAnimation(float delay, bool invert)
{
    CCAssert(spriteSheet != NULL, "Image runFullAnimation called on an object without spritesheet");
    CCArray* animationFrames = CCArray::createWithCapacity(spritesName->count());
    for(int i = 0; i < spritesName->count(); i++)
    {
        CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(((CCString*)spritesName->objectAtIndex(invert ? spritesName->count() - i - 1 : i))->getCString());
        CCAnimationFrame* frame = new CCAnimationFrame();
        frame->initWithSpriteFrame(spriteFrame, 1, NULL);
        frame->autorelease();
        animationFrames->addObject(frame);
    }
    CCAction* action = CCRepeatForever::create(CCAnimate::create(CCAnimation::create(animationFrames, delay)));
    if(runningAnimation != action)
    {
        if(runningAnimation != NULL)
        {
            delegate->stopAction(runningAnimation);
        }
        delegate->runAction(action);
        runningAnimation = action;
    }
}
Exemple #3
0
    void textHandler(void *ctx, const char *ch, int len)
    {
        CC_UNUSED_PARAM(ctx);
        if (m_tState == SAX_NONE)
        {
            return;
        }

        CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
        CCString *pText = new CCString();
        pText->m_sString = std::string((char*)ch,0,len);

        switch(m_tState)
        {
        case SAX_KEY:
            m_sCurKey = pText->m_sString;
            break;
        case SAX_INT:
        case SAX_REAL:
        case SAX_STRING:
            {
                if (SAX_ARRAY == curState)
                {
                    m_pArray->addObject(pText);
                }
                else if (SAX_DICT == curState)
                {
                    CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>");
                    m_pCurDict->setObject(pText, m_sCurKey);
                }
                break;
            }
        default:
            break;
        }
        pText->release();
    }
Exemple #4
0
// on "init" you need to initialize your instance
bool Game::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

    loadBg();
    loadCards();
    
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    char name[20];

     CCSpriteFrameCache* cache =CCSpriteFrameCache::sharedSpriteFrameCache();
    CCArray * sArr = CCArray::create();
    for(int i=1;i<14;i++){
        sprintf(name,"FP%d.BMP",i);
        CCSpriteFrame* frame =cache->spriteFrameByName(name);
        
        CardSprite* sprite =CardSprite::createWithFrame(frame);
        sprite->setPosition(ccp(-50,-50));
        sprite->setTag(i);
        sArr->addObject(sprite);
        addChild(sprite);
    }
    CCObject* pObj;
    int i=1;
    CCARRAY_FOREACH(sArr, pObj)
    {
        CardSprite* cs = (CardSprite*)pObj;
     	CCActionInterval *actionTo = CCMoveTo::create(4.0f,
                                                      ccp(140+i*25,size.height/4));
        cs->runAction(actionTo);
        i++;
    }
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    glClearColor(1, 1, 1, 1);

    CCSprite *sprite = CCSprite::create("CloseNormal.png");
    this->addChild(sprite);
    sprite->setPosition(ccp(240, 160));
    sprite->setScale(2.f);
    CCSize ss = sprite->getContentSize();
    CCOrbitCamera *orbit = CCOrbitCamera::create(5.f, 5.f, 0, 0, 360, 90, -45);
    CCMoveBy *moveBy = CCMoveBy::create(5.f, ccp(100, 0));
    sprite->runAction(CCSequence::create(orbit,moveBy));
    
    CCArray *array = CCArray::create();
    array->addObject(this);
    
    CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(HelloWorld::updateabc), this, 2.f, false);
    
    CCMenuItemImage *i = CCMenuItemImage::create("CloseNormal.png", NULL, this, menu_selector(HelloWorld::clicked));
    CCMenu *menu = CCMenu::create(i,NULL);
    menu->setPosition(100, 100);
    this->addChild(menu);
    
    CCTexture2D *t = WGDirector::textureWithCString("Map_6.png");
    CCSprite *sp = CCSprite::createWithTexture(t);
    this->addChild(sp);
    
    
    return true;
}
void INSPayment_iOS::loadProducts(inewsoft::ol::LoadProductCallback callback)
{
    if(!this->productTable.empty() && productsState == inewsoft::ol::kProductsStateLoaded)
    {
        callback(true);
        return;
    }
    else if(this->productsState == inewsoft::ol::kProductsStateLoading)
    {
        this->loadProductCallback = callback;
        return;
    }
    
    /// loald product from developer server firstly
    this->productsState = inewsoft::ol::kProductsStateLoading;
    Payment::loadProducts([this, callback](bool succeed){
        if(succeed) {
            INSStore::sharedStore()->registerTransactionObserver(this);
            CCArray* productsId = new CCArray();
            productsId->autorelease();
            
            for(auto iter = this->productTable.begin(); iter != this->productTable.end(); ++iter)
            {
                productsId->addObject(newCCString(iter->second.id.c_str()));
            }
            
            this->loadProductCallback = callback;
            INSStore::sharedStore()->loadProducts(productsId, this);
        }
        else {
            this->productsState = inewsoft::ol::kProductsStateUnload;
            callback(false);
            
        }
    });
}
Exemple #7
0
//构造函数
Ship::Ship()
{
    this->speed = 220;
    this->bulletSpeed = 900;
    this->HP = 5;
    this->bulletTypeValue = 1;
    this->bulletPowerValue = 1;
    this->throwBombing = false;
    this->canBeAttack = true;
    this->isThrowingBomb = false;
    this->zOrder = 3000;
    this->maxBulletPowerValue = 4;
    this->appearPosition = ccp(160, 60);
    this->hurtColorLife = 0;
    this->active = true;
    this->timeTick = 0;

    this->initWithSpriteFrameName("ship01.png");
    this->setTag(zOrder);
    this->setPosition(this->appearPosition);


    CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    CCSpriteFrame *frame0 = cache->spriteFrameByName("ship01.png");
    CCSpriteFrame *frame1 = cache->spriteFrameByName("ship02.png");
    CCArray *frames = CCArray::createWithCapacity(2);
    frames->addObject(frame0);
    frames->addObject(frame1);
    CCAnimation *animation = CCAnimation::createWithSpriteFrames(frames, 0.1f);
    CCAnimate *animate = CCAnimate::create(animation);
    this->runAction(CCRepeatForever::create(animate));

    this->schedule(schedule_selector(Ship::shoot),0.2f);

    this->born();
}
void CardScene::loadCardsFromXml()
{
	TiXmlDocument doc;

	//list of card for scroll layer init
	CCArray* cardList = CCArray::create();

	if ( doc.LoadFile(CARDS_XML) )
	{
		TiXmlElement* cards_tag = doc.FirstChildElement();
		TiXmlElement* card_tag = cards_tag->FirstChildElement();
		
		while ( card_tag )
		{
			int number = 0; 
			card_tag->QueryIntAttribute("number", &number);

			const char* path = card_tag->Attribute("path");
			const char* description_id = card_tag->Attribute("description_id");

			//TODO: load description from L10n(Localization) file with description_id

			//create card and add to card list
			Card* card = Card::create(number, path, description_id);
			cardList->addObject( card );
			
			card_tag = card_tag->NextSiblingElement();
		}
	}


	m_pScrollList = CCScrollLayer::create(cardList);
	m_pScrollList->setPosition( ccp(0, 0) );
	addChild( m_pScrollList );

}
//------------------------------------------------------------------------------
CCArray*    LHLayer::spritesWithTag(int tag){
#if COCOS2D_VERSION >= 0x00020000
    CCArray* array = CCArray::create();
#else
    CCArray* array = CCArray::array();
#endif
    
    CCArray* children = getChildren();
    for(int i = 0; i < children->count(); ++i){
        CCNode* node = (CCNode*)children->objectAtIndex(i);
        
        if(LHSprite::isLHSprite(node)){
            if(node->getTag() == tag)
                array->addObject(node);
        }
        else if(LHBatch::isLHBatch(node)){
            array->addObjectsFromArray(((LHBatch*)node)->spritesWithTag(tag));
        }
        else if(LHLayer::isLHLayer(node)){
            array->addObjectsFromArray(((LHLayer*)node)->spritesWithTag(tag));
        }
    }
    return array;       
}
CCAnimation* AnimationManager::createHeroMovingAnimationByDirection(HeroDirection direction)
{
	CCTexture2D *heroTexture = CCTextureCache::sharedTextureCache()->addImage("Hero_image.png");
	CCSpriteFrame *frame0, *frame1, *frame2;
	CCArray* animFrames ;
	//第二个参数表示显示区域的x, y, width, height,根据direction来确定显示的y坐标
	
	
	frame0 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRectMake(eSize*0, eSize*direction, eSize, eSize));
	frame1 = CCSpriteFrame::createWithTexture(heroTexture, cocos2d::CCRectMake(eSize*1, eSize*direction, eSize, eSize));

	
	 animFrames = new CCArray(2);
	animFrames->addObject(frame0);
	animFrames->addObject(frame1);
	
	

	CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, 0.09f);

	animFrames->release();
	
	return animation;
}
Exemple #11
0
void Obstacle::SpawnCrow(int xOffset)
{
    CCArray *allFrames = new CCArray();
    for (int i = 0 ; i <= 14 ; i++)
    {
        char fn[64];
        sprintf(fn, "Fly00%d.png" , i );
        allFrames->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(fn));
    }
    
    CCAnimation *crowAnim = CCAnimation::createWithSpriteFrames(allFrames, 0.04f * 1);
    CCAction *crowAction = CCRepeatForever::create(CCAnimate::create(crowAnim));
    crowAction->retain();
    
    obstacleSprite = CCSprite::createWithSpriteFrameName("Fly000.png");
    obstacleSprite->setPosition(ccp(winSize.width + xOffset * SPAWN_OFFSET  , winSize.height - obstacleSprite->getContentSize().height));
    this->addChild(obstacleSprite);
    
    obstacleSprite->runAction(crowAction);
    moveOnce = true;
//    obstacleSprite->runAction(CCSequence::createWithTwoActions(CCMoveTo::create(1,
//                                                                                ccp( winSize.width - obstacleSprite->getContentSize().width , obstacleSprite->getPosition().y)),
//                                                               CCCallFunc::create(this, callfunc_selector(Obstacle::MoveCrow))));
}
CCAnimation* AnimationUtil::createAnimWithFrameNameAndNum( const char* name, int iNum, float delay, unsigned int iLoops) {
    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();

    CCArray* framesArray = CCArray::create();

    CCSpriteFrame* frame = NULL;
    int index = 1;
    for(int i = 1; i <= iNum; i++) {
        frame = cache->spriteFrameByName(CCString::createWithFormat("%s%d.png", name, i)->getCString());

        if(frame == NULL) {
            break;
        }

        framesArray->addObject(frame);
    }

    CCAnimation* animation = CCAnimation::createWithSpriteFrames(framesArray);
    animation->setLoops(iLoops);
    animation->setRestoreOriginalFrame(true);
    animation->setDelayPerUnit(delay);

    return animation;
}
//public
void RPGStartSceneLayer::goToMapScene()
{
    CCArray *loadTextures = CCArray::create();
    loadTextures->addObject(CCString::create("map.png"));
    loadTextures->addObject(CCString::create("main.png"));
    loadTextures->addObject(CCString::create("joystick.png"));
    loadTextures->addObject(CCString::create("actor4_0.png"));
    loadTextures->addObject(CCString::create("actor111.png"));
    loadTextures->addObject(CCString::create("actor113.png"));
    loadTextures->addObject(CCString::create("actor114.png"));
    loadTextures->addObject(CCString::create("actor115.png"));
    loadTextures->addObject(CCString::create("actor117.png"));
    loadTextures->addObject(CCString::create("actor120.png"));
    
    CCMenu *mainMenu = (CCMenu*)this->getChildByTag(kRPGStartSceneLayerTagMainMenu);
    mainMenu->setEnabled(false);
    
    CCScene *s = RPGLoadingSceneLayer::scene(loadTextures, NULL, "single_map");
    CCTransitionFade *t = CCTransitionFade::create(GAME_SCENE, s);
    CCDirector::sharedDirector()->replaceScene(t);
}
Exemple #14
0
void Effect::init(int type)
{
    effectid=type;
    switch (type)
    {
        case 1:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect1.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1000.png";
            effectName="effect1";
            char str[64] = {0};
            for (int i = 0; i <6; ++i)
            {
                sprintf(str, "100%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 2:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect2.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="2000.png";
            effectName="effect2";
            char str[64] = {0};
            for (int i = 0; i <2; ++i)
            {
                sprintf(str, "200%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 3:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect3.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="3000.png";
            effectName="effect3";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str, "300%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 4:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect4.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="4000.png";
            effectName="effect4";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str, "400%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 5:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect5.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="5000.png";
            effectName="effect5";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str,"500%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 6:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect6.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="6000.png";
            effectName="effect6";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str,"600%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 7:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect7.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="7000.png";
            effectName="effect7";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str,"700%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 8:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect8.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="8000.png";
            effectName="effect8";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str,"800%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 9:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect9.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="9000.png";
            effectName="effect9";
            char str[64] = {0};
            for (int i = 0; i <9; ++i)
            {
                sprintf(str,"900%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 10:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect10.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="10000.png";
            effectName="effect10";
            char str[64] = {0};
            for (int i = 0; i <10; ++i)
            {
                sprintf(str,"1000%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 11:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect11.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1100.png";
            effectName="effect11";
            char str[64] = {0};
            for (int i = 0; i <9; ++i)
            {
                sprintf(str,"110%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 12:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect12.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1200.png";
            effectName="effect12";
            char str[64] = {0};
            for (int i = 0; i <4; ++i)
            {
                sprintf(str,"120%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 13:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect13.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1300.png";
            effectName="effect13";
            char str[64] = {0};
            for (int i = 0; i <1; ++i)
            {
                sprintf(str,"130%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 14:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect14.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1400.png";
            effectName="effect14";
            char str[64] = {0};
            for (int i = 0; i <6; ++i)
            {
                sprintf(str,"140%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 15:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect15.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1500.png";
            effectName="effect15";
            char str[64] = {0};
            for (int i = 0; i <7; ++i)
            {
                sprintf(str,"150%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 16:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect16.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1600.png";
            effectName="effect16";
            char str[64] = {0};
            for (int i = 0; i <9; ++i)
            {
                sprintf(str,"160%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        case 17:
        {
            CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("effect17.plist");
            CCArray *animFrames = CCArray::create();
            firtPngName="1700.png";
            effectName="effect17";
            char str[64] = {0};
            for (int i = 0; i <8; ++i)
            {
                sprintf(str,"170%d.png", i);
                CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str);
                animFrames->addObject(frame);
            }
            CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames, 0.1);
            // 帧动画命名
            CCAnimationCache::sharedAnimationCache()->addAnimation(animation,effectName.c_str());
            break;
        }
        default:
            break;
    }

}
Exemple #15
0
CCArray * Utils::getLevelTools(int levelNum) {
	CCArray * tools = CCArray::createWithCapacity(14);
	switch (levelNum) {
		case 1:
			{
				Bridge * t1 = Bridge::create();
				tools->addObject(t1);
			}
			break;
		case 2:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				tools->addObject(t1);
				tools->addObject(t2);
			}
			break;
		case 3:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Bridge * t3 = Bridge::create();
				Bridge * t4 = Bridge::create();
				Bridge * t5 = Bridge::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
				tools->addObject(t5);
			}
			break;
		case 4:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Bridge * t3 = Bridge::create();
				Bridge * t4 = Bridge::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
			}
			break;
		case 5:
			{
				Spring * t1 = Spring::create();
				Spring * t2 = Spring::create();
				tools->addObject(t1);
				tools->addObject(t2);
			}
			break;
		case 6:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Spring * t3 = Spring::create();
				Spring * t4 = Spring::create();
				Spring * t5 = Spring::create();
				Spring * t6 = Spring::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
				tools->addObject(t5);
				tools->addObject(t6);
			}
			break;
		case 7:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Spring * t3 = Spring::create();
				Spring * t4 = Spring::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
			}
			break;
		case 8:
			{
				Pole * t1 = Pole::create();
				Pole * t2 = Pole::create();
				Pole * t3 = Pole::create();
				Pole * t4 = Pole::create();
				Pole * t5 = Pole::create();
				Pole * t6 = Pole::create();
				Pole * t7 = Pole::create();
				Pole * t8 = Pole::create();
				Pole * t9 = Pole::create();
				Pole * t10 = Pole::create();
				Pole * t11 = Pole::create();
				Pole * t12 = Pole::create();
				Pole * t13 = Pole::create();
				Pole * t14 = Pole::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
				tools->addObject(t5);
				tools->addObject(t6);
				tools->addObject(t7);
				tools->addObject(t8);
				tools->addObject(t9);
				tools->addObject(t10);
				tools->addObject(t11);
				tools->addObject(t12);
				tools->addObject(t13);
				tools->addObject(t14);
			}
			break;
		case 9:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Spring * t3 = Spring::create();
				Pole * t4 = Pole::create();
				Pole * t5 = Pole::create();
				Pole * t6 = Pole::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
				tools->addObject(t5);
				tools->addObject(t6);
			}
			break;
		case 10:
			{
				Bridge * t1 = Bridge::create();
				Bridge * t2 = Bridge::create();
				Bridge * t3 = Bridge::create();
				Spring * t4 = Spring::create();
				Spring * t5 = Spring::create();
				Spring * t6 = Spring::create();
				Spring * t7 = Spring::create();
				Pole * t8 = Pole::create();
				tools->addObject(t1);
				tools->addObject(t2);
				tools->addObject(t3);
				tools->addObject(t4);
				tools->addObject(t5);
				tools->addObject(t6);
				tools->addObject(t7);
				tools->addObject(t8);
			}
			break;
	}
	return tools;
}
bool EnemySpriteClass::init(GAME_ENEMY_MONSTERS_TYPE type, cocos2d::CCArray *posArray)
{
    CCAssert(!(type == GAME_ENEMY_MONSTERS_MAX), "cannot be INVALID");
    CCAssert(!(posArray == NULL), "cannot be NULL");
    
    char *pfileName = NULL;
    float moveSpeed = 10;
    float liveValue = 10;
    int aniNum = 2;
    char pBuffer[100] = {0};
    CCArray* aniArray = CCArray::create();
    
    switch (type) {
        case GAME_ENEMY_MONSTERS_BOSS_BIG:
            {
                pfileName = "boss_big";
                moveSpeed = GAME_ENEMY_MONSTERS_BOSS_BIG_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_BOSS_BIG_LIFE;
                
            }
            break;
        case GAME_ENEMY_MONSTERS_FAT_BOSS_GREEN:
            {
                pfileName = "fat_boss_green";
                moveSpeed = GAME_ENEMY_MONSTERS_FAT_BOSS_GREEN_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FAT_BOSS_GREEN_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_FAT_GREEN:
            {
                pfileName = "fat_green";
                moveSpeed = GAME_ENEMY_MONSTERS_FAT_GREEN_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FAT_GREEN_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_FLY_BLUE:
            {
                pfileName = "fly_blue";
                moveSpeed = GAME_ENEMY_MONSTERS_FLY_BLUE_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FLY_BLUE_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_FLY_BOSS_BLUE:
            {
                pfileName = "fly_boss_blue";
                moveSpeed = GAME_ENEMY_MONSTERS_FLY_BOSS_BLUE_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FLY_BOSS_BLUE_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_FLY_BOSS_YELLOW:
            {
                pfileName = "fly_boss_yellow";
                moveSpeed = GAME_ENEMY_MONSTERS_FLY_BOSS_YELLOW_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FLY_BOSS_YELLOW_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_FLY_YELLOW:
            {
                pfileName = "fly_yellow";
                moveSpeed = GAME_ENEMY_MONSTERS_FLY_YELLOW_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_FLY_YELLOW_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_BOSS_NIMA:
            {
                pfileName = "land_boss_nima";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_BOSS_NIMA_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_BOSS_NIMA_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_BOSS_PINK:
            {
                pfileName = "land_boss_pink";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_BOSS_PINK_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_BOSS_PINK_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_BOSS_STAR:
            {
                pfileName = "land_boss_star";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_BOSS_STAR_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_BOSS_STAR_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_NIMA:
            {
                pfileName = "land_nima";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_NIMA_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_NIMA_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_PINK:
            {
                pfileName = "land_pink";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_PINK_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_PINK_LIFE;
            }
            break;
        case GAME_ENEMY_MONSTERS_LAND_STAR:
            {
                pfileName = "land_star";
                moveSpeed = GAME_ENEMY_MONSTERS_LAND_STAR_SPEED;
                liveValue = GAME_ENEMY_MONSTERS_LAND_STAR_LIFE;
            }
            break;
        default:
            break;
    }
    
    for (int i = 1; i <= aniNum; i++) {
        memset(pBuffer, 0, sizeof(pBuffer));
        sprintf(pBuffer, "%s%02d.png",pfileName,i);
        CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(pBuffer);
        CCAssert(!(frame == NULL), "cannot be NULL");
        aniArray->addObject(frame);
        if (i == 1) {
            this->init(pBuffer, liveValue, moveSpeed, posArray);
        }
    }
    
    enemyMonsterTypeID = type;
    enemyAni = CCAnimation::createWithSpriteFrames(aniArray, 0.25);
    enemyAni->retain();
    this->runAction(CCRepeatForever::create(CCAnimate::create(enemyAni)));
    
    return true;
}
CCObject* NDKHelper::GetCCObjectFromJson(json_t *obj)
{
    if (obj == NULL)
        return NULL;
    
    if (json_is_object(obj))
    {
        CCDictionary *dictionary = new CCDictionary();
        //CCDictionary::create();
        
        const char *key;
        json_t *value;
        
        void *iter = json_object_iter(obj);
        while(iter)
        {
            key = json_object_iter_key(iter);
            value = json_object_iter_value(iter);
            
            dictionary->setObject(NDKHelper::GetCCObjectFromJson(value)->autorelease(), string(key));
            
            iter = json_object_iter_next(obj, iter);
        }
        
        return dictionary;
    }
    else if (json_is_array(obj))
    {
        size_t sizeArray = json_array_size(obj);
        CCArray *array = new CCArray();
        //CCArray::createWithCapacity(sizeArray);
        
        for (unsigned int i = 0; i < sizeArray; i++)
        {
            array->addObject(NDKHelper::GetCCObjectFromJson(json_array_get(obj, i))->autorelease());
        }
        
        return array;
    }
    else if (json_is_boolean(obj))
    {
        stringstream str;
        if (json_is_true(obj))
            str << true;
        else if (json_is_false(obj))
            str << false;
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_integer(obj))
    {
        stringstream str;
        str << json_integer_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_real(obj))
    {
        stringstream str;
        str << json_real_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_string(obj))
    {
        stringstream str;
        str << json_string_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
	else if (json_is_null(obj)) 
	{
		return new CCString("null");
	}
    
    return NULL;
}
Exemple #18
0
void DaojuEngine::daoJuConfirmHitPoint(Point p, int type){
    int row = p.y / this->perHeight;
    int line = p.x / this->perWidth;
    StarModel* model = this->getModelForLineAndRow(line, row);
    if (!model) {
        return;
    }
    switch (type) {
        case 0:
        {
            model->type = 2;
            model->node->sprite->setTexture("image_02.png");
            break;
        }
        case 1:
        {
            CCArray* arr = CCArray::create();
            arr->addObject(model);
            destroySlectedArray(arr,NULL);
            break;
        }
        case 2:
        {
            CCArray* arr = CCArray::create();
            arr->addObject(model);
            StarModel* block = getModelForLineAndRow(model->line-1, model->row);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line+1, model->row);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line, model->row-1);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line, model->row+1);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line-1, model->row-1);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line+1, model->row+1);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line+1, model->row-1);
            if (block) {
                arr->addObject(block);
            }
            block = getModelForLineAndRow(model->line-1, model->row+1);
            if (block) {
                arr->addObject(block);
            }
            destroySlectedArray(arr,NULL);
            break;
        }
        case 3:
        {
            CCArray* nameArray = CCArray::create();
            for (int i = 0; i<5; i++) {
                __String* s = __String::createWithFormat("image_0%d.png",i);
                nameArray->addObject(s);
            }
            
            for (int i = 0; i<dataSource->count(); i++) {
                CCArray* lineArr = (CCArray*)dataSource->objectAtIndex(i);
                for (int j = 0; j<lineArr->count(); j++) {
                    StarModel* model = getModelForLineAndRow(i, j);
                    
                    int type = arc4random()%typeCount;
                    model->type = type;
                    model->line = i;
                    model->row = j;
                    
                    __String* file = (__String*)nameArray->objectAtIndex(model->type);
                    Sprite* bSprite = model->node->sprite;
                    bSprite->setTexture(file->getCString());
                }
            }
            
            break;
        }
        case 4:
        {
            for (int i = 0; i<dataSource->count(); i++) {
                CCArray* lineArr = (CCArray*)dataSource->objectAtIndex(i);
                for (int j = 0; j<lineArr->count(); j++) {
                    StarModel* model = getModelForLineAndRow(i, j);
                    if (!model) {
                        return;
                    }
                    int tLine = arc4random()%dataSource->count();
                    int tRow = arc4random()%(((CCArray*)dataSource->objectAtIndex(tLine))->count());
                    
                    StarModel* tModel = getModelForLineAndRow(tLine, tRow);
                    if (!tModel) {
                        return;
                    }
                    
                    CCArray* TEMP = NULL;
                    
                    if (tModel) {
                        
                        TEMP = (CCArray*)dataSource->objectAtIndex(model->line);
                        TEMP->removeObjectAtIndex(model->row);
                        TEMP->insertObject(tModel, model->row);
                        
                        TEMP = (CCArray*)dataSource->objectAtIndex(tModel->line);
                        TEMP->removeObjectAtIndex(tModel->row);
                        TEMP->insertObject(model, tModel->row);
                        
                        
                        int temp = model->line;
                        model->line = tModel->line;
                        tModel->line = temp;
                        
                        temp = model->row;
                        model->row = tModel->row;
                        tModel->row = temp;
                        
                    }
                }
            }
            
            for (int i = 0; i<dataSource->count(); i++) {
                for (int j = 0; j<((CCArray*)dataSource->objectAtIndex(i))->count(); j++) {
                    StarModel* model = (StarModel*)((CCArray*)dataSource->objectAtIndex(i))->objectAtIndex(j);
                    model->line = i;
                    model->row = j;
                    StarNode* node = model->node;
                    Point p = node->sprite->getPosition();
                    Point t = ccp((i+ 0.5)*this->perHeight, (j+0.5)*this->perWidth);
                    if (p.x != t.x || p.y != t.y) {
                        CCActionInterval * moveBy = CCMoveBy::create(0.3,Vec2(t.x-p.x, t.y-p.y));
                        CCActionInterval * actionmoveback= moveBy;
                        node->sprite->runAction(actionmoveback);
                        allNodes->addObject(node);
                    }
                }
            }
            
            
            break;
        }
        default:
            break;
    }
}
Exemple #19
0
void FacebookInviteView::onSendClick(CCObject *pSender, CCControlEvent event){
    CCArray* arr = CCArray::create();
    for (int i=0; i<m_data->count(); i++) {
        auto dic = _dict(m_data->objectAtIndex(i));
        string flag = dic->valueForKey("flag")->getCString();
        if (arr->count()>50) {
            break;
        }
        if (flag=="1") {
            string id = dic->valueForKey("id")->getCString();;
            arr->addObject(CCString::create(id));
        }
    }
    m_inviteNum = arr->count();
    GlobalData::shared()->isBind = true;
    
    
    string msg = _lang("107087");
    FBUtilies::postFBSelectedFriendList(arr,msg,m_ftype);
    FBUtilies::appEventShareLog(CC_ITOA(GlobalData::shared()->playerInfo.selfServerId), GlobalData::shared()->playerInfo.level, FunBuildController::getInstance()->getMainCityLv(), "107087");
    if (FBUtilies::fbIsLogin() && m_ftype=="2") {
        double lastTime = 0.0;
        string timeStr = CCUserDefault::sharedUserDefault()->getStringForKey("facebookCallForHelpTime","");
        if (timeStr!="") {
            lastTime = atof(timeStr.c_str());
        }
        std:: map<string, CCDictionary*>::iterator it = GlobalData::shared()->shareFbmap.find("call_for_help");
        double ctime = GlobalData::shared()->getWorldTime();
        if (it!=GlobalData::shared()->shareFbmap.end()) {
            CCDictionary* dict = it->second;
            if (dict) {
                int on = dict->valueForKey("ON")->intValue();
                double limit = dict->valueForKey("Limit")->doubleValue();
                string permission = dict->valueForKey("permissions")->getCString();
                if (lastTime > 0) {
                    lastTime = lastTime + limit;
                }
                bool flag = FBUtilies::fbHasGranted(permission);
                if (on==1 && ctime >= lastTime && flag) {
                    CCUserDefault::sharedUserDefault()->setStringForKey("facebookCallForHelpTime", CC_ITOA(ctime));
                    CCUserDefault::sharedUserDefault()->flush();
                    string fbName = CCUserDefault::sharedUserDefault()->getStringForKey(FB_USERNAME, "");
                    string name = _lang_1(dict->valueForKey("name")->getCString(),fbName.c_str());
                    string caption = _lang_1(dict->valueForKey("caption")->getCString(),fbName.c_str());
                    string linkDescription = _lang_1(dict->valueForKey("linkDescription")->getCString(),fbName.c_str());
                    string pictureUrl = dict->valueForKey("pictureUrl")->getCString();
                    string link = dict->valueForKey("link")->getCString();
                    string ref = dict->valueForKey("ref")->getCString();
                    FBUtilies::fbPublishFeedDialog(name,caption,linkDescription,link,pictureUrl,1,ref);
                    CCLog("fb ask for help push ");
                }else{
                    CCLog("fb time or on key error on=%d limit=%f permission=%s flag=%d lastTime=%f ctime=%f",on,limit,permission.c_str(),flag,lastTime,ctime);
                }
            }else{
                CCLog("fb dict null");
            }
        }else{
            CCLog("fb have not call_for_help object");
        }
    }else{
        CCLog("fb facebook not login");
    }

}
// the XML parser calls here with all the elements
void CCTMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
{    
    CC_UNUSED_PARAM(ctx);
    CCTMXMapInfo *pTMXMapInfo = this;
    std::string elementName = (char*)name;
    std::map<std::string, std::string> *attributeDict = new std::map<std::string, std::string>();
    if (atts && atts[0])
    {
        for(int i = 0; atts[i]; i += 2) 
        {
            std::string key = (char*)atts[i];
            std::string value = (char*)atts[i+1];
            attributeDict->insert(pair<std::string, std::string>(key, value));
        }
    }
    if (elementName == "map")
    {
        std::string version = valueForKey("version", attributeDict);
        if ( version != "1.0")
        {
            CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str());
        }
        std::string orientationStr = valueForKey("orientation", attributeDict);
        if (orientationStr == "orthogonal")
            pTMXMapInfo->setOrientation(CCTMXOrientationOrtho);
        else if (orientationStr  == "isometric")
            pTMXMapInfo->setOrientation(CCTMXOrientationIso);
        else if(orientationStr == "hexagonal")
            pTMXMapInfo->setOrientation(CCTMXOrientationHex);
        else
            CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", pTMXMapInfo->getOrientation());

        CCSize s;
        s.width = (float)atof(valueForKey("width", attributeDict));
        s.height = (float)atof(valueForKey("height", attributeDict));
        pTMXMapInfo->setMapSize(s);

        s.width = (float)atof(valueForKey("tilewidth", attributeDict));
        s.height = (float)atof(valueForKey("tileheight", attributeDict));
        pTMXMapInfo->setTileSize(s);

        // The parent element is now "map"
        pTMXMapInfo->setParentElement(TMXPropertyMap);
    } 
    else if (elementName == "tileset") 
    {
        // If this is an external tileset then start parsing that
        std::string externalTilesetFilename = valueForKey("source", attributeDict);
        if (externalTilesetFilename != "")
        {
            // Tileset file will be relative to the map file. So we need to convert it to an absolute path
            if (m_sTMXFileName.find_last_of("/") != string::npos)
            {
                string dir = m_sTMXFileName.substr(0, m_sTMXFileName.find_last_of("/") + 1);
                externalTilesetFilename = dir + externalTilesetFilename;
            }
            else 
            {
                externalTilesetFilename = m_sResources + "/" + externalTilesetFilename;
            }
            externalTilesetFilename = CCFileUtils::sharedFileUtils()->fullPathForFilename(externalTilesetFilename.c_str());
            
            m_uCurrentFirstGID = (unsigned int)atoi(valueForKey("firstgid", attributeDict));
            
            pTMXMapInfo->parseXMLFile(externalTilesetFilename.c_str());
        }
        else
        {
            CCTMXTilesetInfo *tileset = new CCTMXTilesetInfo();
            tileset->m_sName = valueForKey("name", attributeDict);
            if (m_uCurrentFirstGID == 0)
            {
                tileset->m_uFirstGid = (unsigned int)atoi(valueForKey("firstgid", attributeDict));
            }
            else
            {
                tileset->m_uFirstGid = m_uCurrentFirstGID;
                m_uCurrentFirstGID = 0;
            }
            tileset->m_uSpacing = (unsigned int)atoi(valueForKey("spacing", attributeDict));
            tileset->m_uMargin = (unsigned int)atoi(valueForKey("margin", attributeDict));
            CCSize s;
            s.width = (float)atof(valueForKey("tilewidth", attributeDict));
            s.height = (float)atof(valueForKey("tileheight", attributeDict));
            tileset->m_tTileSize = s;

            pTMXMapInfo->getTilesets()->addObject(tileset);
            tileset->release();
        }
    }
    else if (elementName == "tile")
    {
        CCTMXTilesetInfo* info = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject();
        CCDictionary *dict = new CCDictionary();
        pTMXMapInfo->setParentGID(info->m_uFirstGid + atoi(valueForKey("id", attributeDict)));
        pTMXMapInfo->getTileProperties()->setObject(dict, pTMXMapInfo->getParentGID());
        CC_SAFE_RELEASE(dict);
        
        pTMXMapInfo->setParentElement(TMXPropertyTile);

    }
    else if (elementName == "layer")
    {
        CCTMXLayerInfo *layer = new CCTMXLayerInfo();
        layer->m_sName = valueForKey("name", attributeDict);

        CCSize s;
        s.width = (float)atof(valueForKey("width", attributeDict));
        s.height = (float)atof(valueForKey("height", attributeDict));
        layer->m_tLayerSize = s;

        std::string visible = valueForKey("visible", attributeDict);
        layer->m_bVisible = !(visible == "0");

        std::string opacity = valueForKey("opacity", attributeDict);
        if( opacity != "" )
        {
            layer->m_cOpacity = (unsigned char)(255 * atof(opacity.c_str()));
        }
        else
        {
            layer->m_cOpacity = 255;
        }

        float x = (float)atof(valueForKey("x", attributeDict));
        float y = (float)atof(valueForKey("y", attributeDict));
        layer->m_tOffset = ccp(x,y);

        pTMXMapInfo->getLayers()->addObject(layer);
        layer->release();

        // The parent element is now "layer"
        pTMXMapInfo->setParentElement(TMXPropertyLayer);

    } 
    else if (elementName == "objectgroup")
    {
        CCTMXObjectGroup *objectGroup = new CCTMXObjectGroup();
        objectGroup->setGroupName(valueForKey("name", attributeDict));
        CCPoint positionOffset;
        positionOffset.x = (float)atof(valueForKey("x", attributeDict)) * pTMXMapInfo->getTileSize().width;
        positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height;
        objectGroup->setPositionOffset(positionOffset);

        pTMXMapInfo->getObjectGroups()->addObject(objectGroup);
        objectGroup->release();

        // The parent element is now "objectgroup"
        pTMXMapInfo->setParentElement(TMXPropertyObjectGroup);

    }
    else if (elementName == "image")
    {
        CCTMXTilesetInfo* tileset = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject();

        // build full path
        std::string imagename = valueForKey("source", attributeDict);

        if (m_sTMXFileName.find_last_of("/") != string::npos)
        {
            string dir = m_sTMXFileName.substr(0, m_sTMXFileName.find_last_of("/") + 1);
            tileset->m_sSourceImage = dir + imagename;
        }
        else 
        {
            tileset->m_sSourceImage = m_sResources + (m_sResources.size() ? "/" : "") + imagename;
        }
    } 
    else if (elementName == "data")
    {
        std::string encoding = valueForKey("encoding", attributeDict);
        std::string compression = valueForKey("compression", attributeDict);

        if( encoding == "base64" )
        {
            int layerAttribs = pTMXMapInfo->getLayerAttribs();
            pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64);
            pTMXMapInfo->setStoringCharacters(true);

            if( compression == "gzip" )
            {
                layerAttribs = pTMXMapInfo->getLayerAttribs();
                pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip);
            } else
            if (compression == "zlib")
            {
                layerAttribs = pTMXMapInfo->getLayerAttribs();
                pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib);
            }
            CCAssert( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" );
        }
        CCAssert( pTMXMapInfo->getLayerAttribs() != TMXLayerAttribNone, "TMX tile map: Only base64 and/or gzip/zlib maps are supported" );

    } 
    else if (elementName == "object")
    {
        char buffer[32] = {0};
        CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject();

        // The value for "type" was blank or not a valid class name
        // Create an instance of TMXObjectInfo to store the object and its properties
        CCDictionary *dict = new CCDictionary();
        // Parse everything automatically
        const char* pArray[] = {"name", "type", "width", "height", "gid"};
        
        for(size_t i = 0; i < sizeof(pArray)/sizeof(pArray[0]); ++i )
        {
            const char* key = pArray[i];
            CCString* obj = new CCString(valueForKey(key, attributeDict));
            if( obj )
            {
                obj->autorelease();
                dict->setObject(obj, key);
            }
        }

        // But X and Y since they need special treatment
        // X

        const char* value = valueForKey("x", attributeDict);
        if (value) 
        {
            int x = atoi(value) + (int)objectGroup->getPositionOffset().x;
            sprintf(buffer, "%d", x);
            CCString* pStr = new CCString(buffer);
            pStr->autorelease();
            dict->setObject(pStr, "x");
        }

        // Y
        value = valueForKey("y", attributeDict);
        if (value)  {
            int y = atoi(value) + (int)objectGroup->getPositionOffset().y;

            // Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
            y = (int)(m_tMapSize.height * m_tTileSize.height) - y - atoi(valueForKey("height", attributeDict));
            sprintf(buffer, "%d", y);
            CCString* pStr = new CCString(buffer);
            pStr->autorelease();
            dict->setObject(pStr, "y");
        }

        // Add the object to the objectGroup
        objectGroup->getObjects()->addObject(dict);
        dict->release();

         // The parent element is now "object"
         pTMXMapInfo->setParentElement(TMXPropertyObject);

    }
    else if (elementName == "property")
    {
        if ( pTMXMapInfo->getParentElement() == TMXPropertyNone ) 
        {
            CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'",
                valueForKey("name", attributeDict), valueForKey("value",attributeDict) );
        } 
        else if ( pTMXMapInfo->getParentElement() == TMXPropertyMap )
        {
            // The parent element is the map
            CCString *value = new CCString(valueForKey("value", attributeDict));
            std::string key = valueForKey("name", attributeDict);
            pTMXMapInfo->getProperties()->setObject(value, key.c_str());
            value->release();

        } 
        else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer )
        {
            // The parent element is the last layer
            CCTMXLayerInfo* layer = (CCTMXLayerInfo*)pTMXMapInfo->getLayers()->lastObject();
            CCString *value = new CCString(valueForKey("value", attributeDict));
            std::string key = valueForKey("name", attributeDict);
            // Add the property to the layer
            layer->getProperties()->setObject(value, key.c_str());
            value->release();

        } 
        else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) 
        {
            // The parent element is the last object group
            CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject();
            CCString *value = new CCString(valueForKey("value", attributeDict));
            const char* key = valueForKey("name", attributeDict);
            objectGroup->getProperties()->setObject(value, key);
            value->release();

        } 
        else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject )
        {
            // The parent element is the last object
            CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject();
            CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();

            const char* propertyName = valueForKey("name", attributeDict);
            CCString *propertyValue = new CCString(valueForKey("value", attributeDict));
            dict->setObject(propertyValue, propertyName);
            propertyValue->release();
        } 
        else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile ) 
        {
            CCDictionary* dict = (CCDictionary*)pTMXMapInfo->getTileProperties()->objectForKey(pTMXMapInfo->getParentGID());

            const char* propertyName = valueForKey("name", attributeDict);
            CCString *propertyValue = new CCString(valueForKey("value", attributeDict));
            dict->setObject(propertyValue, propertyName);
            propertyValue->release();
        }
    }
    else if (elementName == "polygon") 
    {
        // find parent object's dict and add polygon-points to it
        CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject();
        CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();

        // get points value string
        const char* value = valueForKey("points", attributeDict);
        if(value)
        {
            CCArray* pPointsArray = new CCArray;

            // parse points string into a space-separated set of points
            stringstream pointsStream(value);
            string pointPair;
            while(std::getline(pointsStream, pointPair, ' '))
            {
                // parse each point combo into a comma-separated x,y point
                stringstream pointStream(pointPair);
                string xStr,yStr;
                char buffer[32] = {0};
                
                CCDictionary* pPointDict = new CCDictionary;

                // set x
                if(std::getline(pointStream, xStr, ','))
                {
                    int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
                    sprintf(buffer, "%d", x);
                    CCString* pStr = new CCString(buffer);
                    pStr->autorelease();
                    pPointDict->setObject(pStr, "x");
                }

                // set y
                if(std::getline(pointStream, yStr, ','))
                {
                    int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
                    sprintf(buffer, "%d", y);
                    CCString* pStr = new CCString(buffer);
                    pStr->autorelease();
                    pPointDict->setObject(pStr, "y");
                }
                
                // add to points array
                pPointsArray->addObject(pPointDict);
                pPointDict->release();
            }
            
            dict->setObject(pPointsArray, "points");
            pPointsArray->release();
        }
    }
    else if (elementName == "polyline")
    {
        // find parent object's dict and add polyline-points to it
        // CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject();
        // CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();
        // TODO: dict->setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"];
		CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject();
		CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();

		// get points value string
		const char* value = valueForKey("points", attributeDict);
		if(value)
		{
			CCArray* pPointsArray = new CCArray;

			// parse points string into a space-separated set of points
			stringstream pointsStream(value);
			string pointPair;
			while(std::getline(pointsStream, pointPair, ' '))
			{
				// parse each point combo into a comma-separated x,y point
				stringstream pointStream(pointPair);
				string xStr,yStr;
				char buffer[32] = {0};

				CCDictionary* pPointDict = new CCDictionary;

				// set x
				if(std::getline(pointStream, xStr, ','))
				{
					int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
					sprintf(buffer, "%d", x);
					CCString* pStr = new CCString(buffer);
					pStr->autorelease();
					pPointDict->setObject(pStr, "x");
				}

				// set y
				if(std::getline(pointStream, yStr, ','))
				{
					int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
					sprintf(buffer, "%d", y);
					CCString* pStr = new CCString(buffer);
					pStr->autorelease();
					pPointDict->setObject(pStr, "y");
				}

				// add to points array
				pPointsArray->addObject(pPointDict);
				pPointDict->release();
			}

			dict->setObject(pPointsArray, "points");
			pPointsArray->release();
		}
    }

    if (attributeDict)
    {
        attributeDict->clear();
        delete attributeDict;
    }
}
	bool PluginOptionsDialog::init()	{
		CCDictionary* dataSource(NetworkState::getInstanceDictionary(
			SL_SERIALIZEKEY_PLUGIN_GLOBAL_SETTINGS));

		// configure once
		Dictionary::setObjectIfNotExist(dataSource, 
			CCString::create("networklessons"),SL_SERIALIZEKEY_PEER_SESSION_PASSWORD);
		Dictionary::setObjectIfNotExist(dataSource, 
			CCDouble::create(50),SL_SERIALIZEKEY_PHYSICSFRAMERATE);

		setDataSource(dataSource);

		CCSize ctrlSize(CCSizeMake(0,0));

		CCArray* optionCtrls = CCArray::create();

		CCControlBase* ctrlContainer(nullptr);
		if(_pluginLayerContent != nullptr)	{
			if(_pluginLayerContent->getPluginHasNetwork())	{
				ctrlContainer = ControlUtils::createEditBox("Session password:"******"Physics framerate (hz):", ctrlSize);
				ctrlContainer->setValueKey(SL_SERIALIZEKEY_PHYSICSFRAMERATE);
				ctrlContainer->getCtrlLayoutFlags().addFlag(ECtrlLayoutFlag_ResetPreferredSizeOnSerialize);
				ctrlContainer->deserialize(dataSource);
				optionCtrls->addObject(ctrlContainer);
				// TODO: @student : check this code - this is an example how to track edit box changes
				_ctrlPhysicsFrameRate = dynamic_cast<CCControlEditBox*>(ctrlContainer);
			}
		}

		if(optionCtrls->count() == 0)	{
			ctrlContainer = ControlUtils::createValueBox("Option Info:", ctrlSize, "no plugin wide options available");
			optionCtrls->addObject(ctrlContainer);
		}

		CCControlColumn* ctrlOptionsContainer = ControlUtils::createControlColumn(optionCtrls,ctrlSize);
		ctrlOptionsContainer->getCtrlFlags().removeFlag(ECtrlFlag_UseScissorTest);

		CCArray* dialogCtrls = CCArray::create();
		dialogCtrls->addObject(ctrlOptionsContainer);
		dialogCtrls->addObject(createOkBtn());

		CCControlColumn* ctrlDialogContainer = ControlUtils::createControlColumn(dialogCtrls,ctrlSize);
		ctrlDialogContainer->getCtrlFlags().removeFlag(ECtrlFlag_UseScissorTest);

		CCSize dlgSize(ctrlDialogContainer->getContentSize());
		setPreferredSize(ctrlSize);

		// call the base class here we don't want all those background sprites
		bool initialized(CCControlBase::init());

		addChild(ctrlDialogContainer);
		setCtrlColumn(ctrlDialogContainer);

		// read the data from the datastore
		// we need to redo the layout as we have some edit controls 
		// inside this dialog
		// so force a new layout
		deserializeAll(getDataSource(), true);

		return initialized;
	}
Exemple #22
0
    void startElement(void *ctx, const char *name, const char **atts)
    {
        CC_UNUSED_PARAM(ctx);
        CC_UNUSED_PARAM(atts);
        std::string sName((char*)name);
        if( sName == "dict" )
        {
            m_pCurDict = new CCDictionary();
            if (m_eResultType == SAX_RESULT_DICT && ! m_pRootDict)
            {
				// Because it will call m_pCurDict->release() later, so retain here.
                m_pRootDict = m_pCurDict;
				m_pRootDict->retain();
            }
            m_tState = SAX_DICT;

            CCSAXState preState = SAX_NONE;
            if (! m_tStateStack.empty())
            {
                preState = m_tStateStack.top();
            }

            if (SAX_ARRAY == preState)
            {
                // add the dictionary into the array
                m_pArray->addObject(m_pCurDict);
            }
            else if (SAX_DICT == preState)
            {
                // add the dictionary into the pre dictionary
                CCAssert(! m_tDictStack.empty(), "The state is wrong!");
                CCDictionary* pPreDict = m_tDictStack.top();
                pPreDict->setObject(m_pCurDict, m_sCurKey);
            }

			m_pCurDict->release();

            // record the dict state
            m_tStateStack.push(m_tState);
            m_tDictStack.push(m_pCurDict);
        }
        else if(sName == "key")
        {
            m_tState = SAX_KEY;
        }
        else if(sName == "integer")
        {
            m_tState = SAX_INT;
        }
        else if(sName == "real")
        {
            m_tState = SAX_REAL;
        }
        else if(sName == "string")
        {
            m_tState = SAX_STRING;
        }
        else if (sName == "array")
        {
            m_tState = SAX_ARRAY;
            m_pArray = new CCArray();
            if (m_eResultType == SAX_RESULT_ARRAY && m_pRootArray == NULL)
            {
                m_pRootArray = m_pArray;
                m_pRootArray->retain();
            }
            CCSAXState preState = SAX_NONE;
            if (! m_tStateStack.empty())
            {
                preState = m_tStateStack.top();
            }

            //CCSAXState preState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
            if (preState == SAX_DICT)
            {
                m_pCurDict->setObject(m_pArray, m_sCurKey);
            }
            else if (preState == SAX_ARRAY)
            {
                CCAssert(! m_tArrayStack.empty(), "The state is worng!");
                CCArray* pPreArray = m_tArrayStack.top();
                pPreArray->addObject(m_pArray);
            }
            m_pArray->release();
            // record the array state
            m_tStateStack.push(m_tState);
            m_tArrayStack.push(m_pArray);
        }
        else
        {
            m_tState = SAX_NONE;
        }
    }
void TestLayer::testLogic(int testIndex)
{
    if (testIndex == 1)
    {
		if (m_bSpiderMonkeyInited) 
		{
			c_addLogToCLI(3, "[C++] %s", "Spidermonkey already inited!!!");
			return;
		}
        // init spidermonkey
        ScriptingCore* sc = ScriptingCore::getInstance();
        CCScriptEngineProtocol *pEngine = ScriptingCore::getInstance();
        CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
        sc->addRegisterCallback(register_all_cocos2dx);
        sc->addRegisterCallback(register_all_cocos2dx_extension);
        sc->addRegisterCallback(register_cocos2dx_js_extensions);
        sc->addRegisterCallback(register_all_cocos2dx_extension_manual);
        sc->addRegisterCallback(jsb_register_system);
        sc->addRegisterCallback(JSB_register_opengl);
        sc->start();
        if (!JS_DefineFunctions(sc->getGlobalContext(), sc->getGlobalObject(), myjs_global_functions)) {
            c_addLogToCLI(4, "[C++] JS_DefineFunctions Failed!!!");
            return;
        }
        sc->runScript("GlobalFuncTest.js");
        sc->runScript("SpriteFuncTest.js");
        m_bSpiderMonkeyInited = true;
		//c_addLogToCLI(1, "[C++] %s", "Spidermonkey init success");
        return;
    }
    if (!m_bSpiderMonkeyInited)
    {
		//c_addLogToCLI(4, "[C++] %s", "Init SpiderMonkey First!!!");
        return;
    }
    if (testIndex == 2)
    {
        // call JS function - 0 param, 0 return
        ScriptingCore* sc = ScriptingCore::getInstance();
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "MyLogFunc");
        c_addLogToCLI(1, "[C++] MyLogFunc called");
    }
    else if (testIndex == 3)
    {
        // call JS function - 1 param(Basic Type) , 1 return(Basic Type)
        ScriptingCore* sc = ScriptingCore::getInstance();
        jsval dataVal = INT_TO_JSVAL(10);
        jsval ret;
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "DubleIntFunc", 1, &dataVal, &ret);
        c_addLogToCLI(1, "[C++] DubleIntFunc called with result: %d", JSVAL_TO_INT(ret));
    }
    else if (testIndex == 4)
    {
        // call JS function - 0 param , 1 return(cocos2d Object)
        ScriptingCore* sc = ScriptingCore::getInstance();
        jsval ret;
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "SpawnIconSprite", 0, NULL, &ret);
		c_addLogToCLI(1, "[C++] SpawnIconSprite called");
        if(!JSVAL_IS_NULL(ret)) {
            JSObject *obj = JSVAL_TO_OBJECT(ret);
            js_proxy_t *proxy = jsb_get_js_proxy(obj);
            CCSprite *sprite = (CCSprite *)(proxy ? proxy->ptr : NULL);
            if (sprite) {
                this->addChild(sprite);
				c_addLogToCLI(1, "[C++] Add sprite from js to c++ layer");
            }
        }
    }
    else if (testIndex == 5 )
    {
        // call JS function - 1 param(cocos2d Object) , 0 return
        ScriptingCore* sc = ScriptingCore::getInstance();
        CCSprite *sprite = CCSprite::create("Icon.png");
        sprite->setPosition(ccp(CCRANDOM_0_1() * 1000, CCRANDOM_0_1() * 1000));
        this->addChild(sprite);
        js_proxy_t *p = js_get_or_create_proxy<cocos2d::CCSprite>(sc->getGlobalContext(), sprite);
        jsval dataVal = OBJECT_TO_JSVAL(p->obj);
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "DoubleSpriteSize", 1, &dataVal, NULL);
		c_addLogToCLI(1, "[C++] Add sprite from js to layer");
    }
    else if (testIndex == 6)
    {
        // Bind Simple UI component to c++ CCScene
        ScriptingCore* sc = ScriptingCore::getInstance();
        sc->runScript("CircleLabelTTFTest.js");
		c_addLogToCLI(1, "[C++] %s", "Run CircleLabelTTFTest script");
		c_addLogToCLI(1, "[C++] %s", "Bind UI Component to CCSCene");
    }
    else if (testIndex == 7)
    {
        // Bind Complex UI component to c++ CCScene
        ScriptingCore* sc = ScriptingCore::getInstance();
        sc->runScript("CalendarTest.js");
		c_addLogToCLI(1, "[C++] %s", "Run CalendarTest script");
		c_addLogToCLI(1, "[C++] %s", "Bind UI Component to CCSCene");
    }
    else if (testIndex == 8)
    {
        // call JS function - N param(Mix) , 0 return
        ScriptingCore* sc = ScriptingCore::getInstance();
        js_proxy_t *p = js_get_or_create_proxy<cocos2d::CCLayer>(sc->getGlobalContext(), this);
        jsval layerVal = OBJECT_TO_JSVAL(p->obj);
        
        jsval nowStringVal = c_string_to_jsval(sc->getGlobalContext(), "2013-7-27");
        jsval minYearVal = INT_TO_JSVAL(2010);
        jsval maxYearVal = INT_TO_JSVAL(2016);
        jsval args[4];
        args[0] = layerVal;
        args[1] = minYearVal;
        args[2] = maxYearVal;
        args[3] = nowStringVal;
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "AddCalendarToLayer", 4, args, NULL);
		c_addLogToCLI(1, "[C++] %s", "Bind Calendar UI to speicfied layer");
    }
    else if (testIndex == 9)
    {
        // call JS object function
        ScriptingCore* sc = ScriptingCore::getInstance();
        js_proxy_t *p = js_get_or_create_proxy<cocos2d::CCLayer>(sc->getGlobalContext(), this);
        jsval layerVal = OBJECT_TO_JSVAL(p->obj);
        
        jsval stringVal = c_string_to_jsval(sc->getGlobalContext(), "center");
        
        CCArray *array = CCArray::create();
        array->addObject(CCInteger::create(111));
        array->addObject(CCInteger::create(222));
        array->addObject(CCInteger::create(333));
        array->addObject(CCInteger::create(444));
        array->addObject(CCInteger::create(555));
        array->addObject(CCInteger::create(666));
        array->addObject(CCInteger::create(777));
        array->addObject(CCInteger::create(888));
        jsval arrayVal = ccarray_to_jsval(sc->getGlobalContext(), array);
        jsval radiusVal = INT_TO_JSVAL(200);
        jsval args[4];
        args[0] = layerVal;
        args[1] = stringVal;
        args[2] = arrayVal;
        args[3] = radiusVal;
        jsval ret;
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "AddCircleTTFSpriteToLayer", 4, args, &ret);
		c_addLogToCLI(1, "[C++] %s", "Bind CircleTTF UI to speicfied layer");
        if(!JSVAL_IS_NULL(ret)) {
            sc->executeFunctionWithOwner(ret, "expandTTF", 0, NULL, NULL);
			c_addLogToCLI(1, "[C++] %s", "Call CircleTTF function expandTTF");
        }
    }
    else if (testIndex == 10)
    {
        // Bind UI Component (CLI)
        ScriptingCore* sc = ScriptingCore::getInstance();
        js_proxy_t *p = js_get_or_create_proxy<cocos2d::CCLayer>(sc->getGlobalContext(), this);
        jsval layerVal = OBJECT_TO_JSVAL(p->obj);
        sc->executeFunctionWithOwner(OBJECT_TO_JSVAL(sc->getGlobalObject()), "BindCLILayerTo", 1, &layerVal, &g_cliJSValue);
		c_addLogToCLI(1, "[C++] %s", "Bind CLI Layer to current layer");
        m_bCLIBound = true;
    }
    else
    {
		c_addLogToCLI(4, "[C++] TEST NOT FOUND!!!");
    }
}
Exemple #24
0
void LevelScene::createLevelsLayer()
{
    CCArray *pLayers = CCArray::create();

    CCArray *pLevels = m_pKategoria->getPantailak();
    
    int numLevels = pLevels->count();
    
    int numberPages = numLevels / 4;
    
    if (numLevels % 4 > 0) {
        numberPages++;
    }
    
    int cont = 0;
    
    for (int i = 1; i <= numberPages; i++) {
        
        CCLayer *pContainer = CCLayer::create();
        CCLayer *pContentLayer = CCLayer::create();
        
        CCSize contentSize = CCSizeMake(500, 490);
        CCPoint contentPos = ccp(VisibleRect::center().x - contentSize.width/2, VisibleRect::center().y - contentSize.height/2);
        pContentLayer->setContentSize(contentSize);
        pContentLayer->setPosition(contentPos);
        
        CCPoint texturePosition[] = {ccp(122, 369), ccp(372, 369), ccp(122, 149), ccp(372, 149)};
        CCPoint labelPosition[] = {ccp(125, 250), ccp(375, 250), ccp(125, 30), ccp(375, 30)};
        
        int numberRows = numLevels - (4 * (i-1));
        
        if (numberRows > 4)
            numberRows = 4;
        
        for(int j = 1; j <= numberRows; j++) {
           
            LevelModel *pLevel = (LevelModel*) pLevels->objectAtIndex(cont);
            
            std::string imageName = CCFileUtils::sharedFileUtils()->getWriteablePath().append(pLevel->getList());
            
            CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage("borde.png");
            SpriteButton *pLevelButton = SpriteButton::create(pTexture ,this, callfuncO_selector(LevelScene::levelClicked));
            pLevelButton->setPosition(texturePosition[j-1]);
            pLevelButton->setTag(cont);

            pTexture = CCTextureCache::sharedTextureCache()->addImage(imageName.c_str());
            CCSprite *pImageBorder = CCSprite::createWithTexture(pTexture);
            //pImageBorder->setAnchorPoint(ccp(0, 0));
            pImageBorder->setScale(imageScale);
            pImageBorder->setPosition(ccp(87, 95));
            pLevelButton->addChild(pImageBorder);
            
            pContentLayer->addChild(pLevelButton);
     
            
            CCLabelTTF *pLabel = CCLabelTTF::create(pLevel->getIzena(), fontList[0], 22.0);
            pLabel->setPosition(labelPosition[j-1]);
            pLabel->setColor(ccc3(63, 62, 62));
            pLabel->setDimensions(CCSizeMake(257, 50));
            pContentLayer->addChild(pLabel);
            
            cont++;
        }
        
        pContainer->addChild(pContentLayer);
        pLayers->addObject(pContainer);
    }
    
    CCScrollLayer *pScrollLayer = CCScrollLayer::nodeWithLayers(pLayers, 0);
    pScrollLayer->setPagesIndicatorPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y + 70));
    pScrollLayer->setDelegate(this);
    pScrollLayer->moveToPage(0);
    addChild(pScrollLayer);
}
Exemple #25
0
void SGHttpClient::serverListListener(char *buffer)
{
    CCLOG("下行:服务器列表,数据长度 %ld",sizeof(buffer));
    
    CCArray *serverList = CCArray::create();
    
    SGResponseData *rData = new SGResponseData(buffer);
    if(rData->readChar()==0){
        CCLOG("获取服务器列表失败");
        delete rData;
        return;
    }
    
    short serverNum = rData->readShort();
    for (int i = 0; i<serverNum; i++)
    {
        CCDictionary *serverDict = CCDictionary::create();
        
        //服务器Id
        short serverId = rData->readShort();
        serverDict->setObject(CCString::createWithFormat("%d", serverId), "serverId");
        //是否为新服
        short serverIsNew = rData->readShort();
        serverDict->setObject(CCString::createWithFormat("%d",serverIsNew), "serverIsNew");
		
        //服务器名称
        const char *serverName = rData->readString();
        serverDict->setObject(CCString::create(serverName), "serverName");
        
        //服务器ip地址
        const char *serverIp = rData->readString();
        serverDict->setObject(CCString::create(serverIp), "serverIp");
        
        //服务器端口号
        short serverPost = rData->readShort();
        serverDict->setObject(CCString::createWithFormat("%d", serverPost), "serverPost");
        
        //服务器状态
        char serverState = rData->readChar();
        serverDict->setObject(CCString::createWithFormat("%d", serverState), "serverState");
        
        //是否有角色
        char isHasRole = rData->readChar();
        serverDict->setObject(CCString::createWithFormat("%d", isHasRole), "isHasRole");
        //0.没有角色 1.有角色
        if (isHasRole == 1)
        {
            //昵称
            const char * roleNikeName = rData->readString();
            serverDict->setObject(CCString::create(roleNikeName), "roleNikeName");
			
            //等级
            short  roleLevel = rData->readShort();
            serverDict->setObject(CCString::createWithFormat("%d", roleLevel), "roleLevel");
            
            //国家
            short countryId = rData->readShort();
            serverDict->setObject(CCString::createWithFormat("%d", countryId), "countryId");
        }
        //add by:zyc.服务器详细的状态信息。
        const char * serverDes = rData->readString();
        serverDict->setObject(CCString::create(serverDes), "serverDes");
        
        //MM: serverShowId显示其为几区,与前面的serverId不同,这里只是显示。例如serverId为2009,serverShowId可能为9。
        short serverShowId = rData->readShort();
        serverDict->setObject(CCString::createWithFormat("%d", serverShowId), "serverShowId");
        
        //添加到服务器列表。
        serverList->addObject(serverDict);
        SGPlayerInfo::sharePlayerInfo()->addServerList(serverList);
        
    }
    delete rData;
    if (_delegate)
    {
        _delegate->requestFinished(MSg_HTTP_SERVERLIST, serverList);
    }
}
SGMonster::SGMonster(int type, int hp, int atk, int inkAmount, int score, const CCPoint* const movePoints,
                     const int nPoints, CCLayer* const parent) : parentLayer(parent) {
    this->maxHP = hp;
    this->nowHP = this->maxHP;
    this->atk = atk;
    
    this->bWakeupMonster = false;
    this->nWakeupFrames = -1;
    this->act_wakeup = NULL;
    
    CCSpriteFrameCache *pSpriteFrameCache = CCSpriteFrameCache::sharedSpriteFrameCache();
    
    switch (type) {
        case MONSTER_TYPE_MUD: {
            monsterSprite = CCSprite::create(pSpriteFrameCache->spriteFrameByName("mud_wait_1.png"));
            monsterSprite->retain();
            monsterSprite->setPosition(ccp(-500,-500));
            parentLayer->addChild(monsterSprite, ORDER_MONSTER, TAG_TEXTURE);
            
            CCArray* pWalkFrames = CCArray::create();
            CCArray* pWalkActions = CCArray::create();
            for(int i=1; i<=nPoints; i++) {
                pWalkFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_walk_%d.png", i)->getCString()));
            }
            for(int i=0; i<nPoints; i++) {
                pWalkActions->addObject(CCSpawn::create(CCDelayTime::create(GAME_FRAME_SPEED), CCPlace::create(movePoints[i])));
                if(i==11) {
                    //mett or Not
                    pWalkActions->addObject(CCCallFunc::create(this, callfunc_selector(SGMonster::confirmBattlePos)));
                }
            }
            pWalkActions->addObject(CCPlace::create(ccp(-500,-500)));
            act_run = CCSpawn::create(CCAnimate::create(CCAnimation::create(pWalkFrames, GAME_FRAME_SPEED)),
                                      CCSequence::create(pWalkActions));
            act_run->retain();
            pWalkActions->release();
            pWalkFrames->release();
            
            CCArray* pWaitFrames = CCArray::create();
            for(int i=1; i<=3; i++) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_wait_%d.png", i)->getCString()));
            }
            pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName("mud_wait_2.png"));
            act_wait = CCRepeatForever::create(CCAnimate::create(CCAnimation::create(pWaitFrames,GAME_FRAME_SPEED)));
            act_wait->retain();
            pWaitFrames->release();
            
            bWakeupMonster = true;
            nWakeupFrames = 6;
            CCArray* pWakeupFrames = CCArray::create();
            for(int i=1; i<=6; i++) {
                pWakeupFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_wakeup_%d.png", i)->getCString()));
            }
            //act_wakeup = CCAnimate::create(CCAnimation::create(pWakeupFrames,GAME_FRAME_SPEED));
            act_wakeup = CCSequence::create(CCAnimate::create(CCAnimation::create(pWakeupFrames,GAME_FRAME_SPEED)),
                                            CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
            act_wakeup->retain();
            pWakeupFrames->release();
            
            CCArray* pDefendFrames = CCArray::create();
            for(int i=1; i<=4; i++) {
                pDefendFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_defend_%d.png", i)->getCString()));
            }
            act_defend = CCSequence::create(CCAnimate::create(CCAnimation::create(pDefendFrames,GAME_FRAME_SPEED)),
                                            CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
            act_defend->retain();
            pDefendFrames->release();
            
            CCArray* pDieFrames = CCArray::create();
            for(int i=1; i<=9; i++) {
                pDieFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_die_%d.png", i)->getCString()));
            }
            act_die = CCSequence::create(CCAnimate::create(CCAnimation::create(pDieFrames,GAME_FRAME_SPEED)),
                                         CCPlace::create(ccp(-500,-500)));
            act_die->retain();
            pDieFrames->release();
            nDieFrames=9;
            
			numAttacks = 1;
            act_attack = new SGAttackAction[numAttacks];
            
            CCArray* pAttackRightFrames = CCArray::create();
            for(int i=1; i<=7; i++) {
                pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_attack_right_%d.png", i)->getCString()));
            }
            for(int i=4; i>=1; i--) {
                pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("mud_attack_right_%d.png", i)->getCString()));
            }
			act_attack[0].atkDir = ATK_DIR_RIGHT;
            act_attack[0].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackRightFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[0].act_attack->retain();
            act_attack[0].nFrames = 7;
            pAttackRightFrames->release();
            
            break;
        }
            
        case MONSTER_TYPE_BAT: {
            monsterSprite = CCSprite::create(pSpriteFrameCache->spriteFrameByName("bat_wait_1.png"));
            monsterSprite->retain();
            monsterSprite->setPosition(ccp(-500,-500));
            parentLayer->addChild(monsterSprite, ORDER_MONSTER, TAG_TEXTURE);
            
            CCArray* pWalkFrames = CCArray::create();
            CCArray* pWalkActions = CCArray::create();
            for(int i=1; i<=nPoints; i++) {
                pWalkFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_walk_%d.png", i)->getCString()));
            }
            for(int i=0; i<nPoints; i++) {
                pWalkActions->addObject(CCSpawn::create(CCDelayTime::create(GAME_FRAME_SPEED), CCPlace::create(movePoints[i])));
                if(i==11) {
                    //mett or Not
                    pWalkActions->addObject(CCCallFunc::create(this, callfunc_selector(SGMonster::confirmBattlePos)));
                }
            }
            pWalkActions->addObject(CCPlace::create(ccp(-500,-500)));
            act_run = CCSpawn::create(CCAnimate::create(CCAnimation::create(pWalkFrames, GAME_FRAME_SPEED)),
                                      CCSequence::create(pWalkActions));
            act_run->retain();
            pWalkActions->release();
            pWalkFrames->release();
            
            CCArray* pWaitFrames = CCArray::create();
            for(int i=1; i<=7; i++) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_wait_%d.png", i)->getCString()));
            }
            for(int i=6; i>=2; i--) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_wait_%d.png", i)->getCString()));
            }
            act_wait = CCRepeatForever::create(CCAnimate::create(CCAnimation::create(pWaitFrames,GAME_FRAME_SPEED)));
            act_wait->retain();
            pWaitFrames->release();
            
            CCArray* pDefendFrames = CCArray::create();
            for(int i=1; i<=3; i++) {
                pDefendFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_defend_%d.png", i)->getCString()));
            }
            act_defend = CCSequence::create(CCAnimate::create(CCAnimation::create(pDefendFrames,GAME_FRAME_SPEED)),
                                            CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
            act_defend->retain();
            pDefendFrames->release();
            
            CCArray* pDieFrames = CCArray::create();
            for(int i=1; i<=9; i++) {
                pDieFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_die_%d.png", i)->getCString()));
            }
            act_die = CCSequence::create(CCAnimate::create(CCAnimation::create(pDieFrames,GAME_FRAME_SPEED)),
                                         CCPlace::create(ccp(-500,-500)));
            act_die->retain();
            pDieFrames->release();
            nDieFrames=9;
            
			numAttacks = 2;
            act_attack = new SGAttackAction[numAttacks];
            
            CCArray* pAttackLeftFrames = CCArray::create();
            for(int i=1; i<=11; i++) {
                pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_attack_left_%d.png", i)->getCString()));
            }
			pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_wait_2.png")->getCString()));
			act_attack[0].atkDir = ATK_DIR_LEFT;
			act_attack[0].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackLeftFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[0].act_attack->retain();
            act_attack[0].nFrames = 9;
            pAttackLeftFrames->release();
            
            CCArray* pAttackRightFrames = CCArray::create();
            for(int i=1; i<=11; i++) {
                pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_attack_right_%d.png", i)->getCString()));
            }
			pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("bat_wait_2.png")->getCString()));
			act_attack[1].atkDir = ATK_DIR_RIGHT;
            act_attack[1].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackRightFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[1].act_attack->retain();
            act_attack[1].nFrames = 9;
            pAttackRightFrames->release();
            
            break;
        }
            
        case MONSTER_TYPE_WING: {
            monsterSprite = CCSprite::create(pSpriteFrameCache->spriteFrameByName("wing_wait_1.png"));
            monsterSprite->retain();
            monsterSprite->setPosition(ccp(-500,-500));
            parentLayer->addChild(monsterSprite, ORDER_MONSTER, TAG_TEXTURE);
            
            CCArray* pWalkFrames = CCArray::create();
            CCArray* pWalkActions = CCArray::create();
            for(int i=1; i<=nPoints; i++) {
                pWalkFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_walk_%d.png", i)->getCString()));
            }
            for(int i=0; i<nPoints; i++) {
                pWalkActions->addObject(CCSpawn::create(CCDelayTime::create(GAME_FRAME_SPEED), CCPlace::create(movePoints[i])));
                if(i==11) {
                    //mett or Not
                    pWalkActions->addObject(CCCallFunc::create(this, callfunc_selector(SGMonster::confirmBattlePos)));
                }
            }
            pWalkActions->addObject(CCPlace::create(ccp(-500,-500)));
            act_run = CCSpawn::create(CCAnimate::create(CCAnimation::create(pWalkFrames, GAME_FRAME_SPEED)),
                                      CCSequence::create(pWalkActions));
            act_run->retain();
            pWalkActions->release();
            pWalkFrames->release();
            
            CCArray* pWaitFrames = CCArray::create();
            for(int i=1; i<=5; i++) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_wait_%d.png", i)->getCString()));
            }
            for(int i=4; i>=2; i--) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_wait_%d.png", i)->getCString()));
            }
            act_wait = CCRepeatForever::create(CCAnimate::create(CCAnimation::create(pWaitFrames,GAME_FRAME_SPEED)));
            act_wait->retain();
            pWaitFrames->release();
            
            CCArray* pDefendFrames = CCArray::create();
            for(int i=1; i<=3; i++) {
                pDefendFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_defend_%d.png", i)->getCString()));
            }
            act_defend = CCSequence::create(CCAnimate::create(CCAnimation::create(pDefendFrames,GAME_FRAME_SPEED)),
                                            CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
            act_defend->retain();
            pDefendFrames->release();
            
            CCArray* pDieFrames = CCArray::create();
            for(int i=1; i<=8; i++) {
                pDieFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_die_%d.png", i)->getCString()));
            }
            act_die = CCSequence::create(CCAnimate::create(CCAnimation::create(pDieFrames,GAME_FRAME_SPEED)),
                                         CCPlace::create(ccp(-500,-500)));
            act_die->retain();
            pDieFrames->release();
            nDieFrames=8;
            
			numAttacks = 3;
            act_attack = new SGAttackAction[numAttacks];
            
            CCArray* pAttackLeftFrames = CCArray::create();
            pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName("wing_attack_1.png"));
            for(int i=2; i<=5; i++) {
                pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_attack_left_%d.png", i)->getCString()));
            }
			act_attack[0].atkDir = ATK_DIR_LEFT;
			act_attack[0].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackLeftFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[0].act_attack->retain();
            act_attack[0].nFrames = 5;
            pAttackLeftFrames->release();
            
            CCArray* pAttackRightFrames = CCArray::create();
            pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName("wing_attack_1.png"));
            for(int i=2; i<=5; i++) {
                pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_attack_right_%d.png", i)->getCString()));
            }
			act_attack[1].atkDir = ATK_DIR_RIGHT;
            act_attack[1].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackRightFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[1].act_attack->retain();
            act_attack[1].nFrames = 5;
            pAttackRightFrames->release();
            
            CCArray* pAttackUpFrames = CCArray::create();
            pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName("wing_attack_up_.png"));
            for(int i=3; i<=7; i++) {
                pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("wing_attack_up_%d.png", i)->getCString()));
            }
            pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName("wing_attack_up_4.png"));
            pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName("wing_attack_up_3.png"));
			act_attack[2].atkDir = ATK_DIR_UP;
            act_attack[2].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackUpFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[2].act_attack->retain();
            act_attack[2].nFrames = 5;
            pAttackUpFrames->release();
            
            break;
        }
            
        case MONSTER_TYPE_BALL: {
            monsterSprite = CCSprite::create(pSpriteFrameCache->spriteFrameByName("ball_wait_1.png"));
            monsterSprite->retain();
            monsterSprite->setPosition(ccp(-500,-500));
            parentLayer->addChild(monsterSprite, ORDER_MONSTER, TAG_TEXTURE);
            
            CCArray* pWalkFrames = CCArray::create();
            CCArray* pWalkActions = CCArray::create();
            for(int i=1; i<=nPoints; i++) {
                pWalkFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_walk_%d.png", i)->getCString()));
            }
            for(int i=0; i<nPoints; i++) {
                pWalkActions->addObject(CCSpawn::create(CCDelayTime::create(GAME_FRAME_SPEED), CCPlace::create(movePoints[i])));
                if(i==11) {
                    //mett or Not
                    pWalkActions->addObject(CCCallFunc::create(this, callfunc_selector(SGMonster::confirmBattlePos)));
                }
            }
            pWalkActions->addObject(CCPlace::create(ccp(-500,-500)));
            act_run = CCSpawn::create(CCAnimate::create(CCAnimation::create(pWalkFrames, GAME_FRAME_SPEED)),
                                      CCSequence::create(pWalkActions));
            act_run->retain();
            pWalkActions->release();
            pWalkFrames->release();
            
            CCArray* pWaitFrames = CCArray::create();
            for(int i=1; i<=3; i++) {
                pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_wait_%d.png", i)->getCString()));
            }
            pWaitFrames->addObject(pSpriteFrameCache->spriteFrameByName("ball_wait_2.png"));
            act_wait = CCRepeatForever::create(CCAnimate::create(CCAnimation::create(pWaitFrames, GAME_FRAME_SPEED)));
            act_wait->retain();
            pWaitFrames->release();
            
            CCArray* pDefendFrames = CCArray::create();
            for(int i=1; i<=2; i++) {
                pDefendFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_defend_%d.png", i)->getCString()));
            }
            act_defend = CCSequence::create(CCAnimate::create(CCAnimation::create(pDefendFrames,GAME_FRAME_SPEED)),
                                            CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
            act_defend->retain();
            pDefendFrames->release();
            
            CCArray* pDieFrames = CCArray::create();
            for(int i=1; i<=8; i++) {
                pDieFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_die_%d.png", i)->getCString()));
            }
            act_die = CCSequence::create(CCAnimate::create(CCAnimation::create(pDieFrames,GAME_FRAME_SPEED)),
                                         CCPlace::create(ccp(-500,-500)));
            act_die->retain();
            pDieFrames->release();
            nDieFrames=8;
            
			numAttacks = 4;
            act_attack = new SGAttackAction[numAttacks];
            
            CCArray* pAttackLeftFrames = CCArray::create();
            for(int i=1; i<=7; i++) {
                pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_attack_left_%d.png", i)->getCString()));
            }
			pAttackLeftFrames->addObject(pSpriteFrameCache->spriteFrameByName("ball_attack_right_1.png"));
			act_attack[0].atkDir = ATK_DIR_LEFT;
			act_attack[0].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackLeftFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[0].act_attack->retain();
            act_attack[0].nFrames = 7;
            pAttackLeftFrames->release();
            
            CCArray* pAttackRightFrames = CCArray::create();
            for(int i=1; i<=7; i++) {
                pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_attack_right_%d.png", i)->getCString()));
            }
			pAttackRightFrames->addObject(pSpriteFrameCache->spriteFrameByName("ball_attack_left_1.png"));
			act_attack[1].atkDir = ATK_DIR_RIGHT;
            act_attack[1].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackRightFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[1].act_attack->retain();
            act_attack[1].nFrames = 7;
            pAttackRightFrames->release();
            
            CCArray* pAttackUpFrames = CCArray::create();
            for(int i=1; i<=5; i++) {
                pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_attack_up_%d.png", i)->getCString()));
            }
            pAttackUpFrames->addObject(pSpriteFrameCache->spriteFrameByName("ball_attack_up_2.png"));
			act_attack[2].atkDir = ATK_DIR_UP;
            act_attack[2].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackUpFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[2].act_attack->retain();
            act_attack[2].nFrames = 5;
            pAttackUpFrames->release();
            
            CCArray* pAttackDownFrames = CCArray::create();
            for(int i=1; i<=5; i++) {
                pAttackDownFrames->addObject(pSpriteFrameCache->spriteFrameByName(CCString::createWithFormat("ball_attack_down_%d.png", i)->getCString()));
            }
			act_attack[3].atkDir = ATK_DIR_DOWN;
            act_attack[3].act_attack = CCSequence::create(CCAnimate::create(CCAnimation::create(pAttackDownFrames,GAME_FRAME_SPEED)),
                                                          CCCallFunc::create(this, callfunc_selector(SGMonster::func_waiting)));
			act_attack[3].act_attack->retain();
            act_attack[3].nFrames = 4;
            pAttackDownFrames->release();
            break;
        }
    }
}
void RPGMapSceneLayer::playerMoveEnd()
{
    CCTMXTiledMap *bgMap = (CCTMXTiledMap*)this->getChildByTag(kRPGMapSceneLayerTagBgMap);
    RPGMapRoleSprite *player = (RPGMapRoleSprite*)bgMap->getChildByTag(kRPGMapSceneLayerTagPlayer);
    player->stopMove();
    
    player->stopActionByTag(kRPGMapSceneLayerActTagPlayerMove);

    this->m_playerMoveAct = NULL;
    
    //地图切换点的判断
    CCTMXObjectGroup *transitionsObjects = bgMap->objectGroupNamed("transitions");
    for (int i = 0; i < transitionsObjects->getObjects()->count(); i++)
    {
        CCDictionary *transitionsObject = (CCDictionary*)transitionsObjects->getObjects()->objectAtIndex(i);
        const CCString *x = transitionsObject->valueForKey("x");
        const CCString *y = transitionsObject->valueForKey("y");
        const CCString *width = transitionsObject->valueForKey("width");
        const CCString *height = transitionsObject->valueForKey("height");
        
        const CCString *mapId = transitionsObject->valueForKey("map_id");
        const CCString *playerToX = transitionsObject->valueForKey("player_to_x");
        const CCString *playerToY = transitionsObject->valueForKey("player_to_y");
        const CCString *playerDirection = transitionsObject->valueForKey("player_direction");
        
        CCRect transitionsRect = CCRectMake(stringToNumber<float>(x->getCString()), stringToNumber<float>(y->getCString()), stringToNumber<float>(width->getCString()), stringToNumber<float>(height->getCString()));
        
        if(transitionsRect.containsPoint(player->getPosition()))
        {
//            CCLog("切换场景%s", mapId->getCString());
            
            //数据库部分,更新进度记录
            
            //修正偏差位置,因为无法得知下一个地图的大小,所以目前只能在tmx上面定死
            float toX = stringToNumber<float>(playerToX->getCString()) + 0.5;
            float toY = stringToNumber<float>(playerToY->getCString()) + 0.5;
            
            //保存数据
            
            RPGSaveData *saveDataObj = RPGSaveData::create();
            saveDataObj->m_mapId = stringToNumber<int>(mapId->getCString());
            saveDataObj->m_playerToX = toX;
            saveDataObj->m_playerToY = toY;
            saveDataObj->m_playerDirection = playerDirection->getCString();
            saveDataObj->m_gold = this->m_mapData.gold;
            saveDataObj->m_windowStyle = CCUserDefault::sharedUserDefault()->getStringForKey(GAME_STYLE);
            saveData(&this->m_db, saveDataObj);
            
            CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
            this->unscheduleUpdate();
            
            CCScene *s = RPGMapSceneLayer::scene(0.0);
            CCTransitionFade *t = CCTransitionFade::create(GAME_SCENE, s);
            CCDirector::sharedDirector()->replaceScene(t);
            return;
        }
        
    }
    
    //遇敌处理
//    this->m_hasEnemy = true; //test
    if(this->m_hasEnemy)
    {
        float val = CCRANDOM_0_1();
        val = CCRANDOM_0_1();
        if(val >= 0.0 && val <= GAME_MAP_ENCOUNTER)
        {
//            CCLog("遇敌!");
            CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
            this->unscheduleUpdate();
            
            CCTMXTiledMap *bgMap = (CCTMXTiledMap*)this->getChildByTag(kRPGMapSceneLayerTagBgMap);
            
            CCArray *loadTextures = CCArray::create();
            loadTextures->addObject(CCString::create("monsters.png"));
            loadTextures->addObject(CCString::create("battle_bg.png"));
            
            CCArray *releaseTextures = CCArray::create();
            releaseTextures->addObject(CCString::create("map.png"));
            releaseTextures->addObject(CCString::create("joystick.png"));
            releaseTextures->addObject(CCString::create("actor4_0.png"));
            releaseTextures->addObject(CCString::create("actor111.png"));
            releaseTextures->addObject(CCString::create("actor113.png"));
            releaseTextures->addObject(CCString::create("actor114.png"));
            releaseTextures->addObject(CCString::create("actor115.png"));
            releaseTextures->addObject(CCString::create("actor117.png"));
            releaseTextures->addObject(CCString::create("actor120.png"));
            
            CCMenu *mainMenu = (CCMenu*)bgMap->getChildByTag(kRPGMapSceneLayerTagMainMenu);
            mainMenu->setEnabled(false);
            
            SimpleAudioEngine::sharedEngine()->playEffect("audio_battle_start.wav");
            
//            CCLog("%i", this->m_saveData.mapId);
            
            RPGMapRoleSprite *player = (RPGMapRoleSprite*)bgMap->getChildByTag(kRPGMapSceneLayerTagPlayer);
            
            CCUserDefault::sharedUserDefault()->setIntegerForKey("map_id", this->m_mapData.mapId);
            CCUserDefault::sharedUserDefault()->setFloatForKey("player_to_x", player->getPosition().x / GAME_TMX_ROLE_WIDTH);
            CCUserDefault::sharedUserDefault()->setFloatForKey("player_to_y", player->getPosition().y / GAME_TMX_ROLE_HEIGHT);
            CCUserDefault::sharedUserDefault()->setIntegerForKey("gold", this->m_mapData.gold);            
            switch (player->m_direction)
            {
                case kRPGMapRoleSpriteDirectionUp:
                    CCUserDefault::sharedUserDefault()->setStringForKey("player_direction", "up");
                    break;
                case kRPGMapRoleSpriteDirectionDown:
                    CCUserDefault::sharedUserDefault()->setStringForKey("player_direction", "down");
                    break;
                case kRPGMapRoleSpriteDirectionLeft:
                    CCUserDefault::sharedUserDefault()->setStringForKey("player_direction", "left");
                    break;
                case kRPGMapRoleSpriteDirectionRight:
                    CCUserDefault::sharedUserDefault()->setStringForKey("player_direction", "right");
                    break;
                default:
                    break;
            }
            
            CCScene *s = RPGLoadingSceneLayer::scene(loadTextures, releaseTextures, "single_battle");
            CCTransitionFade *t = CCTransitionFade::create(GAME_SCENE, s);
            CCDirector::sharedDirector()->replaceScene(t);
        }
    }
    
}
void CCSuperAnim::update(float dt)
{
	if (mAnimState != kAnimStatePlaying)
	{
		return;
	}
	
	bool isNewLabel = false;
	float anOriginFrameRate = mAnimHandler.mAnimRate;
	mAnimHandler.mAnimRate *= mSpeedFactor;
	IncAnimFrameNum(mAnimHandler, dt, isNewLabel);
	mAnimHandler.mAnimRate = anOriginFrameRate;
	
	float aTimeFactor = (mAnimHandler.mCurFrameNum - mAnimHandler.mFirstFrameNumOfCurLabel) / (float)(mAnimHandler.mLastFrameNumOfCurLabel - mAnimHandler.mFirstFrameNumOfCurLabel);
	for (TimeEventInfoArray::iterator anIter = mCurTimeEventInfoArray.begin(); anIter != mCurTimeEventInfoArray.end(); anIter++) {
		if (aTimeFactor >= anIter->mTimeFactor) {
			// trigger time event
			CCLog("Trigger anim time event: %d, %s, %d", mId, anIter->mLabelName.c_str(), anIter->mEventId);
			if (mListener) {
				mListener->OnTimeEvent(mId, anIter->mLabelName, anIter->mEventId);
			}
            if(m_scriptHandler.handler) {
                CCArray* pArrayArgs = CCArray::createWithCapacity(5);
                pArrayArgs->addObject(this);
                pArrayArgs->addObject(CCString::create("time"));
                pArrayArgs->addObject(CCInteger::create(mId));
                pArrayArgs->addObject(CCString::create(anIter->mLabelName));
                pArrayArgs->addObject(CCInteger::create(anIter->mEventId));
                CCScriptEngineManager::sharedManager()->getScriptEngine()->executeEventWithArgs(m_scriptHandler, pArrayArgs);
            }
			break;
		}
	}
	
	// remove obsolete time event
	for (TimeEventInfoArray::iterator anIter = mCurTimeEventInfoArray.begin(); anIter != mCurTimeEventInfoArray.end();) {
		if (aTimeFactor >= anIter->mTimeFactor) {
			anIter = mCurTimeEventInfoArray.erase(anIter);
		} else {
			anIter++;
		}
	}
	
	if (isNewLabel && mIsLoop) {
		PlaySection(mAnimHandler.mCurLabel, mIsLoop);
	}
	
	if (isNewLabel)
	{
        if(mListener) {
            mListener->OnAnimSectionEnd(mId, mAnimHandler.mCurLabel);
        }
        if(m_scriptHandler.handler) {
            CCArray* pArrayArgs = CCArray::createWithCapacity(4);
            pArrayArgs->addObject(this);
            pArrayArgs->addObject(CCString::create("end"));
            pArrayArgs->addObject(CCInteger::create(mId));
            pArrayArgs->addObject(CCString::create(mAnimHandler.mCurLabel));
            CCScriptEngineManager::sharedManager()->getScriptEngine()->executeEventWithArgs(m_scriptHandler, pArrayArgs);
        }
	}
}
Exemple #29
0
    void endElement(void *ctx, const char *name)
    {
        CC_UNUSED_PARAM(ctx);
        CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
        std::string sName((char*)name);
        if( sName == "dict" )
        {
            m_tStateStack.pop();
            m_tDictStack.pop();
            if ( !m_tDictStack.empty())
            {
                m_pCurDict = m_tDictStack.top();
            }
        }
        else if (sName == "array")
        {
            m_tStateStack.pop();
            m_tArrayStack.pop();
            if (! m_tArrayStack.empty())
            {
                m_pArray = m_tArrayStack.top();
            }
        }
        else if (sName == "true")
        {
            CCString *str = new CCString("1");
            if (SAX_ARRAY == curState)
            {
                m_pArray->addObject(str);
            }
            else if (SAX_DICT == curState)
            {
                m_pCurDict->setObject(str, m_sCurKey.c_str());
            }
            str->release();
        }
        else if (sName == "false")
        {
            CCString *str = new CCString("0");
            if (SAX_ARRAY == curState)
            {
                m_pArray->addObject(str);
            }
            else if (SAX_DICT == curState)
            {
                m_pCurDict->setObject(str, m_sCurKey.c_str());
            }
            str->release();
        }
        else if (sName == "string" || sName == "integer" || sName == "real")
        {
            CCString* pStrValue = new CCString(m_sCurValue);

            if (SAX_ARRAY == curState)
            {
                m_pArray->addObject(pStrValue);
            }
            else if (SAX_DICT == curState)
            {
                m_pCurDict->setObject(pStrValue, m_sCurKey.c_str());
            }

            pStrValue->release();
            m_sCurValue.clear();
        }
        
        m_tState = SAX_NONE;
    }
Exemple #30
0
void ActionNode::initWithDictionary(const rapidjson::Value& dic,CCObject* root)
{
	setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag"));
	int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist");
	for (int i=0; i<actionFrameCount; i++) {

		const rapidjson::Value& actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i);
		int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid");

		bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx");
		if (existPosition)
		{
			float positionX = DICTOOL->getFloatValue_json(actionFrameDic, "positionx");
			float positionY = DICTOOL->getFloatValue_json(actionFrameDic, "positiony");
			ActionMoveFrame* actionFrame = new ActionMoveFrame();
			actionFrame->autorelease();
			actionFrame->setFrameIndex(frameInex);
			actionFrame->setPosition(CCPointMake(positionX, positionY));
			CCArray* cActionArray = (CCArray*)m_FrameArray->objectAtIndex((int)kKeyframeMove);
			cActionArray->addObject(actionFrame);
		}

		bool existScale = DICTOOL->checkObjectExist_json(actionFrameDic,"scalex");
		if (existScale)
		{
			float scaleX = DICTOOL->getFloatValue_json(actionFrameDic, "scalex");
			float scaleY = DICTOOL->getFloatValue_json(actionFrameDic, "scaley");
			ActionScaleFrame* actionFrame = new ActionScaleFrame();
			actionFrame->autorelease();
			actionFrame->setFrameIndex(frameInex);
			actionFrame->setScaleX(scaleX);
			actionFrame->setScaleY(scaleY);
			CCArray* cActionArray = (CCArray*)m_FrameArray->objectAtIndex((int)kKeyframeScale);
			cActionArray->addObject(actionFrame);
		}

		bool existRotation = DICTOOL->checkObjectExist_json(actionFrameDic,"rotation");
		if (existRotation)
		{
			float rotation = DICTOOL->getFloatValue_json(actionFrameDic, "rotation");
			ActionRotationFrame* actionFrame = new ActionRotationFrame();
			actionFrame->autorelease();
			actionFrame->setFrameIndex(frameInex);
			actionFrame->setRotation(rotation);
			CCArray* cActionArray = (CCArray*)m_FrameArray->objectAtIndex((int)kKeyframeRotate);
			cActionArray->addObject(actionFrame);
		}

		bool existOpacity = DICTOOL->checkObjectExist_json(actionFrameDic,"opacity");
		if (existOpacity)
		{
			int opacity = DICTOOL->getIntValue_json(actionFrameDic, "opacity");
			ActionFadeFrame* actionFrame = new ActionFadeFrame();
			actionFrame->autorelease();
			actionFrame->setFrameIndex(frameInex);
			actionFrame->setOpacity(opacity);
			CCArray* cActionArray = (CCArray*)m_FrameArray->objectAtIndex((int)kKeyframeFade);
			cActionArray->addObject(actionFrame);
		}

		bool existColor = DICTOOL->checkObjectExist_json(actionFrameDic,"colorr");
		if (existColor)
		{
			int colorR = DICTOOL->getIntValue_json(actionFrameDic, "colorr");
			int colorG = DICTOOL->getIntValue_json(actionFrameDic, "colorg");
			int colorB = DICTOOL->getIntValue_json(actionFrameDic, "colorb");
			ActionTintFrame* actionFrame = new ActionTintFrame();
			actionFrame->autorelease();
			actionFrame->setFrameIndex(frameInex);
			actionFrame->setColor(ccc3(colorR,colorG,colorB));
			CCArray* cActionArray = (CCArray*)m_FrameArray->objectAtIndex((int)kKeyframeTint);
			cActionArray->addObject(actionFrame);
		}

	}
	initActionNodeFromRoot(root);
}