Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incremental chance increase in Javascript?

Tags:

javascript

I'm pretty new to Javascript and I'm doing a little game as a learning experience. The issue I've hit is that I need to increase the odds of an action being successful based on player level. For example: To cook x you need a cooking level of 40.

If the player has a cooking level = to the requirement they succeed 50% of the time. The odds go up 2.5% per level over the requirement until they succeed 100% of the time.

I have a way that is working but I'm not sure if there is an easier, more efficient way to do this or if this is the right answer.

if (cooklvl < lvlreq) {
    alert("You require level:");
} else if (cooklvl === lvlreq) {
    if (Math.random() < 0.5) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
} else if (cooklvl === lvlreq + 1) {
    if (Math.random() < 0.475) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
} else if (cooklvl === lvlreq + 2) {
    if (Math.random() < 0.45) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
} else if (cooklvl === lvlreq + 3) {
    if (Math.random() < 0.425) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
} else if (cooklvl === lvlreq + 4) {
    if (Math.random() < 0.4) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
} else if (cooklvl === lvlreq + 5) {
    if (Math.random() < 0.375) {
        alert("You burn the");
    } else {
        alert("You cook the");
    };
};
like image 282
Sticks Avatar asked Jun 07 '26 22:06

Sticks


1 Answers

Instead of writing each validation individually you can make your code do the operation you are calculating by yourself. That means for each level subtract 0.025 from the 0.5 you have at the beginning.

if (cooklvl < lvlreq) {
  alert("You require level:");
} else {
  if (Math.random() < (0.5 - (cooklvl - lvlreq) * 0.025)) {
    alert("You burn the");
  } else {
    alert("You cook the");
  }
}
like image 70
Pietro Nadalini Avatar answered Jun 09 '26 12:06

Pietro Nadalini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!