Cocos2d-x-Lua development of a simple game (count on the white block)
Cocos2d-x-Lua development of a simple game (count on the white block)
This blog will show you how to use the Lua language to develop a simple little game-remember the numbers and step on the white block.
The game process is as follows: generate 5 numbers 1 ~ on the Interface ~ 5 Characters and displayed at random positions. Click the first digit. Other digits are displayed as white digits, players can delete the white block by remembering the position where the number is displayed and clicking it in order until the White block is cleared, the game is successful.
As follows:
First, describe the development environment of the author:
- Xcode 5.1 (Apple development tool in Mac system)
- Cocos2d-x 3.1.1 (Cocos2d-x game engine)
- LDT (Lua integrated development environment)
First you have to create a Cocos2d-x project, there will be multiple platform code, the specific creation method trouble readers refer to the author's previous articles, if you have any questions can directly Leave a message.
Let's take a look at our project structure:
"AppDelegate. cpp
# Include "AppDelegate. h "# include" CCLuaEngine. h "# include" SimpleAudioEngine. h "# include" cocos2d. h "using namespace CocosDenshion; USING_NS_CC; using namespace std; AppDelegate: AppDelegate () {} AppDelegate ::~ AppDelegate () {SimpleAudioEngine: end ();} bool AppDelegate: applicationDidFinishLaunching () {// initialize director auto director = Director: getInstance (); auto glview = director-> getOpenGLView (); if (! Glview) {// create a visible area, location (0, 0) width: 900, height: 640 glview = GLView: createWithRect ("count on the white block", Rect, 900,640); director-> setOpenGLView (glview);} // set the design resolution glview-> setDesignResolutionSize (800,480, ResolutionPolicy: SHOW_ALL ); // turn on display FPS // enable the displayed FPS ctor-> setDisplayStats (true); // set FPS. the default value is 1.0/60 if you don't call this ctor-> setAnimationInterval (1.0/60); auto engine = LuaEngine: getInstance (); ScriptEngineManager: getInstance () -> setScriptEngine (engine); // execute main. lua script file if (engine-> executeScriptFile ("src/main. lua ") {return false;} return true;} // This function will be called when the app is inactive. when comes a phone call, it's be invoked toovoid AppDelegate: applicationDidEnterBackground () {Director: getInstance ()-> stopAnimation (); SimpleAudioEngine: getInstance () -> pauseBackgroundMusic ();} // this function will be called when the app is active againvoid AppDelegate: applicationWillEnterForeground () {Director: getInstance ()-> startAnimation (); simpleAudioEngine: getInstance ()-> resumeBackgroundMusic ();}
We mainly implement our logic in the Lua file. How can we get started? First, we need to imagine a scenario with 6*10 squares. There are 60 squares in total and each square is a card, what we need to do is to put our cards in the 60 squares and randomly put them.
Let's first define the card category "card. lua
-- [[Card. lua] -- function card (num) -- creates an genie representing a card local self = cc. sprite: create () local txt, bg -- card text and background -- initialization method local function init () self. num = num -- set the content Size self: setContentSize (cc. size (80, 80) -- set the anchorpoint self: setAnchorPoint (cc. p (0, 0) -- set the text txt = cc for displaying numbers. label: create () txt: setString (num) txt: setSystemFontSize (50) txt: setSystemFontName ("Courier") -- set the text display position. Here is the intermediate txt: setPosition (cc. p (self: getContentSize (). width/2, self: getContentSize (). height/2) -- add to table self: addChild (txt) -- create an genie, representing the background bg = cc. sprite: create () -- Color Block bg: setTextureRect (cc. rect (0, 0, 80, 80) -- The default value is white. Here it is set to white bg: setColor (cc. c3b (255,255,255) -- bg: setPosition (cc. p (0, 0) -- set the anchorpoint bg: setAnchorPoint (cc. p (0, 0) self: addChild (bg) -- display text self: showTxt () end -- Define the display text method self. showTxt = function () txt: setVisible (true) bg: setVisible (false) end -- defines the method for displaying the background self. showBg = function () txt: setVisible (false) bg: setVisible (true) end init () return selfend
From the card class, we can know that we need to input a number and then initialize the card class to display the corresponding number. Our card is a Sprite (the genie we call ), we need to add numbers to Sprite (display with Label) and add our background (also a Sprite ).
After the card category is defined, we need to implement the desired effect. Define our portal. "main. lua
-- [Record the number of dashboard games for entering the white block: 2014/6/22 main. lua] -- Introduce card. lua file require ("src/card") -- Main method function Main () -- creates a scenario local self = cc. scene: create () -- declare a layer local allPoints -- store all points local allCards ={} -- store all cards local currentNum -- current number -- generate available points local function genPoints () allPoints = {} -- 6 rows * 10 columns for I = 0, 9 do for j = 0, 5 do -- insert point to the table in the allPoints array. insert (allPoints, 1, cc. p (I * 80, j * 80) end -- add the card local function addCards () -- set the Random Seed math. randomseed (OS. time () local c -- card local randNum -- random number local p -- point -- add 5 cards for var = 1, 5 do c = card (var) -- generate a card layer: addChild (c) -- add to layer -- generate a random number randNum = math based on the maximum value of the array. random (table. maxn (allPoints) p = table. remove (allPoints, randNum) c: setPosition (p) c: setAnchorPoint (cc. p (0, 0) print ("p. x :".. p. x .. ", p. y :".. p. y); -- insert to the card array table. insert (allCards, 1, c) end -- start the game local function startGame () -- The initial value is 1 currentNum = 1 -- the available point genPoints () -- then add the card addCards () end -- display all card backgrounds local function showAllCardsBg () for key, var in pairs (allCards) do var: showBg () end -- touch event, the first parameter is the event type, the second parameter is the x coordinate, and the second is the y coordinate local function onTouch (type, x, y) -- generate a point local p = cc according to x and y. p (x, y) for key, var in pairs (allCards) do print (var: getPosition () -- determines whether the click range is local pX, pY = var: getPosition () if (p. x <(pX + 80) and (p. y <(pY + 80) and (p. x> pX) and (p. y> pY) then -- if var: getBoundingBox (): containsPoint (p) then if currentNum = var. num then -- if the number is clicked, the card table is removed. remove (allCards, key) layer: removeChild (var, true) -- after 1 is clicked, other numbers are switched over the background if currentNum = 1 then showAllCardsBg () end -- when all cards are clicked sequentially, if table is displayed successfully. maxn (allCards) <= 0 then print ("Success") end -- add 1 currentNum = currentNum + 1 end each time -- initialize the method local function init () -- create a layer = cc. layer: create () -- add the layer to the scenario self: addChild (layer) -- set the layer that can be clicked: setTouchEnabled (true) -- register the listener event Layer: registerScriptTouchHandler (onTouch) -- start the game startGame () -- self: addChild (layer) -- test code -- local s = cc. sprite: create ("res/mn.jpg") -- s: setPosition (cc. p (0, 0) -- s: setAnchorPoint (cc. p (0, 0) -- layer: addChild (s) -- layer: setTouchEnabled (true) -- layer: registerScriptTouchHandler (function (type, x, y) -- if s: getBoundingBox (): containsPoint (cc. p (x, y) then -- print ("mn clicked") -- end -- print (type) -- return true -- end) -- self: addChild (layer) end init () return selfend -- entry method local function _ main () -- Obtain the director class instance local dir = cc. director: getInstance () -- set do not display frame dir: setDisplayStats (false) -- run scenario dir: runWithScene (Main () end -- call entry method _ main ()
The above code is very detailed and I will not explain it more. I will mention it here. If I use the development environment, I need to pay attention to the following questions: 1. XCode does not support Lua editing. Therefore, we use LDT for encoding, but the XCode running program does not display the latest results. In this case, we need to Clean XCode and then compile it. This process is very troublesome. I am looking for other better solutions. 2. because of the changes in the Cocos2d-x version, the use of Lua to write C ++ logic Code has also undergone a corresponding change, Some APIs are abandoned by the new version, such as the previous CCDirector will cc. director format. I did not find the corresponding instructions on the Internet, you can only find the use of related APIS by viewing the sample program provided by the Cocos2d-x.