Esempio n. 1
0
bool Chicken::initWithLayer( HelloWorld * layer )
{
	if (initWithSpriteFrameName("chicken_001.png"))
	{   
		_layer = layer;
		auto animation = Animation::create();
		for (int i = 1; i <= 40; i++)
		{   
			auto str = String::createWithFormat("chicken_%03d.png",i);
			auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str->getCString());
			animation->addSpriteFrame(frame);
		}
		animation->setDelayPerUnit(1.0f / 1000 * 90);
		setNormalAnimation(animation);

		animation = Animation::create();
		for (int i = 1; i <= 12; i++)
		{   
			auto str = String::createWithFormat("ccchick_%03d.png",i);
			auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str->getCString());
			animation->addSpriteFrame(frame);
		}
		animation->setDelayPerUnit(1.0f / 1000 * 40);
		setTrapAnimation(animation);
		layer->addChild(this);

		runAnimation(getNormalAnimation());

		return true;
	}
	return false;
}
Esempio n. 2
0
//cocos2dx 是单线程的 单你要执行两个动作是要开辟一个线程
void HelloWorld:: testArray(){
    auto str1=__String::create("String1");
    auto str2=__String::create("String2");
    auto str3=__String::create("String3");
    auto str4=__String::create("String4");
    auto str5=__String::create("String5");
    __Array* array=__Array::create();
    
    auto temp=__Array::create();
    array->addObject(str1);
    array->addObject(str2);
    array->addObject(str3);
    array->addObject(str4);
    array->addObject(str5);
    
    for (int i=0; i<array->count(); i++) {
        //删除一个对象时不能再对数组进行遍历因为删除一个对象时,下一个对象会自动填充前一个位置 而i++会向后走,就会遍历不到往前移动的哪一个对象。解决办法  ,在外面定义一个临时数组 当你要删除哪个是把 那个放入临时数组 最后遍历临时数组进行删除。
        auto str=(__String*)array->objectAtIndex(i);
        log("str::%s",str->getCString());
        if (i==2) {
            temp->addObject(array->getObjectAtIndex(i));
        }
    }
    for (int i=0; i<temp->count(); i++) {
        auto str=(__String*)temp->objectAtIndex(i);
        log("str::%s",str->getCString());
        array->removeObject(temp->objectAtIndex(i));
        
    }
}
Esempio n. 3
0
	std::string SqliteDb::convertConditionDictionary(Map *conditionDict)
	{
		std::string conditionStr;

		if (conditionDict && conditionDict->getLength() > 0)
		{
			conditionStr.append(" where ");

			Vector *columnNameArray = conditionDict->allKeys();
			int count = columnNameArray->getLength();

			for (int i = 0; i < count; ++i)
			{
				auto columnName = (RefString*)columnNameArray->objectAt(i);
				auto columnValue = (RefString*)conditionDict->objectForKey(columnName->getCString());

				conditionStr.append(columnName->getCString());
				conditionStr.append("='");
				conditionStr.append(columnValue->getCString());
				conditionStr.append("'");

				if (i != count - 1)
				{
					conditionStr.append(" and ");
				}
			}
		}
		return conditionStr;
	}
