yet another question about random number generating

Hi,

I'm currently designing a small combat system for my story, and I regularly have to generate random numbers (for values, rolls and text variants).

For that I am using a which someone showed on this forum (I don't remember who it was but thank you!), but I'm wondering if it's really necessary to repeat the "var randomnumber=function bla bla bla" before every roll? I tried removing all but the first ones and it seemed to work but I'd rather be sure I'm not missing anything important.


    var randomnumber = function rng(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    set ("text_roll_A", randomnumber(1,5));
    
    var randomnumber = function rng(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    set ("ambushed", randomnumber(1,21));
    
    var randomnumber = function rng(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    set ("01_enemy", randomnumber(1,3));


Also I found if I want to throw a d20 (c.f. above "ambushed"), I have to type "randomnumber(1,21), else it never lands on a 20. Is this normal?
Thanks!

Yes, the off-by-one error is usual. The function Math.random generates a number which is less that 1.0, and greater than or equal to 0.0. So the range in that function includes the min value but not the max.

You shouldn't need to repeat the function. I don't know how Squiffy handles javascript scope, but unless it's doing something really weird the function should continue to be available once it's been set.


Ok thanks for the help!
It does need to be set for every section, though, right?


It does need to be set for every section, though, right?

I don't know. With var in front of it, it'll be limited to the current scope frame. It's probably safe to assume Squiffy has one frame per section, but there are other ways it could be implemented, so it might be worth testing that.

From my javascript experience (a long time ago), I would have made the code something like:

    window.randomnumber = function(min, max) {
      return Math.floor(Math.random() * (max + 1 - min)) + min;
    };

(which lets 'max' be the highest number generated so it's more intuitive to use, and explicitly makes randomnumber a global function so you can carry on using it until the page is reloaded)

I don't have the Squiffy experience; and the developers could have done something to stop window. working like that, but I can't see why they would.


This topic is now closed. Topics are closed after 180 days of inactivity.

Support

Forums