Skip to content

Instantly share code, notes, and snippets.

Created June 3, 2020 12:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Calculate luck in Javascript, based on a RPG stat
Calculate a RNG value with a percent chance to succeed,
based on a range and an stat input value somewhere between.
This is how the challenges in Sunless Sea work, for example.
- The lower bound defines a starting value required to get over 0%
- The upper bound defines the value at which you always succeed
- The stat value should between the two in order to produce a meaningful chance.
let statValue = 138;
let upperBound = 150;
let lowerBound = 40;
let span = upperBound - lowerBound;
let chance = (statValue-lowerBound)/(span/100);
if (chance <= lowerBound) chance = 0;
if (chance >= upperBound) chance = 100;
let randomValue = Math.random();
if (randomValue < chance/100) {
console.log('You succeeded in a challenge!');
} else {
console.log('You failed the challenge.');
// stats
console.log('The random value was ' + Math.floor(randomValue*100));
console.log('Your stat gave you a chance of ' + Math.floor(chance) + '% to succeed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment