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
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  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
[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值