Cocos2d-X games -- do not step on the white Block

Source: Internet
Author: User
Tags getcolor

Cocos2d-X games -- do not step on the white Block

I learned two months of cocos2d-x, a few days ago I watched the teaching video, followed by a small game-Don't step on the white block.

Let's talk about how I wrote this project today. The logic is a bit messy. I don't know what to understand ....

First, this game has two scenarios: the first scenario, and the second scenario, the failure scenario.

The scenario is as follows:

There are three types of blocks in the initial scenario:

Start block (yellow, with Start Game) normal block (black and white block) End Block (green, with You Win)

The starting block is as follows:

The normal block is as follows:

The ending block is as follows:

Because this game is based on blocks, these blocks can be collectively referred toAbstract BlockTherefore, you need to write a create method for the block as follows:

static Block * create(Size size,Color3B color,String str,                      float strSize,Color3B strColor);

There are five parameters in this function. The first parameter is the block size, the second parameter is the block color, and the third parameter is the string str to be displayed on the block; the fourth parameter is the strSize of the string, and the fifth parameter is the strColor of the string.

When creating a block, we need to determine the block size, as shown in figure

Start block: the width is, WinSize. width; High, WinSize. height/4Normal block: the width is, WinSize. width/4; High, WinSize. height/4
Divide 4Is to divide the screen 4× 4Normal block end block: the width is, WinSize. width; High, WinSize. height

Note:The winSize here is the screen size.

Now write the Block class:

# Ifndef _ Block_H _ # define _ Block_H _ # include "cocos2d. h "USING_NS_CC; class Block: public Sprite {public: static Block * create (Size size, Color3B color, String str, float strSize, Color3B strColor); bool init (Size size Size, color3B color, String str, float strSize, Color3B strColor); // The static members in the class exist in the separate memory. // it already exists during definition, it does not belong to a certain object. It only belongs to this class of static Vector.
  
   
Vec; // used to store the created static Vector.
   
    
GetBlockVector (); // generate the get method and set method CC_SYNTHESIZE (int, _ LineIndex, LineIndex); // move the block down and clear void moveDownAndCleanUp () ;}; # endif
   
  

After writing the Block class, you can start writing.Game Logic.

The game starts from the very beginning, as long as the player clicks the Black Block game at the very beginning. Players can only click Black Blocks in sequence, that is, each time a Black Block is clicked at the bottom. As long as the player clicks the Black Block correctly, the Black Block that is clicked will become gray,
The row to be clicked will move down and add a new row above the screen. After a player clicks all the black blocks, the player wins and the final block appears. If the player clicks the white block, the game fails and switches Game failure scenarios.

The failure scenario is as follows:

Start the gameWe need to set the initial layout of the screen. You may have noticed that there isRow numberFunction <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> CC_SYNTHESIZE(int,_LineIndex,LineIndex);

Row numberThe function is usedSet(Set) andGetThe row number of the (get) block. The row number is only 0 to 3 rows on the screen,
As shown in

First, we need to add three functions: Start block, normal block, and end block.

Add the start block in the first row of the layout, and add the normal block in rows 1, 2, and 3.
After clicking all the black blocks, add the ending blocks.

The function for adding the start block is as follows:

Void LayerGame: addStartLineBlock () {Size startBlockSize = Size (winSize. width, winSize. height/4); Block * B = Block: create (startBlockSize, Color3B: YELLOW, "Start Game", 30, Color3B: BLUE ); b-> setPosition (Point (); this-> addChild (B); B-> setLineIndex (0); // set the row number to 0 _ lineCount ++; // The number of rows + 1. Note that the row number is not a line number. The row number is only 0, 1, 3, and the number of rows can be increased all the time}

The function for adding a normal block is as follows:

Void LayerGame: addNormalLineBlocks (int LineIndex) {Size normalBlockSize = Size (winSize. width/4, winSize. height/4); int idx = rand () % 4; // obtain a random value between 0 and 3 for (int I = 0; I <4; I ++) // Add a row, that is, four {Block * B = Block: create (normalBlockSize, I = idx? Color3B: BLACK: Color3B: WHITE,/* set the BLACK and WHITE blocks */"", 30, Color3B: WHITE); B-> setLineIndex (LineIndex ); // set the position B-> setPosition (Point (I * winSize. width/4, LineIndex * winSize. height/4); this-> addChild (B);} _ lineCount ++; // number of rows + 1}

The function for adding an ending block is as follows:

Void LayerGame: addEndLineBlock () {Block * B = Block: create (winSize, Color3B: GREEN, "You Win! ", 50, Color3B: RED); B-> setAnchorPoint (Point (0, 0); B-> setPosition (Point (0, winSize. height); this-> addChild (B); B-> setLineIndex (4); _ lineCount ++; // number of rows + 1 // Add two buttons Again and Exit LabelBMFont * bm = LabelBMFont: create ("Again", "fonts/arial-unicode-26.fnt"); LabelBMFont * bm1 = LabelBMFont :: create ("Exit", "fonts/arial-unicode-26.fnt"); MenuItem * again = MenuItemLabel: create (bm); MenuItem * ext = MenuItemLabel: create (bm1 ); again-> setTarget (this, menu_selector (LayerGame: tryAgainCallback); ext-> setTarget (this, menu_selector (LayerGame: exitCallback); Menu * menu = Menu :: create (again, ext, NULL); B-> addChild (menu); menu-> setPosition (Point: ZERO ); again-> setPosition (Point (again-> getBoundingBox (). size. width/2, winSize. height-again-> getBoundingBox (). size. height/2); ext-> setPosition (Point (winSize. width-ext-> getBoundingBox (). size. width/2, winSize. height-ext-> getBoundingBox (). size. height/2 ));}

Now, we can set the initial layout. Write a StatGame function as follows:

void LayerGame::startGame(){    addStartLineBlock();    addNormalLineBlocks(1);    addNormalLineBlocks(2);    addNormalLineBlocks(3);}

Now I have the first layout, you can start to write Click Event, Because I watch the video tutorial is the version of the cocos2d-x3.0 below, and I use the version of 3.0, therefore, it makes a mix of the versions below 3.0 and 3.0 that I wrote ......

First, set the touch listener:

// Version 3.0 auto listener = listener: create (); listener-> setSwallowTouches (true); // swallowed listener-> onTouchBegan = CC_CALLBACK_2 (LayerGame: onTouchBegan, this ); this-> _ eventDispatcher-> addEventListenerWithSceneGraphPriority (listener, this );

Then, write the Click Event function:

Bool LayerGame: onTouchBegan (Touch * touch, Event * unused_event) {// traverses all blocks in vec. C ++ 11 Method for (auto obj: Block: getBlockVector ()) {Block * B = (Block *) obj; // determines whether to click the Block and the row number is 1 if (B-> boundingBox (). containsPoint (touch-> getLocation () & B-> getLineIndex () = 1) {if (B-> getColor () = Color3B: BLACK) // point to the Black Block {// play sound SimpleAudioEngine: getInstance ()-> playEffect ("onclick.wav"); // start timing this-> startTimer (); // GRAY the Black Block to be clicked B-> setColor (Color3B: GRAY); // this-> moveDown ();} else if (B-> getColor () = Color3B: GREEN) // point to the end block {// play sound effects SimpleAudioEngine: getInstance () -> playEffect ("gamewin.wav"); // terminate timing this-> stopTimer (); // move this-> moveDown ();} else if (B-> getColor () = Color3B: WHITE) // point to the WHITE block {// play the sound SimpleAudioEngine: getInstance ()-> playEffect ("wrong.wav"); Scene * scene = LayerFailed :: scene (); Director: getInstance ()-> replaceScene (scene); // switch to failure scenario} break ;}} return false ;}

Now let's take a look atMoveDownFunction:

Void LayerGame: moveDown () {if (this-> getLineCount () <20) // if the row number is smaller than 20 {this-> addNormalLineBlocks (4 ); // Add a normal row and set the row number to 4} else if (! ShowEnd) // If the row number is not less than 20 and the flag showEnd is false {this-> addEndLineBlock (); // Add the end block showEnd = true; // set showEnd to true} for (auto obj: Block: getBlockVector () // traverse all blocks in this row {Block * B = (Block *) obj; b-> moveDownAndCleanUp (); // move them down and delete them from the rendering tree }}

MoveDownThere is another functionMoveDownAndCleanUpFunction. We wrote it in the Block class.

Void Block: moveDownAndCleanUp () {// The row number minus 1. Because this function is in the for loop of the moveDown function, all the row numbers in vec are reduced by 1 _ LineIndex --; // move down (time, shift distance) MoveTo * to = MoveTo: create (0.01, Point (getPositionX (), getPositionY ()-winSize. height/4); this-> runAction (to); // execute the action if (_ LineIndex <0) // determine whether the current row number is smaller than 0 {// get this-> removeFromParentAndCleanup (true) from the rendering tree; // Delete the current block vec from vec. eraseObject (this );}}

AboveMoveDownFunctions andMoveDownAndCleanUpThe function is used to achieve the scrolling effect when a player clicks.

FrontIt is about the successful completion of the game. The following describes the failure of the game-the failure of the game when the white block is clicked.
We usedIfStatement to determine whether the white block is clicked:

else if (b->getColor() == Color3B::WHITE){    SimpleAudioEngine::getInstance()->playEffect("wrong.wav");    Scene * scene = LayerFailed::scene();    Director::getInstance()->replaceScene(scene);}

If you step on the white block, the wrong sound is played and the game fails to be switched.

SupplementWe also addedTiming FunctionAndPlay MusicFunctions

First, let's talk about the timing function:

1. First set a flag and a variable

Long startTime = 0; // all variables bool isRunning = false; // global variables

2. Create a Label to display the time.

LabelTTF * ttf = LabelTTF: create ("0.000", "Courier New", 30); // ttf is the global variable ttf-> setZOrder (100 ); ttf-> setPosition (Point (winSize. width/2, winSize. height-20); ttf-> setColor (Color3B: BLUE); this-> addChild (ttf );

3. Then write two function timers.StartTimerAndStopTimer

Void LayerGame: startTimer () {if (! IsRunning) // set the flag and only run it once {this-> scheduleUpdate (); // start frame loop timer, each frame calls the default update function startTime = clock (); // gets the current system time isRunning = true ;}} void LayerGame: stopTimer () {if (isRunning) // run it only once {this-> unscheduleUpdate (); // disable the frame loop timer }}

4. ThenStartTimerAndStopTimerPut in the touch Response FunctionIfCondition

If (B-> getColor () = Color3B: BLACK) {SimpleAudioEngine: getInstance ()-> playEffect ("onclick.wav"); this-> startTimer (); // enable the timer B-> setColor (Color3B: GRAY); this-> moveDown ();} else if (B-> getColor () = Color3B: GREEN) {SimpleAudioEngine: getInstance ()-> playEffect ("gamewin.wav"); this-> stopTimer (); // disable the timer this-> moveDown ();}

Let's talk about the function of playing music:

1. First include the header file

#include "SimpleAudioEngine.h"using namespace CocosDenshion;

2. Add the audio playback code to the corresponding part.

If (B-> getColor () = Color3B: BLACK) {// play click sound SimpleAudioEngine: getInstance ()-> playEffect ("onclick.wav "); this-> startTimer (); B-> setColor (Color3B: GRAY); this-> moveDown ();} else if (B-> getColor () = Color3B :: GREEN) {// play the victory sound SimpleAudioEngine: getInstance ()-> playEffect ("gamewin.wav"); this-> stopTimer (); this-> moveDown ();} else if (B-> getColor () = Color3B: WHITE) {// playback failure sound SimpleAudioEngine: getInstance ()-> playEffect ("wrong.wav "); scene * scene = LayerFailed: scene (); Director: getInstance ()-> replaceScene (scene );}

Well, it's almost done here. Some code snippets are provided above. To view the complete code, please go:(Github) do not step on the white Block

It is a bit messy. If there are any deficiencies, please make an ax.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.