CoinFlip of quick-cocos2d-x Learning Series

Source: Internet
Author: User

CoinFlip of quick-cocos2d-x Learning Series

 

1. Code Logic

The start part is basically the same as the other parts. It enters from the main. lua file and reaches the MyApp. lua file. (MyApp inherits from cc. mvc. AppBase)

The main functions are run, enterMenuScene, enterMoreGamesScene, enterChooseLevelScene, and playLevel.

(The logic structure of the program is slightly more complex than before: there are multiple folders data, scenes, ui, views.

Data is used to store the level information, the ui is a UI-related file, scenes is four scenario files, and views is used to display related functions and classes)

1.1.1 Run

This function adds the res file in the program search path, loads the PNG file related to the game, loads the sound file, and then calls the program self: enterMenuScene ().

 

2.1.1 enterMenuScene

The function is called as follows:

Self: enterScene (MenuScene, nil, fade, 0.6, display. COLOR_WHITE)

This enterScene function inherits from the parent class.

Directly go to the MenuScene scenario, which is defined in the app/scenes/MenuScene. lua file.

 

3.1.1 nterMoreGamesScene

The function is called as follows:

 

Self: enterScene (MoreGamesScene, nil, fade, 0.6, display. COLOR_WHITE)

Others same as above

4.1.1 enterChooseLevelScene

 

The function is called as follows:

Self: enterScene (ChooseLevelScene, nil, fade, 0.6, display. COLOR_WHITE)

Others same as above

 

5.1.1 playLevel

The function is called as follows:

Self: enterScene (PlayLevelScene, {levelIndex}, fade, 0.6, display. COLOR_WHITE)

Others same as above

 

 

2. MenuScene

Import other functions as follows:

LocalAdBar =Import(.. Views. AdBar)

LocalBubbleButton =Import(.. Views. BubbleButton)

The first scenario after the game starts, that is, the menu scenario.

Code is in the ctor function (constructor)

Add a background image and set two buttons.

One start, one for more games.

Click Start to select the LEVEL scenario.

Click More games to go to The MoreGamesScene scenario.

Note: There is a BUG here. If you click the start button and then click more game buttons immediately, the program will die. You can fix it by yourself.

4.1 BubbleButton

A function is defined to create a BUTTON. This BUTTON has a jelly-like special effect. It looks very professional and returns the BUTTON, the core of this file is to achieve this jelly effect (mainly to combine the time with simple actions ).

 

 

3. MoreGamesScene

In this scenario, there is only one ctor constructor to add background images,

Add a test BAR and add a return button.

Note: BAR is in the views/AdBar. lua folder.

 

 

4. ChooseLevelScene

This LEVEL selection scenario is currently used in many popular games. It should be said that it is a means, but it is basically the same.

The main function in this scenario is its constructor. In addition, there are two functions: onTapLevelIcon and onEnter.

Two other functional blocks are imported (this achieves function decoupling)

LocalAdBar =Import(.. Views. AdBar)

LocalLevelsList =Import(.. Views. LevelsList)

 

4.2 Ctor

First, add a background image, a TITLE, and a BAR for testing.

Create a rectangle, create a LevelsList using the rectangle, and add the listener onTapLevelIcon to it.

Create a BACK button.

Note: LevelsList is used in the views/LevelsList. lua file.

4.2.1 LevelsList

 

3 other files are imported as follows:

LocalLevelsListCell =Import(. LevelsListCell)

LocalLevels =Import(.. Data. Levels)

LocalPageControl =Import(.. Ui. PageControl)

 

Defines a LevelsList class, inherited from PageControl, PageControl inherited from ScrollView.

This class is a set of all levels separated by pages.

Defines a constant

LevelsList. INDICATOR_MARGIN = 46 (indicating the black dot Spacing on the level page)

Each level page contains 4X4 = 16 levels. If the height is greater than 1000, five rows are stored.

There are also three functions: ctor, scrollToCell, and onTapLevelIcon.

Ctor is a constructor.

Call the constructor LevelsList. super. ctor (self, rect, PageControl. DIRECTION_HORIZONTAL) of the parent class)

Calculate the total number of pages by dividing the total number of levels by the number of lines per page and the number of columns.

