NewiOS Developer
NewiOS Developer

Reputation: 25

How to get the timed bonus

I am making a game in Lua - specifically Corona SDK - and I am stuck on a timed health bonus (the player would get a health bonus every 4 hours) and the second part is the player would get a free spin of a wheel type game that will give them the chance to win free items to use in the game.

The part that is really confusing me is how do I get the timed bonus to be accurate (ex. every 4 hours and once a day) to fire off the functions for the bonuses? I also want there to be a count down timer showing hours:minutes:seconds left before next available bonus can be collected. Is this impossible to do?

Here is some of my code so far...

function hourlyBonus()

    local date = os.date( "*t" )   
    local currentHour =  date.hour
    lastHourlyBonusClaimedHour = 
        GameSave.lastHourlyBonusClaimedHour or date.hour

    --account for the 24 hour clock           
    if currentHour > 12 then
        currentHour = currentHour - 12
    end
    if lastHourlyBonusClaimedHour > 12 then
        lastHourlyBonusClaimedHour = lastHourlyBonusClaimedHour - 12
    end

    if currentHour == (lastHourlyBonusClaimedHour + 4) then
        lastHourlyBonusClaimedHour = currentHour
        -- increase the bonus
        print("New 4 hour bonus  ThisHour is: " .. thisHourNum)
    else
        local hoursToWait = (4 - (currentHour - lastHourlyBonusClaimedHour))
        --have to wait for hourly bonus
        print("Have to wait: " 
            .. hoursToWait .. "hours, " 
            .. minutes .. "minutes, and " 
            .. second .. "seconds to collect hourly Bonus still!"
        )
        print("CurrentHour is:" .. currentHour)
        print("LastHourlyBonusClaimedHour is :" .. lastHourlyBonusClaimedHour)
    end                  

    GameSave.lastHourlyBonusClaimedHour = lastHourlyBonusClaimedHour
    GameSave:save()         
end

If anyone has some sample code I could look at or show me how to do this I would greatly appreciate it!

Upvotes: 1

Views: 154

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

I think you are making it too difficult for yourself. If you want to calculate the difference between time now and next bonus (or last bonus) up to seconds, you need to capture the number of seconds when you gave bonus and add 4*60*60 to it:

local lastbonus = os.time() - 1*60*60 - 2*60 - 30 -- 1 hour, 2 minutes, 30 seconds ago
local nextbonus = lastbonus + 4*60*60
local timeleft = nextbonus - os.time()
print(timeleft > 0 and os.date("!Left %H:%M:%S", timeleft) or "Bonus time!")

This should return/print Left 02:57:30.

[Updated based on lhf's comment; thanks Luiz!] Note that ! in os.date call is part of the format to indicate the date to be formatted in Coordinated Universal Time and will not appear in the output.

Upvotes: 1

Related Questions