void SGRegisterBox::requestFinished(int msgid, CCObject *data)
{
    if(msgid == MSG_HTTP_REGISTER)
    {
        CCString *backString = (CCString*)data;
        if(backString->intValue() == 1)
        {
            CCUserDefault::sharedUserDefault()->setStringForKey("username", m_pEditName->getText());
            CCUserDefault::sharedUserDefault()->setStringForKey("password", m_pEditPassword->getText());
            CCUserDefault::sharedUserDefault()->setBoolForKey("isExist", true);
            CCUserDefault::sharedUserDefault()->setBoolForKey("isAccount", true);
            CCUserDefault::sharedUserDefault()->flush();
            
            
            std::string userId = CCUserDefault::sharedUserDefault()->getStringForKey("userId");
			
			//外部适配类调用
#if (PLATFORM == IOS)
			OcCaller::getInstance()->setAccountSDK(userId, m_pEditName->getText());
#else
			//android code
            AndroidSDKAdp::getInstance()->setAccountSDK(userId, m_pEditName->getText());
#endif
			/*
            [sdkReqCallBack setAccount:[NSString stringWithFormat:@"%d",userId]
                           accountName:[NSString stringWithUTF8String:m_pEditName->getText()]
                           accountType:kAccountRegistered];
			 */
            
            SGRegisterSuccess *su = SGRegisterSuccess::create(deletage);
            this->boxCloseWithOutCallBack();
            SGMainManager::shareMain()->showBox(su);
            
        }else{
            
            labelAccountError->setVisible(true);
            labelAccountError->setString(str_RegisterBox_str10);
            this->processErrorState(FLAG_ERROR, FLAG_NODISPLAY, FLAG_NODISPLAY);
        }
    }else if(msgid == MSG_HTTP_BING)
    {
        CCDictionary *dict = (CCDictionary*)data;

        CCString *string1 = (CCString*)dict->objectForKey("string1");
        CCString *string2 = (CCString*)dict->objectForKey("string2");

        
        if(1 == string1->intValue())
        {
            //绑定成功
            SG_SHOW_WINDOW(str_RegisterBox_str11);
            
            CCUserDefault::sharedUserDefault()->setStringForKey("username", m_pEditName->getText());
            CCUserDefault::sharedUserDefault()->setStringForKey("password", m_pEditPassword->getText());
            CCUserDefault::sharedUserDefault()->setBoolForKey("isAccount", true);
            CCUserDefault::sharedUserDefault()->flush();
            
            SGBindSuccessBox *success = SGBindSuccessBox::create(deletage);
            this->boxCloseWithOutCallBack();
            SGMainManager::shareMain()->showBox(success);    
            
        }else
        {
            if(string2->intValue() == 1)
            {
                //绑定失败
                SG_SHOW_WINDOW(str_RegisterBox_str12);
            }
            else if(2 == string2->intValue())
            {
                SG_SHOW_WINDOW(str_RegisterBox_str1301);
            }else if(3 == string2->intValue())
            {
                SG_SHOW_WINDOW(str_RegisterBox_str14);
            }
        }
    }
}
Exemple #2
0
void SGCardsLayer::initView(CCArray *array)
{
    ResourceManager::sharedInstance()->bindTexture("sgcardslayer/sgcardslayer.plist", RES_TYPE_LAYER_UI, sg_cardsLayer);
    ResourceManager::sharedInstance()->bindTexture("soldier/soldier3101-1-3303-3.plist", RES_TYPE_LAYER_UI, sg_cardsLayer);
    ResourceManager::sharedInstance()->bindTexture("sggeneralinfolayer/sggeneralinfolayer1.plist", RES_TYPE_LAYER_UI, sg_cardsLayer);
    ResourceManager::sharedInstance()->bindTexture("sgstrenglayer/sgstrenglayer.plist", RES_TYPE_LAYER_UI, sg_cardsLayer, LIM_PNG_AS_PNG);

    tableViewHeight = 145;
    tableViewColumns = 5;
    float headhgt = SGMainManager::shareMain()->getTotleHdHgt();
    float btmhgt = SGMainManager::shareMain()->getBottomHeight();
    CCSize s = CCDirector::sharedDirector()->getWinSize();

    CCSprite *title_bg = CCSprite::createWithSpriteFrameName("title_bg.png");
    title_bg->setAnchorPoint(ccp(0.5, 1));
    title_bg->setPosition(ccpAdd(SGLayout::getPoint(kUpCenter), ccp(0, -headhgt + title_bg->getContentSize().height-2)));
    this->addChild(title_bg,-1);
    
    CCSprite *titlecenter = CCSprite::createWithSpriteFrameName("title_bg_2.png");
    titlecenter->setAnchorPoint(ccp(0.5, 0));
    titlecenter->setPosition(ccpAdd(title_bg->getPosition(), ccp(0,  - title_bg->getContentSize().height -10)));
    this->addChild(titlecenter,10);
    titlecenter->setScaleX(4);
    
    CCSprite *title_bg_l = CCSprite::createWithSpriteFrameName("title_bg_LR.png");
    title_bg_l->setAnchorPoint(ccp(0, 0));
    title_bg_l->setPosition(ccpAdd(title_bg->getPosition(), ccp(-s.width/2,  - title_bg->getContentSize().height -10)));
    this->addChild(title_bg_l,10);
    
    CCSprite *title_bg_r = CCSprite::createWithSpriteFrameName("title_bg_LR.png");
    title_bg_r->setFlipX(true);
    title_bg_r->setAnchorPoint(ccp(1, 0));
    title_bg_r->setPosition(ccpAdd(title_bg->getPosition(), ccp(s.width/2,  - title_bg->getContentSize().height -10)));
    this->addChild(title_bg_r,10);
    
	SGButton *backBtn = SGButton::createFromLocal("store_exchangebtnbg.png", str_back, this, menu_selector(SGCardsLayer::backHandler),CCPointZero,FONT_PANGWA,ccWHITE,32);

    this->addBtn(backBtn);
    backBtn->setPosition(ccp(backBtn->getContentSize().width*.55,title_bg->getPosition().y -title_bg->getContentSize().height*.5f));

    
    
    SGCCLabelTTF *title = NULL;
    
    datas = CCArray::create();
    datas->retain();
    _array = CCArray::create();
    _array->retain();
    if (enterType == 0 || enterType == 1 || enterType == 2 || enterType == 3) {
        
        CCDictionary * dic = NULL;
        switch (enterType) {
            case 0:
            {
                title = SGCCLabelTTF::create(str_CardsLayer_str1, FONT_XINGKAI, 36 , COLOR_UNKNOW_TAN);
                dic = SGStaticDataManager::shareStatic()->getWeiOfficerDict();
            }
                break;
            case 1:
            {
                title = SGCCLabelTTF::create(str_CardsLayer_str2, FONT_XINGKAI, 36 , COLOR_UNKNOW_TAN);
                dic = SGStaticDataManager::shareStatic()->getShuOfficerDict();
            }
                break;
            case 2:
            {
                title = SGCCLabelTTF::create(str_CardsLayer_str3, FONT_XINGKAI, 36 , COLOR_UNKNOW_TAN);
                dic = SGStaticDataManager::shareStatic()->getWuOfficerDict();
            }
                break;
            case 3:
            {
                title = SGCCLabelTTF::create(str_CardsLayer_str4, FONT_XINGKAI, 36 , COLOR_UNKNOW_TAN);
                dic = SGStaticDataManager::shareStatic()->getQunOfficerDict();
            }
                break;
            case 4:
            {
                dic = SGStaticDataManager::shareStatic()->getEquipViewDict();
            }
                break;

        }

        
        for (int i = 0; i<dic->allKeys()->count(); i++) {
            CCString *string = (CCString*)dic->allKeys()->objectAtIndex(i);
            SGOfficerDataModel *oCard = SGStaticDataManager::shareStatic()->getOfficerById(string->intValue());
            
            if (oCard)
            {
                int areId = ((CCString*)((CCDictionary *)dic->objectForKey(string->getCString()))->objectForKey("areaId"))->intValue();
                
                SGOfficerCard *officerCard = new SGOfficerCard;
                officerCard->setSsid(areId);//排序用
                
                officerCard->setOfficerName(oCard->getOfficerName()); 
                officerCard->setMaxLevel(oCard->getOfficerMaxLevel());
                officerCard->setCurrExp(0);
                officerCard->setCurrStar(oCard->getOfficerCurrStarLevel());
                officerCard->setCurrLevel(1);
                officerCard->setRace(oCard->getOfficerRace());
                officerCard->setItemId(oCard->getOfficerId());
                //转生最大星级
                officerCard->setUpgradestar(oCard->getUpgradestar());
                //转生等级
                officerCard->setUpgradelevel(oCard->getUpgradelevel());
                //武将计最大等级
                officerCard->setSkillMaxLevel(oCard->getSkillMaxLevel());
                //主将计最大等级
                officerCard->setLordMaxLevel(oCard->getLordMaxLevel());
                //性别和缘分
                officerCard->setGender((OfficerGender) oCard->getOfficerGender());
                officerCard->setFateList(oCard->getOfficerFateList());
                //武将原型ID
                officerCard->setProtoId(oCard->getOfficerProtoId());
                //速度修正系数
                officerCard->setSpeedFactor(oCard->getOfficerSpeedFactor());
                //转生次数
                officerCard->setAdNum(oCard->getAdvNum());
                officerCard->setHeadSuffixNum(oCard->getIconId());//12.05
                
                if (oCard->getOfficerGeneralsSkill()&& !oCard->getOfficerGeneralsSkill()->isEqual(CCString::create(""))) {
                   // CCLOG("%s",oCard->getOfficerGeneralsSkill()->getCString());
                    
                    officerCard->setOfficerSkil(SGStaticDataManager::shareStatic()->getAnyoneIdByBeanId(oCard->getOfficerGeneralsSkill()->getCString()));
                }
                
                if (oCard->getOfficerLordSkill() &&!oCard->getOfficerLordSkill()->isEqual(CCString::create(""))) {
                    
                    int lordskill = SGStaticDataManager::shareStatic()->getAnyoneIdByBeanId(oCard->getOfficerLordSkill()->getCString());
                    
                    
                    officerCard->setLordSkill(lordskill);
                    
                }
                officerCard->setAtk(oCard->getOfficerBaseAtk());
                officerCard->setDef(oCard->getOfficerBaseDef());
                officerCard->setRound(oCard->getOfficerRound());
                officerCard->setSpeed(oCard->getOfficerBaseSpeed());
                officerCard->setMorale(oCard->getOfficerMorale());
                officerCard->setGoverning(oCard->getOfficerGoverning());
                officerCard->setHeadSuffixNum(oCard->getIconId());//12.05
                
                datas->addObject(officerCard);
                officerCard->autorelease();
            }
        }
        sortArray();
        CCObject *obj = NULL;
        for (int i = 0; i<datas->count(); i++) {
            SGBaseMilitaryCard *card = (SGBaseMilitaryCard *)datas->objectAtIndex(i);
            CCARRAY_FOREACH(array, obj)
            {
                SGHaveCards *temp = (SGHaveCards*)obj;
                if (temp->getcardItem() == card->getItemId()) {
                    temp->setcardPosition(i);
                    _array->addObject(temp);
                }
            }
        }
void QuestionLayer::startAnswer()
{
    timerCount = timerTotal;

    CCSize size = this->getContentSize();
    CCLOG("%f %f", size.width, size.height);

    CCScale9Sprite* labelBg = CCScale9Sprite::create("bg_question.png");
    labelBg->setAnchorPoint(ccp(0.5, 0.5));
    labelBg->setPosition(ccp(0, size.height/2-100));
    labelBg->setContentSize(CCSizeMake(size.width, 160));
    this->addChild(labelBg, 0);

    const char* filePath = NULL;
    if (queType == SingleQuestion) {
        filePath = CCFileUtils::sharedFileUtils()->fullPathForFilename("question_4.plist").c_str();
    } else if (queType == JudgeQuestion) {
        filePath = CCFileUtils::sharedFileUtils()->fullPathForFilename("question_2.plist").c_str();
    } else {
        filePath = CCFileUtils::sharedFileUtils()->fullPathForFilename("question_3.plist").c_str();
    }
    CCArray* plistArray = CCArray::createWithContentsOfFile(filePath);
    //开始查找随机题目,并且不能重复
    bool bFind = false;
    while (!bFind) {
        serialNo = arc4random()%plistArray->count(); //serialNo = CCRANDOM_0_1()*plistArray->count()-1;
        CCLOG("serialNo:%d", serialNo);
        bool isSame = false;
        for (int i=0; i<historyQuestiones->count(); i++) {
            CCInteger* integer = (CCInteger *)historyQuestiones->objectAtIndex(i);
            if (integer->getValue() == serialNo) {
                isSame = true;
                break;
            }
        }
        if (!isSame) {
            bFind = true;
        }
    }
    historyQuestiones->addObject(CCInteger::create(serialNo));

    CCDictionary* dic = (CCDictionary*)plistArray->objectAtIndex(serialNo);
    CCString* qType = (CCString *)(dic->objectForKey("type")); //Number类型
    CCString* pStr = (CCString *)(dic->objectForKey("question"));
    CCLOG("%d %s", qType->intValue(), pStr->getCString());
    CCArray* ans = (CCArray *)(dic->objectForKey("answer"));

    questionObj = new QuestionObj(qType->intValue(), pStr->getCString(), ans);
    CCLOG("读取题目信息完成");

    questionString = questionObj->questionString;
    displayLen = 0;
    //题目
    CCLabelTTF* pLabel = CCLabelTTF::create(questionStr.c_str(), "Arial", 24, CCSize(size.width-20, 90), kCCTextAlignmentLeft, kCCVerticalTextAlignmentTop);
    pLabel->setAnchorPoint(ccp(1, 0));
    pLabel->setPosition(ccp(-size.width/2+15, size.height/2-130));
    pLabel->setAnchorPoint(ccp(0, 0));
    this->addChild(pLabel, 1, 11);

    const char* typeStr = "单选题";
    if (questionObj->questionType == 1) {
        typeStr = "单选题";
        timerTotal = 15;
    } else if (questionObj->questionType == 2) {
        typeStr = "判断题";
        timerTotal = 12;
    } else {
        typeStr = "多选题";
        timerTotal = 30;
    }
    CCString* title = CCString::createWithFormat("题型:%s", typeStr);
    CCLabelTTF* label = CCLabelTTF::create(title->getCString(), "Arial", 24);
    label->setAnchorPoint(ccp(0, 1));
    label->setPosition(ccp(140, size.height/2-135));
    this->addChild(label, 1, 12);

//    CCSprite* timerBg = CCSprite::create("money_bg.png");
//    timerBg->setPosition(ccp(0, size.height/2-200));
//    this->addChild(timerBg);
    progressTimer = CCProgressTimer::create(CCSprite::create("money_bg.png"));
    progressTimer->setType(kCCProgressTimerTypeBar);
    progressTimer->setMidpoint(ccp(0, 0));
    progressTimer->setBarChangeRate(ccp(1, 0));
    progressTimer->setAnchorPoint(ccp(0.5, 0.5));
    progressTimer->setPosition(ccp(0, size.height/2-200));
    progressTimer->setPercentage(100);
    progressTimer->setContentSize(CCSizeMake(300, 38));
    this->addChild(progressTimer, 2);
    timerLabel_ = CCLabelTTF::create(CCString::createWithFormat("%d", timerCount)->getCString(), "Arial", 24);
    timerLabel_->setAnchorPoint(ccp(1, 0));
    timerLabel_->setPosition(ccp(0, 0));
    progressTimer->addChild(timerLabel_);
    warnTipSpr = CCSprite::create("arrow000.png");
    warnTipSpr->setPosition( ccp(progressTimer->getContentSize().width/3*2, 0) );
    warnTipSpr->setAnchorPoint( ccp(0.5, 0) );
    progressTimer->addChild(warnTipSpr);

    //显示宫格答案
    this->displaySubViews();

    this->schedule(schedule_selector(QuestionLayer::displayActionTimerCB), 0.05f);

    isAnswerFinished = false;
    //
    serialNo++;
    if (serialNo > plistArray->count()-1) {
        serialNo = 0;
    }

    propLayer_ = FightPropLayer::create();
    propLayer_->setDelegate(this);
    propLayer_->setAnchorPoint( ccp(0.5, 0.5) );
    propLayer_->setPosition( ccp(-size.width/2, -size.height/2) );
    this->addChild(propLayer_, 100, 100);
}
void QuestionLayer::touchDownAction(CCObject *sender, CCControlEvent controlEvent)
{
    CCLOG("QuestionLayer::touchDownAction");

    if (isAnswerFinished) {
        return;
    }
    this->unschedule(schedule_selector(QuestionLayer::timerCB));

    CCControlButton* button = (CCControlButton *)sender;
    CCLOG("%d", button->getTag());
    button->setEnabled(false);

    bool bFind = false;
    CCDictionary* results = questionObj->rightAnswer;
    for (int i=0; i<results->allKeys()->count(); i++) {
        CCString* key = (CCString *)(results->allKeys()->objectAtIndex(i));
        if (key->intValue() == button->getTag()) {
            results->setObject(CCString::createWithFormat("%d", 1), key->getCString());
            bFind = true;
            break;
        }
    }

    if (bFind) {
        //统计已经回答正确答案的数量
        int rCount = 0;
        for (int i=0; i<results->allKeys()->count(); i++) {
            CCString* key = (CCString *)(results->allKeys()->objectAtIndex(i));
            CCString* value = (CCString *)(results->objectForKey(key->getCString()));
            if (value->intValue() == 1) {
                rCount++;
            }
        }
        CCLOG("rCount:%d", rCount);

        if (rCount == results->allKeys()->count()) {
            //回答完成所有正确答案
            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(button->getContentSize().width/2, button->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;

        } else {
            CCLOG("正确答案没选完");
        }
    } else {
        //回答错误
        CCSprite* spr = CCSprite::create("arrow000.png");
        spr->setAnchorPoint(ccp(0.5f, 0.5f));
        spr->setPosition(ccp(button->getContentSize().width/2, button->getContentSize().height/2));
        button->addChild(spr);
        CCFadeIn* fadeIn = CCFadeIn::create(1.0f);
        CCAction* pAction = CCCallFuncND::create(this, callfuncND_selector(QuestionLayer::noticeDelegate), NULL);
        spr->runAction(CCSequence::create(fadeIn, pAction, NULL));

        errorAnswer++;
        isAnswerFinished = true;

        //播放错误音效
        GameSoundManager::shareManager()->playAnswerError();
    }
}
Exemple #5
0
void MapEventsNode::readEventForDic(CCDictionary *pEvent)
{
	CCArray*  eventKeys = pEvent->allKeys();
	LevelEvent  *event = new LevelEvent;
	event->posX = ((CCString*)pEvent->objectForKey("x"))->intValue();
	event->posY = ((CCString*)pEvent->objectForKey("y"))->intValue();
	//LD("event->posX = %d",event->posX);
	//LD("event->posY= %d",event->posY);
	event->eventType = ((CCString*)pEvent->objectForKey("type"))->intValue();
	m_floatMaxPosY = event->posY;
	event->eventName = string(pEvent->valueForKey("name")->getCString());
	//LD("event->eventName = %s",event->eventName.c_str());
	vector<KEY_VALUE>  keyValues;

	//LD("arrayCount = %d",eventKeys->count());
	for(int i = 0;  i != eventKeys->count(); ++i)
	{
		//LD("i = %d",i);
		KEY_VALUE keyValue;
		keyValue.keyName = ((CCString*)eventKeys->objectAtIndex(i))->getCString();
		keyValue.keyValue = ((CCString*)pEvent->objectForKey(((CCString*)eventKeys->objectAtIndex(i))->getCString()))->getCString();
		keyValues.push_back(keyValue);
		event->keyValues = keyValues;
	}

	if(event->eventName == "cE")
	{
		if(event->eventType >= 0)
		{
			m_monsterIds.push_back(event->eventType);
		}
		else
		{
			//LD("cE event error!");
		}
	}
	else if(event->eventName == "cI")
	{
		if(event->eventType >= 0)
		{
			m_itemIds.push_back(event->eventType);
		}
		else
		{
			//LD("cE event error!");
		}
	}
	else if(event->eventName == "addTip")
	{
		CCString* valueString = (CCString*)pEvent->objectForKey("tipId");

		if(valueString)
		{
			int mId = valueString->intValue();
			m_tipIds.push_back(mId);
		}
		else
		{
			//LD("addTip event error!");
		}
	}
	else if(event->eventName == "addStory")
	{
		CCString* valueString = (CCString*)pEvent->objectForKey("storyId");

		if(valueString)
		{
			int mId = valueString->intValue();
			m_storyIds.push_back(mId);
		}
		else
		{
			//LD("addStory event error!");
		}
	}

	m_levelEvents.push_back(event);
}
Exemple #6
0
void SGHelpLayer::showBoxCall(CCObject *obj)
{
    //不知道为什么需要加一个,返回的已经有了呀
    SGMainLayer *mainLayer = (SGMainLayer *)SGMainManager::shareMain()->getMainScene()->getChildByTag(sg_mainLayer);
    if (mainLayer) {
        mainLayer->setIsCanTouch(true);
    }
    if (obj)
    {
        CCDictionary *dict = (CCDictionary *)obj;
        CCString *key =  (CCString*)dict->objectForKey("key");
        
        if(key->isEqual(CCString::create("serverList")))
        {
            CCString *serverName = (CCString*)dict->objectForKey("serverName");
            CCString *serverIp = ((CCString*)dict->objectForKey("serverIp"));
            CCString *serverId = (CCString*)dict->objectForKey("serverId");
            CCString *serverPost = (CCString*)dict->objectForKey("serverPost");
            
            CCLOG("选中服务器名字:  %s",serverName->getCString());
            CCLOG("选中服务器Ip:   %s",serverIp->getCString());
            CCLOG("选中服务器Post: %s",serverPost->getCString());
            CCLOG("选中服务器Id:   %s",serverId->getCString());
            
            
            CCUserDefault::sharedUserDefault()->setStringForKey("serverip", serverIp->getCString());
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverpost", (short)serverPost->intValue());
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverid", (short)serverId->intValue());
            CCUserDefault::sharedUserDefault()->setStringForKey("servername", serverName->getCString());
            CCUserDefault::sharedUserDefault()->flush();
            
            
            std::string un = CCUserDefault::sharedUserDefault()->getStringForKey("username");
            std::string pw = CCUserDefault::sharedUserDefault()->getStringForKey("password");
            
            SGMainManager::shareMain()->setServerInfo(serverIp , (short)serverPost->intValue());
            //SGHttpClient::shareHttpClient()->login(this, accountId, sid);
			
			//OC调用改到外围
//#if (PLATFORM == IOS)
            SGMainManager::shareMain()->dealIosLogin(un,pw);
//			//OcCaller::getInstance()->pyUserSDKLoginReq(un.c_str(), pw.c_str());
//#else
//			//android code
//			SdkManager::shareSdkManager()->userLogin(un.c_str(), pw.c_str());
//#endif
			/*
            id  sdkReqCallBack = SGMainManager::shareMain()->getSdkdelegate();
            [[PYUserSDKLib sharedUserSDKLib] userLogin:[[NSString alloc] initWithUTF8String:un.c_str()]
                                              Password:[[NSString alloc] initWithUTF8String:pw.c_str()]
                                              GameId:@"1"
                                              ChannelId:[sdkReqCallBack ChannelId]
                                              SubChannelId:[sdkReqCallBack SubChannelId]
                                              OsVersion:[sdkReqCallBack OsVersion]
                                              OsType:[sdkReqCallBack OsType]
                                      CallBackDelegate:sdkReqCallBack FinishSelector:@selector(loginFinished:) FailSelector:@selector(requestFailed:)];
			 */
            
        }
    }
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback));
    
	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    CCLabelTTF* pLabel = CCLabelTTF::create("TileMap", "Arial", TITLE_FONT_SIZE);

    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorld" splash screen"
   tileMap = CCTMXTiledMap::create("C:/Users/bisprasad/Desktop/TileMap1.tmx");
    this->addChild(tileMap);
    CCTMXLayer *background = tileMap->layerNamed("Background");
	CCTMXObjectGroup *objectGroup = tileMap->objectGroupNamed("Objects");
	/*CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint");
	
	CCString *pX = (CCString*)spawnPoint->objectForKey("x");
	CCString *pY = (CCString*)spawnPoint->objectForKey("y");
 */

	cocos2d::CCDictionary *spawnPoint = objectGroup->objectNamed("SpawnPoint");
	CCAssert(spawnPoint != NULL, "SpawnPoint object not found");
	CCString *pX = (CCString*)spawnPoint->objectForKey("x");
	CCString *pY = (CCString*)spawnPoint->objectForKey("y");
	 
	 int x = pX->intValue();
	 int y = pY->intValue();
	y = (tileMap->getMapSize().height*tileMap->getTileSize().height)-y-24;
	 this->addChild(tileMap );

	player = CCSprite::create("C:/Users/bisprasad/Desktop/Player.png");
	
	 player->setPosition(ccp(x,y ));
	 this->addChild(player);
		this->setViewPointCenter(player->getPosition());
	this->setTouchEnabled(true);
	
	

    return true;
}
Exemple #8
0
bool TestScene::init(){
    if (!CCLayer::init()) {
        return false;
    }
    tileMap = new CCTMXTiledMap();
    tileMap->initWithTMXFile("lvl5/map2.tmx");
    background = tileMap->layerNamed("Background");
    this->addChild(tileMap);
    walls = tileMap->layerNamed("Walls");
    walls->setVisible(false);
    CCTMXObjectGroup *objectGroup = tileMap->objectGroupNamed("Objects");
    if (objectGroup == NULL) {
        CCLog("tile map has no objects layer");
        return false;
    }
    
    CCDictionary *exitPointDic = objectGroup->objectNamed("ExitPoint");
    int xE = ((CCString)*exitPointDic->valueForKey("x")).intValue();
    int yE =  ((CCString)*exitPointDic->valueForKey("y")).intValue();
    //    exitPointCoord = tileCoordForPosition(ccp(x2,y2));
    CCSprite *exitPointImg = CCSprite::create("lvl5/exitpoint.png");
    exitPointImg->setPosition(ccp(xE + tileMap->getPositionX(), yE + tileMap->getPositionY()));
    this->addChild(exitPointImg);
    exitPointCoord = tileCoordForPosition(ccp(xE + tileMap->getPositionX(), yE + tileMap->getPositionY()), tileMap);
    
    // init player
    CCDictionary *playerSpawnPoint = objectGroup->objectNamed("PlayerSpawnPoint");
    int x = ((CCString)*playerSpawnPoint->valueForKey("x")).intValue();
    int y = ((CCString)*playerSpawnPoint->valueForKey("y")).intValue();
    player = (Player*)GameSprite::gameSpriteWithFile("lvl5/player.png");
    //    player->setPosition(ccp(x, y));
    player->setPosition(ccp(x + tileMap->getPositionX(), y + tileMap->getPositionY()));
    this->addChild(player);
    
    CCPoint tileCoord = this->tileCoordForPosition(player->getPosition(), tileMap);
    int tileGid = walls->tileGIDAt(tileCoord);
    if (tileGid) {
        CCDictionary *properties = tileMap->propertiesForGID(tileGid);
        if (properties) {
            CCString *wall = new CCString();
            *wall = *properties->valueForKey("Wall");
            CCString abc = *wall;
            CCLog("%d", abc.intValue());
            player->setCharWall(abc.intValue());
        }
    }
    player->setIsMove(false);
    
    CCDictionary *npc3SpawnPoint = objectGroup->objectNamed("NPC3SpawnPoint");
    if (npc3SpawnPoint != NULL) {
        int x3 = ((CCString)*npc3SpawnPoint->valueForKey("x")).intValue();
        int y3 = ((CCString)*npc3SpawnPoint->valueForKey("y")).intValue();
        
        npc3 = GameSprite::gameSpriteWithFile("lvl5/npc3.png");
        //    npc1->setPosition(ccp(x1, y1));
        npc3->setPosition(ccp(x3 + tileMap->getPositionX(), y3 + tileMap->getPositionY()));
        this->addChild(npc3);
        tileCoord = this->tileCoordForPosition(npc3->getPosition(), tileMap);
        tileGid = walls->tileGIDAt(tileCoord);
        if (tileGid) {
            CCDictionary *properties = tileMap->propertiesForGID(tileGid);
            if (properties) {
                CCString *wall = new CCString();
                *wall = *properties->valueForKey("Wall");
                CCString abc = *wall;
                CCLog("%d", abc.intValue());
                npc3->setCharWall(abc.intValue());
            }
        }
        npc3->setIsMove(false);
    }
    
    // init tile array
    mazeRow = tileMap->getMapSize().height;
    mazeCol = tileMap->getMapSize().width;
    if (true) {
        tileArray = new TileObject * [mazeRow];
        for (int i = 0; i < mazeRow; i++) {
            tileArray[i] = new TileObject [mazeCol];
            tileArray[i]->retain();
        }
        
        for (int i = 0; i < mazeRow; i++) {
            for (int j = 0; j < mazeCol; j++) {
                // wall
                tileGid = walls->tileGIDAt(ccp(i, j));
                if (tileGid) {
                    CCDictionary *properties = tileMap->propertiesForGID(tileGid);
                    if (properties) {
                        CCString *wall = new CCString();
                        *wall = *properties->valueForKey("Wall");
                        CCString abc = *wall;
                        tileArray[i][j] = TileObject(i, j, abc.intValue());
                    }
                }
            }
        }
    }
    CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
    mapSize = tileMap->getMapSize();
    
    resetButton = CCSprite::create("lvl1/resetButton.png");
    resetButton->cocos2d::CCNode::setPosition(screenSize.width - resetButton->getContentSize().width/2, resetButton->getContentSize().height/2);
    this->addChild(resetButton);
    
    findButton = CCSprite::create("lvl5/findbutton.jpg");
    findButton->cocos2d::CCNode::setPosition(screenSize.width - findButton->getContentSize().width/2, screenSize.height - findButton->getContentSize().height/2);
    this->addChild(findButton);


    this->setTouchEnabled(true);
    return true;
}
Exemple #9
0
bool CMGameMap::Init(CMReceiver* pReceiver,enumMarioLevel &eMarioLevel)
{
	do 
	{
		//初始化成员变量
		m_fDropSpeedPlus = 0;
		m_fJumpSpeed = 0;
		m_bIsLeftKeyDown = false;
		m_bIsRightKeyDown = false;
		m_bIsJumpKeyDown = false;
		m_bIsFireKeyDown = false;
		m_bIsHeroDead = false;
		m_pReceiver = pReceiver;
		m_bNeedResetStage = false;

		//初始化游戏对象数组
		m_pArrayItems = CCArray::create();
		m_pArrayItems->retain();
		m_pArrayMonsters = CCArray::create();
		m_pArrayMonsters->retain();
		m_pArrayBlocks = CCArray::create();
		m_pArrayBlocks->retain();
		m_pArrayFireBall = CCArray::create();
		m_pArrayFireBall->retain();

		//初始化Mario
		CMMario* pMario = CMMario::CreateHero(this,eMarioLevel);
		CC_BREAK_IF(pMario==NULL);
		pMario->setPosition(TileMapPosToTileMapLayerPos(ccp(2,11)));
		addChild(pMario,enZOrderFront,enTagMario);
		//pMario->SetStatus(enMarioStatusBig);

		//隐藏原落坑判断层
		CCTMXLayer* pTrapLayer = layerNamed("trap");
		CC_BREAK_IF(pTrapLayer==NULL);
		pTrapLayer->setVisible(false);

		//初始化显示金币
		CCTMXLayer* pCoinLayer = layerNamed("coin");
		CC_BREAK_IF(pCoinLayer==NULL);
		pCoinLayer->setVisible(false);
		//获得地图的瓦片数量
		int nMapHorizontalTileNum = pCoinLayer->boundingBox().size.width/getTileSize().width;
		int nMapVerticalTileNum = pCoinLayer->boundingBox().size.height/getTileSize().height;
		//遍历每片瓦片,寻找金币,建立并加入金币集合
		for (int i = 0;i<nMapHorizontalTileNum;i++)
		{
			for (int j = 0;j<nMapVerticalTileNum;j++)
			{
				if (TileMapPosToTileType(ccp(i,j))==enTileTypeCoin)
				{
					//将瓦片地图坐标转换为瓦片地图层坐标
					CCPoint CoinTileMapLayerPos = TileMapPosToTileMapLayerPos(ccp(i,j));
					CMItemCoin* pCoin = CMItemCoin::CreateItemIcon(CoinTileMapLayerPos,getTileSize(),pMario,this);
					if (pCoin==NULL)
					{
						CCLog("Coin init Error!");
					}
					pCoin->setPosition(CoinTileMapLayerPos);
					pCoin->setAnchorPoint(ccp(0,0));
					m_pArrayItems->addObject(pCoin);
					addChild(pCoin);
				}
			}
		}

		//初始化怪物显示
		CCTMXObjectGroup* pObjectLayer = objectGroupNamed("objects");
		CC_BREAK_IF(pObjectLayer==NULL);
		CCArray *ObjectArray = pObjectLayer->getObjects();
		CCDictionary *pDic = NULL;
		for (unsigned int i = 0; i < ObjectArray->count(); i++)
		{
			pDic = (CCDictionary *)ObjectArray->objectAtIndex(i);
			int PosX = ((CCString*)pDic->objectForKey("x"))->intValue();
			int PosY = ((CCString*)pDic->objectForKey("y"))->intValue();
			PosY -= this->getTileSize().height;
			CCPoint TileXY = ccp(PosX, PosY);

			CCString *strName = (CCString*)pDic->objectForKey("name");
			CCString *strType = (CCString*)pDic->objectForKey("type");

			// 进行怪物的初始化,先根据名字来判断是不是enemy,再细分enemy类型		
			if (strName->m_sString == "enemy")
			{
				if (strType->m_sString == "mushroom")
				{
					CMMonsterMushrooms *pMonster = CMMonsterMushrooms::CreateMonsterMushrooms(TileXY,pMario,this,this);
					if (pMonster==NULL)
					{
						CCLog("pMonster==NULL!");
					}
					pMonster->setPosition(ccp(TileXY.x,TileXY.y));
					pMonster->setAnchorPoint(ccp(0,0));
					m_pArrayMonsters->addObject(pMonster);
					addChild(pMonster,enZOrderFront);
				}
				if (strType->m_sString == "tortoise")
				{
					CMMonsterTortoise *pMonster = CMMonsterTortoise::CreateMonsterTortoise(TileXY,pMario,this,this);
					if (pMonster==NULL)
					{
						CCLog("pMonster==NULL!");
					}
					pMonster->setPosition(ccp(TileXY.x,TileXY.y));
					pMonster->setAnchorPoint(ccp(0,0));
					m_pArrayMonsters->addObject(pMonster);
					addChild(pMonster,enZOrderFront);
				}
				if (strType->m_sString == "flower")
				{
					CMMonsterFlower *pMonster = CMMonsterFlower::CreateMonsterFlower(TileXY,pMario,this,this);
					if (pMonster==NULL)
					{
						CCLog("pMonster==NULL!");
					}
					pMonster->setPosition(ccp(TileXY.x,TileXY.y));
					pMonster->setAnchorPoint(ccp(0,0));
					m_pArrayMonsters->addObject(pMonster);
					addChild(pMonster,enZOrderFront);
				}
			}
		}

		//初始化砖块显示
		CCTMXLayer* pBlockLayer = layerNamed("block");
		CC_BREAK_IF(pBlockLayer==NULL);
		pBlockLayer->setVisible(false);
		//获得地图的瓦片数量
		// 		int nMapHorizontalTileNum = pCoinLayer->boundingBox().size.width/getTileSize().width;
		// 		int nMapVerticalTileNum = pCoinLayer->boundingBox().size.height/getTileSize().height;
		//遍历每片瓦片,寻找瓦片,建立并加入瓦片集合
		for (int i = 0;i<nMapHorizontalTileNum;i++)
		{
			for (int j = 0;j<nMapVerticalTileNum;j++)
			{
				if (TileMapPosToTileType(ccp(i,j))==enTileTypeBlock)
				{
					//解析得到当前砖块的属性
					int GID = pBlockLayer->tileGIDAt(ccp(i,j));
					CCDictionary *pDic = propertiesForGID(GID);
					CC_BREAK_IF(pDic==NULL);
					CCString *strBlockType = (CCString*)pDic->objectForKey("blockType");
					if (strBlockType==NULL)
					{
						continue;
					}
					int nBlockType = strBlockType->intValue();

					//将瓦片地图坐标转换为瓦片地图层坐标
					CCPoint BlockTileMapLayerPos = TileMapPosToTileMapLayerPos(ccp(i,j));
					CMItemBlock* pBlock = CMItemBlock::CreateItemBlock(BlockTileMapLayerPos,getTileSize(),pMario,this,(enumBlockType)nBlockType);
					if (pBlock==NULL)
					{
						CCLog("Block init Error!");
					}
					pBlock->setPosition(BlockTileMapLayerPos);
					pBlock->setAnchorPoint(ccp(0,0));
					m_pArrayBlocks->addObject(pBlock);
					addChild(pBlock);
				}
			}
		}

		return true;
	} while (false);
	CCLog("Fun CMGameMap::Init Error!");
	return false;
}
void SGWelComeLayer::requestFinished(int msgid, CCObject *data)
{
    CCLOG("收到数据");
    switch (msgid)
    {
        case MSG_HTTP_FAST_LOGIN:
        {
            std::string serverip = CCUserDefault::sharedUserDefault()->getStringForKey("serverip");
            short serverpost = (short)CCUserDefault::sharedUserDefault()->getIntegerForKey("serverpost");
            
            //记录服务器ip和端口号
            SGMainManager::shareMain()->setServerInfo(CCString::create(serverip.c_str()) , serverpost);
            
            //连接socket
            SGSocketClient::sharedSocketClient()->startConn(serverip.c_str() , serverpost);
            
        }
            break;
        case MSG_HTTP_LOGIN:
        {
            int isLogin = SGMainManager::shareMain()->getIsFBLogin();
            if (isLogin != 1 || !SGMainManager::shareMain()->getIsFbAutologin())
            {
                std::string serverip = CCUserDefault::sharedUserDefault()->getStringForKey("serverip");
                int serverpost = CCUserDefault::sharedUserDefault()->getIntegerForKey("serverpost");
                SGSocketClient::sharedSocketClient()->startConn(serverip.c_str() ,(short)serverpost);
            }
            else
            {
                SGMainManager::shareMain()->setIsFbAutologin(false);
            }
        }
            break;
        case MSg_HTTP_SERVERLIST:
        {
            SGServerListLayer *box = SGServerListLayer::create(this, (CCArray *)data, SGServerListLayerComeFromFirst);
            SGMainManager::shareMain()->showBox(box,false);

            
        }
            break;
        case MSG_HTTP_UPDATE_SERVER_STATE:
        {
            CCDictionary *dict = (CCDictionary*)data;
            CCString *serverIp = (CCString*)dict->objectForKey("serverIp");
            CCString *serverPost = (CCString*)dict->objectForKey("serverPost");
            CCString *serverId = (CCString*)dict->objectForKey("serverId");
            CCString *serverShowId = (CCString*)dict->objectForKey("serverShowId");
            CCString* serverName = (CCString*)dict->objectForKey("serverName");
            //保存即将登陆的服务器的描述
            serverDes = ((CCString * )dict->objectForKey("serverDes") )->m_sString;
            //save ip and post of server
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverid",serverId->intValue());
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverShowId", serverShowId->intValue());
            CCUserDefault::sharedUserDefault()->setStringForKey("serverip", serverIp->getCString());
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverpost", serverPost->intValue());
            CCUserDefault::sharedUserDefault()->setStringForKey("servername", serverName->getCString());
            CCUserDefault::sharedUserDefault()->flush();
            
            
            CCLog("最新服务器 ip=%s\n post=%s\n id=%s\n name=%s",serverIp->getCString(),serverPost->getCString(),serverId->getCString(),serverName->getCString());
            
            changeServerbtn->setFont(serverName->getCString());
            CCUserDefault::sharedUserDefault()->setStringForKey("servername", serverName->getCString());
            
            //如果是维护中 则不再登陆。
            short serverState = (short)(  ( (CCString *)dict->objectForKey("serverState") )->intValue() );
            if (1 != serverState)
            {
                ;
            }
            //提示不能登陆的详细信息。
            else
            {
                SGMainManager::shareMain()->showMessage(serverDes.c_str());
            }
            //MM: 即使维护中,也尝试登录,101用户会自动放过。
            this->realLogin();
        }
            break;

        case MSg_HTTP_LASTESTSERVER:
        {
            CCDictionary *dict = (CCDictionary*)data;
            CCString *serverIp = (CCString*)dict->objectForKey("serverIp");
            CCString *serverPost = (CCString*)dict->objectForKey("serverPost");
            CCString *serverId = (CCString*)dict->objectForKey("serverId");
            CCString* serverName = (CCString*)dict->objectForKey("serverName");
            //保存即将登陆的服务器的描述
            serverDes = ((CCString * )dict->objectForKey("serverDes") )->m_sString;
            //save ip and post of server
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverid",serverId->intValue());
            CCUserDefault::sharedUserDefault()->setStringForKey("serverip", serverIp->getCString());
            CCUserDefault::sharedUserDefault()->setIntegerForKey("serverpost", serverPost->intValue());
            CCUserDefault::sharedUserDefault()->setStringForKey("servername", serverName->getCString());
            CCUserDefault::sharedUserDefault()->flush();
            
            
            CCLog("最新服务器 ip=%s\n post=%s\n id=%s\n name=%s",serverIp->getCString(),serverPost->getCString(),serverId->getCString(),serverName->getCString());
            
            changeServerbtn->setFont(serverName->getCString());
            CCUserDefault::sharedUserDefault()->setStringForKey("servername", serverName->getCString());
            
        }
            break;
        case MSG_HTTP_GET_CHANNEL_USER_ID:
        {
            CCDictionary* dict = (CCDictionary*) data;
            CCUserDefault* ccud = CCUserDefault::sharedUserDefault();
            CCString* actId = (CCString*) dict->objectForKey("sdkAccountId");
            ccud->setStringForKey("userId", actId->m_sString);
            ccud->setStringForKey("username", actId->m_sString);
            ccud->setStringForKey("password", actId->m_sString);
            ccud->setIntegerForKey("channelId", GlobalConfig::gi()->getRealChannelId());
#if (GCCT_CHINA_UC_ADR_THIRD == GAME_CHANNEL_TYPE) //uc adr
            //MM: 将本次s_sid作为loginkey,登入使用。
            ccud->setStringForKey("loginKey", UCSdk::s_sid);
#elif (GCCT_CHINA_KUAIYONG_IOS_THIRD == GAME_CHANNEL_TYPE)
            //MM: 将快用的tokenKey作为loginkey,登入使用。
            ccud->setStringForKey("loginKey", ( (KuaiYongIosImp*) SdkController::gi()->getSdkImp() )->kyToken );
#else
            
#endif
            CCString* nickName = (CCString*) dict->objectForKey("sdkNickName");
            ccud->setStringForKey("sdk_user_nick_name", nickName->m_sString);
            //还有一个"sdkCreator"字段,但是未起作用,所以没有在这里添加。
            registerBtn->setFont(nickName->getCString()); //将按钮文本变为其uc账号昵称。

            ccud->setBoolForKey("isExist", true);
            ccud->setBoolForKey("isAccount", true);
            ccud->flush();
            //MMD: SDKIF SDK登陆成功!仅当21号http消息完成后,才设置SDK登陆成功标志,其他情况一概无视。
            ExtClassOfSDK::sharedSDKInstance()->setIsLoginSDK(true);
            //添加的针对非注册体系下的td数据设置,目前有uc在使用。
            ExtClassOfSDK::sharedSDKInstance()->setTdData(actId->m_sString, nickName->m_sString);
        }
            break;
        default:
            break;
    }
    SGMainManager::shareMain()->getMainScene()->plat->removeConnection();
}
void GameOver::onEnter()
{	
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)  
	const char* FILE_NAME = "/mnt/sdcard/ninjadash/ninjadata";
#elif(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	const char* FILE_NAME = "../assets/data";
#endif
	FILE* p = fopen(FILE_NAME,"r");
	if(!p)
	{
		FILE* w = fopen(FILE_NAME,"w");
		fwrite("0",1,1,w);
		fclose(w);
	}
	p = fopen(FILE_NAME,"r+");

	char data[8] = {0};
	fread(data,1,8,p);
	
	CCString* sMax = CCString::create(data);
	int nMax = sMax->intValue();
	if(m_nThisScore > nMax)
	{
		CCString* sWrite = CCString::createWithFormat("%d",m_nThisScore);
		fseek(p,0,SEEK_SET);
		int l = sWrite->length();
		fwrite(sWrite->getCString(),l,1,p);
	}
	fclose(p);
	// End Haha

	const float fontSize = 40.0f;
	
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	if( !m_bFromMenu )
	{
		CCSprite* background = CCSprite::create( "bg_gameover.png" );
		background->setScaleX(CCEGLView::sharedOpenGLView()->getFrameSize().width / background->getContentSize().width);
		background->setScaleY(CCEGLView::sharedOpenGLView()->getFrameSize().height / background->getContentSize().height);
		background->setPosition( ccp( CCEGLView::sharedOpenGLView()->getFrameSize().width / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height / 2 ) );
		this->addChild( background, -1 );

		// Create 2 Menu Items
		CCMenuItemImage* quitItem = CCMenuItemImage::create( "quit_up.png", "quit_down.png" );
		quitItem->setTag( MT_Menu );
		quitItem->setTarget( this, menu_selector( GameOver::menuCallback ) );
		quitItem->setPosition( ccp( visibleSize.width * (1.0 - 0.3) / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height * 0.375 ) );
		quitItem->setScale( 1.5f );

		CCMenuItemImage* retryItem = CCMenuItemImage::create( "tryagain_up.png", "tryagain_down.png" );
		retryItem->setTag( MT_Retry );
		retryItem->setTarget( this, menu_selector( GameOver::menuCallback ) );
		retryItem->setPosition( ccp( visibleSize.width * (1.0 + 0.3) / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height * 0.375 ) );
		retryItem->setScale( 1.5f );

		// Add to Menu
		CCMenu* pMenu = CCMenu::create( quitItem, retryItem, NULL );
		pMenu->setPosition( CCPointZero );
		this->addChild( pMenu );

		
		// Font
		CCString* s1 = CCString::createWithFormat("%d",m_nThisScore);
		CCLabelTTF* info1 = CCLabelTTF::create(s1->getCString(),"Stencil Std",fontSize);
		info1->setPosition(CCPoint(CCEGLView::sharedOpenGLView()->getFrameSize().width / 2,CCEGLView::sharedOpenGLView()->getFrameSize().height * 1.35 / 2 ));
		addChild(info1);
		
		CCLabelTTF* info2 = CCLabelTTF::create(sMax->getCString(),"Stencil Std",fontSize);
		info2->setPosition(CCPoint(CCEGLView::sharedOpenGLView()->getFrameSize().width / 2,CCEGLView::sharedOpenGLView()->getFrameSize().height * 1.1 / 2 ));
		addChild(info2);

	}
	else
	{
		CCSprite* background = CCSprite::create( "bg_setting.png" );
		background->setScaleX(CCEGLView::sharedOpenGLView()->getFrameSize().width / background->getContentSize().width);
		background->setScaleY(CCEGLView::sharedOpenGLView()->getFrameSize().height / background->getContentSize().height);
		background->setPosition( ccp( CCEGLView::sharedOpenGLView()->getFrameSize().width / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height / 2 ) );
		this->addChild( background, -1 );
		
		CCSprite* bscore = CCSprite::create( "bestscore.png" );
		bscore->setScale(1.5);
		bscore->setPosition( ccp( CCEGLView::sharedOpenGLView()->getFrameSize().width / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height * 0.8 ) );
		this->addChild( bscore, -1 );
	
		// Create 2 Menu Items
		CCMenuItemImage* backItem = CCMenuItemImage::create( "back_up.png", "back_down.png" );
		backItem->setTag( MT_Back );
		backItem->setTarget( this, menu_selector( GameOver::menuCallback ) );
		backItem->setPosition( ccp( visibleSize.width / 2, CCEGLView::sharedOpenGLView()->getFrameSize().height * 0.375 ) );
		backItem->setScale( 1.5f );

		// Add to Menu
		CCMenu* pMenu = CCMenu::create( backItem, NULL );
		pMenu->setPosition( CCPointZero );
		this->addChild( pMenu );

		CCLabelTTF* info2 = CCLabelTTF::create(sMax->getCString(),"Stencil Std",fontSize);
		info2->setPosition(CCPoint(CCEGLView::sharedOpenGLView()->getFrameSize().width / 2,CCEGLView::sharedOpenGLView()->getFrameSize().height * 1.4 / 2 ));
		addChild(info2);

	}

	CCLayer::onEnter();
}
bool TollgateMapLayer::init() {
    bool bRet = false;

    do {
        CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

        /* 读取关卡配置 */
        loadConfig();

		/* 加载怪物队列数量 */
		CCString* sMonsterListPath = CCString::createWithFormat("%slevel_%d_others.plist",CCFileUtils::sharedFileUtils()->getWritablePath().c_str(), m_iCurLevel);
	
		if(!CCFileUtils::sharedFileUtils()->isFileExist(sMonsterListPath->getCString()))
		{
			sMonsterListPath = CCString::createWithFormat("tollgate/level_%d_others.plist", m_iCurLevel);
		}
		tinyxml2::XMLDocument * xmlDoc = new tinyxml2::XMLDocument();
		unsigned char* pBuffer = NULL;
		unsigned long bufferSize = 0;

		pBuffer = CCFileUtils::sharedFileUtils()->getFileData(sMonsterListPath->getCString(), "r", &bufferSize);

		if (pBuffer)
		{
			xmlDoc->Parse((const char*)pBuffer);
			CCString* nums = CCString::create(xmlDoc->RootElement()->FirstChildElement()->FirstChildElement()->GetText());
			m_monsterListNum = nums->intValue();
		}
		delete xmlDoc;

		
		/* 创建怪物管理器 */
		m_monsterMgrList = CCArray::createWithCapacity(m_monsterListNum);
		CC_SAFE_RETAIN(m_monsterMgrList);
		for(int i = 0; i < m_monsterListNum; i++){
			m_monsterMgrList->insertObject(MonsterManager::createWithLevel(m_iCurLevel, i), i);
			this->addChild((MonsterManager*)m_monsterMgrList->objectAtIndex(i), MONSTER_LAYER_LVL);
		}
		
		/* 创建英雄管理器 */
		m_heroMgr = HeroManager::createWithLevel(m_iCurLevel);
		this->addChild(m_heroMgr, HERO_LAYER_LVL);

        /* 创建起始点 */
        createStartPoint();

        /* 创建堡垒 */
        createHome();
		
        /* 初始化塔魂、怪物和魔力数量 */
        CCDictionary* dict = CCDictionary::create();

        dict->setObject(CCInteger::create(5), enMsgDataKey_TowerSoulNum);
        NOTIFY->postNotification("TowerSoulChange", dict);

        dict->removeAllObjects();
		CCObject* it = NULL;
		int NotShowMonster = 0;
		CCARRAY_FOREACH(m_monsterMgrList, it){
			MonsterManager* m_monsterMgr = dynamic_cast<MonsterManager*>(it);
			NotShowMonster += m_monsterMgr->getNotShowMonsterCount();
		}
		dict->setObject(CCInteger::create(NotShowMonster), enMsgDataKey_MonsterNum);
        //dict->setObject(CCInteger::create(m_monsterMgr->getNotShowMonsterCount()), enMsgDataKey_MonsterNum);
        NOTIFY->postNotification("MonsterNumChange", dict);

        dict->removeAllObjects();
        dict->setObject(CCInteger::create(100), enMsgDataKey_MagicNum);
        NOTIFY->postNotification("MagicChange", dict);

		dict->removeAllObjects();
        dict->setObject(CCInteger::create(3), enMsgDataKey_MagicNum);
		NOTIFY->postNotification("MonsterListNumChange", dict);

		NOTIFY->addObserver(this, 
			callfuncO_selector(TollgateMapLayer::removeMonsterList), 
			"AllMonsterDead", 
		NULL);

        bRet = true;

    } while (0);
Exemple #13
0
void GB2ShapeCache::addShapesWithFile(const std::string &plist) {
    
	//const char *fullName = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist.c_str()).c_str();
    
    CCDictionary *dict = CCDictionary::createWithContentsOfFile(plist.c_str());
    // not triggered - cocos2dx delivers empty dict if non was found

	CCAssert(dict != NULL, "Shape-file not found");
    
    CCAssert(dict->count() != 0, "plist file empty or not existing");
	
	CCDictionary *metadataDict = (CCDictionary *)dict->objectForKey("metadata");
    
    int format = static_cast<CCString *>(metadataDict->objectForKey("format"))->intValue();
    ptmRatio = static_cast<CCString *>(metadataDict->objectForKey("ptm_ratio"))->floatValue();
    CCLOG("ptmRatio = %f",ptmRatio);
	CCAssert(format == 1, "Format not supported");

    
	CCDictionary *bodyDict = (CCDictionary *)dict->objectForKey("bodies");

    b2Vec2 vertices[b2_maxPolygonVertices];
    
    CCDictElement *dictElem;
    std::string bodyName;
	CCDictionary *bodyData;
    //iterate body list
    CCDICT_FOREACH(bodyDict,dictElem )
    {
        bodyData = (CCDictionary*)dictElem->getObject();
        bodyName = dictElem->getStrKey();
        
        
        BodyDef *bodyDef = new BodyDef();
        bodyDef->anchorPoint = CCPointFromString(static_cast<CCString *>(bodyData->objectForKey("anchorpoint"))->getCString());
        CCArray *fixtureList = (CCArray*)(bodyData->objectForKey("fixtures"));
        FixtureDef **nextFixtureDef = &(bodyDef->fixtures);
        
        //iterate fixture list
        CCObject *arrayElem;
        CCARRAY_FOREACH(fixtureList, arrayElem)
        {
            b2FixtureDef basicData;
            CCDictionary* fixtureData = (CCDictionary*)arrayElem;
            
            basicData.filter.categoryBits = static_cast<CCString *>(fixtureData->objectForKey("filter_categoryBits"))->intValue();
            
            basicData.filter.maskBits = static_cast<CCString *>(fixtureData->objectForKey("filter_maskBits"))->intValue();
            basicData.filter.groupIndex = static_cast<CCString *>(fixtureData->objectForKey("filter_groupIndex"))->intValue();
            basicData.friction = static_cast<CCString *>(fixtureData->objectForKey("friction"))->floatValue();
            
            basicData.density = static_cast<CCString *>(fixtureData->objectForKey("density"))->floatValue();
            
            basicData.restitution = static_cast<CCString *>(fixtureData->objectForKey("restitution"))->floatValue();
            
            basicData.isSensor = (bool)static_cast<CCString *>(fixtureData->objectForKey("isSensor"))->intValue();
           
            CCString *cb = static_cast<CCString *>(fixtureData->objectForKey("userdataCbValue"));
            
            int callbackData = 0;

			if (cb)
				callbackData = cb->intValue();

			std::string fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->m_sString;

			if (fixtureType == "POLYGON") {
				CCArray *polygonsArray = (CCArray *)(fixtureData->objectForKey("polygons"));
				
                CCObject *dicArrayElem;
                CCARRAY_FOREACH(polygonsArray, dicArrayElem)
                {
                    FixtureDef *fix = new FixtureDef();
                    fix->fixture = basicData; // copy basic data
                    fix->callbackData = callbackData;
                    
                    b2PolygonShape *polyshape = new b2PolygonShape();
                    int vindex = 0;
                    
                    CCArray *polygonArray = (CCArray*)dicArrayElem;
                    
                    assert(polygonArray->count() <= b2_maxPolygonVertices);
                    
                    CCObject *piter;
                    CCARRAY_FOREACH(polygonArray, piter)
                    {
                        CCString *verStr = (CCString*)piter;
                        CCPoint offset = CCPointFromString(verStr->getCString());
                        vertices[vindex].x = (offset.x / ptmRatio) ;
                        vertices[vindex].y = (offset.y / ptmRatio) ;
                        vindex++;
                    }