Set the last level on each page. If the total number of levels is exceeded, set it to the actual last level.

Then, the pages are filled with the LevelsListCell class to reciprocating.

Then, set the dots at the bottom of the page to indicate the level page on which the user is currently located.

Add a solid image to the small dot that represents the first page, and then add a hollow image cyclically as follows:

LocalX = (self: getClippingRect (). width-LevelsList. INDICATOR_MARGIN * (numPages-1)/2

LocalY = self: getClippingRect (). y + 20

 

Self. indicator _ =Display.Newsprite(lelevellistscellselected.png)

Self. indicator _: setPosition (x, y)

Self. indicator _. firstX _ = x

 

ForPageIndex = 1, numPagesDo

LocalIcon =Display.Newsprite(lelevellistscellindicator.png)

Icon: setPosition (x, y)

Self: addChild (icon)

X = x + LevelsList. INDICATOR_MARGIN

End

 

ScrollToCell

Call the scrollToCell function of the parent node.

Then move the solid image to the displayed page.

 

The onTapLevelIcon function has the following statement:

Self: dispatchEvent ({name = onTapLevelIcon, levelIndex = event. levelIndex })

The onTapLevelIcon distribution time. The parameter is levelIndex = event. levelIndex.

 

4.2.2 PageControl

Imported File local ScrollView = import (. ScrollView)

The class inherits from ScrollView (this class is defined in the ScrollView. lua file)

Mainly implements the onTouchEndedWithoutTap function.

Local variables offsetX, offset, index, count

Based on the direction variable, perform operations on the sliding level page.

 

4.2.3 ScrollView

The ScrollView class is defined. a rect matrix parameter is required for initialization. If no RECT matrix parameter is available, the matrix parameter is)

Create a cut area using this matrix.

Run the following command to add components:

Cc (node): addComponent (components. behavior. EventProtocol): exportMethods ()

Some variables are defined in the initialization function,

Self. dragThreshold = 40 -- upper limit of dragging

Self. bouncThreshold = 140 -- maximum value of the sliding level page, see setContentOffset

Self. defaultAnimateTime = 0.4-default animation time

Self. defaultAnimateEasing = backOut-default animation effect

 

Self. direction = direction

Self. touchRect = rect

Self. offsetX = 0

Self. offsetY = 0

Self. cells = {}

Self. currentIndex = 0

Add NODE event listening,

Self: addNodeEventListener (Cc. NODE_EVENT,Function(Event)

IfEvent. name = enterThen

Self: onEnter ()

ElseifEvent. name = exitThen

Self: onExit ()

End

End)

In addition, create a touch layer, add a touch listener to it, and call the onTouch function.

Self. view =Display. NewLayer ()

Self: addChild (self. view)

 

Self. view: addNodeEventListener (Cc. NODE_TOUCH_EVENT,Function(Event)

ReturnSelf: onTouch (event. name, event. x, event. y)

End)

The onTouch function is used to handle multiple situations, such as pressing, moving, and popping up.

Call onTouchBegan after pressing

Call after moving: onTouchMoved

Call onTouchEnded after popping up

Others are called: onTouchEnded

The getCurrentCell function gets the current level.

 

The Addcell function adds a page containing a level to the visible view layer. This function calls the reorderAllCells function.

LevelsList directly calls the Addcell function.

The reorderAllCells function is used to sort the pages of CELLS in the view. The value of the variable currentIndex is set. This variable specifies the number of currently touched pages, which are all routed to the views layer according to rules.

 

The processing of touch functions is complicated in this class:

L touch functions:

A) onTouch

This function is called at the beginning of the touch. If there is no level, it will exit and there will be no background. If it is just pressed, the system checks whether it is within the touchable range. If it is not, FALSE is returned to exit the touch. In this case, the onTouchBegan function is called. Its parameter is the coordinate of the pressed. If it is not just pressed, call onTouchMoved to process the mouse movement.

If the touch ends, the onTouchEnded function is called. If the touch ends, the onTouchCancelled function is called.

 

B) onTouchBegan

Set the start point of the drag and set isTap to True (this parameter is set to True for each start touch, and the value is changed to FALSE After sliding to prevent the sliding from entering a certain level)

