Cocos2d-x-Lua 開發簡單的小遊戲(記數字踩白塊)
本篇博客來給大家介紹如何使用Lua這門語言來開發一個簡單的小遊戲—記數字踩白塊。
遊戲的流程是這樣的:在界面上生成5個數1~5字並顯示在隨機的位置上,點擊第一個數字,其他數字會顯示成白塊數字消失,玩家可以通過記住數字的顯示的位置點擊按順序消除白塊,直到白塊消除完,遊戲成功。
效果圖如下:
先說明一下筆者的開發環境:
- Xcode 5.1(Mac系統下的蘋果開發工具)
- Cocos2d-x 3.1.1(Cocos2d-x遊戲引擎)
- LDT(Lua集成開發環境)
- #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();
- }
#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();
}
- --[[
- 卡片
- 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
--[[
卡片
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)
- --[[
- 記數字踩白塊小遊戲
- 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, 5do
- 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, varin 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, varin 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()
--[[
記數字踩白塊小遊戲
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,然後再編譯。這個過程很麻煩,筆者正在在尋求其他更好的解決方案。
IT_xiao小巫
原文地址:http://blog.csdn.net/wwj_748/article/details/37054671