Question

My google links are all purple from how many links I've searched through to find this answer, and I've tried a lot of different suggestions and I'm starting to get frustrated so I'm coming to Stack directly. I am trying to add critical chance to attacks being dealt by the hero, so more or less I'm just trying to figure out how to calculate the chance of something occurring. This is my code block right now:

public void attack(){
    enemydmg = hero.att - enemy.def;
    herodmg = enemy.att - hero.def;
    enemy.hp -= enemydmg;
    hero.hp -= herodmg;

    if(Math.random() < hero.critchnc){
        enemydmg = enemydmg * 2;
    }
}

I've looked up how to deal with percentages as well, which is the way I think I need to go, I just don't know how it works or how to implement it. Any help would be great. Thanks in advance.

Was it helpful?

Solution

If you want a percentage, then Math.random() yields a number between 0 and 1. All you need to do is multiply it by 100 and cast it to an int to get your percentage.

int percentage = ((int)(Math.random() * 100));

This will yield a value between 0 and 99 in your variable percentage.

NOTE: Here's a link to the working code, which generates 10 random percentages.

OTHER TIPS

Lets hero.critchnc be a floatting number between 0 and 1 (0 no chance of critical, 1 always critical), then you have :

if(Math.random() >= (1 - hero.critchnc))
{
   // Critical hit
}

You actually need a random value that have a chance of happening as the hero crit chance, for instance if a hero has 17% percent crit chance and you have a random function that gives you one of one hundred values then 17 of those values (selected in any manner) should actually make a crit hit happen (that is if all one hundred values have the same chance of happening) to translate this to code:

We'll use Random.nextInt(99); this should give us one of one hundred (almost evenly distributed) values. If hero crit chance is expressed as an integer between 0 and 100 (eg 17) now the probability that the returned value by nextInt is a number between 0 - 16 is actually 17% so we can express that in code like this:

    rand = Random.nextInt(99);
    if(rand <= critchance - 1){
       //we have a crit
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top