Use the getCurrentCell function to obtain the current cell.

Call the onTouch function of the CELL itself (this function is in the LevelsListCell. lua file to implement button changes ).

 

C) onTouchMoved

Obtain the current CELL. Determine whether it is set to isTrap after the value of dragThreshold is exceeded, and call setContentOffset to process the current CELL. Otherwise, call the onTouch of the CELL.

 

D) onTouchEnded

If isTrap is set, the onTouchEndedWithTap function is called.

If no value is set, the onTouchEndedWithoutTap function is called.

 

 

E) onTouchCancelled

This function only sets the self. drag variable to nil.

 

Other related functions

F) onTouchEndedWithTap

Call the onTouch and onTrap functions of the cell itself.

The onTrap function of the Cell itself implements self: dispatchEvent ({name = onTapLevelIcon, levelIndex = button. levelIndex}) event distribution, which is handled by the onTapLevelIcon function in the LevelsList class and then processed by the ChooseLevelScene: onTapLevelIcon (event) function to enter a specific level.

This function does not slide the page.

 

G) onTouchEndedWithoutTap

It is overwritten in the PageControl. lua file. This function is used to process the sliding level page.

Slide Based on judgment and call the scrollToCell function, which calls the setContentOffset function.

Process sliding pages. The final claimed function is still setContentOffset. It has an animated effect.

 

H) setContentOffset

Process the real-time sliding effect. Set the real-time coordinate value based on the horizontal and vertical values. The upper and lower limits cannot be exceeded, and the last position is set. If there is an animation, play it.

The input parameter is offset, Which is copied to self. offsetX for saving.

This parameter is assigned to self. drag. currentOffsetX at the beginning of each touch.

Changes occur when the setContentOffset function is passed, and the changes are saved to self. offsetX.

 

4.2.4 ScrollViewCell

Create a class ScrollViewCell and create a Node with the given size.

Add the following components for the node:

Cc (node): addComponent (components. behavior. EventProtocol): exportMethods ()

This class is a touch unit class.

 

4.2.5 LevelsListCell

This class inherits from ScrollViewCell and is a sliding screen unit class. Defined by the screen size

RowHeight screen height-340 divided by the total number of rows

The screen width of colWidth is multiplied by 0.9 by the total number of columns.

PageIndex is the current page number of the level.

The X and Y values at the beginning of the page are calculated based on the display screen.

BeginLevelIndex, endLevelIndex parameter in the constructor.

Based on the number of buttons that can be accommodated on a page, click the BUTTON, and add a LABEL to the BUTTON to indicate the level.

This class defines the onTap function, and returns the BUTTON Based on the click position. The most important thing is that the function has been distributed by onTrapLevelIcon. (BUTTON is a table structure with an image and levelIndex variable)

(This class is mainly completed in its own class. The main work of its parent class is the following code.

LocalNode =Display. NewNode ()

IfContentSizeThenNode: setContentSize (contentSize)End

Node: setNodeEventEnabled (True)

Cc(Node): addComponent (components. behavior. EventProtocol): exportMethods ()

ReturnNode

)

 

4.2.6 Levels

Defined level information, such:

Levels table structure

LevelsData table structure

Function numLevels ()

Get (levelIndex)

4.3 onTapLevelIcon

It is the onTapLevelIcon Event Callback Function of levelsList (this event is distributed by the onTap function in the LevelsListCell class, but the specific distribution time is called by the onTouchEndedWithTap function in the ScrollView class), play the button sound, and then call: the playLevel function enters the selected game scenario.

 

4.4 onEnter

This function is executed after the constructor is executed. It is mainly used to enable the button.

 

5 PlayLevelScene

Import other functional modules first:

LocalLevels =Import(.. Data. Levels)

LocalBoard =Import(.. Views. Board)

LocalAdBar =Import(.. Views. AdBar)

 

The Levels. lua file defines the data of each level. You can set the number of Levels multiplied by a few, and the Level Initialization Conditions.

 

A background image, a TITLE, a test BAR, and a level LABEL are displayed. BORAD of the game, a returned BUTTON.

