Davidobot / love.js

LÖVE ported to the web using Emscripten, updated to the latest Emscripten and LÖVE (v11.5)
MIT License
605 stars 27 forks source link

Float value for random seed yields predicatable results #94

Open wesleywerner opened 1 month ago

wesleywerner commented 1 month ago

Problem Statement

When the math.randomseed(n) function is called with float values < 1 then subsequent calls to math.random() yields the same amount.

The work-around is to seed the RNG using integers and not float values derived from math.random(). This ticket is a reminder of this fact, and also to document the steps to test, for anybody encountering this in the future.

Test Case

local seed_bag = {}

function love.draw ()
    love.graphics.print("click to generate random numbers, watch the web console.")
end

function love.mousepressed(x, y, button, istouch)
    if #seed_bag == 0 then
        print("filling bag with seeds.")
        for i = 0, 10 do
            table.insert(seed_bag, math.random())
        end
    end
    next_seed = table.remove(seed_bag)
    print("set random seed of " .. next_seed)
    math.randomseed(next_seed)
    random_amount = math.random(100, 500)
    print("random amount between 100 and 500 for this seed equals " .. random_amount)
end

The above code outputs the following when run in Löve on the Desktop:

filling bag with seeds. set random seed of 0.11446190140255 random amount between 100 and 500 for this seed equals 319 set random seed of 0.56859228170254 random amount between 100 and 500 for this seed equals 389 set random seed of 0.42668680786097 random amount between 100 and 500 for this seed equals 479 set random seed of 0.73573903003308 random amount between 100 and 500 for this seed equals 378 set random seed of 0.33933341140343 random amount between 100 and 500 for this seed equals 150 etc cetera

The same code running via Löve .js:

filling bag with seeds. set random seed of 0.421925941213 random amount between 100 and 500 for this seed equals 482 set random seed of 0.6700635201624 random amount between 100 and 500 for this seed equals 482 set random seed of 0.31313096560218 random amount between 100 and 500 for this seed equals 482 set random seed of 0.60369106969037 random amount between 100 and 500 for this seed equals 482 ad infinitum ...

This behaviour does not happen when the seed value is an integer value > 0.