void TestFeedBackView::onOkClick(cocos2d::CCObject *pSender, CCControlEvent event) { // if (TESTFEEDBACK_CONTROL->getServerId().length() == 0 || TESTFEEDBACK_CONTROL->getName().length() == 0 || TESTFEEDBACK_CONTROL->getServerId() == "0") // { // CCCommonUtils::flyHint("", "", "请输入服务器号和名字");//todocfb // return; // } //////////点确认按钮单独传递玩家的服务器号和名字,反馈内容在每次填写完面板后已经向后台传递完成 CCObject* obj = NULL; CCDictionary* pelem = NULL; CCARRAY_FOREACH(m_data, obj) { pelem = (CCDictionary*)obj; pelem->setObject(ccs("1"), "fixFlag"); break;//所以只需要每其中一项理性“fixFlag”即可 }
void ThirdPartyHelper::setAd(int tag){ if (tag == SET_AD_SCREEN) { const char *key = "admobscreenad"; int time = UserDefault::getInstance()->getIntegerForKey(key, SCREEN_AD_TIME); if (time !=1 ) { UserDefault::getInstance()->setIntegerForKey(key, time-1); return; }else{ UserDefault::getInstance()->setIntegerForKey(key, SCREEN_AD_TIME); } } CCDictionary *dic = CCDictionary::create(); dic->setObject(CCString::create(StringUtils::format("%d",tag)), "setAd"); SendMessageWithParams("setAd", dic); }
static int tolua_Cocos2dx_CCArmatureAnimation_setFrameEventCallFunc00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"CCArmatureAnimation",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { CCArmatureAnimation* self = (CCArmatureAnimation*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setFrameEventCallFunc'", NULL); #endif LuaArmatureWrapper* wrapper = new LuaArmatureWrapper(); if (NULL == wrapper) { tolua_error(tolua_S,"LuaArmatureWrapper create fail\n", NULL); return 0; } wrapper->autorelease(); LUA_FUNCTION handler = ( toluafix_ref_function(tolua_S,2,0)); wrapper->setHandler(handler); CCDictionary* dict = static_cast<CCDictionary*>(self->getUserObject()); if (NULL == self->getUserObject()) { dict = CCDictionary::create(); self->setUserObject(dict); } dict->setObject(wrapper, "frameEvent"); self->setFrameEventCallFunc(wrapper, frameEvent_selector(LuaArmatureWrapper::frameEventCallback)); } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setFrameEventCallFunc'.",&tolua_err); return 0; #endif }
static int tolua_Cocos2dx_CCTableView_setDataSource(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"CCTableView",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { CCTableView* self = (CCTableView*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setDataSource'", NULL); #endif LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCDictionary* userDict = static_cast<CCDictionary*>(self->getUserObject()); if (NULL == userDict) { userDict = new CCDictionary(); if (NULL == userDict) return 0; self->setUserObject(userDict); userDict->release(); } userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); self->setDataSource(dataSource); dataSource->release(); return 0; } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setDataSource'.",&tolua_err); return 0; #endif }
static int tolua_Cocos2dx_Widget_addTouchEventListener00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"Widget",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { Widget* self = (Widget*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'addTouchEventListener'", NULL); #endif LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create(); if (NULL == listener) { tolua_error(tolua_S,"LuaCocoStudioEventListener create fail\n", NULL); return 0; } LUA_FUNCTION handler = ( toluafix_ref_function(tolua_S,2,0)); listener->setHandler(handler); CCDictionary* dict = static_cast<CCDictionary*>(self->getScriptObjectDict()); if (NULL == dict) { dict = CCDictionary::create(); self->setScriptObjectDict(dict); } dict->setObject(listener, "widgetTouchEvent"); self->addTouchEventListener(listener, toucheventselector(LuaCocoStudioEventListener::eventCallbackFunc)); } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'addTouchEventListener'.",&tolua_err); return 0; #endif }
static int tolua_Cocos2dx_CCTableView_create00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S, 1, "CCTableView", 0, &tolua_err) || !tolua_isusertype(tolua_S, 2, "CCSize", 0, &tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCSize size = *((CCSize*) tolua_tousertype(tolua_S,2,0)); CCTableView* tolua_ret = CCTableView::create(dataSource, size); if (NULL == tolua_ret) return 0; tolua_ret->reloadData(); CCDictionary* userDict = new CCDictionary(); userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); tolua_ret->setUserObject(userDict); userDict->release(); dataSource->release(); int nID = (int)tolua_ret->m_uID; int* pLuaID = &tolua_ret->m_nLuaID; toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCTableView"); return 1; } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'create'.",&tolua_err); return 0; #endif }
void MutiTouchTestLayer::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) { CCSetIterator iter = pTouches->begin(); for (; iter != pTouches->end(); iter++) { CCTouch* pTouch = (CCTouch*)(*iter); TouchPoint* pTouchPoint = TouchPoint::touchPointWithParent(this); CCPoint location = pTouch->getLocation(); pTouchPoint->setTouchPos(location); pTouchPoint->setTouchColor(s_TouchColors[pTouch->getID()]); addChild(pTouchPoint); s_dic.setObject(pTouchPoint, pTouch->getID()); } }
void CCEGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) { CCSet set; for (int i = 0; i < num; ++i) { int id = ids[i]; float x = xs[i]; float y = ys[i]; CCInteger* pIndex = (CCInteger*)s_TouchesIntergerDict.objectForKey(id); int nUnusedIndex = 0; // it is a new touch if (pIndex == NULL) { nUnusedIndex = getUnUsedIndex(); // The touches is more than MAX_TOUCHES ? if (nUnusedIndex == -1) { CCLOG("The touches is more than MAX_TOUCHES, nUnusedIndex = %d", nUnusedIndex); continue; } CCTouch* pTouch = s_pTouches[nUnusedIndex] = new CCTouch(); pTouch->setTouchInfo(nUnusedIndex, (x - m_obViewPortRect.origin.x) / m_fScaleX, (y - m_obViewPortRect.origin.y) / m_fScaleY); //CCLOG("x = %f y = %f", pTouch->getLocationInView().x, pTouch->getLocationInView().y); CCInteger* pInterObj = new CCInteger(nUnusedIndex); s_TouchesIntergerDict.setObject(pInterObj, id); set.addObject(pTouch); pInterObj->release(); } } if (set.count() == 0) { CCLOG("touchesBegan: count = 0"); return; } m_pDelegate->touchesBegan(&set, NULL); }
void HelloWorld::menuCloseCallback(CCObject* pSender) { // Register a selector in a global space // So that when our native environment will call the method with the string // It can respond to the selector // Note : Group name is there for ease of removing the selectors NDKHelper::AddSelector("HelloWorldSelectors", "SampleSelector", callfuncND_selector(HelloWorld::SampleSelector), this); // Making parameters for message to be passed to native language // For the ease of use, i am sending the method to be called name from C++ CCDictionary* prms = CCDictionary::create(); prms->setObject(CCString::create("SampleSelector"), "to_be_called"); // Finally call the native method in current environment SendMessageWithParams(string("SampleSelector"), prms); }
void SGHttpClient::bindListener(char *buffer) { SGResponseData *rData = new SGResponseData(buffer); char ch = rData->readChar(); short type = rData->readShort(); CCString *string1 = CCString::createWithFormat("%d",ch); CCString *string2 = CCString::createWithFormat("%d",type); CCDictionary *dict = CCDictionary::create(); dict->setObject(string1, "string1"); dict->setObject(string2, "string2"); delete rData; if(_delegate) { _delegate->requestFinished(MSG_HTTP_BING, dict); } }
static int tolua_Cocos2dx_CCTableView_create01(lua_State* tolua_S) { tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"CCTableView",0,&tolua_err) || !tolua_isusertype(tolua_S, 2, "CCSize", 0, &tolua_err) || !tolua_isusertype(tolua_S,3,"CCNode",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else { LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); if (NULL == dataSource) return 0; CCSize size = *((CCSize*) tolua_tousertype(tolua_S,2,0)); CCNode* node = static_cast<CCNode*>(tolua_tousertype(tolua_S, 3, 0)); CCTableView* tolua_ret = CCTableView::create(dataSource,size,node); if (NULL == tolua_ret) return 0; tolua_ret->reloadData(); CCDictionary* userDict = new CCDictionary(); userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); tolua_ret->setUserObject(userDict); userDict->release(); dataSource->release(); int nID = (int)tolua_ret->m_uID; int* pLuaID = &tolua_ret->m_nLuaID; toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCTableView"); return 1; } return 0; tolua_lerror: return tolua_Cocos2dx_CCTableView_create00(tolua_S); }
void CCBalsamiqLayer::setBalsamiqControl(const std::string &controlType, const std::string &controlName, CCNode *control) { if (controlType.length() == 0 || controlName.length() == 0) { return; } CCObject *controlsDic = this->getBalsamiqControlDic()->objectForKey(controlType); if (controlsDic == NULL) { CCDictionary *dic = CCDictionary::create(); dic->setObject(control, controlName); this->getBalsamiqControlDic()->setObject(dic, controlType); } else { static_cast<CCDictionary *>(controlsDic)->setObject(control, controlName); } }
void TestFilenameLookup::onEnter() { FileUtilsDemo::onEnter(); CCFileUtils *sharedFileUtils = CCFileUtils::sharedFileUtils(); CCDictionary *dict = CCDictionary::create(); dict->setObject(CCString::create("Images/grossini.png"), "grossini.bmp"); dict->setObject(CCString::create("Images/grossini.png"), "grossini.xcf"); sharedFileUtils->setFilenameLookupDictionary(dict); // Instead of loading carlitos.xcf, it will load grossini.png CCSprite *sprite = CCSprite::create("grossini.xcf"); this->addChild(sprite); CCSize s = CCDirector::sharedDirector()->getWinSize(); sprite->setPosition(ccp(s.width/2, s.height/2)); }
int GlobalData::sqliteExecCallBack( void * para, int n_column, char ** column_value, char ** column_name ) { const char *myPara = (const char *)para; if (strcmp(myPara, QUERY_CATEGORY_FRACTION)==0) { CCDictionary *dict = CCDictionary::create(); for(int i = 0 ; i < n_column; i ++ ) { dict->setObject(CCString::create(column_value[i]), column_name[i]); } arrayFraction->addObject(dict); } else if(strcmp(myPara, QUERY_CATEGORY_CARDINFO)==0) { dictCard = CCDictionary::create(); for(int i = 0 ; i < n_column; i ++ ) { dictCard->setObject(CCString::create(column_value[i]), column_name[i]); } } else if(strcmp(myPara, QUERY_CATEGORY_CARDBYGROUP)==0) { dictCard = CCDictionary::create(); for(int i = 0 ; i < n_column; i ++ ) { dictCard->setObject(CCString::create(column_value[i]), column_name[i]); } arrayCardProfile->addObject(dictCard); } else if(strcmp(myPara, QUERY_CARD_PROFILE_BY_NAME)==0) { dictCard = CCDictionary::create(); for(int i = 0 ; i < n_column; i ++ ) { dictCard->setObject(CCString::create(column_value[i]), column_name[i]); } } else if(strcmp(myPara, QUERY_CARD_PROFILE_ALL)==0) { dictCard = CCDictionary::create(); for(int i = 0 ; i < n_column; i ++ ) { dictCard->setObject(CCString::create(column_value[i]), column_name[i]); } arrayCards->addObject(dictCard); } return 0; }
void InputLabel::editBoxEditingDidEnd(ui::EditBox* editBox) { CCLOG("Edit Box editing did end"); if(isOpened) { //on dealloc, the isOpened flag will be false to prevent this code from being executed (could be used for a cancel method too) isOpened = false; if(linkTo != NULL) { if(strlen(delegate->getText()) > 0) { if(isPassword) { IFEXIST(passwordText)->autorelease(); passwordText = new CCString(delegate->getText()); std::string bulletString; for(int i = 0; i < (int)strlen(delegate->getText()); i++) { bulletString.append("●"); } linkTo->setLabelValue(bulletString.c_str()); } else { linkTo->setLabelValue(delegate->getText()); } } else { linkTo->setLabelValue(initialText->getCString()); } delegate->setText(""); linkTo->setVisible(true); } CCDictionary* param = this->getEventInfos(); param->setObject(Screate(this->getLabelValue()), "Text"); Director::getInstance()->getEventDispatcher()->dispatchCustomEvent("TextAdded", param); } delegate->detachWithIME(); }
void QuestionLayer::simulateAnswerRight() { this->unschedule(schedule_selector(QuestionLayer::timerCB)); CCDictionary* results = questionObj->rightAnswer; for (int i=0; i<results->allKeys()->count(); i++) { CCString* key = (CCString *)(results->allKeys()->objectAtIndex(i)); results->setObject(CCString::createWithFormat("%d", 1), key->getCString()); } //回答完成所有正确答案 for (int i=0; i<results->allKeys()->count(); i++) { CCString* key = (CCString *)(results->allKeys()->objectAtIndex(i)); CCControlButton* btn = (CCControlButton *)(this->getChildByTag(key->intValue())); CCSprite* spr = CCSprite::create("star000.png"); spr->setAnchorPoint(ccp(0.5f, 0.5f)); spr->setPosition(ccp(btn->getContentSize().width/2, btn->getContentSize().height/2)); btn->addChild(spr); CCBlink* blink = CCBlink::create(1.0f, 3); if (i < results->allKeys()->count()-1) { spr->runAction(blink); } else { CCAction* pAction = CCCallFuncND::create(this, callfuncND_selector(QuestionLayer::noticeDelegate), NULL); spr->runAction(CCSequence::create(blink, pAction, NULL)); } } rightAnswer++; if (timerCount >= timerTotal*2/3) { rightLimit += 1; //播放快速答题音效 GameSoundManager::shareManager()->playAnswerCool(); } else { //播放普通答题正确音效 GameSoundManager::shareManager()->playAnswerRight(); } isAnswerFinished = true; }
void TapRecognizer::onTouchEnded(CCTouch *touch, CCEvent *pEvent) { #if VERBOSE_TOUCH_RECOGNIZERS CCLOG("linked ? %s", mainLinker->linkedObjectOf(touch) == NULL ? "yes" : "no"); CCLOG("is in start ? %s", touchStart->objectForKey(touch->getID()) != NULL ? "yes" : "no"); CCLOG("time ? %s", (TIME - ((CCFloat*)touchStart->objectForKey(touch->getID()))->getValue()) < 2.0 ? "yes" : "no"); CCLOG("distance ? %s : real : %f", ccpDistance(Scene::touchPosition(touch), touchInitialPosition->at(touch->getID())) < 20 ? "yes" : "no", ccpDistance(Scene::touchPosition(touch), touchInitialPosition->at(touch->getID()))); CCLOG("initial position : %f, %f, current : %f, %f", touchInitialPosition->at(touch->getID()).x, touchInitialPosition->at(touch->getID()).y, Scene::touchPosition(touch).x, Scene::touchPosition(touch).y); #endif if(mainLinker != NULL //&& mainLinker->linkedObjectOf(touch) == NULL //prevent drag + tap from working at the same time && touchStart->objectForKey(touch->getID()) != NULL && (TIME - ((CCFloat*)touchStart->objectForKey(touch->getID()))->getValue()) < 2.0 && ccpDistance(Scene::touchPosition(touch), touchInitialPosition.at(touch->getID())) < 50 * RESOLUTION_MULTIPLIER) { CCDictionary* infos = CCDictionary::create(); infos->setObject(touch, "Touch"); CCNotificationCenter::sharedNotificationCenter()->postNotification("TapRecognized", infos); } touchStart->removeObjectForKey(touch->getID()); touchInitialPosition.erase(touch->getID()); }
void SGHttpClient::updateSelectServerResponse(char *buf) { //获取最新服务器 20 //字符串 服务器ip string //端口post short //服务器id short //服务器名字 string //服务器当前状态具体描述 string CCDictionary *dict = CCDictionary::create(); SGResponseData *response = new SGResponseData(buf); CCString *serverIp = CCString::create(response->readString()); CCString *serverPost = CCString::createWithFormat("%d",response->readShort()); CCString *serverId = CCString::createWithFormat("%d",response->readShort()); CCString *serverIsNew = CCString::createWithFormat("%d",response->readShort()); CCString *serverName = CCString::create(response->readString()); CCString *serverState = CCString::createWithFormat("%d" , response->readChar() ); CCString *serverDes = CCString::create(response->readString()); CCString *serverShowId = CCString::createWithFormat("%d",response->readShort()); dict->setObject(serverIp, "serverIp"); dict->setObject(serverPost, "serverPost"); dict->setObject(serverId, "serverId"); dict->setObject(serverIsNew, "serverIsNew"); dict->setObject(serverName, "serverName"); dict->setObject(serverState, "serverState"); dict->setObject(serverDes, "serverDes"); //MM: 添加server的显示ID。 dict->setObject(serverShowId, "serverShowId"); delete response; if(_delegate) { _delegate->requestFinished(MSG_HTTP_UPDATE_SERVER_STATE, dict); } }
//note : keys have to be passed as CCString, unfortunately. Must be NULL terminated CCDictionary* createDictionaryWithParameters(CCObject* firstObject, ... ) { CCObject* eachObject; va_list argumentList; bool key = true; CCObject* object; if (firstObject) // The first argument isn't part of the varargs list, { // so we'll handle it separately. //put all parameters in a Dictionary to access them as key/value pairs CCDictionary* values = CCDictionary::create(); object = firstObject; va_start(argumentList, firstObject); // Start scanning for arguments after firstObject. while ((eachObject = va_arg(argumentList, CCObject*)) != NULL) // As many times as we can get an argument of type "id" { if(key) { //keys should be Strings if(!isKindOfClass(eachObject, CCString)) { CCLOG("Warning : not a key, value ignored"); } else { CCString* key = (CCString*)eachObject; values->setObject(object, key->m_sString); } } else { object = eachObject; } key = !key; } va_end(argumentList); return values; } else {
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: { CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>"); if (SAX_ARRAY == curState) { m_pArray->addObject(pText); } else if (SAX_DICT == curState) { m_pCurDict->setObject(pText, m_sCurKey); } break; } default: break; } pText->release(); }
// 在我方底线放置一排防御墙,可以抵御下回合75%伤害, //(上限为武将攻击力)如果没有受到伤害,将以主将攻击力25%的伤害进行全列攻击 void SGHeroSkill27::activateSkill_20063(SGHeroLayer *heroLayer, SGHeroLayer *heroLayer1, int roleid, int buffid, int round, float value1, float value2, float value3) { CCDictionary *buff = CCDictionary::create(); buff->setObject(heroLayer, "hero"); buff->setObject(heroLayer1, "hero1"); buff->setObject(CCString::createWithFormat("%d",roleid), "roleid"); buff->setObject(CCString::createWithFormat("%d",buffid), "buffId");// buff->setObject(CCString::createWithFormat("%d",round), "round"); buff->setObject(CCString::createWithFormat("%f",value1), "value1"); if (buffid == 1012) {//虚空盾 if (heroLayer && value2 > 0) { heroLayer->changBloodNum(value2, true, true); } }else{ buff->setObject(CCString::createWithFormat("%f",value2), "value2"); } heroLayer->addBuff(buff); bool isme = true; if (SGPlayerInfo::sharePlayerInfo()->getPlayerRoleId() != roleid) { isme = false; } // CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("animationFile/dq.plist"); ResourceManager::sharedInstance()->bindTexture("animationFile/dq.plist", RES_TYPE_BATTLE_IMAGE, sg_battleLayer); for (int i = 0; i < mapList; i++) { CCSpriterX *fermEffect = CCSpriterX::create("animationFile/dq.scml", true, true); fermEffect->setanimaID(0); fermEffect->setisloop(true); CCPoint pos = GameConfig::getGridPoint(isme ? mapRow : -mapRow, abs(isme ? -i : (mapList - 1 - i)),true); fermEffect->setPosition(ccp(pos.x, isme ? heroLayer->uibgY : (screenheight - heroLayer->uibgY))); fermEffect->play(); heroLayer->addChild(fermEffect, SKILLS_BULLET_TAG, SKILLS_BULLET_TAG + i); } }
void LotteryRotateView::rotateFinished() { if (m_rotating == false || m_targetCell == NULL) { m_rotating = false; this->unschedule(schedule_selector(LotteryRotateView::rotatingHandler)); return; } this->unschedule(schedule_selector(LotteryRotateView::rotatingHandler)); m_rotating = false; m_rotateAngle = m_fEndAngle; if (m_rotateAngle>0) { m_rotateAngle = fmodf(m_rotateAngle, 360.0f); } else { m_rotateAngle = fmodf(m_rotateAngle, -360.0f); } CCDictionary* dict = CCDictionary::create(); dict->setObject(ccs(LOTTERYACTVIEW_COM), "key"); CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(LOTTERYROTATEVIEW, dict); }
void MoreDiamondDialog::shareCallback( CCObject* pSender ) { PLAY_BUTTON_EFFECT; bool isLogIn = DataManager::sharedDataManager()->GetFbIsLogIn(); if (isLogIn) { NDKHelper::AddSelector("MoreDiamondDialog", "onPublishFeedCompleted", callfuncND_selector(MoreDiamondDialog::onPublishFeedCompleted), this); string message = "Game này được, có bạn chơi cùng thì khỏi chê!"; string name = "The Croods"; string caption = "Thánh thức cùng bạn bè"; string description = "Game hay, thuộc thể loại này nọ..."; string picture = "http://vfossa.vn/tailen/news/2012_01/knowledge.jpg"; string link = "https://play.google.com/store/apps/details?id=com.supercell.hayday"; CCDictionary* prms = CCDictionary::create(); prms->setObject(CCString::create(message), "message"); prms->setObject(CCString::create(name), "name"); prms->setObject(CCString::create(caption), "caption"); prms->setObject(CCString::create(description), "description"); prms->setObject(CCString::create(picture), "picture"); prms->setObject(CCString::create(link), "link"); SendMessageWithParams(string("PublishFeed"), prms); } else { m_curOperator = string("share"); NDKHelper::AddSelector("MoreDiamondDialog", "onLogInCompleted", callfuncND_selector(MoreDiamondDialog::onLogInCompleted), this); SendMessageWithParams(string("LogIn"), NULL); } }
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; } }
CCDictionary *HEditBox::toDictionary(int command) { CCDictionary *pRet = CCDictionary::create(); pRet->setObject(HString::createWithInteger((int)this), HVIEWKEY_ID); pRet->setObject(HString::createWithInteger(HVIEWTYPE_EDITBOX), HVIEWKEY_TYPE); pRet->setObject(HString::createWithBoolean(isVisible()), HVIEWKEY_VISIBLE); do { if (command == HVIEWCMD_REMOVE) break; if (command == HVIEWCMD_GETTEXT) break; if (command == HVIEWCMD_SHOW) break; if (command == HVIEWCMD_HIDE) break; if (command == HVIEWCMD_SETTEXT) { if (m_strText.length() > 0) pRet->setObject(HString::create(m_strText.c_str()), HVIEWKEY_TEXT); break; } CCRect rect = AppDelegate::getInstance()->getGameManager()->rectToDeviceInPixels(this); pRet->setObject(HString::createWithInteger((int)rect.origin.x), HVIEWKEY_X); pRet->setObject(HString::createWithInteger((int)rect.origin.y), HVIEWKEY_Y); pRet->setObject(HString::createWithInteger((int)rect.size.width), HVIEWKEY_W); pRet->setObject(HString::createWithInteger((int)rect.size.height), HVIEWKEY_H); int feature = 0; switch (m_eEditBoxInputMode) { case kEditBoxInputModeSingleLine: feature |= HVIEWFEATURE_SINGLINE; break; case kEditBoxInputModeEmailAddr: feature |= HVIEWFEATURE_SINGLINE | HVIEWFEATURE_EMAIL; break; case kEditBoxInputModeNumeric: feature |= HVIEWFEATURE_SINGLINE | HVIEWFEATURE_NUMERIC; break; default: break; } switch (m_eEditBoxInputFlag) { case kEditBoxInputFlagPassword: feature |= HVIEWFEATURE_SINGLINE | HVIEWFEATURE_PASSWORD; break; default: break; } if (feature != 0) pRet->setObject(HString::createWithInteger(feature), HVIEWKEY_FEATURE); if (m_strText.length() > 0) pRet->setObject(HString::create(m_strText.c_str()), HVIEWKEY_TEXT); if (m_strPlaceHolder.length() > 0) pRet->setObject(HString::create(m_strPlaceHolder.c_str()), HVIEWKEY_HINT); //if (m_pFontName && (m_pFontName->length() > 0)) pRet->setObject(HString::create(m_pFontName->c_str()), HVIEWKEY_FONTNAME); // if (m_nFontSize != 20) { // pRet->setObject(HString::createWithInteger(m_nFontSize), HVIEWKEY_FONTSIZE); // } pRet->setObject(HString::createWithInteger((int)(m_nFontSize * CC_CONTENT_SCALE_FACTOR())), HVIEWKEY_FONTSIZE); //if (!HColor3BEqual(m_colText, ccWHITE)) { pRet->setObject(HString::createWithInteger(HColor3BToInt(m_colText)), HVIEWKEY_FONTCOLOR); //} //if (!HColor3BEqual(m_colPlaceHolder, ccGRAY)) { pRet->setObject(HString::createWithInteger(HColor3BToInt(m_colPlaceHolder)), HVIEWKEY_HINTCOLOR); //} if (m_nMaxLength > 0) { pRet->setObject(HString::createWithInteger(m_nMaxLength), HVIEWKEY_MAXLEN); } } while (0); m_bCreated = true; return pRet; }
// on "init" you need to initialize your instance bool GameScene::init() { if ( !CCLayer::init() ) { return false; } // Variables de tamanyo CCSize vs = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); // Layer con los botones al hacer pause _layerPause = CCLayerColor::create(ccc4(255,255,255,0)); _layerPause->setContentSize(CCSizeMake(350, 100)); _layerPause->ignoreAnchorPointForPosition(false); _layerPause->setAnchorPoint(ccp(0.5, 0.5)); _layerPause->setPosition(ccp(vs.width/2, vs.height/2)); _layerPause->retain(); CCMenuItem* button_resume = CCMenuItemImage::create("btn_resume.png", "btn_resume_h.png", this, menu_selector(GameScene::menuResumeCallback)); button_resume->setPosition(ccp(50, 50)); CCMenuItem* button_restart = CCMenuItemImage::create("btn_restart.png", "btn_restart_h.png", this, menu_selector(GameScene::menuRestartCallback)); button_restart->setPosition(ccp(175, 50)); CCMenuItem* button_exit = CCMenuItemImage::create("btn_exit.png", "btn_exit_h.png", this, menu_selector(GameScene::menuExitCallback)); button_exit->setPosition(ccp(300, 50)); CCMenu* menu_pause = CCMenu::create(button_resume, button_restart, button_exit, NULL); menu_pause->setPosition(ccp(0,0)); _layerPause->addChild(menu_pause); // Layer que se muestra al terminar la carrera _layerEnd = CCLayerColor::create(ccc4(0,0,0,0)); _layerEnd->setContentSize(CCSizeMake(225, 225)); _layerEnd->ignoreAnchorPointForPosition(false); _layerEnd->setAnchorPoint(ccp(0.5, 0.5)); _layerEnd->setPosition(ccp(vs.width/2, vs.height/2)); _layerEnd->retain(); CCMenuItem* button_end_restart = CCMenuItemImage::create("btn_restart.png", "btn_restart_h.png", this, menu_selector(GameScene::menuRestartCallback)); button_end_restart->setPosition(ccp(50, 50)); CCMenuItem* button_end_exit = CCMenuItemImage::create("btn_exit.png", "btn_exit_h.png", this, menu_selector(GameScene::menuExitCallback)); button_end_exit->setPosition(ccp(175, 50)); CCMenu* menu_end = CCMenu::create(button_end_restart, button_end_exit, NULL); menu_end->setPosition(ccp(0,0)); CCLayerColor* layerTime = CCLayerColor::create(ccc4(255,255,255,255)); layerTime->setContentSize(CCSizeMake(225, 100)); layerTime->ignoreAnchorPointForPosition(false); layerTime->setAnchorPoint(ccp(0.5, 0.5)); layerTime->setPosition(ccp(112.5, 175)); layerTime->retain(); _labelTimeEnd = CCLabelTTF::create("Time:\n0:00:000", "fonts/FrancoisOne.ttf", 30, CCSizeMake(225, 100), kCCTextAlignmentCenter); _labelTimeEnd->setColor(ccc3(0,0,0)); _labelTimeEnd->setPosition(ccp(112.5, 50)); layerTime->addChild(_labelTimeEnd); _layerEnd->addChild(menu_end); _layerEnd->addChild(layerTime); // Boton de pause (menu) CCMenuItem* button_pause = CCMenuItemImage::create("btn_pause.png", "btn_pause_h.png", this, menu_selector(GameScene::menuPauseCallback)); button_pause->setPosition(ccp(75, vs.height - 75)); CCMenu* menu = CCMenu::create(button_pause, NULL); menu->setPosition(ccp(0,0)); // Velocidad CCString* stringVel = CCString::createWithFormat("%d km/h", (int)_vel); _labelVel = CCLabelTTF::create(stringVel->getCString(), "fonts/FrancoisOne.ttf", 30, CCSizeMake(140, 50), kCCTextAlignmentCenter); _labelVel->setColor(ccc3(255,255,255)); _labelVel->setPosition(ccp(vs.width - 72, 50)); // Distancia CCString* stringDist = CCString::createWithFormat("%d m", (int)_dist); _labelDist = CCLabelTTF::create(stringDist->getCString(), "fonts/FrancoisOne.ttf", 30, CCSizeMake(140, 50), kCCTextAlignmentCenter); _labelDist->setColor(ccc3(255,255,255)); _labelDist->setPosition(ccp(72, 50)); // Tiempo int hs = _time/3600000; int mins = (_time%3600000)/60000; int ss = ((_time%3600000)%60000)/1000; int ms = ((_time%3600000)%60000)%1000; CCString* stringTime = CCString::createWithFormat("%d:%02d:%03d", mins, ss, ms); _labelTime = CCLabelTTF::create(stringTime->getCString(), "fonts/FrancoisOne.ttf", 30, CCSizeMake(140, 50), kCCTextAlignmentCenter); _labelTime->setColor(ccc3(255,255,255)); _labelTime->setPosition(ccp(vs.width - 72, vs.height - 50)); // Click to start _labelStart = CCLabelTTF::create("Click to Start", "fonts/FrancoisOne.ttf", 50, CCSizeMake(200, 200), kCCTextAlignmentCenter); _labelStart->setColor(ccc3(255,255,255)); _labelStart->setPosition(ccp(vs.width/2, vs.height/2)); _labelStart->retain(); // Hierba ccTexParams tp = { GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT}; CCTexture2D* texture = CCTextureCache::sharedTextureCache()->addImage("texture_grass2.jpg"); texture->setTexParameters(&tp); _grass = CCSprite::createWithTexture(texture, CCRectMake(0, 0, vs.width, vs.height + 256)); _grass->setPosition( ccp( vs.width/2, vs.height/2 + 128 ) ); // Carretera texture = CCTextureCache::sharedTextureCache()->addImage("texture_road2.jpg"); texture->setTexParameters(&tp); _road = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 512, vs.height + 512)); _road->setPosition( ccp( vs.width/2, vs.height/2 + 256 ) ); // Pianos texture = CCTextureCache::sharedTextureCache()->addImage("piano.png"); texture->setTexParameters(&tp); _piano1 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, vs.height + 64)); _piano1->setPosition( ccp(vs.width * 0.15, vs.height / 2 + 32) ); _piano2 = CCSprite::createWithTexture(texture, CCRectMake(0, 0, 64, vs.height + 64)); _piano2->setPosition( ccp(vs.width * 0.85, vs.height / 2 + 32) ); // Coche _car = CCSprite::create("car_above_blue.png"); _car->setPosition(ccp(vs.width/2, 50)); // Creamos los indicadores de curva _curvasI = new CCArray; _curvasD = new CCArray; for (int i = 1; i <= 5; i++) { CCString* str_curvaI = CCString::createWithFormat("curva_izq_%d.png", i); CCString* str_curvaD = CCString::createWithFormat("curva_der_%d.png", i); CCSprite* curvaI = CCSprite::create(str_curvaI->getCString()); curvaI->setOpacity(0); curvaI->setPosition(ccp(vs.width/2, vs.height/4*3)); CCSprite* curvaD = CCSprite::create(str_curvaD->getCString()); curvaD->setOpacity(0); curvaD->setPosition(ccp(vs.width/2, vs.height/4*3)); _curvasI->addObject(curvaI); _curvasD->addObject(curvaD); this->addChild(curvaI, 5); this->addChild(curvaD, 5); } // Anyadimos los elementos a la vista this->addChild(_grass, 1); this->addChild(_road, 2); this->addChild(_car, 3); this->addChild(menu, 5); this->addChild(_labelVel, 5); this->addChild(_labelDist, 5); this->addChild(_labelTime, 5); this->addChild(_labelStart, 5); // Inicializamos el vector de curvas segun el nivel if (_level == 1) { _curvas.push_back(Curva(250, 200, 2, false)); _curvas.push_back(Curva(550, 200, 2, false)); _curvas.push_back(Curva(1200, 100, 4, false)); _curvas.push_back(Curva(1650, 200, 2, false)); _curvas.push_back(Curva(1950, 200, 2, false)); _curvas.push_back(Curva(2500, 200, 2, false)); _curvas.push_back(Curva(2800, 200, 2, false)); _mCircuito = 3000; } else if (_level == 2) { _curvas.push_back(Curva(100, 150, 2, false)); _curvas.push_back(Curva(350, 150, 2, false)); _curvas.push_back(Curva(700, 250, 1, false)); _curvas.push_back(Curva(1150, 150, 3, false)); _curvas.push_back(Curva(1500, 100, 4, false)); _curvas.push_back(Curva(1800, 100, 4, false)); _curvas.push_back(Curva(2000, 200, 2, true)); _curvas.push_back(Curva(2300, 50, 5, true)); _curvas.push_back(Curva(2750, 150, 2, true)); _curvas.push_back(Curva(3000, 50, 4, true)); _curvas.push_back(Curva(3100, 100, 2, false)); _curvas.push_back(Curva(3300, 100, 2, false)); _curvas.push_back(Curva(3500, 100, 4, false)); _curvas.push_back(Curva(3800, 250, 2, false)); _curvas.push_back(Curva(4250, 250, 1, false)); _curvas.push_back(Curva(4700, 150, 3, false)); _mCircuito = 5350; } else { // _level == 3 _curvas.push_back(Curva(100, 50, 2, true)); _curvas.push_back(Curva(250, 50, 2, false)); _curvas.push_back(Curva(400, 100, 4, false)); _curvas.push_back(Curva(600, 100, 2, false)); _curvas.push_back(Curva(800, 50, 4, true)); _curvas.push_back(Curva(950, 50, 4, true)); _curvas.push_back(Curva(1100, 100, 2, false)); _curvas.push_back(Curva(1300, 50, 4, true)); _curvas.push_back(Curva(1450, 50, 4, true)); _curvas.push_back(Curva(1600, 100, 4, false)); _curvas.push_back(Curva(1900, 100, 2, false)); _curvas.push_back(Curva(2100, 50, 5, true)); _curvas.push_back(Curva(2450, 100, 2, true)); _curvas.push_back(Curva(2650, 50, 5, false)); _curvas.push_back(Curva(2900, 100, 4, false)); _curvas.push_back(Curva(3200, 150, 2, true)); _curvas.push_back(Curva(3450, 100, 4, true)); _curvas.push_back(Curva(3650, 50, 4, true)); _curvas.push_back(Curva(3800, 100, 4, false)); _curvas.push_back(Curva(4000, 50, 4, true)); _curvas.push_back(Curva(4150, 150, 2, true)); _curvas.push_back(Curva(4400, 100, 2, false)); _curvas.push_back(Curva(4600, 100, 2, false)); _curvas.push_back(Curva(4800, 100, 5, true)); _curvas.push_back(Curva(5000, 50, 2, true)); _curvas.push_back(Curva(5150, 100, 5, false)); _curvas.push_back(Curva(5450, 200, 5, true)); _mCircuito = 5850; } // Inicializamos el vector de coches en contra _oppCars = new CCArray; // Activamos el acelerometro y el touch this->setTouchEnabled(true); // Calculamos el tamanyo de cada tramo para informar al Arduino int nleds = CCUserDefault::sharedUserDefault()->getIntegerForKey("nleds"); _longTramo = (int) (_mCircuito/nleds); // Enviamos al Arduino que hemos entrado int iColor = CCUserDefault::sharedUserDefault()->getIntegerForKey("color"); CCDictionary* prms = CCDictionary::create(); prms->setObject(CCString::createWithFormat("%d", iColor), "color"); SendMessageWithParams(string("JugadorEntra"), prms); return true; }
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; }
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); } }
// 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; } }
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; }