Self. board: addEventListener (LEVEL_COMPLETED, handler (self, self. onLevelCompleted) is added to the game to listen to events. When the game wins, the event message is sent and

PlayLevelScene: The onLevelCompleted function.

 

Note: The BOARD is defined in the views. Board. lua file.

Core logic in the BOARD

5.1 Board

Import the following files

LocalLevels =Import(.. Data. Levels)

LocalCoin =Import(.. Views. Coin)

 

Get game level variables grid, rows, cols

OffsetX and offset are calculated.

Place the gold coin background genie. Determines whether the current position is empty. If it is not empty, a gold coin is created.

Store the gold coins in the coins array. Enable touch to create a touch listener.

The onTouch function reverses the coins.

The measurement constant is padding = NODE_PADDING/2.

The flipCoin function can reverse the gold coins next door at the same time.

The flipCoin function checks whether the level is complete.

 

 

 

5.2 Coin

Defines a Coin class, which creates an image based on the front and back of initialization, and an isWhite variable.

Another important function is Coin: flip, which defines an animation and sets the animation direction based on isWhite, that is, the flip animation.

At the same time, set isWhite variable inversion.

 

 

 

6. Description of individual functions

Self. levelsList: addEventListener (onTapLevelIcon, handler (self, self. onTapLevelIcon ))

Package the Lua object and its methods into an anonymous function.

 

Format:

Function = handler (object, object. Method)

In the quick-cocos2d-x, many features require passing in a Lua function as a parameter, and then the incoming function is called when a specific event occurs. Such as touch events and frame events.

Custom events in Quick-Cocos2d-x

Visit the official website:

Http://cn.cocos2d-x.org/article/index? Type = quick_doc & url =/doc/cocos-docs-master/manual/framework/quick/V3/events/zh. md

· AddEventListener

· RemoveEventListener

· RemoveAllEventListenersForEvent

· RemoveAllEventListeners

 

Cc (node): addComponent (components. behavior. EventProtocol): exportMethods ()

This sentence adds an extended Event Processing Method for the node class. Now we can use the functions in EventProxy. Through these functions, we can let cc (node) receive and process custom messages.

Distribution event "addCell"

Self: dispatchEvent ({name = addCell, count = # self. cells })

 

Display. addSpriteFrames ()

Display. addSpriteFrames (plistFilename, image, handler)

Load the specified Sprite Sheets Material file and its data file into the image frame cache.

Format:

Display. addSpriteFrames (data file name, Material file name)

Cc. rect

The actual parameters are x, y, width, and height.

Coordinates X, Y, width, and height. The actual usage is as follows:

Local rect = cc. rect (display. left, display. bottom + 180, display. width, display. height-280)

 

 

Display. newBatchNode ()

Display. newBatchNode (image, capacity)

Creates an image file and returns a batch rendering object.

Local imageName = Sprites.png

Display. addSpriteFrames (Sprites. plist, imageName) -- load the image to the frame Cache

 

-- The following code only uses OpenGL draw call once to draw 100 images.

Local batch = display. newBatch (imageName)

For I = 1,100 do

Local sprite = display.newsprite(w.sprite0001.png)

Batch: addChild (sprite)

End

 

-- The following code uses 100 OpenGL draw call to draw 100 images

Local group = display. newNode ()

For I = 1,100 do

Local sprite = display.newsprite(w.sprite0001.png)

Group: addChild (sprite)

End

Parameters

StringImageImage File Name

IntegerCapacity

 

 

ReorderChild

ReorderChild has two parameters:

 

Child is the node to be added, and zOrder is the z value in cocos2d.

This function re-sorts the child priority based on the new zOrder.

For example, if an image is added to a layer (scenario), the image priority has been set. In some cases, this priority has some problems, you want to modify the priority of the image. In this case, I do not need to use layer (scenario) first)

Call removeFromParentAndCleanup (boolcleanup); then addChild (Node * child, int zOrder); this is so troublesome

Transition. playAnimationOnce ()

Transition. playAnimationOnce (target, animation, removeWhenFinished, onComplete, delay)

Play an animation on the displayed object and return the Action object.

 

 

 

7. logical topology

 

 

 

 

 

 

 

 

 

 

 

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.