Cocos2d-x-Lua 開發簡單的小遊戲(記數字踩白塊)

 

 

Cocos2d-x-Lua 開發簡單的小遊戲(記數字踩白塊)


本篇博客來給大家介紹如何使用Lua這門語言來開發一個簡單的小遊戲—記數字踩白塊。

遊戲的流程是這樣的:在界面上生成5個數1~5字並顯示在隨機的位置上,點擊第一個數字,其他數字會顯示成白塊數字消失,玩家可以通過記住數字的顯示的位置點擊按順序消除白塊,直到白塊消除完,遊戲成功。

效果圖如下:


先說明一下筆者的開發環境:

  • Xcode 5.1(Mac系統下的蘋果開發工具)
  • Cocos2d-x 3.1.1(Cocos2d-x遊戲引擎)
  • LDT(Lua集成開發環境)
首先你得創建一個Cocos2d-x項目,裏面會多個平臺代碼,具體創建方法麻煩讀者參考筆者前面所寫的文章,如有疑問可以直接留言交流。


來看看我們項目結構:


》》AppDelegate.cpp
  1. #include "AppDelegate.h" 
  2. #include "CCLuaEngine.h" 
  3. #include "SimpleAudioEngine.h" 
  4. #include "cocos2d.h" 
  5.  
  6. using namespace CocosDenshion; 
  7.  
  8. USING_NS_CC; 
  9. using namespace std; 
  10.  
  11. AppDelegate::AppDelegate() 
  12.  
  13. AppDelegate::~AppDelegate() 
  14.     SimpleAudioEngine::end(); 
  15.  
  16. bool AppDelegate::applicationDidFinishLaunching() 
  17.     // initialize director 
  18.     auto director = Director::getInstance(); 
  19.     auto glview = director->getOpenGLView(); 
  20.     if(!glview) { 
  21.         // 創建可視區域,位置(0,0)寬:900,高:640 
  22.         glview = GLView::createWithRect("記數字踩白塊", Rect(0,0,900,640)); 
  23.         director->setOpenGLView(glview); 
  24.     } 
  25.      
  26.     // 設置設計分辨率 
  27.     glview->setDesignResolutionSize(800, 480, ResolutionPolicy::SHOW_ALL); 
  28.  
  29.     // turn on display FPS 
  30.     // 打開顯示的FPS 
  31.     director->setDisplayStats(true); 
  32.  
  33.     // set FPS. the default value is 1.0/60 if you don't call this 
  34.     director->setAnimationInterval(1.0 / 60); 
  35.  
  36.  
  37.     auto engine = LuaEngine::getInstance(); 
  38.     ScriptEngineManager::getInstance()->setScriptEngine(engine); 
  39.     // 執行src目錄下的main.lua腳本文件 
  40.     if (engine->executeScriptFile("src/main.lua")) { 
  41.         return false
  42.     } 
  43.  
  44.     return true
  45.  
  46. // This function will be called when the app is inactive. When comes a phone call,it's be invoked too 
  47. void AppDelegate::applicationDidEnterBackground() 
  48.     Director::getInstance()->stopAnimation(); 
  49.  
  50.     SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); 
  51.  
  52. // this function will be called when the app is active again 
  53. void AppDelegate::applicationWillEnterForeground() 
  54.     Director::getInstance()->startAnimation(); 
  55.  
  56.     SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); 
#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) {
        // 創建可視區域,位置(0,0)寬:900,高:640
		glview = GLView::createWithRect("記數字踩白塊", Rect(0,0,900,640));
		director->setOpenGLView(glview);
	}
    
    // 設置設計分辨率
    glview->setDesignResolutionSize(800, 480, ResolutionPolicy::SHOW_ALL);

    // turn on display FPS
    // 打開顯示的FPS
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0 / 60);


    auto engine = LuaEngine::getInstance();
    ScriptEngineManager::getInstance()->setScriptEngine(engine);
    // 執行src目錄下的main.lua腳本文件
    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 too
void AppDelegate::applicationDidEnterBackground()
{
    Director::getInstance()->stopAnimation();

    SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
    Director::getInstance()->startAnimation();

    SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}


我們主要在Lua文件中實現我們的邏輯,如何開始呢,首先我們要想象一個場景6*10的方格,一共60個方格,每個方格一個卡片,我們要做的是如何在這60個方格里放入我們的卡片,並且要隨機放上去的。

