Ejemplo n.º 1
0
 void ComicScene::showCurrentPage() {
     currentPage++;
     int textTag;
     int imageTag;
     int textMargin;
     if ( currentPage == 1 ) {
         imageTag = 1;
         textTag = 2;
         textMargin = Config::sharedConfig()->COMIC_MARGIN_TXT_A;
     } else if ( currentPage == 2 ) {
         imageTag = 3;
         textTag = 4;
         if (this->sequence == 1)
             textMargin = Config::sharedConfig()->COMIC_MARGIN_TXT_B;
         else if (this->sequence == 2)
             textMargin = Config::sharedConfig()->COMIC_MARGIN_TXT_E;
     } else if ( currentPage == 3) {
         imageTag = 5;
         textTag = 6;
         textMargin = Config::sharedConfig()->COMIC_MARGIN_TXT_C;
     }
     cleanPages();
     CCSprite* currentImage = (CCSprite*)this->getChildByTag(imageTag);
     CCLabelBMFont* currentText = (CCLabelBMFont*)this->getChildByTag(textTag);
     CCFiniteTimeAction* MoveText = CCMoveTo::actionWithDuration(2.0, Geometry::getScreenUpCenter(textMargin));
     CCActionInterval* wait = CCDelayTime::actionWithDuration(0.5);
     CCFiniteTimeAction* FadeImage = CCFadeIn::actionWithDuration(1.5);
     CCFiniteTimeAction* fancyMoveLeft = CCMoveBy::actionWithDuration(10, CCPoint(-5,0) );
     CCFiniteTimeAction* fancyMoveRight = CCMoveBy::actionWithDuration(10, CCPoint(5,0) );
     currentText->runAction(CCSequence::actions(MoveText, fancyMoveLeft, NULL));
     currentImage->runAction(CCSequence::actions(wait, FadeImage, fancyMoveRight, NULL));
 }
