Generate a random number, but every random seconds

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
hycday
Prole
Posts: 2
Joined: Wed Jun 11, 2014 7:45 pm

Generate a random number, but every random seconds

Post by hycday »

Hello,


I am trying to generate a random number, every random seconds (the final purpose would be to change the color of a block from time to time, randomly).

For that, I am using the Hump library (http://vrld.github.io/hump/#hump.timer).

Here is my code at the moment, I am true beginner in LUA/Love2d coding. It generates a number, and displays it every seconds, instead of every random seconds... (but the random seconds is also generated). I don't really understand why it is not working.

Code: Select all

local Timer = require "timer"

function love.load()
    text="t"
    number2=1
end

local f = function()
math.randomseed(os.time())
    number = math.random( 2,10 )
    text="in " .. number2 .. " seconds (random)...  random number =" .. number
    return true
end

function love.update(dt)

    number2 = math.random( 2,4 ) 
    Timer.update(number2)
    Timer.addPeriodic(number2, f)
end

function love.draw()
    love.graphics.print( text, 330, 300 )
end

Thanks for any help !
User avatar
veethree
Inner party member
Posts: 877
Joined: Sat Dec 10, 2011 7:18 pm

Re: Generate a random number, but every random seconds

Post by veethree »

This doesn't use hump, But it does what you described, I'm sure you can apply it with hump.

Code: Select all

local number = math.random(255)
local next_number = math.random(10)
local tick = 0

function love.update(dt)
	tick = tick + dt
	if tick > next_number then
		number = math.random(255)
		next_number = math.random(10)
		tick = 0
	end
end

function love.draw()
	love.graphics.print(number.."\n"..next_number, 12, 12)
end
Basically there's 3 variables.
I add dt to the tick variable every frame, Resulting in tick going up by 1 roughly every second, Then when it reaches next_number, I generate a random number, And set next_number to a random value between 0 and 10.
hycday
Prole
Posts: 2
Joined: Wed Jun 11, 2014 7:45 pm

Re: Generate a random number, but every random seconds

Post by hycday »

W.O.W.

that works perfectly well, as needed, without any external library and smoothly !
and I understand it :)

thanks a lot !
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Google [Bot], Semrush [Bot] and 5 guests