Math.Random,计算百分比

时间:2015-01-20 21:18:32

标签: java percentage

:d 我正在制作一个RPG,制作战斗系统,如果玩家攻击与敌人接触造成伤害,那么现在我要做的就是在混合和阻挡中添加致命一击。

它应该如何运作?首先它将基于他的阻挡机会来阻止怪物阻挡的几率,如果它阻止传入的伤害减少到零,如果它没有根据玩家的爆击几率滚动爆击几率,如果它的关键它将根据玩家的爆击倍数处理x额外伤害。

现在我想知道的是如何计算百分比机会,我已经看过几个帖子,但他们通常会将百分比变成一个整数,而且我的玩家可能会以1.7%或3.9%的低点开始,但不是1-2-3-5,百分比不变。有人有关于如何制作它的建议吗?

到目前为止代码是这样的:

public class Player{
private double criticalStrikeChance = 0.009; <--- thats 0.9% chance.
private double criticalStrikeMultiplier = 1.2; <--- thats 120% moar damage

public double getCritStrk(){
   return criticalStrikeChance;
                       }

}

public class Monster(){
private double blockingChance = 0.3; <--- thats 30%
private double blockingReduction = 0.75; <--- thats 75% reduced damage when blocking

}


public class Game(){

public void checkIfDamaged(){

if(intersects){

       // blockroll should be done here based on the monster chance

       if(blockRoll >= minimum he had to roll){
         //means its successfull
          monster.getHit(0); //PEANUT DAMAGE ACHIEVED GREAT SUCCESS 
          }else{

           //Critical strike chance should be rolled here based on player
           //chance
            if(critstrike successful){ 
               incdamage + (incdamage * player.criticalStrikeMultiplier;
                      monster.getHit(incdamage);
                                  }
          }else{//Crit didnt roll with cinnamon
                 monster.getHit(player.getDamage);
               }


       }

}

}

好的,所以它几乎就像伪代码一样,因为我的代码看起来有所不同,但这很简单,应该让你们知道它应该如何工作,所以请帮助我senpais!我应该给你CHOCO COOKIES +一个很好的盾牌,100%的阻挡率:D对任何人遏制我!

2 个答案:

答案 0 :(得分:1)

如果您只是想要随机滚动百分比,可以在java中使用Random类。

    Random rand = new Random(); 
    Double pickedNumber = rand.nextDouble();

运行它会导致pickedNumber在0和1之间变为double。例如:

0.3650998187710377

然后检查该百分比是否小于你的阻挡/暴击几率。例如:

if(pickedNumber < blockChange)
    //doBlock();

完整的示例,对于测试用例可能是这样的:

private static Random rand = new Random(); 

public static void main(String[] args) {

    double blockChance = .5; // 50% chance to block the attack

    Double pickedNumber = rand.nextDouble(); // Roll to see if we block the attack

    System.out.println(pickedNumber); // output roll for debug purposes

    if(pickedNumber < blockChance){ // if the attack was blocked
        System.out.println("Blocked"); // do block logic
    }else{ // if the attack wasn't blocked
        System.out.println("Damaged"); // do damage logic
    }
}

这给了我输出:

0.2768592334674802
Blocked

并且:

0.8762124334674802
Damaged

答案 1 :(得分:1)

另一种方法: 得到0.75:

if (Math.random() < 0.75) {
   //do this with probability 0.75
}