Reputation: 45
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");
};
};
Upvotes: 3
Views: 184
Reputation: 1800
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");
}
}
Upvotes: 4