我們先定義卡片類》》card.lua
  1. --[[ 
  2. 卡片 
  3. card.lua 
  4. ]]-- 
  5.  
  6.  
  7. function card(num) 
  8.   -- 創建一個精靈,代表一張卡片 
  9.   local self = cc.Sprite:create() 
  10.   local txt,bg -- 卡片文本和背景 
  11.  
  12.   --初始化方法 
  13.   local function init() 
  14.     self.num = num 
  15.     --設置內容尺寸 
  16.     self:setContentSize( cc.size( 80, 80 ) ) 
  17.     --設置錨點 
  18.     self:setAnchorPoint(  cc.p( 0, 0 ) ) 
  19.  
  20.     --設置顯示數字的文本 
  21.     txt = cc.Label:create() 
  22.     txt:setString( num ) 
  23.     txt:setSystemFontSize( 50 ) 
  24.     txt:setSystemFontName( "Courier"
  25.     --設置文本顯示的位置,這裏是中間 
  26.     txt:setPosition( cc.p( self:getContentSize().width / 2,  self:getContentSize().height / 2 ) ) 
  27.     --添加到表 
  28.     self:addChild(txt) 
  29.  
  30.     --創建一個精靈,代表背景 
  31.     bg = cc.Sprite:create() 
  32.     --顏色塊 
  33.     bg:setTextureRect( cc.rect( 0, 0, 80, 80 ) ) 
  34.     --默認爲白色,這裏設置爲白色 
  35.     bg:setColor( cc.c3b( 255, 255, 255 ) ) 
  36.     --bg:setPosition( cc.p(0, 0)) 
  37.     --設置錨點 
  38.     bg:setAnchorPoint(  cc.p( 0, 0 ) ) 
  39.     self:addChild(bg) 
  40.  
  41.     --顯示文本 
  42.     self:showTxt() 
  43.   end 
  44.  
  45.   --定義顯示文本的方法 
  46.   self.showTxt = function() 
  47.     txt:setVisible(true
  48.     bg:setVisible(false
  49.   end 
  50.  
  51.   --定義顯示背景的方法 
  52.   self.showBg = function() 
  53.     txt:setVisible(false
  54.     bg:setVisible(true
  55.   end 
  56.   init() 
  57.  
  58.   return self 
  59. end 
--[[
卡片
card.lua
]]--


function card(num)
  -- 創建一個精靈,代表一張卡片
  local self = cc.Sprite:create()
  local txt,bg -- 卡片文本和背景

  --初始化方法
  local function init()
    self.num = num
    --設置內容尺寸
    self:setContentSize( cc.size( 80, 80 ) )
    --設置錨點
    self:setAnchorPoint(  cc.p( 0, 0 ) )

    --設置顯示數字的文本
    txt = cc.Label:create()
    txt:setString( num )
    txt:setSystemFontSize( 50 )
    txt:setSystemFontName( "Courier" )
    --設置文本顯示的位置,這裏是中間
    txt:setPosition( cc.p( self:getContentSize().width / 2,  self:getContentSize().height / 2 ) )
    --添加到表
    self:addChild(txt)

    --創建一個精靈,代表背景
    bg = cc.Sprite:create()
    --顏色塊
    bg:setTextureRect( cc.rect( 0, 0, 80, 80 ) )
    --默認爲白色,這裏設置爲白色
    bg:setColor( cc.c3b( 255, 255, 255 ) )
    --bg:setPosition( cc.p(0, 0))
    --設置錨點
    bg:setAnchorPoint(  cc.p( 0, 0 ) )
    self:addChild(bg)

    --顯示文本
    self:showTxt()
  end

  --定義顯示文本的方法
  self.showTxt = function()
    txt:setVisible(true)
    bg:setVisible(false)
  end

  --定義顯示背景的方法
  self.showBg = function()
    txt:setVisible(false)
    bg:setVisible(true)
  end
  init()

  return self
end

從卡片類我們可以知道,我們需要傳入一個數字,然後對卡片類進行初始化,顯示相應的數字,我們的卡片是一個Sprite(我們所說的精靈),我們要往Sprite添加數字(用Label來顯示),還要添加我們的背景(同樣也是一個Sprite)

卡片類定義好之後,我們就要實現我們想要的效果了,定義我們的入口
》》》main.lua
  1. --[[ 
  2.  
  3. 記數字踩白塊小遊戲 
  4.  
  5. 2014/6/22 
  6. main.lua 
  7.  
  8. ]] 
  9. -- 引入card.lua文件 
  10. require( "src/card"
  11.  
  12. --主方法 
  13. function Main() 
  14.   -- 創建一個場景 
  15.   local self = cc.Scene:create() 
  16.  
  17.   -- 聲明一個層 
  18.   local layer 
  19.   local allPoints -- 存儲所有點 
  20.   local allCards = {} -- 存儲所有卡片 
  21.   local currentNum -- 當前數字 
  22.  
  23.   -- 生成可用點 
  24.   local function genPoints() 
  25.     allPoints = {} 
  26.     -- 6行*10列 
  27.     for i = 0, 9 do 
  28.       for j = 0, 5 do 
  29.         -- 插入點到allPoints數組當中 
  30.         table.insert( allPoints, 1, cc.p( i * 80, j * 80 ) ) 
  31.       end 
  32.     end 
  33.     
  34.   end 
  35.  
  36.   -- 添加卡片 
  37.   local function addCards() 
  38.  
  39.     -- 設置隨機種子 
  40.     math.randomseed( os.time() ) 
  41.  
  42.     local c  -- 卡片 
  43.     local randNum -- 隨機數 
  44.     local p -- 所在點 
  45.  
  46.     -- 添加5張卡片 
  47.     for var = 1, 5do 
  48.       c = card( var ) -- 生成一張卡片 
  49.       layer:addChild( c ) -- 添加到層當中 
  50.       -- 根據數組最大值生成隨機數 
  51.       randNum = math.random( table.maxn(allPoints)  ) 
  52.       p = table.remove( allPoints, randNum ) 
  53.       c:setPosition( p ) 
  54.       c:setAnchorPoint(  cc.p( 0, 0 ) ) 
  55.       print("p.x:"..p.x..",p.y:"..p.y); 
  56.        
  57.       -- 插入到卡片數組 
  58.       table.insert( allCards, 1, c ) 
  59.     end 
  60.  
  61.   end 
  62.  
  63.   -- 開始遊戲 
  64.   local function startGame() 
  65.     -- 初始值爲1 
  66.     currentNum = 1 
  67.     -- 先生成可用點 
  68.     genPoints() 
  69.     -- 然後添加卡片 
  70.     addCards() 
  71.   end 
  72.  
  73.  
  74.   -- 顯示所有卡片背景 
  75.   local function showAllCardsBg() 
  76.     for key, varin pairs(allCards)do 
  77.       var:showBg() 
  78.     end 
  79.   end 
  80.  
  81.   -- 觸摸事件,第一個參數爲事件類型,第二個參數爲x座標,第二個爲y座標 
  82.   local function onTouch( type, x, y ) 
  83.     -- 根據x,y生成一個點 
  84.     local p = cc.p(x,y) 
  85.     for key, varin pairs(allCards)do 
  86.       print(var:getPosition()) 
  87.       -- 判斷是否是點擊範圍 
  88.       local pX,pY = var:getPosition() 
  89.       if (p.x < (pX + 80)) and (p.y < (pY + 80) and (p.x > pX) and (p.y > pY)) then 
  90.       --if var:getBoundingBox():containsPoint(p) then 
  91.         if currentNum ==var.num then 
  92.           -- 如果是點擊的數字,則移除卡片 
  93.           table.remove(allCards, key) 
  94.           layer:removeChild(var, true
  95.  
  96.           -- 點擊了1之後,其他數字翻過背景 
  97.           if currentNum == 1 then 
  98.             showAllCardsBg() 
  99.           end 
  100.  
  101.           -- 當所有卡片都被順序點擊了,提示成功 
  102.           if table.maxn( allCards ) <= 0 then 
  103.             print( "Success"
  104.              
  105.           end 
  106.  
  107.           -- 每次增加1 
  108.           currentNum = currentNum + 1 
  109.         end 
  110.       end 
  111.     end 
  112.   end 
  113.  
  114.   -- 初始化方法 
  115.   local function init() 
  116.  
  117.     -- 創建一個層 
  118.     layer = cc.Layer:create() 
  119.     -- 將層添加到場景 
  120.     self:addChild( layer ) 
  121.     -- 設置可點擊 
  122.     layer:setTouchEnabled( true
  123.     -- 註冊監聽事件 
  124.     layer:registerScriptTouchHandler( onTouch ) 
  125.     -- 開始遊戲 
  126.     startGame() 
  127.     -- self:addChild(layer) 
  128.  
  129.     --    --測試代碼 
  130.     --    local s = cc.Sprite:create("res/mn.jpg"
  131.     --    s:setPosition(cc.p(0,0)) 
  132.     --    s:setAnchorPoint( cc.p( 0, 0 ) ) 
  133.     --    layer:addChild(s) 
  134.     -- 
  135.     --    layer:setTouchEnabled(true
  136.     --    layer:registerScriptTouchHandler( function (type,x,y) 
  137.     -- 
  138.     --        if s:getBoundingBox():containsPoint(cc.p(x,y)) then 
  139.     --          print("mn clicked"
  140.     --        end 
  141.     --        print(type) 
  142.     --        return true 
  143.     --    end ) 
  144.     -- 
  145.     --    self:addChild(layer) 
  146.   end 
  147.  
  148.   init() 
  149.  
  150.   return self 
  151. end 
  152.  
  153.  
  154.  
  155. --入口方法 
  156. local function _main() 
  157.   -- 獲得導演類實例 
  158.   local dir = cc.Director:getInstance() 
  159.   -- 設置不顯示幀 
  160.   dir:setDisplayStats(false
  161.   -- 運行場景 
  162.   dir:runWithScene(Main()) 
  163.  
  164. end 
  165.  
  166. -- 調用入口方法 
  167. _main() 
--[[

記數字踩白塊小遊戲

2014/6/22
main.lua

]]
-- 引入card.lua文件
require( "src/card" )

--主方法
function Main()
  -- 創建一個場景
  local self = cc.Scene:create()

  -- 聲明一個層
  local layer
  local allPoints -- 存儲所有點
  local allCards = {} -- 存儲所有卡片
  local currentNum -- 當前數字

  -- 生成可用點
  local function genPoints()
    allPoints = {}
    -- 6行*10列
    for i = 0, 9 do
      for j = 0, 5 do
        -- 插入點到allPoints數組當中
        table.insert( allPoints, 1, cc.p( i * 80, j * 80 ) )
      end
    end
   
  end

  -- 添加卡片
  local function addCards()

    -- 設置隨機種子
    math.randomseed( os.time() )

    local c  -- 卡片
    local randNum -- 隨機數
    local p -- 所在點

    -- 添加5張卡片
    for var = 1, 5 do
      c = card( var ) -- 生成一張卡片
      layer:addChild( c ) -- 添加到層當中
      -- 根據數組最大值生成隨機數
      randNum = math.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);
      
      -- 插入到卡片數組
      table.insert( allCards, 1, c )
    end

  end

  -- 開始遊戲
  local function startGame()
    -- 初始值爲1
    currentNum = 1
    -- 先生成可用點
    genPoints()
    -- 然後添加卡片
    addCards()
  end


  -- 顯示所有卡片背景
  local function showAllCardsBg()
    for key, var in pairs(allCards) do
      var:showBg()
    end
  end

  -- 觸摸事件,第一個參數爲事件類型,第二個參數爲x座標,第二個爲y座標
  local function onTouch( type, x, y )
    -- 根據x,y生成一個點
    local p = cc.p(x,y)
    for key, var in pairs(allCards) do
      print(var:getPosition())
      -- 判斷是否是點擊範圍
      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
          -- 如果是點擊的數字,則移除卡片
          table.remove(allCards, key)
          layer:removeChild(var, true)

          -- 點擊了1之後,其他數字翻過背景
          if currentNum == 1 then
            showAllCardsBg()
          end

          -- 當所有卡片都被順序點擊了,提示成功
          if table.maxn( allCards ) <= 0 then
            print( "Success" )
            
          end

          -- 每次增加1
          currentNum = currentNum + 1
        end
      end
    end
  end

  -- 初始化方法
  local function init()

    -- 創建一個層
    layer = cc.Layer:create()
    -- 將層添加到場景
    self:addChild( layer )
    -- 設置可點擊
    layer:setTouchEnabled( true )
    -- 註冊監聽事件
    layer:registerScriptTouchHandler( onTouch )
    -- 開始遊戲
    startGame()
    -- self:addChild(layer)

    --    --測試代碼
    --    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 self
end



--入口方法
local function _main()
  -- 獲得導演類實例
  local dir = cc.Director:getInstance()
  -- 設置不顯示幀
  dir:setDisplayStats(false)
  -- 運行場景
  dir:runWithScene(Main())

end

-- 調用入口方法
_main()

以上代碼已經很詳盡,筆者就不多做解釋,主要在這裏提一下,如果使用筆者的開發環境的話,需要注意以下幾個問題:

1. XCode不能很好的支持Lua的編輯,所以我們使用LDT來進行編碼,但會遇到XCode運行程序沒有呈現最新效果,這時我們需要對XCode進行Clean,然後再編譯。這個過程很麻煩,筆者正在在尋求其他更好的解決方案。

2. 因爲Cocos2d-x版本的變化,使用Lua編寫C++邏輯代碼也發生了相應的變化,一些API被新版本拋棄,比如之前CCDirector會以cc.Director的形式呈現。筆者在網上也沒有找到相應的說明,只能通過查看Cocos2d-x提供的示例程序查找相關API的使用。

IT_xiao小巫

原文地址:http://blog.csdn.net/wwj_748/article/details/37054671

發佈了123 篇原創文章 · 獲贊 80 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章