cocos2dx3.0 2048 Multi-function edition

Source: Internet
Author: User
Tags addchild

1.2048Project Description1.1.2048function Description

Realize the function of 2048 on mobile phone, and have the function that can delete any block, undo function, Exit Auto Save, start automatic loading function.

1.2.2048the required technology

Userdefult Save the file, save the chessboard information, eliminate the core algorithm


2.2048Run the process

3.2048Detailed Design3.1Block class

The game is a game composed of 4*4 blocks, first of all the movable block is an entity, by the Block manager Unified management of their actions (move, disappear).

Class Csquare:p ublic node{public:csquare (); ~csquare (); virtual bool init (); Create_func (csquare); void Showat (int irow,int icol,int iNum);//Where to show void MoveTo (int iRow, int icol, bool BENDALIVEFLG, En_ Move_dir endir);//The block moves to where void setinumdoubleandshow ();//make its own score * *, and show out void SetPos (int irow,int icol);//Fusion, Position to change void Animationscaleadd ();//Add Zoom animation effect bool Clickjudge (point pot);//Click to determine void Scalewhendel ();//Add animation private when deleting: Cc_synthesize (int, m_inum, iNum);//The level of the block relates to the display 0,2,4,8...cc_synthesize (layercolor*, M_laybackground, Laybackground) ;//block background, use background layer cc_synthesize (label*,m_labvalue,labvalue),///block to display the numeric value, with the level is bound cc_synthesize (int, m_irow, iRow); /row cc_synthesize (int, m_icol, icol);//column};

3.1.1the first flash of a blockShowat
/************************************************************ function: Blocks are displayed in the specified position parameter: The row number is converted to the real world coordinates, the origin is in the lower left corner of the *********** /void Csquare::showat (int iRow, int icol,int iNum) {//according to M_ INum create different underlying colors switch (m_inum) ... m_laybackground->setposition (Point (0,0)); This->addchild (m_ Laybackground,layer_first); M_labvalue->setposition (Point (SQUARE_WIDE/2, SQUARE_HIGH/2));m_labValue-> SetString (Value (iNum). asstring ());//Set each block above the number shown m_laybackground->addchild (M_labvalue, Layer_first);}
3.1.2change of block position
/************************************************************ function: Position instantaneous change ***************************************** /void csquare::setpos (int iRow, int icol) {this->setposition (point (X_init + icol* (square_wide + Crood_int), Y_init + irow* (Square_high + crood_int));}

Whenever a block moves successfully, it changes m_irow,m_icol, and when it determines that it is m_inum with the adjacent block , it will delete itself. When the delete button is pressed, if the block is pressed, the block is deleted.

3.2Block Management class

The Block manager has a member variable container vector<csquare*> m_listsquare manages all occurrences of the block on the map.

Class Csquaremgr:p ublic node{public:struct smapinf//lattice struct {int inum;//fractional int index;//on each grid with index};struct Sgameinf Game info contains lattice with current game score {int iscore; Smapinf Strmap[row_max][col_max];}; Csquaremgr (); ~csquaremgr (); Create_func (csquaremgr); virtual bool init (); void Initrestart (); void Tdamapinfinit ();//Initialize map information two-dimensional array void Listsquareremoveall ();//clear all block elements void Test ();//test lay down the first lattice void newsquarecreate ();//Generate new block void touchdeal ();//Touch Response En_ Move_dir Touchdirjudge (Point Potbegan, point potend);//Determine the sliding direction bool Squaresmovebydir (En_move_dir endir);// The movement of all squares in the direction of bool Squaresmoveup (); bool Squaresmovedown (); bool Squaresmoveright (); bool Squaresmoveleft (); bool Gameoverjudge ();//Judge the game by the end of void Onnotifydelaftermove (ref* pData);//After the response block Fusion action is finished, remove void ONNOTIFYCHANGEDELFLG from the list (Ref * pData);//change touch delete state void Onnotifyregret (ref* pData);//Response undo notify void Twosquarefuse (int irow,int icol,int Irowafter,int Icolafter);//two blocks fused, with the latter a block fraction of *2void squaremovetoblank (int iRow, int icol, int irowafter, int icolafter);// A block moves csquare* findwhichc to a blank blockLick (point pot);//find which block is clicked Void Squaredel (Point pot);//delete the selected block void Mapinfremoveall ();//delete all map information mapvoid Mapinfstore ( );//save map Information void Readgameinffromjson ();//Read data from json file void Storegameinftojson ();//save game information to Jsonvoid Highscorechange (); /change the highest score function void Xmlinit ();//Initialize XML, create various East void Storegameinftoxml ();//save game Information data to XML private:vector<csquare*> m_ listsquare;//saves the container of all moving blocks point m_potbegan;//the start position of the button m_potend;//the end position of the button cc_synthesize (bool, M_BDELFLG, BDELFLG); Smapinf m_strmapinf[row_max][col_max];//The structure of the lattice on the map std::vector<sgameinf> m_vecgameinf;//game Information container for undo};

3.2.1member Variable Description

Vector<csquare*> M_listsquare: Whenever a new block is generated, it is stored in the container. When a block disappears, remove it from the container.

Smapinf M_strmapinf[row_max][col_max]: Record the index of each lattice on the map, and if there is a block on that grid, the block is recorded in the m_listsquare . No block, the value is -1.

Std::vector<sgameinf> M_vecgameinf: Game information container for Undo. The inside sgameinf encapsulates the score generated after each move, as well as the board information that was changed after the move.

3.2.2UserDefultRead Game Information

The main point is to read the highest score, last played scores, and board information.

int iindexinvecsquare = 0;for (int iRow = 0; IRow < Row_max; irow++)//Read map information {for (int icol = 0; icol < Col_max; icol + +) {int index = IRow * 4 + icol;std::string Sindex = Value (index). asstring (); int iNum = Getintfromxml (Sindex.c_str ()); if ( INum! = 0) {csquare* objsquare = Csquare::create (); Objsquare->showat (IRow, Icol, INum); This->addchild (Objsquare) ; M_listsquare.pushback (objsquare); m_strmapinf[irow][icol].index = Iindexinvecsquare++;m_strmapinf[irow][icol]. INum = INum;}}}

Description: When reading the board information, scan the entireUserdefultfrom the "0"to" the"ofKey(the corresponding position on the board), when the value is not0, indicating that there is a block at that location, and that the score is itsvalue. So1.Create a new block, appear in the position, and put itsM_inumReset toINum, specifically seeShowatfunction;2.Press the new block into theM_listsquare;3.m_strmapinf[irow][icol].indexthe index is set to the corresponding value,M_strmapinf[irow][icol].inumset toINum. This completes loading information for the last game when it is started. Similarly, when the game exits, save the map information toUserdefult.


3.2.3Slide Direction judgment

Touch listening, when the finger touch the screen to get the coordinates of the position M_potbegan, the finger left the screen when the end of the position m_potend, through the direction of the decision function The Touchdirjudge gets the direction of the slide.

3.2.4Block moving core algorithm

1. A block moves toward the adjacent blank block


/************************************************************ function: A block moves to a blank block ********************************** /void csquaremgr::squaremovetoblank (int iRow, int icol, int irowafter, int icolafter) {m_ Strmapinf[irowafter][icolafter].index = M_strmapinf[irow][icol].index;m_strmapinf[irowafter][icolafter].inum = m_ strmapinf[irow][icol].inum;m_listsquare.at (M_strmapinf[irow][icol].index)->moveto (IRowAfter, IColAfter, True, Dir_left);//The original position of the block coordinates moved to the previous empty position M_strmapinf[irow][icol].index = -1;//in-situ plot information block self-clear 0 m_strmapinf[irow][icol].inum = 0;}

Description:iRow,icol is the coordinate before the move (actually the coordinates of the corresponding two-dimensional array),irowafter, The Icolafter is the coordinates after the move. After moving, the value of the M_strmapinf in the two-dimensional array structure of the map information is changed, and the values in the m_listsquare container are obtained according to the index on the position before moving . Call its moveTo function again to make the block move. After moving the map information of the current location to clear 0 processing.

1. A block moves to a block adjacent to the same score

/************************************************************ function: Two blocks fused, with the latter a block fraction *2**************************** /void csquaremgr::twosquarefuse (int iRow, int icol, int irowafter, int icolafter) {m_ listsquare.at (M_strmapinf[irowafter][icolafter].index)->setinumdoubleandshow ();//previous block score *2m_strmapinf[irow][ Icol].inum = 0;m_strmapinf[irowafter][icolafter].inum *= 2;int icurindex = m_strmapinf[irow][icol].index;// Map two-dimensional array record index number m_listsquare.at (M_strmapinf[irow][icol].index)->removefromparentandcleanup (true); m_ Listsquare.erase (M_strmapinf[irow][icol].index); for (int i = 0, i < Row_max; i++) {for (int j = 0; J < Col_max; J + +) { if (M_strmapinf[i][j].index >= icurindex) {m_strmapinf[i][j].index-= 1;}}} M_strmapinf[irow][icol].index =-1;}

Neighboring fractional values the same block object's score,at the same time, the map information of the neighboring location scores * *, then the current block is eliminated, and all the index values on the map information after the current block index are 1 , because after the deletion of an object inside the M_listsquare, more than one index will occur -1. This is to synchronize the map information with the block container corresponding.

1. All blocks move in the specified direction

Here's an example of moving up the direction.

/************************************************************ function: All blocks move up return value: Move Success * * /bool Csquaremgr::squaresmoveup () {bool BHAVEMOVEFLG = false;for (int icol = 0; icol < Col_max; icol++) {for (int iRow = row_max-1; iRow >= 0; irow--)//scan from top down {if (m_strmap Inf[irow][icol].index >= 0)//If the scan to the current block has a value, it is going to be moved by processing {for (int irowup = IRow; irowup < row_max-1; irowup++)// Scan up from the current block because it is moving up {if (-1 = = M_strmapinf[irowup+1][icol].index)//The previous of the current block is-1, indicating that the previous block is not, the next judgment statement is written in the previous {Squaremovetoblank ( Irowup, Icol, irowup + 1, icol); BHAVEMOVEFLG = true;//produced a move}else//the previous non-1 null {int icurnum = m_listsquare.at (m_strmapinf) of the current block [Irowup] [Icol].index)->getinum ();//Get the current block's score int iupnum = m_listsquare.at (m_strmapinf[irowup + 1][icol].index)->getiNum ();//Get previous Courier Amount Score if (Icurnum = = iupnum)//two blocks of the same number {Twosquarefuse (irowup, Icol, irowup + 1, icol); BHAVEMOVEFLG = true;// The mobile}break;//has been found to block the above, no longer traverse}}}}}return bhavemoveflg;} 

Map two-dimensional array from bottom to top is line 0 , line 1 , line 2 , line 3 , from left to right is section 0 columns, section 1 , column 2 , column 3 . When all blocks are moving upwards:

A scan all the columns from left to right, then scan all rows from top to bottom, the Current position value is not 0in the map information M_strmapinf,indicating the current position has a block, record the current position.

B scans up from the current position and calls Quaremovetoblank when the upper adjacent block is empty

C When the previous neighboring block is not empty, determine if their values are equal, and if they are equal, execute the twosquarefuse function

3.2.5block Delete Implementation
/************************************************************ function: Delete the selected block **************************************** /void Csquaremgr::squaredel (Point pot) {csquare* Objsquare = Findwhichclick (pot); if (Objsquare = = NULL) return;else//a square in the description point {objsquare->stopallactions (); int iRow = Objsquare->getirow (); int icol = objsquare- >geticol (); Objsquare->removefromparentandcleanup (true); M_listsquare.eraseobject (objSquare); int iCurIndex = m_strmapinf[irow][icol].index;//Map the index number of the two-dimensional array record is more than 1for in the list (int i = 0; i < Row_max; i++) for (int j = 0; j < Col_max; J + +) M_strmapinf[irow][icol].index = -1;m_strmapinf[irow][icol].inum = 0;}}

Note: In the delete state, if clicked to a corresponding piece, first to remove it from the parent node (that is no longer displayed), and then removed from the Block container. Cycle through the map information, delete the corresponding location of the data, and the map information in the index behind this block to 1.

3.2.6The realization of the regret step function

After each move, save the current map information and the current score to the game information structure.

/************************************************************ function: Save map information ***************************************** /void Csquaremgr::mapinfstore () {sgameinf Strgame;int iscore = cglobalcomm::getinstance () Getiscore (); strgame.iscore = iscore;for (int iRow = 0; IRow < Row_max; irow++) {for (int icol = 0; icol < Col_max; IC ol++) {Strgame.strmap[irow][icol].index = M_strmapinf[irow][icol].index;strgame.strmap[irow][icol].inum = m_ Strmapinf[irow][icol].inum;}} M_vecgameinf.push_back (strgame);}

When the regret step button is pressed:1. clear all the blocks on the map, map information Two-dimensional array initialization, delete the last element of the game information container; 2. Remove the last element of the game information, assign the score to the corresponding value, rearrange the blocks on the map according to the map information taken out, and update the map information at the same time. Shown in the following list of programs.

/************************************************************ function: Response undo Notification ***************************************** /void Csquaremgr::onnotifyregret (ref* pData) {int index = 0;int istoresize = m_vecgameinf.size (); if ( Istoresize > 1) {listsquareremoveall ();//emptying the board already has a lattice container tdamapinfinit ();//emptying the two-dimensional array on the keyboard m_vecgameinf.pop_back (); Sgameinf strgame = M_vecgameinf.back ();//get last element int iscore = Strgame.iscore; Cglobalcomm::getinstance ()->setiscore (iscore); Notify->postnotification (Notify_setscore, (ref*) 0); for (int. IRow = 0; IRow < Row_max; irow++) {for (int icol = 0; iCo L < Col_max; icol++) {if (Strgame.strmap[irow][icol].inum! = 0) {int iNum = Strgame.strmap[irow][icol].inum; csquare* Objsquare = Csquare::create () Objsquare->showat (IRow, Icol, INum); This->addchild (objsquare); m_ Listsquare.pushback (objsquare); m_strmapinf[irow][icol].index = Index++;m_strmapinf[irow][icol].inum = INum; .....................}

4.2048Run Results


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

cocos2dx3.0 2048 Multi-function edition

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.