Ejemplo n.º 2
0
void PlayerBoard::playBloodAnimation(const char * text, ccColor3B color) {
    CCLabelBMFont* animationFont = CCLabelBMFont::create(text , "bmfont_hp.fnt");
    animationFont->setColor(color);

    this->addChild(animationFont, 1, ANIMATION_FONT_TAG);
    animationFont->runAction(CCSequence::create(CCMoveBy::create(1,ccp(0, 100)),::CCCallFunc::create(this, callfunc_selector(PlayerBoard::bloodAnimationCallback)), NULL));
}
void GameScene::showStartLabel() {
	CCLabelBMFont* startLabel = CCLabelBMFont::create("Touch to Start",
			FONT_TOUCH);
	startLabel->setPosition(
			ccp(g_visibleSize.width * 0.5, g_visibleSize.height * 0.5));
	startLabel->setTag(kTagStartLabel);
	this->addChild(startLabel);
	startLabel->runAction(Animations::topLabelAction());
}
Ejemplo n.º 4
0
void PointsManager::AnihilationHappened(int numberOfBlocks, cocos2d::CCPoint spot)
{
	// number of points that will be added depends upon the number of blocks that are being anihilated
	int addpoints = 0;
	// in case it's a power up
	if (numberOfBlocks == 1) {addpoints = 2;}
	// normal anihilation
	else if (numberOfBlocks == 3){addpoints = 10;}
	// 4-block anihilation
	else if (numberOfBlocks == 4){addpoints = 30;}
	// bigger anihiltion
	else if (numberOfBlocks == 5){addpoints = 60;}
	
	points += addpoints;
	// update number of points
	pointsToDisplay.initWithFormat("%i",points);
	pointsLabel->setCString(pointsToDisplay.getCString());


	// create a flying number on the screen
	CCString flyingNumberString;
	flyingNumberString.initWithFormat("%i",addpoints);
	CCLabelBMFont* flyingNumber = CCLabelBMFont::create(flyingNumberString.getCString(),"Assets/badab.fnt");
	flyingNumber->setColor(ccc3(0,0,0));
	flyingNumber->setPosition(spot);
	//put some nice actions on the number
	CCAction* sequence = CCSequence::create(CCDelayTime::actionWithDuration(1.0),
											  CCFadeOut::actionWithDuration(1.0f),
											  CCCallFuncO::actionWithTarget(this,callfuncO_selector(PointsManager::DeleteTextCallback),flyingNumber),
											  NULL);
	// add to node
	flyingNumber->runAction(sequence);
	flyingNumber->runAction(CCMoveBy::actionWithDuration(2.0f,ccp(0.0f,120.0f)));
	this->addChild(flyingNumber);

	if (isConnected)
	{
		// send update points to other player
		RakNet::BitStream BsOut;
		BsOut.Write((RakNet::MessageID)ID_GAME_NEW_POINTS);
		BsOut.Write((const char*)&points,sizeof(int));
		player2->Send(&BsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,player2Adress,false);
	}
}
Ejemplo n.º 5
0
//执行去除老数字的动画
void CFScoreBoard::doChangeAnimation(int change){
    char* buffer = new char[5];
    sprintf(buffer, "%d", change);
    CCLabelBMFont* pLabel =  CCLabelBMFont::labelWithString(buffer,"fonts/fonts.fnt");
    CCSize size = this->getContentSize();
    CCPoint lpos = ccp(size.width/2, size.height/2);
    pLabel->setPosition(lpos);
    this->addChild(pLabel);
    CCMoveTo* pMove = CCMoveTo::actionWithDuration(0.5, ccp(lpos.x, lpos.y-100));
    CCFadeTo* pFade = CCFadeTo::actionWithDuration(0.5, 0);
    CCFiniteTimeAction* pMoveFade = CCSpawn::actions(pMove, pFade,NULL);
    CCDelayTime* pDelay = CCDelayTime::actionWithDuration(0.5);
    CCCallFunc* pFunc = CCCallFuncN::actionWithTarget(this,callfuncN_selector(CFScoreBoard::freeLabel));
    CCAction* pSeq = CCSequence::actions(pMoveFade, pDelay, pFunc,NULL);
    pLabel->runAction(pSeq);
}
Ejemplo n.º 6
0
KDvoid CScrGame::onEnterTransitionDidFinish ( KDvoid )
{
	CCLayer::onEnterTransitionDidFinish ( );

    CCFiniteTimeAction*  pAction = CCSequence::create 
    (
        CCSpawn ::create ( CCScaleTo ::create ( 0.7f, 3 ), CCFadeIn::create  ( 0.7f ), KD_NULL ),
        CCRepeat::create ( CCSequence::create ( CCFadeOut::create ( 0.5f ), CCFadeIn ::create ( 0.5f ), KD_NULL ), 3 ),
        CCSpawn ::create ( CCScaleTo ::create ( 0.7f, 10 ), CCFadeOut::create ( 0.7f ), KD_NULL ),     
        CCCallFuncN::create ( this, callfuncN_selector ( CScrGame::onStart ) ), 
        CCCallFuncN::create ( this, callfuncN_selector ( CScrGame::onRemove ) ), 
        KD_NULL
    );
    
    CCLabelBMFont*   pStart = g_pResMgr->getLabel ( this, "Game Start !!!" );
    
    pStart->setPosition ( ccpMid ( CCDirector::sharedDirector ( )->getWinSize ( ) ) );
    pStart->setScale ( 10 );
    pStart->setOpacity ( 0 );
    pStart->runAction ( pAction );
}
Ejemplo n.º 7
0
void WordPuzzleLayer::didCorrectCharacterSelected(CCArray* wordIdxArray, int index)
{
	//맥스 콤보 업데이트
	combo++;
	if (report.maxCombo < combo) 
	{
		report.maxCombo = combo;
	}
	
	SimpleAudioEngine::sharedEngine()->playEffect("sound/main_card_popup.mp3");
	char buf[20];
	
	CCSprite* sprMultiplier;
	
	if (combo < 5) 
	{
		sprMultiplier = NULL;
		multiplier = 1;
	}
	else if (combo < 10)
	{
		// x2
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_double_01.png"));
#else
		sprMultiplier = CCSprite::spriteWithFile("game/effect/game_double_01.png");
#endif
		multiplier = 2;
	}
	else if (combo < 20)
	{
		// x4
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_double_02.png"));
#else
		sprMultiplier = CCSprite::spriteWithFile("game/effect/game_double_02.png");
#endif
		
		multiplier = 4;
	}
	else if (combo < 30)
	{
		// x8
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_double_03.png"));
#else
		sprMultiplier = CCSprite::spriteWithFile("game/effect/game_double_03.png");
#endif
		multiplier = 8;
	}
	else if (combo < 50)
	{
		// x16
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_double_04.png"));	
#else
		sprMultiplier = CCSprite::spriteWithFile("game/effect/game_double_04.png");	 
#endif
		
		multiplier = 16;
	}
	else 
	{
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_double_05.png"));	 
#else
		sprMultiplier = CCSprite::spriteWithFile("game/effect/game_double_05.png");	 
#endif
		
		multiplier = 32;
	}


#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
	CCSprite* label = CCSprite::spriteWithFile(__CONFIG_IMAGE_PATH_GAME__("effect/game_up.png"));
#else
	CCSprite* label = CCSprite::spriteWithFile("game/effect/game_up.png");
#endif
	
	label->setPosition(pointLabelPosition);
	this->addChild(label, 9999);
	
	if (sprMultiplier) 
	{
		sprMultiplier->setAnchorPoint(ccp(0,0.5));
#if (defined PD_IPHONE) || (defined ANDROID_PHONE)
		sprMultiplier->setPosition(ccp(label->getContentSize().width - 5,35));
#else
		sprMultiplier->setPosition(ccp(175,35));
#endif
		label->addChild(sprMultiplier);
	}


	
	label->setScale(0.2);
	
	CCEaseExponentialOut * fadeout = CCEaseExponentialOut::actionWithAction( CCActionTween::actionWithDuration(1.5,"opacity",255,0) );
	CCCallFuncN* callfunc = CCCallFuncN::actionWithTarget(this, callfuncN_selector(WordPuzzleLayer::onPointLabelFadeOut));
	
	label->runAction(CCMoveBy::actionWithDuration(0.8, ccp(0,100)));
	label->runAction(CCEaseBounceInOut::actionWithAction(CCScaleTo::actionWithDuration(0.3,labelScaleTo)));
	label->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(0.7),fadeout,callfunc, NULL));

	
	if (combo > 2)
	{
		sprintf(buf, "%dCombo",combo);
		CCLabelBMFont* lblCombo = (CCLabelBMFont*)getChildByTag(TAG_COMBO);
		
		CCEaseExponentialOut * fadeout = CCEaseExponentialOut::actionWithAction( CCActionTween::actionWithDuration(1.5,"opacity",255,0) );
		CCCallFuncN* callfunc = CCCallFuncN::actionWithTarget(this, callfuncN_selector(WordPuzzleLayer::onPointLabelFadeOut));
		
		if (lblCombo)
		{
			lblCombo->setString(buf);
			
			lblCombo->stopAllActions();
			lblCombo->setOpacity(255);
			lblCombo->setPosition(comboLabelPosition);

			lblCombo->setScale(0.2);			
			lblCombo->runAction(CCEaseBounceInOut::actionWithAction(CCScaleTo::actionWithDuration(0.3,labelScaleTo)));
			lblCombo->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(1.5),fadeout,callfunc, NULL));
		}
		else
		{
			lblCombo = CCLabelBMFont::labelWithString(buf, "font/combo.fnt");
			lblCombo->setPosition(comboLabelPosition);
			
			this->addChild(lblCombo, 9999, TAG_COMBO);
			
			lblCombo->setScale(0.2);			
			lblCombo->runAction(CCEaseBounceInOut::actionWithAction(CCScaleTo::actionWithDuration(0.3,labelScaleTo)));
			lblCombo->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(1.5),fadeout,callfunc, NULL));
		}
	}

		
	
}
Ejemplo n.º 8
0
void GameLayer::update(float dt)
{
    if(gameSuspended)
        return;
    
    // MainLayer shows the background with clouds that does just scrolls but does not interact
    MainLayer::update(dt);
    
    CCSpriteBatchNode* batchNode = dynamic_cast<CCSpriteBatchNode*>(getChildByTag(kSpriteManager));
    CCSprite* bird = dynamic_cast<CCSprite*>(batchNode->getChildByTag(kBird));
    
    bird_position.x += bird_velocity.x * dt;
    // birdLookingRight/Left is used to flip the bird in the right direction i.e. direction of the velocity
    // so the bird does not travel backwards
    if(bird_velocity.x < -30.0f && birdLookingRight)
    {
        birdLookingRight = false;
        
        // what is the point of setting scaleX?
        bird->setScaleX(-1.0f);
    }
    else if(bird_velocity.x > 30.0f && !birdLookingRight)
    {
        birdLookingRight = true;
        bird->setScaleX(1.0f);
    }
    
    CCSize bird_size = bird->getContentSize();
    float max_x = SCREEN_WIDTH + bird_size.width * 0.5f;
    float min_x = -bird_size.width * 0.5f;
    
    if(bird_position.x > max_x)
        bird_position.x = min_x;
    
    if(bird_position.x < min_x)
        bird_position.x = max_x;
    
    bird_velocity.y += bird_acceleration.y * dt;
    bird_position.y += bird_velocity.y * dt;
    
  
    // TODO: (fix this hack) - just set it so that every 20 frames, we decrease the percentage by 1
    // when the percentage goes below zero, the healthbar is finished and finish the game
    // We should show some animation that the health is over.
    fuelInTank--;
    if (fuelInTank%20 == 0)
    {
        pHealthBar->setPercentage(pHealthBar->getPercentage()-1.0);
        if (pHealthBar->getPercentage() <= 0)
        {
            _showHighScores();
        }
    }
    
    
    CCSprite* bonus = dynamic_cast<CCSprite*>(batchNode->getChildByTag(kBonusStartTag + currentBonusType));
    
    // check if the bonus node is visible
    if(bonus->isVisible())
    {
        // check if the bird and the bonus are colliding, if so, give the bird the bonus
        CCPoint bonus_position = bonus->getPosition();
        float range = 20.0f;
        if(bird_position.x > bonus_position.x - range &&
           bird_position.x < bonus_position.x + range &&
           bird_position.y > bonus_position.y - range &&
           bird_position.y < bonus_position.y + range)
        {
            // TODO: Our bonuses should be more rocket fuel or additional lives
            switch(currentBonusType)
            {
                case kBonus5:
                    score += 5000;
                    break;
                case kBonus10:
                    score += 10000;
                    break;
                case kBonus50:
                    score += 50000;
                    break;
                case kBonus100:
                    score += 100000;
                    break;
            }
            
            CCString* scoreStr = CCString::createWithFormat("%d", score);
            CCLabelBMFont* scoreLabel = dynamic_cast<CCLabelBMFont*>(getChildByTag(kScoreLabel));
            scoreLabel->setString(scoreStr->getCString());
            
            CCScaleTo* action1 = CCScaleTo::create(0.2f, 1.5f, 0.8f);
            CCScaleTo* action2 = CCScaleTo::create(0.2f, 1.0f, 1.0f);
            
            // What are CCScaleTo and CCSequence.. what do these actions do?
            // Likely, this just makes the bird move up very fast without it having to collide with anything
            CCSequence* action3 = CCSequence::create(action1, action2, action1, action2, action1, action2, NULL);
            scoreLabel->runAction(action3);

            // what does resetBonus do?
            _resetBonus();
            
            _superJump();
            
        }
    }
    
    int cloudTag;
    int platformTag;
    
    // bird collisions with platforms are detected only when the bird is falling down
    if(bird_velocity.y < 0)
    {
        for(platformTag = kPlatformsStartTag; platformTag < kPlatformsStartTag + K_NUM_PLATFORMS; platformTag++)
        {
            CCSprite* platform = dynamic_cast<CCSprite*>(batchNode->getChildByTag(platformTag));
            CCSize platform_size = platform->getContentSize();
            CCPoint platform_position = platform->getPosition();
            
            max_x = platform_position.x - platform_size.width * 0.5f - 10;
            min_x = platform_position.x + platform_size.width * 0.5f + 10;
            float min_y = platform_position.y + (platform_size.height + bird_size.height) * 0.5f - K_PLATFORM_TOP_PADDING;
            
            // check if the bird and the platform is colliding, if so, make the bird jump
            if(bird_position.x > max_x && bird_position.x < min_x &&
               bird_position.y > platform_position.y && bird_position.y < min_y)
                _jump();
        }
        
        // The game is endless in the original version.. when the bird falls down and is longer on the screen, call the game done and
        // show the high score screen
        if(bird_position.y < - bird_size.height)
            _showHighScores();
        
    }
    else if(bird_position.y > SCREEN_HEIGHT * 0.5f)
    {
        float delta = bird_position.y - SCREEN_HEIGHT * 0.5f;
        bird_position.y = SCREEN_HEIGHT * 0.5f;
        currentPlatformY -= delta;
        
        for(cloudTag = kCloudsStartTag; cloudTag < kCloudsStartTag + K_NUM_CLOUDS; cloudTag++)
        {
            CCSprite* cloud = dynamic_cast<CCSprite*>(batchNode->getChildByTag(cloudTag));
            CCPoint position = cloud->getPosition();
            position.y -= delta * cloud->getScaleY() * 0.8f;
            
            // assuming that the clouds in the background, when they have scrolled off the screen
            // reset them so that they will scroll in from the bottom
            if(position.y < -cloud->getContentSize().height * 0.5f)
            {
                currentCloudTag = cloudTag;
                resetCloud();
            }
            else
            {
                cloud->setPosition(position);
            }
        }
        

        for(platformTag = kPlatformsStartTag; platformTag < kPlatformsStartTag + K_NUM_PLATFORMS; platformTag++)
        {
            CCSprite* platform = dynamic_cast<CCSprite*>(batchNode->getChildByTag(platformTag));
            CCPoint position = platform->getPosition();
            position = ccp(position.x, position.y - delta);
            
            // If the platform just became invisible, reset it to just above the screen
            if(position.y < -platform->getContentSize().height * 0.5f)
            {
                currentPlatformTag = platformTag;
                _resetPlatform();
            }
            else
            {
                // If the platform is still visible, decrease its Y coordinates so it looks like the scene is scrolling
                platform->setPosition(position);
            }
        }

        
        CCSprite* exit = dynamic_cast<CCSprite*>(getChildByTag(kExit));
        if(exit->isVisible())
        {
            CCPoint position = exit->getPosition();
            // check if the bird and the exit are colliding, if so, finish the game
            float range = 20.0f;
            if(bird_position.x > position.x - range &&
               bird_position.x < position.x + range &&
               bird_position.y > position.y - range &&
               bird_position.y < position.y + range)
            {
                // TODO: (would be nice to show an animation when exiting)
                _showHighScores();
            }
            
            position.y -= delta;
            if(position.y < -exit->getContentSize().height*0.5)
            {
              // the exit just passed out of the screen... you should show a "Game Over... you lose" kind of thing here
               // TODO: show an animation or something like... you lose!!
                _showHighScores();
            }
            
            exit->setPosition(position);
            
        }
        
        // if the bonus was visible and is going to become invisible, reset it.
        if(bonus->isVisible())
        {
            CCPoint position = bonus->getPosition();
            position.y -= delta;
            if(position.y < -bonus->getContentSize().height * 0.5f)
            {
                _resetBonus();
            }
            else
            {
                bonus->setPosition(position);
            }
        }
        
        score += (int) delta;
        CCString* scoreStr = CCString::createWithFormat("%d", score);
        CCLabelBMFont* scoreLabel = dynamic_cast<CCLabelBMFont*>(getChildByTag(kScoreLabel));
        scoreLabel->setString(scoreStr->getCString());
    }
    
    // draw the bird at its new position
    bird->setPosition(bird_position);
}
void GameScene::step(float dt)
{
//	CCLog("Game::step");

	// Return if game suspended
	if(gameSuspended) return;

	// Get the bird sprite
	CCSprite *bird = (CCSprite*)getChildByTag(kBird);
	
	// Update the player x position based on velocity and delta time
	bird_pos.x += bird_vel.x * dt;
	
	// Flip the player based on it's x velocity and current looking direction
	if(bird_vel.x < -30.0f && birdLookingRight) 
	{
		birdLookingRight = false;
		bird->setScaleX(-1.0f);
	}
	else if (bird_vel.x > 30.0f && !birdLookingRight) 
	{
		birdLookingRight = true;
		bird->setScaleX(1.0f);
	}

	// Calculate the max and min x values for the bird
	// based on the screen and bird widths
	CCSize bird_size = bird->getContentSize();
	float max_x = (float)CCDirector::sharedDirector()->getWinSize().width - bird_size.width/2;
	float min_x = bird_size.width/2;
	
	// Limit the bird position based on max and min values allowed
	if(bird_pos.x>max_x) bird_pos.x = max_x;
	if(bird_pos.x<min_x) bird_pos.x = min_x;

	// Update the bird velocity based on acceleration and time
	bird_vel.y += bird_acc.y * dt;

	// Update the bird y positin based on velocity and time
	bird_pos.y += bird_vel.y * dt;
	
	////////////////////////////////////////////////////////////////////////////
	// Handle the bonus scoring
	CCSprite *bonus = (CCSprite*)getChildByTag(kBonusStartTag+currentBonusType);

	// If bonus is visible then see if the bird is within range to get the bonus
	if(bonus->isVisible() )
	{
		CCPoint bonus_pos = bonus->getPosition();
		float range = 20.0f;

		// If the player is within range of the bonus value then award the prize
		if(bird_pos.x > bonus_pos.x - range &&
		   bird_pos.x < bonus_pos.x + range &&
		   bird_pos.y > bonus_pos.y - range &&
		   bird_pos.y < bonus_pos.y + range ) 
		{
			// Update score based on bonus
			switch(currentBonusType) 
			{
				case kBonus5:   score += 5000;   break;
				case kBonus10:  score += 10000;  break;
				case kBonus50:  score += 50000;  break;
				case kBonus100: score += 100000; break;
			}

			// Build the score string to display
			char scoreStr[10] = {0};
			sprintf(scoreStr, "%d", score);
			CCLabelBMFont* scoreLabel = (CCLabelBMFont*) getChildByTag(kScoreLabel);
			scoreLabel->setString(scoreStr);

			// Highlight the score with some actions to celebrate the bonus win
			CCActionInterval* a1 = CCScaleTo::create(0.2f, 1.5f, 0.8f);
			CCActionInterval* a2 = CCScaleTo::create(0.2f, 1.0f, 1.0f);
			scoreLabel->runAction(CCSequence::create(a1, a2, a1, a2, a1, a2, NULL));

			// Reset the bonus to another platform
			resetBonus();
		}
	}

	// If the bird has stopped moving then make it jump from the platform it is on
	int t;
	if(bird_vel.y < 0) 
	{
		t = kPlatformsStartTag;

		// Search through all the platforms and compare the birds position with the platfor position
		for(t; t < kPlatformsStartTag + kNumPlatforms; t++) 
		{
			CCSprite *platform = (CCSprite*)getChildByTag(t);

			CCSize platform_size = platform->getContentSize();
			CCPoint platform_pos = platform->getPosition();
			
			max_x = platform_pos.x - platform_size.width/2 - 10;
			min_x = platform_pos.x + platform_size.width/2 + 10;

			float min_y = platform_pos.y + (platform_size.height+bird_size.height)/2 - kPlatformTopPadding;
			
			if(bird_pos.x > max_x &&
			   bird_pos.x < min_x &&
			   bird_pos.y > platform_pos.y &&
			   bird_pos.y < min_y) 
			{
				jump();
				break;	// Can only jump from one platform at a time to break out of the loop
			}
		}
	
		// If the bird has fallen below the screen then game over
		if(bird_pos.y < - bird_size.height/2) 
		{
			// [self showHighscores];   <== NEED TO IMPLEMENT THE HIGHTSCORE
			resetBird();	// Highscore not implmented yet so just keep on going.
		}
	} 
	else if ( bird_pos.y > ((float)CCDirector::sharedDirector()->getWinSize().height / 2)) 
	{
		// If bird position is greater than the middle of the screen then move the platforms
		// the difference between the bird y position and middle point of the screen
		float delta = bird_pos.y - ((float)CCDirector::sharedDirector()->getWinSize().height / 2);

		// Set the bird y position to the middle of the screen
		bird_pos.y = (float)CCDirector::sharedDirector()->getWinSize().height / 2;

		// Move the current platform y by the delta amount
		currentPlatformY -= delta;

		// Move the clouds vertically and reset if necessary
		t = kCloudsStartTag;
		for (t; t < kCloudsStartTag + kNumClouds; t++) 
		{
			CCSprite *cloud = (CCSprite*) getChildByTag(t);

			CCPoint pos = cloud->getPosition();

			// Calculate new position for cloud
			pos.y -= delta * cloud->getScaleY() * 0.8f;

			// If the cloud is off the screen then need to reset this cloud else set its new position
			if (pos.y < -cloud->getContentSize().height/2) 
			{
				currentCloudTag = t;
				resetCloud();
			} 
			else 
			{	// Update the new y position for the cloud.
				cloud->setPosition(pos);
			}
		}

		// Move the platforms vertically and reset if necessary
		t = kPlatformsStartTag;
		for (t; t < kPlatformsStartTag + kNumPlatforms; t++) 
		{
			CCSprite *platform = (CCSprite*)getChildByTag(t);
			
			CCPoint pos = platform->getPosition();

			// Calculate new position for platform
			pos = ccp(pos.x, pos.y - delta);

			// If the platform is off the screen then reset the platform else set its new position
			if(pos.y < - platform->getContentSize().height/2) 
			{
				currentPlatformTag = t;
				resetPlatform();
			} 
			else 
			{
				platform->setPosition(pos);
			}
		}

		// If the bonus is visible then adjust it's y position
		if(bonus->isVisible()) 
		{
			CCPoint pos = bonus->getPosition();

			// Calculate new position of bonus
			pos.y -= delta;
			
			// If the bonus is off the screen then reset the bonus else set its new position
			if(pos.y < -bonus->getContentSize().height/2 ) 
			{
				resetBonus();
			} 
			else 
			{
				bonus->setPosition(pos);
			}
		}
		
		// Update score based on how much the bird has moved
		score += (int)delta;

		// Display the new score value
		char scoreStr[10] = {0};
		sprintf(scoreStr, "%d", score);
		CCLabelBMFont* scoreLabel = (CCLabelBMFont*) getChildByTag(kScoreLabel);
		scoreLabel->setString(scoreStr);
	}

	// Set the birds position
	bird->setPosition(bird_pos);
}
Ejemplo n.º 10
0
void MeleeSystem::update(float dt) {
       
    CCArray * entities = this->entityManager->getAllEntitiesPosessingComponentOfClass("MeleeComponent");
    CCObject* object = NULL;
    CCARRAY_FOREACH(entities, object)
    {
        Entity* entity = (Entity*) object;
        RenderComponent* render = entity->render();
        MeleeComponent* melee = entity->melee();
        TeamComponent* team = entity->team();
        if (!render || !melee || !team) continue;
        
        bool aoeDamageCaused = false;
        CCArray * enemies = entity->getAllEntitiesOnTeam(OPPOSITE_TEAM(team->team),"RenderComponent");
        CCObject* temp = NULL;
        CCARRAY_FOREACH(enemies, temp){
            Entity* enemy = (Entity*) temp;
	        RenderComponent * enemyRender = enemy->render();
            HealthComponent * enemyHealth = enemy->health();
	     
            if (!enemyRender || !enemyHealth) continue;
 
			float distance = ccpDistance(render->node->getPosition(), enemyRender->node->getPosition());
			MonsterComponent* monsterCom = entity->monster();
            if (render->node->boundingBox().intersectsRect(enemyRender->node->boundingBox())
				||monsterCom && abs(distance) < monsterCom->monster->deck->fight.Range) {
                if (GetTickCount() - melee->_damage->lastDamageTime > melee->deck->fight.FireRate * 1000) {
                    CCPoint edge = ccp((render->node->getPosition().x+enemyRender->node->getPosition().x)/2,
						(render->node->getPosition().y+enemyRender->node->getPosition().y)/2);
					//make slow enemy
					MoveComponent* move = (MoveComponent*) enemy->move();
					if(move)
						move->velocity = ccpNormalize(move->velocity) ; 
#if SOUND
                    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(melee->deck->sound);
#endif
					
            

					MonsterComponent* enemyMonster = enemy->monster();
					if(enemyMonster)
					{
						CCPoint currrent = enemyRender->node->getPosition();
						//float scale = enemyRender->node->getScale();
						CCScaleTo* a = CCScaleBy::create(0.1f,1.5f);
						int ran = rand()%2;
						CCRotateTo* b = CCRotateTo::create(0.1f,ran?15:-15);
						//CCRotateTo* c = CCRotateTo::create(0.1f,-30);
						CCRotateTo* d = CCRotateTo::create(0.1f,0);
						CCScaleTo* e = CCScaleTo::create(0.1f,1.0f);
						CCSequence* sequence = CCSequence::create(a,b,d,e,NULL);
						enemyRender->node->runAction(sequence);
								
					}

					MonsterComponent* monster = entity->monster();
					if(monster)
					{
						entityFactory->createEffect(EffectType((int)monster->monsterType +4),edge);
					}
					if (melee->deck->fight.aoe) {
		                        aoeDamageCaused = true;
		                    } else {
		                        melee->_damage->lastDamageTime = GetTickCount();
		                    }
		                    enemyHealth->curHP -= melee->deck->fight.Damage;
					char temp[64];
					sprintf(temp, "%d", (int)melee->deck->fight.Damage);
			
					CCLabelBMFont* hitLabel = CCLabelBMFont::create(temp,"Courier_red.fnt");
					hitLabel->setPosition(edge);
					entityFactory->_batchNode->getParent()->addChild(hitLabel);
					CCScaleTo* scaleFrom = CCScaleTo::create(0.1f,1.5f);
					CCDelayTime* delay = CCDelayTime::create(0.1f);
					CCScaleTo* scaleTo = CCScaleTo::create(0.1f,1.0f);
					CCFiniteTimeAction* actionMoveDone = CCCallFuncN::create(this,callfuncN_selector(MeleeSystem::clean));

					CCSequence* sequence = CCSequence::create(scaleFrom,delay,scaleTo,delay,actionMoveDone,NULL);

					hitLabel->runAction(sequence);

                    if (enemyHealth->curHP < 0) {
                        enemyHealth->curHP = 0;
                    }
                    if (melee->_damage->destroySelf) {
                        render->node->removeFromParentAndCleanup(true);
                        //CCLog("Removing entity:%d, I am a bullet.",entity->_eid);
                        this->entityManager->removeEntity(entity);
                    }
                }
            }
        }
Ejemplo n.º 11
0
bool GameOverLayer::init()
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(!CCLayer::init());
		//停止背景音乐,播放gameover的音效
		if (CocosDenshion::SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying())
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
		}
		CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sound/game_over.mp3");

		CCSize winSize = CCDirector::sharedDirector()->getWinSize();

		//加载gameover_background
		CCSprite* background = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("gameover.png"));
		background->setPosition(ccp(winSize.width / 2, winSize.height / 2));
		this->addChild(background);

		//加载BackMenu
		CCSprite* normalBackToGame = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("btn_finish.png"));//正常状态下的按钮图片
		CCSprite* pressedBackToGame = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("btn_finish.png"));//按下状态下的按钮图片
		CCMenuItemImage* pBackItem = CCMenuItemImage::create();//创建menu的item
		pBackItem->initWithNormalSprite(normalBackToGame, pressedBackToGame, NULL, this, menu_selector(GameOverLayer::menuBackCallback));//设置
		pBackItem->setPosition(ccp(winSize.width - normalBackToGame->getContentSize().width / 2 - 10, normalBackToGame->getContentSize().height / 2 + 10));//位置
		CCMenu *menuBack = CCMenu::create(pBackItem, NULL);//创建menu并加入item
		menuBack->setPosition(Point::ZERO);//位置
		this->addChild(menuBack);//加入layer

		//加载score
		CCString* strScore = CCString::createWithFormat("%d", score);
		CCLabelBMFont* finalScore = CCLabelBMFont::create(strScore->_string.c_str(), "res/assets/font/font.fnt");
		finalScore->setColor(ccc3(143, 146, 147));
		finalScore->setPosition(ccp(winSize.width / 2, winSize.height / 2));
		this->addChild(finalScore);

		CCDelayTime* delay = CCDelayTime::create(1.0f);
		CCScaleTo* scalebig = CCScaleTo::create(1.0f, 3.0f);
		CCScaleTo* scalelittle = CCScaleTo::create(0.3f, 2.0f);
		CCCallFunc* showAD = CCCallFunc::create(this, callfunc_selector(GameOverLayer::showAD));
		CCFiniteTimeAction* sequence = CCSequence::create(delay, scalebig, scalelittle, showAD, NULL);
		finalScore->runAction(sequence);

		//加载历史最高分
		//CCLabelTTF* tip=CCLabelTTF::create("Congratulations! Your Score is","Monaco",20);
		//tip->setColor(ccc3(143,146,147));
		//tip->setPosition(ccp(finalScore->getPosition().x,finalScore->getPosition().y+finalScore->getContentSize().height+50));
		//this->addChild(tip);
		CCString* strHighestScore = CCString::createWithFormat("%d", highestHistoryScore);
		highestScore = CCLabelBMFont::create(strHighestScore->_string.c_str(), "res/assets/font/font.fnt");
		highestScore->setColor(ccc3(143, 146, 147));
		highestScore->setAnchorPoint(ccp(0, 0.5));//设置锚点,即为缩放等操作的发生点。
		highestScore->setPosition(ccp(140, winSize.height - 30));
		this->addChild(highestScore);
		//如果分数比最高分高,则更新最高分,并显示,播放动画
		if (score > highestHistoryScore)
		{
			CCUserDefault::sharedUserDefault()->setIntegerForKey("HighestScore", score);
			highestHistoryScore = score;
			CCDelayTime* delayChange = CCDelayTime::create(1.3f);
			CCMoveBy* moveOut = CCMoveBy::create(0.1f, ccp(0, 100));
			CCCallFuncN* beginChange = CCCallFuncN::create(this, callfuncN_selector(GameOverLayer::beginChangeHighestScore));
			CCMoveBy* moveIn = CCMoveBy::create(0.1f, ccp(0, -100));
			CCFiniteTimeAction* sequence = CCSequence::create(delayChange, moveOut, beginChange, moveIn, NULL);
			highestScore->runAction(sequence);
		}

		this->setKeypadEnabled(true);

		bRet = true;
	} while (0);
	return bRet;
}
Ejemplo n.º 12
0
void MainGameScene::update(float dt)
{

	// update game scene
	
	//update character
	mainCharacter->Update(dt);

	// update blocks
	//iterate through the list
	std::list<ColorBlock*>::iterator it;
	//lets just pretend that no more than 5 blocks will be deleted in the same frame

	std::list<ColorBlock*>::iterator toDelete[5];
	int amountToDelete = 0;
	for (it = blocksList.begin(); it != blocksList.end(); it++)
	{
		// only process if the block isn't dying
		if (!(*it)->GetDying())
		{
			// check if it's time to kill the block
			if ((*it)->getPositionY() > 650.0f || (*it)->getPositionY() < -85.0f ||
				(*it)->getPositionX() < -20.0f || (*it)->getPositionX() > 850.0f)
			{
				if(amountToDelete < 5)
				{
					toDelete[amountToDelete] = it;
					amountToDelete++;
				}
			}
			else
			{
				// dont process if the block is already connected with the character
				if (!(*it)->GetAttached())
				{
					// process colision detection
					b2ContactEdge* edge = (*it)->GetBody()->GetContactList();
					while (edge != NULL) // if == null, no more collisions
					{
						if (edge->contact->IsTouching())
						{
							// iterate through the list of contacts
							// if collided with character, don't delete
							if (((CCSprite*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->getTag() == CHARACTER_TAG ||
								((CCSprite*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->getTag() == CHARACTER_TAG)
							{
								// the block collided with character
								(*it)->AttachTo(mainCharacter->GetBody());
							}
							// check if it's a attached block, so attached to this one
							else if (((CCSprite*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->getTag() == BLOCK_TAG && 
								((CCSprite*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->getTag() == BLOCK_TAG)
							{
								// check which one is the IT
								// attached based on this
								if (edge->contact->GetFixtureA()->GetBody() == (*it)->GetBody())
								{
									// make sure it's already attached
									if(((ColorBlock*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->GetAttached() &&
										!((ColorBlock*)edge->contact->GetFixtureB()->GetBody()->GetUserData())->GetDying())
									{
										// attach on B fixture
										(*it)->AttachTo(edge->contact->GetFixtureB()->GetBody());
									}
								}
								else
								{
									if(((ColorBlock*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->GetAttached() &&
										!((ColorBlock*)edge->contact->GetFixtureA()->GetBody()->GetUserData())->GetDying())
									{
										// attach on A fixture
										(*it)->AttachTo(edge->contact->GetFixtureA()->GetBody());
									}
								}
							}
						}
						edge = edge->next; // go to the next colision
					}
				}
				// now process those which are already attached to the character body
				else
				{
					(*it)->BuildConnections(NULL, -1);

					// check if one of the attached blocks is on the death area
					if ((*it)->getPositionX() < 0.0f || (*it)->getPositionX() > 800.0f || 
						(*it)->getPositionY() > 600.0f || (*it)->getPositionY() < 0.0f)
					{
						if (isConnected)
						{
							//send gameover signal through network
							RakNet::BitStream BsOut;
							BsOut.Write((RakNet::MessageID)ID_GAME_PLAYER_LOST);
							player2->Send(&BsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,player2Adress,false);
						}
						// game over animation goes here
						// for now just call the next scene
						//CCDirector::sharedDirector()->replaceScene(CCTransitionProgressHorizontal::transitionWithDuration(1.0f,PointsScene::scene()));
						CCDirector::sharedDirector()->pushScene(CCTransitionProgressHorizontal::transitionWithDuration(1.0f,PointsScene::scene()));
						// to prevent thousands of scenes being created
						this->unscheduleUpdate();
					}

				}
			}
		}
		else
		{
			// check if it's time to be deleted
			if((*it)->getOpacity() == 0)
			{
				if(amountToDelete < 5)
				{
					toDelete[amountToDelete] = it;
					amountToDelete++;
				}
			}
		}
	}

	// delete dead ones
	for (int i = 0; i < amountToDelete; i++)
	{
		// remove from batch
		blocksBatch->removeChild((*toDelete[i]),true);
		// remove from local list
		blocksList.erase(toDelete[i]);
	}

	// update physics engine
	box2DWorld->Step(dt,20,20);
	
	// update raknet
	if (isConnected)
	{
		// receive packets
		RakNet::Packet* packet;
		for (packet = player2->Receive();packet;player2->DeallocatePacket(packet),packet=player2->Receive())
		{
			// only process a packet that came from the other player
			if (packet->systemAddress == player2Adress)
			{
				// player disconnected
				if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || 
					packet->data[0] == ID_CONNECTION_LOST)
				{
					isConnected = false;
					// put some warning on the screen
					//create a text and make it goes up
					CCLabelBMFont* discWarning = CCLabelBMFont::create("Your opponent just disconnected","Assets/badab.fnt");
					discWarning->setColor(ccc3(255,0,0));
					discWarning->setPosition(ccp(400.0f,-20.0f));
					CCSequence* warningSequence = CCSequence::create(CCMoveTo::create(4.0f,ccp(400.0f,200.0f)),
						CCCallFuncO::create(this,callfuncO_selector(MainGameScene::DeleteDisctionnectionWarning),discWarning));
					discWarning->runAction(warningSequence);
					discWarning->runAction(CCFadeOut::create(4.0f));//fade
					this->addChild(discWarning,1000);
				}
				// other player just lost
				else if (packet->data[0] == ID_GAME_PLAYER_LOST)
				{
					otherGameOver = true;
				}
				else if (packet->data[0] == ID_GAME_NEW_POINTS)
				{
					// read new points from the other player
					int rs = 0;
					RakNet::BitStream bsIn(packet->data,packet->length,false);
					bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
					bsIn.Read((char*)&rs,sizeof(int));
					pointsManager->SetP2Points(rs);
				}
				else if(packet->data[0] == ID_GAME_INIT_SWAP)
				{
					// other player will swap, prepare
					ChangeScreenSpecial* change = ChangeScreenSpecial::create();
					this->addChild(change,701);
					change->ExecuteActual();
					change->setTag(978);
				}
				else if(packet->data[0] == ID_GAME_SWAP_SCREENS)
				{
					// received information
					std::vector<BlockInformation> received;
					RakNet::BitStream bsIn(packet->data,packet->length,false);
					bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
					// number of blocks within the package
					int size = 0;
					bsIn.Read((char*)&size,sizeof(int));
					BlockInformation* reci = new BlockInformation[size];
					bsIn.Read((char*)reci,sizeof(BlockInformation) * size);
					// put on the received vector
					for (int p = 0; p < size; p++)
					{
						received.push_back(reci[p]);
					}
					delete reci;
					// now change the blocks
					//delete all non-dying blocks
					std::list<ColorBlock*>::iterator it;
					std::vector<ColorBlock*> toDelete;
					for (it = blocksList.begin(); it != blocksList.end(); it++)
					{
						if (!(*it)->GetDying())
						{
							toDelete.push_back(*it);
						}
					}
					//delete them
					for (int c = 0; c < toDelete.size();c++)
					{
						blocksBatch->removeChild(toDelete[c],true);
						blocksList.remove(toDelete[c]);
					}
					//put them back

					for (int c = 0; c < received.size(); c++)
					{
						// create block on a random location
						ColorBlock* newBlock = ColorBlock::create("Assets/block.png");
						// unattached blocks have 50% opacity
						newBlock->setOpacity(127);

						newBlock->setPositionX(received[c].posX);
						newBlock->setPositionY(received[c].posY);

						// add as a child to the batch
						blocksBatch->addChild(newBlock);
						//mainScene->addChild(newBlock);

						newBlock->InitInWorld(box2DWorld);

						if (received[c].color == BLOCK_GREEN)
						{
							newBlock->setColor(ccc3(0,255,0));
						}
						else if (received[c].color == BLOCK_RED)
						{
							newBlock->setColor(ccc3(255,0,0));
						}
						else if (received[c].color == BLOCK_BLUE)
						{
							newBlock->setColor(ccc3(0,0,255));
						}
						// add to local list
						blocksList.push_back(newBlock);
					}
				}
			}
		}
	}
}