游戏里的概率
首先看随机数的获取
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(101); // 生成0到100之间的随机整数
System.out.println("随机数: " + randomNumber);
}
}
这样的获取随机值是最简单的,也是java学到变量之后最有趣的一环(比如我5年前学到随机值时多了3,4个demo跑不同的随机数输出)
而打个比方来说,一般游戏中的随机概率值一般应用在如“攻击力50~70”、“暴击概率加成13%”等,这样的概率增强后,一般作为之后的概率基础来进行攻击判定了,比如攻击力这次是打出50还是70还是58还是60,是取的随机值,而暴击则可能是根据原本打出的攻击值乘以数倍的常量,比如原本这一次攻击没有暴击,则可能是伤害值100,打出暴击则是伤害值800……
比如上面这件装备镶嵌的宝石属性中显示,造成伤害时有20%的概率获得某某之力6秒,这个期间暴击率提高16%……
也就是说最终获取暴击率提高是有16%的提升,不过这个提升建立在前一个基础上,即造成伤害时的20%概率,而
整体的20%获取之后也只有6秒的时间,并且冷却时间是20秒,也就是说假如这个20%是100%,那么每次提高暴击率的时间周期也至少有20秒的间隔。
我们把秒数忽略再看,
其中20%的概率打出暴击率提升16%的伤害是毋庸置疑的,在游戏中,如果有这个概率和提升可以说提升是比较大的,但设计者为了减少这种太Bug的存在,则设计成为20%后只生效6秒,也就是6秒里暴击率才提升,并且整体20%打出后的冷却为20秒,当然提升宝石后就不一定是这个值了。
整体暴击概率提升为:
$ \text{{整体概率}} = \text{{获得莉莉斯之力概率20%}} \times \text{{暴击率提高概率16%}} = 0.2 \times 0.16 = 0.032 $
这里给出一段代码模拟这个概率打击:
java
import java.util.Random;
public class Gemstone {
private double lilyPowerProbability; // 获得莉莉斯之力的概率
private double critRateIncrease; // 暴击率提高的幅度
public Gemstone(double lilyPowerProbability, double critRateIncrease) {
this.lilyPowerProbability = lilyPowerProbability;
this.critRateIncrease = critRateIncrease;
}
public boolean hasLilyPower() {
Random random = new Random();
double randomValue = random.nextDouble(); // 生成0到1之间的随机数
return randomValue <= lilyPowerProbability;
}
public double getCritRateIncrease() {
return critRateIncrease;
}
public static void main(String[] args) {
Gemstone gemstone = new Gemstone(0.2, 0.16);
if (gemstone.hasLilyPower()) {
double critRateIncrease = gemstone.getCritRateIncrease();
System.out.println("获得莉莉斯之力,暴击率提高了 " + critRateIncrease * 100 + "%");
} else {
System.out.println("没有获得莉莉斯之力");
}
}
}
python
import random
class Gemstone:
def __init__(self, lilyPowerProbability, critRateIncrease):
self.lilyPowerProbability = lilyPowerProbability
self.critRateIncrease = critRateIncrease
def hasLilyPower(self):
randomValue = random.random() # 生成0到1之间的随机数
return randomValue <= self.lilyPowerProbability
def getCritRateIncrease(self):
return self.critRateIncrease
if __name__ == "__main__":
gemstone = Gemstone(0.2, 0.16)
if gemstone.hasLilyPower():
critRateIncrease = gemstone.getCritRateIncrease()
print("获得莉莉斯之力,暴击率提高了 {:.2%}".format(critRateIncrease))
else:
print("没有获得莉莉斯之力")
本文来自博客园,作者:ukyo--BlackJesus,转载请注明原文链接:https://www.cnblogs.com/ukzq/p/17794792.html