Lua 实现倒计时功能

欢迎各位童鞋转载,转载请注明出处:http://blog.csdn.net/song_hui_xiang

作者新浪微博:http://weibo.com/u/3168848533

作者腾讯微博:http://t.qq.com/song_huixiang

--Lua 实现倒计时功能
local size = CCDirector:sharedDirector():getWinSize()
local scheduler = CCDirector:sharedDirector():getScheduler()
local run_logic = nil

--时 分 秒 数值
local hour = 1
local minute = 0
local second = 0

--将int类型转换为string类型
hour = hour..""
minute = minute..""
second = second..""

--当显示数字为个位数时,前位用0补上
if string.len(hour) == 1 then
    hour = "0"..hour
end

if string.len(minute) == 1 then
    minute = "0"..minute
end

if string.len(second) == 1 then
    second = "0"..second
end

--创建时间标签用以显示
local time = CCLabelTTF:create("倒计时:"..hour..":"..minute..":"..second,"Thonburi",35)
time:setColor(ccc3(0,255,0))
time:setPosition(ccp(size.width*0.5,size.height*0.6))
mainLayer:addChild(time,1,123)

--倒计时更新函数
local function anticlockwiseUpdate()
    local time = mainLayer:getChildByTag(123)
    time = tolua.cast(time,"CCLabelTTF")

    second = second-1
    if second == -1 then
        if minute ~= -1 or hour ~= -1 then
            minute = minute-1
            second = 59
            if minute == -1 then
                if hour ~= -1 then
                    hour = hour-1
                    minute = 59
                    if hour == -1 then
                        --倒计时结束停止更新
                        if run_logic ~= nil then
                            scheduler:unscheduleScriptEntry(run_logic)
                            run_logic = nil
                        end
                        second = 0
                        minute = 0
                        hour = 0
                        time:setColor(ccc3(255,0,0)) --以红色标识结束
                    end
                end
            end
        end
    end
    
    second = second..""
    minute = minute..""
    hour = hour..""
    
    if string.len(second) == 1 then
        second = "0"..second
    end
    
    if string.len(minute) == 1 then
        minute = "0"..minute
    end
    
    if string.len(hour) == 1 then
        hour = "0"..hour
    end

    time:setString("倒计时:"..hour..":"..minute..":"..second)
end

--开始倒计时 每1秒调用一次anticlockwiseUpdate方法
run_logic = scheduler:scheduleScriptFunc(anticlockwiseUpdate,1,false)


local scene = CCScene:create()
scene:addChild(mainLayer)
CCDirector:sharedDirector():runWithScene(scene)


你可能感兴趣的:(Lua 实现倒计时功能)