Esempio n. 4
0
TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx)
{
    auto string = String::createWithFormat("%ld", idx);
    TableViewCell *cell = table->dequeueCell();
    if (!cell) {
        cell = new (std::nothrow) CustomTableViewCell();
        cell->autorelease();
        auto sprite = Sprite::create("Images/Icon.png");
        sprite->setAnchorPoint(Vec2::ZERO);
        sprite->setPosition(Vec2(0, 0));
        cell->addChild(sprite);

        auto label = Label::createWithSystemFont(string->getCString(), "Helvetica", 20.0);
        label->setPosition(Vec2::ZERO);
		label->setAnchorPoint(Vec2::ZERO);
        label->setTag(123);
        cell->addChild(label);
    }
    else
    {
        auto label = (Label*)cell->getChildByTag(123);
        label->setString(string->getCString());
    }


    return cell;
}
void HUD::initOption()	{

	this->remainingDistance = 50;
	this->remainingFuel = 20;
	this->score = 0;

	visibleSize = Director::getInstance()->getVisibleSize();
	origin = Director::getInstance()->getVisibleOrigin();

	/////////////////////////////////////////////////
	// distance
	auto stringDistance = __String::createWithFormat( "Remaining distance: %d", this->remainingDistance );
	labelDistance = LabelTTF::create(stringDistance->getCString(), "fonts/Backslash.ttf", 40);
	labelDistance->setAnchorPoint(Vec2(0, 0));
	labelDistance->setColor( Color3B::WHITE );
	labelDistance->setFontFillColor(Color3B::YELLOW);
	labelDistance->setPosition( origin.x + visibleSize.width - labelDistance->getContentSize().width,
		origin.y + visibleSize.height - labelDistance->getContentSize().height );

	///////////////////////////////////////////////
	// fuel
	__String fuelDescription = "";
	for (int i = 0; i < remainingFuel; i++)
		fuelDescription.append("I");
	auto stringFuel = __String::createWithFormat("Fuel: %s", fuelDescription.getCString());
	labelFuel = LabelTTF::create(stringFuel->getCString(), "fonts/Backslash.ttf", 40);
	labelFuel->setAnchorPoint(Vec2(0, 0));
	labelFuel->setColor(Color3B::WHITE);
	labelFuel->setFontFillColor( (remainingFuel >= 5) ? Color3B::GREEN : Color3B::RED );
	labelFuel->setPosition(labelDistance->getPositionX(), labelDistance->getPositionY() - labelFuel->getContentSize().height);

	//////////////////////////////////////////////
	// score
	auto stringScore = __String::createWithFormat("Score: %ld", score);
	labelScore = LabelTTF::create(stringScore->getCString(), "fonts/Backslash.ttf", 40);
	labelScore->setAnchorPoint(Vec2(0, 1));
	labelScore->setColor(Color3B::WHITE);
	labelScore->setFontFillColor(Color3B::YELLOW);
	labelScore->setPosition(origin.x, origin.y + visibleSize.height);

	//////////////////////////////////////////////
	// warning
	__String warningDescription = "W A R N I N G";
	auto stringWarning = __String::createWithFormat("%s", warningDescription.getCString());
	labelWarning = LabelTTF::create(stringWarning->getCString(), "fonts/Backslash.ttf", 90);
	labelWarning->setAnchorPoint(Vec2(0.5f, 0.5f));
	labelWarning->setColor(Color3B::WHITE);
	labelWarning->setFontFillColor(Color3B::RED);
	labelWarning->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
	labelWarning->setVisible(false);

	// add all component to gamescene
	this->addChild( labelDistance );
	this->addChild( labelFuel );
	this->addChild( labelScore );
	this->addChild( labelWarning );
	
	this->scheduleUpdate();
}
Esempio n. 6
0
//第一关(添加5关的关卡刚体)
void GameLayer:: addGangti1(){
    
    //木头
    for (int i = 1; i<=9 ;i++ ) {
        auto str = __String::createWithFormat("wood_%d",i);
        Sprite* woods1 = node->getChildByName<Sprite*>(str->getCString());
//       log("tag = %d",woods1->getTag());
        if (woods1->getTag() ==5) {
            auto body = PhysicsBody::createBox(woods1->getContentSize());
        body->setDynamic(false);
            body->getShape(0)->setRestitution(1);//反弹力
         body->getShape(0)->setFriction(0);//摩擦力
            woods1->setPhysicsBody(body);
            woods1->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }

        
    }

    //墙壁
    for (int i =1; i<=4; i++) {
        auto str2 =__String::createWithFormat("wall_%d",i);
        auto wall = node->getChildByName<Sprite*>(str2->getCString());
        if (wall->getTag() == 25) {
            auto body2 = PhysicsBody::createBox(Size(wall->getContentSize().width,wall->getContentSize().height));//den res fri
            
            body2->setDynamic(false);
            body2->getShape(0)->setFriction(0);
            body2->getShape(0)->setRestitution(1);

            
            wall->setPhysicsBody(body2);
            
            wall->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }
        
    }
    
    //石头
    for (int i =1; i<= 2; i++) {

        auto str3 =__String::createWithFormat("stone_%d",i);
        auto stone = node->getChildByName<Sprite*>(str3->getCString());
        if (stone->getTag() == 45) {
//            auto body2 = PhysicsBody::createBox(Size(stone->getContentSize().width,stone->getContentSize().height));//den res fri
//
            auto body3 = PhysicsBody::createCircle(stone->getContentSize().width/2);
            
            body3->setDynamic(false);
            body3->getShape(0)->setFriction(0);
            body3->getShape(0)->setRestitution(1.5);//弹力
            stone->setPhysicsBody(body3);
            stone->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }
    }
    
    
}
Esempio n. 7
0
bool GameLayer::init(){
    
    if ( !LayerColor::initWithColor(Color4B(255, 255, 255, 255)) )
    {
        return false;
    }
    

    
    visibleSize = Director::getInstance()->getVisibleSize();

    gun = Gun::create();
    gun->setScale(0.25);
    gun->setPosition(Vec2(120,visibleSize.height/2-180));
    addChild(gun,1);

    touchTest();    //触摸检测
    
    
    this->schedule(schedule_selector(GameLayer::checkCollision), 0.1);//启动检测碰撞的函数

    ////////////////////////////

    //文件解析
    str="Data.xml";
//    xmller.giveBirthTo(str);
    xmller.createwithxmlfile(str);
    
    //更换背景
    std::string a= xmller.getLevel01();
    int i = atoi(a.c_str());

    log("哇擦了%d",i);
    auto levelNumber = __String::createWithFormat("bg%d.png",i);
    log("%s",levelNumber->getCString());
    auto bg = Sprite::create(levelNumber->getCString());
    bg->setPosition(visibleSize/2);
    
    auto fade1 = FadeTo::create(2.0, 150);
    auto fade2 = FadeIn::create(2.0);
    auto seq = RepeatForever::create( Sequence::create(fade1,fade2,NULL));
    bg->runAction(seq);
    addChild(bg);
    
    loadLayer();    //加载场景
    addSprite();    //添加界面UI元素
    
    //拿到子弹数量,给全局变量
    auto bulletnm = xmller.getLevel03();
    int b = atoi(bulletnm.c_str());
    bulletNumber = b;

    butemp =0;
    return true;
}
Esempio n. 8
0
TableViewCell* SelectMissionScene::tableCellAtIndex(TableView *table, ssize_t idx)
{
	log("%d:geted!", idx);
	GameManager *manager = GameManager::getInstance();
	MissionInfoItem *info = MissionInfoItem::create(manager->getMissionStatus()[idx]);

	TableViewCell *cell = table->dequeueCell();
	if(!cell)
	{
		cell = TableViewCell::create();		//or cell = new TTableViewCell(); cell->autorelease()	
	}
	else
	{
		MissionInfoItem *tmp = static_cast<MissionInfoItem *>(cell->getChildByTag(100));
		tmp->removeFromParent();
	}

	info->setAnchorPoint(Vec2::ZERO);
	info->setPosition(Vec2::ZERO);
	info->setTag(100);
	cell->addChild(info);

#ifdef TEST
	/************ Test TableView ******************/
	auto index_text = __String::createWithFormat("%ld",idx + 1);
	if(!cell)
	{
		Label *label = Label::create(index_text->getCString(), "Marker Felt.ttf", 18);
		label->setPosition( 80, 50 );
		label->setTag(150);

		cell = TableViewCell::create();
		Sprite *sprite = Sprite::create("lock.png");
		sprite->setPosition(270, 50);
		sprite->setTag(100);

		cell->addChild(label );
		cell->addChild(sprite);
	}
	else
	{
		Label *label = static_cast<Label *>(cell->getChildByTag(150));
		label->setString(index_text->getCString());
	}

#endif // TEST





	return cell;
}
Esempio n. 9
0
void Loading::loadCaChe()
{
	spriteCount = textureCacheArray->count();
	if (spriteCount == 0)
		callBackReplaceScene();
	Ref* pSender;
	CCARRAY_FOREACH(textureCacheArray, pSender)
	{
		auto pString = static_cast<__String*>(pSender);
		auto pngString = __String::createWithFormat("%s.png", pString->getCString());
		Director::getInstance()->getTextureCache()->addImageAsync(pngString->getCString(), CC_CALLBACK_1(Loading::loadSpriteCountCallBack, this, pString->getCString() ));
	}
Esempio n. 10
0
TableViewCell* UIBuyBuildingLayer::tableCellAtIndex( TableView *table, ssize_t idx )
{
	auto string = String::createWithFormat("%ld", idx);
	auto cell = dynamic_cast<CustomTableViewCell*>(table->dequeueCell());
	if (!cell)
	{
		cell = CustomTableViewCell::create();
		cell->setCilckTarget(CC_CALLBACK_1(UIBuyBuildingLayer::onCardClick,this));
	}   
	auto buycfg = BuyListConfig::getBuyListFromType( (OpenBuilding::BuyBuildingType)_curtag).at(idx);
	auto con = Configuration::getInstance();

	auto texture = Director::getInstance()->getTextureCache()->addImage(BuildingCommon::getPicFromId(buycfg->buildcfg->id));
	cell->getInfoPic()->setTexture(texture,BuildingCommon::getPicFromId(buycfg->buildcfg->id).c_str());

    cell->getTitle()->setString(buycfg->buildcfg->name);
	auto str = String::createWithFormat("%d",buycfg->buildcfg->cost_value);
	cell->getLableCost()->setString(str->getCString());
	str = String::createWithFormat("%d s",buycfg->buildcfg->cost_time);
	cell->getTimeLable()->setString(str->getCString());
	str = String::createWithFormat("%d/%d",buycfg->current,buycfg->opencfg->getLimitCountFormLevel(BuildingFunc::getInstance()->getMainLevel()));
	cell->getHasBuildLable()->setString(str->getCString());

	//Check is Disable
	if (buycfg->current >= buycfg->opencfg->getLimitCountFormLevel(BuildingFunc::getInstance()->getMainLevel()))
	{  
		auto level = 1;
		for (auto i = level;i <= 10; i++)
		{
			if ( buycfg->opencfg->getLimitCountFormLevel(i) > buycfg->current )
			{   
				level = i;
				break;
			}
		}
       if (level != 1)
       {
		   auto str = String::createWithFormat(con->getValue("levelcanmake").asString().c_str(),level);
		   cell->setDisable(true,str->getCString());
       }
	   else
	   {
		   cell->setDisable(true);
	   }
	}
	else
	{
		cell->setDisable(false);
	}
     
	return cell;
}
Esempio n. 11
0
std::string CommonUtil::getPropById(std::string xmlId, std::string propName)
{
    auto retDict = LocalController::shared()->DBXMLManager()->getObjectByKey(xmlId);
    if (!retDict) {
        return string("");
    }
    auto ret = retDict->valueForKey(propName);
    if (!ret->getCString()) {
        return string("");
    }
    return string(ret->getCString());

}
DialogueHelper* DialogueHelper::parseWithFile(const char *xmlFileName){
	DialogueHelper* dialogueHelper = new DialogueHelper();

	//读取文本
	auto xmlFileUrl = String::createWithFormat("data/dialogue/%s.xml", xmlFileName);
	auto doc = new tinyxml2::XMLDocument();
	log("is loading %s", xmlFileUrl->getCString());
	doc->LoadFile(xmlFileUrl->getCString());

	//解析
	auto dialogues = doc->RootElement();
	for (auto dialogue = dialogues->FirstChildElement("dialogue"); dialogue != NULL; dialogue = dialogue->NextSiblingElement()){
		//循环添加序列组
		std::vector<DialogueData> dialogueData;//对话序列组对象
		int dialogueId = std::atoi(dialogue->Attribute("id"));//该对话序列组对象
		const char* triggerPos = dialogue->Attribute("triggerPos");//暂时不保存

		if (dialogueId == 0){
			continue;//无id标识,跳过循环
		}

		for (auto content = dialogue->FirstChildElement(); content; content = content->NextSiblingElement()){
			//循环添加对话序列
			DialogueData data;//直接使用对象。由系统维护生命周期防止内存泄露
			std::string contentType = content->Name();
			if (contentType == "string"){
				data.type = DialogueType::string;
				data.speakerName = content->Attribute("name");
				data.content = content->GetText();
			}
			else if (contentType == "options")
			{
				data.type = DialogueType::option;
				std::vector<Option> options;
				for (auto option = content->FirstChildElement(); option; option = option->NextSiblingElement()){
					Option _option;
					_option.text = option->GetText();
					_option.toId = option->Attribute("toId") != NULL ? (int)option->Attribute("toId") : -1;
					options.push_back(_option);
				}
				data.options = options;
			}
			dialogueData.push_back(data);
			log("loading text: %s", content->GetText());
		}

		dialogueHelper->_dialogueList[dialogueId] = dialogueData;//重复id后面会覆盖前面的
	}

	return dialogueHelper;
}
bool GameOverScene::init()	{
    if(!Layer::init())	{
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    auto origin = Director::getInstance()->getVisibleOrigin();

    UserDefault* userScore = UserDefault::getInstance();
    if(score >= userScore->getIntegerForKey( "highscore" ))	{
        userScore->setIntegerForKey( "highscore", score );
    }
    userScore->flush();

    //create background for game over scene
    auto background = Sprite::create("FlappyResources/Background.png");
    background->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
    this->addChild(background);

    //create retry item
    auto retry = MenuItemImage::create( "FlappyResources/Retry_Button.png", "FlappyResources/Retry_Button_Clicked.png", CC_CALLBACK_1(GameOverScene::goToGameScene, this) );
    retry->setPosition( origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 );

    //create quit item
    auto quit = MenuItemImage::create( "FlappyResources/Menu_Button.png", "FlappyResources/Menu_Button_Clicked.png", CC_CALLBACK_1(GameOverScene::goToMainMenuScene, this) );
    quit->setPosition( origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - quit->getContentSize().height * 2);

    //create menu
    auto menu = Menu::create( retry, quit, NULL );
    menu->setPosition( Vec2(0, 0) );

    //create label score
    auto stringScore = __String::createWithFormat( "Your score: %d", score );
    auto labelScore = LabelTTF::create( stringScore->getCString(), "fonts/Marker Belt.ttf", 50 );
    labelScore->setPosition( origin.x + labelScore->getContentSize().width, origin.y + visibleSize.height / 2 + labelScore->getContentSize().height * 4 );
    labelScore->setFontFillColor( Color3B::YELLOW );

    //create label display best score
    auto stringBestScore = __String::createWithFormat( "High score: %d", userScore->getIntegerForKey( "highscore" ) );
    auto labelHighScore = LabelTTF::create( stringBestScore->getCString(), "fonts/Marker Belt.ttf", 50 );
    labelHighScore->setPosition( origin.x + labelScore->getContentSize().width + visibleSize.width / 2, origin.y + visibleSize.height / 2 + labelHighScore->getContentSize().height * 4);
    labelHighScore->setFontFillColor( Color3B::RED );

    this->addChild( menu );
    this->addChild( labelScore );
    this->addChild( labelHighScore );

    return true;
}
Esempio n. 14
0
TMXTiledMap* GameMap::loadMap(char *mapName){
	auto name = String::createWithFormat("map/%s.tmx", mapName);
	log("is loading map which named %s [%s]", mapName, name->getCString());
	auto map = TMXTiledMap::create(name->getCString());//加载地图对象

	if (map == NULL){
		log("loading error: no such tmx file");
	}
	else
	{
		log("loading completed");
	}

	return map;
}
Esempio n. 15
0
bool HelpScene::init()
{
	if (!Layer::init())
	{
		return false;
	}

	auto size = Director::getInstance()->getWinSize();
	auto visible = Director::getInstance()->getVisibleSize();
	auto origin = Director::getInstance()->getVisibleOrigin();
	//ÉèÖñ³¾°
	auto spriteBK = Sprite::create("background.png");
	spriteBK->setPosition(size.width / 2, size.height / 2);
	spriteBK->setOpacity(75);
	this->addChild(spriteBK, 0);
	//¶ÁÈ¡xml×Ö·û
	CCDictionary* message = CCDictionary::createWithContentsOfFile("chinese.xml");
	auto helpTitleKey = message->valueForKey("helpTitle");
	const char* helpTitle = helpTitleKey->getCString();
	//°ïÖúÐÅÏ¢
	auto helpTitleLabel = Label::createWithTTF(helpTitle, "fonts/newSongTi.ttf", 25);
	helpTitleLabel->setPosition(Point(
		size.width - helpTitleLabel->getContentSize().width,
		size.height - helpTitleLabel->getContentSize().height));
	this->addChild(helpTitleLabel, 1);

	auto helpMessageKey = message->valueForKey("helpMessage");
	const char* helpMessage = helpMessageKey->getCString();
	auto helpMessageLabel = Label::createWithTTF(helpMessage, "fonts/newSongTi.ttf",20);
	helpMessageLabel->setDimensions(300,200);
	helpMessageLabel->enableOutline(Color4B(255, 0, 0, 0), 1);
	//helpMessageLabel->setAnchorPoint(Point(1,1));
	/*helpMessageLabel->setPosition(Point(
		size.width - helpTitleLabel->getContentSize().width,
		size.height - (helpTitleLabel->getContentSize().height*2)));*/
	helpMessageLabel->setPosition(size.width / 2, size.height / 2);
	this->addChild(helpMessageLabel, 1);

	//·µ»Ø°´Å¥
	auto menuItemBack = MenuItemFont::create("Back", CC_CALLBACK_1(HelpScene::gotoMenuCallback, this));
	auto menu = Menu::create(menuItemBack, NULL);
	menu->setPosition(Point::ZERO);
	menuItemBack->setPosition(Point(
		size.width - menuItemBack->getContentSize().width,
		menuItemBack->getContentSize().height));
	this->addChild(menu, 2);
	return true;
}
Esempio n. 16
0
ActionInterval* Player::getRunActionsFromSprite(std::string &strPath, FigureStateType nType, FigureDirectionType nDir)
{
	//CCArray* array = CCArray::createWithCapacity(8);
	Vector<SpriteFrame*> array;
	int flag = 0;
	do
	{
		int dirType = nDir;
		if (8 > dirType && dirType > 4)
		{
			dirType = 8 - dirType;
		}

		auto string = String::createWithFormat("%s_%d_%d_%02d.png", strPath.c_str(), nType, dirType, flag);
		
		//std::string string;
		//sprintf(string, "%s_%d_%d_%02d.png", strPath.c_str(), nType, dirType, flag);
		auto spriteFrame = SpriteFrameCache::getInstance()->spriteFrameByName(string->getCString());
		CC_BREAK_IF(spriteFrame == NULL);
		array.pushBack(spriteFrame);
		flag++;
	} while (1);

	CCAnimation* movie = CCAnimation::createWithSpriteFrames(array,getFrameRate(nType,1));
	CCAnimate* animate = CCAnimate::create(movie);
	return animate;
}
  //Native functions called by java
void s3eNOpenFeint_NOFLoginCallback(JNIEnv *env, jobject _this, jstring userId, bool loginResult)
{
    //loginResult is really s3eResult
  bool bInIsCopy = true;
  
  const char *tmpUserId = getCString(userId);
  if(loginResult)
    IwTrace(NOPENFEINT, ("User logged in %s",tmpUserId));
  else
    IwTrace(NOPENFEINT, ("User logged out %s",tmpUserId));  
  
  if(s3eEdkCallbacksIsRegistered(S3E_EXT_NOPENFEINT_HASH, 
                                 S3E_NOPENFEINT_CALLBACK_PLAYER_LOGGEDIN)
     == false)
		return; // no callback registered for this one
	
	
	s3eNOFPlayerInfo info;
	
  info.playerId = (char*)tmpUserId; // lets just hope our consumer doesn't change it. not that it matters much
  
	s3eEdkCallbacksEnqueue(S3E_EXT_NOPENFEINT_HASH,
                         S3E_NOPENFEINT_CALLBACK_PLAYER_LOGGEDIN,
                         (void*)&info,
                         sizeof(info),
                         NULL,
                         S3E_FALSE,
                         NULL,
                         NULL);	
}
Esempio n. 18
0
bool Game::right()
{  log("right");
    bool move = false;
    for (int y=0; y<4; y++) {
        for (int x=3; x>=0; x--) {
            for (int x1=x-1; x1>0; x1--) {
                if (arr[x1][y]->getNumber()>0) {
                    if (arr[x][y]->getNumber()<=0) {
                        arr[x][y]->setNumber(arr[x1][y]->getNumber());
                        arr[x1][y]->setNumber(0);
                        x++;
                        move=true;
                    }else if (arr[x][y]->getNumber()==arr[x1][y]->getNumber()){
                        arr[x][y]->setNumber((arr[x][y]->getNumber())*2);
                        arr[x1][y]->setNumber(0);
                        
                        score+=arr[x][y]->getNumber();
                        
                        auto s = __String::createWithFormat("%d",score);
                        scoreLabel->setString(s->getCString());
                        move = true;
                    }
                    break;
                }
            }
        }
    }
    return move;
}
Esempio n. 19
0
void Arcade::updateClock(float dt){
  _time --;
  auto value = String::createWithFormat("%02i", _time);
  _clock_label->setString(value->getCString());
  _clock_label->setFontFillColor(Color3B(255,255,0));

  if(_time < 0 && !_in_combo){
    showLosser();
    _time_over = true;
  }else if(_time < getTimeStart() * 0.20){
    _clock_label->setColor(Color3B::RED);
    _clock_label->runAction(
			    Sequence::create(
					     FadeOut::create(0.4f),
					     FadeIn::create(0.4f),
					     NULL
					     )
			    );
  } else if(_time < getTimeStart() * 0.5) {
    _clock_label->setColor(Color3B::YELLOW);
    _clock_label->runAction(
			    Sequence::create(
					     FadeOut::create(0.7f),
					     FadeIn::create(0.3f),
					     NULL
					     )
			    );
  }

}
Esempio n. 20
0
//往左移
bool Game::left()
{ log("left");
    bool move = false;
    for (int y=0; y<4; y++) {
        for (int x=0; x<4; x++) {
            for (int x1=x+1; x1<4; x1++) {
                if (arr[x1][y]->getNumber()>0) {
                    if(arr[x][y]->getNumber()<=0){
                    //前后数字交换
                    arr[x][y]->setNumber(arr[x1][y]->getNumber());
                    arr[x1][y]->setNumber(0);
                    x--;
                    move = true;
                }else if (arr[x][y]->getNumber() == arr[x1][y]->getNumber())
                {
                    arr[x][y]->setNumber((arr[x][y]->getNumber())*2);
                    arr[x1][y]->setNumber(0);
                    score+=arr[x][y]->getNumber();
                    auto s = __String::createWithFormat("%d",score);
                    scoreLabel->setString(s->getCString());
                    move = true;
                }
                break;
              }
           }
       }
    }
    return  move;
}
Esempio n. 21
0
void  Predator::loadFramesFromDataFile(const char *framesDataKey){
	ValueMap framesData = DataManager::getInstance()->_staticData\
		.at("character").asValueMap()\
		.at("predator").asValueMap()\
		.at(Value(_id).asString().c_str()).asValueMap()\
		.at("frames").asValueMap()\
		.at(framesDataKey).asValueMap();

	std::string spriteFrameNamePrefix = framesData.at("spriteframe_name_prefix").asString();
	int frameNum = framesData.at("frame_num").asInt();

	int frameIndexStart = this->_frames.size();
	_animationsFrameIndexStart[std::string(framesDataKey)] = frameIndexStart;

	float frameAnchorPointX = framesData.at("frame_anchor_point_x").asFloat();
	float frameAnchorPointY = framesData.at("frame_anchor_point_y").asFloat();

	for (int index = 0; index < frameNum; index++)
	{
        auto spriteFrameName =String::createWithFormat("%s_%02d.png", spriteFrameNamePrefix.c_str(), index+1);
        this->_frames[frameIndexStart + index]=Sprite::createWithSpriteFrameName(spriteFrameName->getCString())->getSpriteFrame();
		
		this->_frames[frameIndexStart + index]->retain();

		_framesAnchorPoint[frameIndexStart + index] = Point(frameAnchorPointX, frameAnchorPointY);
	}

}
Esempio n. 22
0
bool SJIndex::ok(cocos2d::Touch *touch, cocos2d::Event *event){
    auto target = static_cast<Sprite*>(event->getCurrentTarget());

    cocos2d::Point locationInNode = target->convertToNodeSpace(touch->getLocation());
    cocos2d::Size s = target->getContentSize();
    cocos2d::Rect rect = cocos2d::Rect(0, 0, s.width, s.height);

    if (rect.containsPoint(locationInNode))
    {

        auto move=MoveTo::create(0.3, Vec2(WIDTH/2, HEIGHT+HEIGHT/2));
        auto t=EaseOut::create(move, 0.5);
        alertBox->runAction(t);

        int coinCount = UserDefault::getInstance()->getIntegerForKey("coinCount");
        if (coinCount>1000) {
            alert("关卡解锁成功");
            coinCount-=1000;
            UserDefault::getInstance()->setIntegerForKey("coinCount", coinCount);
            UserDefault::getInstance()->setBoolForKey("isVeryHardUnLock", true);
            auto cStr=String::createWithFormat("金币:%d",coinCount);
            coinLabel->setString(cStr->getCString());
            Sprite* btn4=(Sprite*)this->getChildByTag(5);
            btn4->setTexture("veryHard.png");

        }else{
            alert("金币不足");
        }

    }
    return false;
}
Esempio n. 23
0
bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
		auto dic = Dictionary::createWithContentsOfFile("text.xml");
		auto str = (__String *)dic->objectForKey("title");
        glview = GLViewImpl::create(str->getCString());
        director->setOpenGLView(glview);
		glview->setFrameSize(480, 640);
    }
	glview->setDesignResolutionSize(480, 640, ResolutionPolicy::NO_BORDER);

    // turn on display FPS
    director->setDisplayStats(false);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0 / 60);

    // create a scene. it's an autorelease object
    auto scene = StartGame::createScene();

    // run
    director->runWithScene(scene);

    return true;
}
void HelloWorld::moveYCallback(Ref * pSender)
{
	auto animation = Animation::createWithSpriteFrames(attack, 0.1f);
	auto animate = Animate::create(animation);
	auto idleAnimation = Animation::createWithSpriteFrames(idle, 0.1f);
	auto idleAnimate = Animate::create(idleAnimation);
	auto seq = Sequence::create(animate, idleAnimate, CCCallFunc::create(this, callfunc_selector(HelloWorld::enCallback)), NULL);
	if (en == false) {
		en = true;
		player->runAction(seq);
	}

	auto fac = Factory::getInstance();
	Rect playerRect = player->getBoundingBox();
	Rect attackRect=Rect(playerRect.getMinX()-40,playerRect.getMinY(),
		playerRect.getMaxX()-playerRect.getMinX()+80,
		playerRect.getMaxY() - playerRect.getMinY());
	Sprite* collision = fac->collider(attackRect);
	if (collision != NULL) {
		fac->removeMonster(collision);

		hp += 20;
		if (hp > 100)
			hp = 100;
		CCProgressTo* ac1 = CCProgressTo::create(2.0f, hp);
		pT->runAction(ac1);

		++sc;
		auto temp = CCString::createWithFormat("%d", sc);
		score->setString(temp->getCString());
		UserDefault::getInstance()->setIntegerForKey("score", sc);
	}
}
Esempio n. 25
0
bool Game::down()
{
    bool move=false;
    for (int x=0; x<4; x++) {
        for (int y=0; y<4; y++) {
            for (int y1=y+1; y1<4; y1++) {
                if (arr[x][y1]->getNumber()>0) {
                    if (arr[x][y]->getNumber()<=0) {
                        arr[x][y]->setNumber(arr[x][y1]->getNumber());
                        arr[x][y1]->setNumber(0);
                        y++;
                        move= true;
                    }else if(arr[x][y]->getNumber() == arr[x][y1]->getNumber())
                    {
                        arr[x][y]->setNumber((arr[x][y]->getNumber())*2);
                        arr[x][y1]->setNumber(0);
                        score += arr[x][y]->getNumber();
                        auto s= __String::createWithFormat("%d",score);
                        scoreLabel->setString(s->getCString());
                        move=true;
                    }
                    break;
                }
            }
        }
    }
    return move;
}
Esempio n. 26
0
void RogueScene::refreshStatus()
{
    auto pStatusBarLayer = getChildByTag(RogueScene::kStatusBarTag);
    auto pStatusText = pStatusBarLayer->getChildren().at(0); // TODO: とりあえず1要素なので。。。
    if (pStatusText)
    {
        // プレイヤー取得
        auto pPlayerSprite = getPlayerActorSprite(1);
        auto pPlayerDto = pPlayerSprite->getActorDto();
        int floor = 1; // TODO: フロア情報
        int gold = 0; // TODO: player情報
        // 作成
        auto pStr = String::createWithFormat(" %2dF Lv%3d HP %3d/%3d 満腹度 %d/%d %10d G", floor, pPlayerDto->lv, pPlayerDto->hitPoint, pPlayerDto->hitPointLimit, pPlayerDto->magicPoint, pPlayerDto->magicPointLimit, gold);
        
        auto pLabelText = static_cast<LabelTTF*>(pStatusText);
        pLabelText->setString(pStr->getCString());
        pLabelText->setPositionX(pLabelText->getContentSize().width / 2);
        
        // TODO: 死亡判定ここで?
        if (pPlayerDto->hitPoint == 0)
        {
            logMessage("%sは死亡した。", pPlayerDto->name.c_str());
        }
        if (pPlayerDto->magicPoint == 0)
        {
            logMessage("%sは空腹で倒れた。", pPlayerDto->name.c_str());
        }
    }
}
Esempio n. 27
0
Vec2 StaticData::pointFromKey(std::string key)
{
	auto str = _dic->valueForKey(key);
	float x, y;
	sscanf_s(str->getCString(), "{%f,%f}", &x, &y);
	return Point(x, y);
}
void Bug::createBug()
{
    auto frameName = String::createWithFormat("worm%d_0.png",_type);
    this->initWithSpriteFrameName(frameName->getCString());
    
    this->createPosAndDir();
    this->randSpeed();
    this->randBlood();
    
    Vector<SpriteFrame*> animFrams;
    for (int i =0; i<2; i++) {
        std::string  strName;
        if (i == 0) {
            strName = StringUtils::format("worm%d_0.png",_type);
        }else
        {
            strName = StringUtils::format("worm%d_1.png",_type);
        }
        auto frameName = SpriteFrameCache::getInstance()->getSpriteFrameByName(strName.c_str());
        animFrams.pushBack(frameName);
    }
    
    auto animation = Animation::createWithSpriteFrames(animFrams,0.5);
    auto animate = Animate::create(animation);
    
    this->runAction(RepeatForever::create(animate));
    
    this->schedule(schedule_selector(Bug::randMove),0.01);
}
Esempio n. 29
0
void HelloWorld:: testDic(){
    //打印字符串
    std::string a="ddddd";
    log("a=%s",a.c_str());
    char b[10];
    log("%lu",sizeof(b));
    //拼接
    int i=20;
    sprintf(b, "%d.png",i);
    printf("%s",b);
    
    auto pDic=__Dictionary::create();
    auto pValue1=__String::create("100");
    auto pValue2=__String::create("120");
    auto pValue3=__Integer::create(200);
    pDic->setObject(pValue1, "key1");
    pDic->setObject(pValue2, "key2");
    pDic->setObject(pValue3, "key3");
    auto pStr1=(__String *)pDic->objectForKey("key1");
    log("{key1:%s}",pStr1->getCString());
    auto pInteger=(__Integer*)pDic->objectForKey("key3");
    log("{key3:%d}",pInteger->getValue());
    auto name=__String::create("zhangsan");
    auto pass=__String::create("password");
    auto dic=__Dictionary::create();
    dic->setObject(name, "NAME");
    dic->setObject(pass, "PWD");
    
}
Esempio n. 30
0
bool MapScene::init()
{
	if (!Layer::create())
	{
		return false;
	}
	/*╪стьмъф╛╣ьм╪*/

	switch (this->step)
	{
	case 1:{
			   std::string file = "Map.tmx";
			   auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str());
			   this->map = TMXTiledMap::createWithXML(str->getCString(), "");
			   TMXLayer* obscatle= map->layerNamed("obscatle");
			   obscatle->setVisible(false);
			   this->objGroup = map->getObjectGroup("Object");
			   this->addChild(map, 0);
	}break;
	case 2:{
			   std::string file = "MapStep2.tmx";
			   auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str());
			   this->map = TMXTiledMap::createWithXML(str->getCString(), "");
			   TMXLayer* obscatle = map->layerNamed("obscatle");
			   obscatle->setVisible(false);
			   this->objGroup = map->getObjectGroup("Object"); 
			   this->addChild(map, 0);

	}break;
	case 3:{
			   std::string file = "MapStep3.tmx";
			   auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str());
			   this->map = TMXTiledMap::createWithXML(str->getCString(), "");
			   TMXLayer* obscatle = map->layerNamed("obscatle");
			   obscatle->setVisible(false);
			   this->objGroup = map->getObjectGroup("Object");
			   this->addChild(map, 0);

	}break;
	default:
		break;
	}

	
	
	return true;
}