java – 如何编写一个可以轻松维护的概率算法?

前端之家收集整理的这篇文章主要介绍了java – 如何编写一个可以轻松维护的概率算法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我想创造一个游戏.在游戏开始时,玩家将挑选一个怪物.

公平地挑选怪物很容易.

  1. // get all monsters with equal chance
  2. public Monster getMonsterFair(){
  3. Monster[] monsters = {new GoldMonster(),new SilverMonster(),new BronzeMonster()};
  4. int winIndex = random.nextInt(monsters.length);
  5. return monsters[winIndex];
  6. }

并不公平地挑选怪物.

  1. // get monsters with unequal chance
  2. public Monster getMonsterUnFair(){
  3. double r = Math.random();
  4. // about 10% to win the gold one
  5. if (r < 0.1){
  6. return new GoldMonster();
  7. }
  8. // about 30% to winthe silver one
  9. else if ( r < 0.1 + 0.2){
  10. return new SilverMonster();
  11. }
  12. // about 70% to win the bronze one
  13. else {
  14. return new BronzeMonster();
  15. }
  16. }

问题是,当我在游戏中添加一个新怪物时,我必须编辑if-else.
或者我将赢得GoldMonster的机会改为0.2,我必须将所有0.1改为0.2
这很难看,也不容易维护.

  1. // get monsters with unequal change & special monster
  2. public Monster getMonsterSpecial(){
  3. double r = Math.random();
  4. // about 10% to win the gold one
  5. if (r < 0.1){
  6. return new GoldMonster();
  7. }
  8. // about 30% to win the silver one
  9. else if ( r < 0.1 + 0.2){
  10. return new SilverMonster();
  11. }
  12. // about 50% to win the special one
  13. else if ( r < 0.1 + 0.2 + 0.2){
  14. return new SpecialMonster();
  15. }
  16. // about 50% to win the bronze one
  17. else {
  18. return new BronzeMonster();
  19. }
  20. }

如何重构这种概率算法,以便在添加新怪物并调整获胜怪物的机会时可以轻松维护代码

解决方法

基本上是@Egor Skriptunoff所说的.这应该很容易扩展.你可以使用Class< Monster>的集合.如果你不想使用枚举.
  1. enum Monster {
  2. GOLD(1),SILVER(3),BRONZE(6) // pseudo probabilities
  3.  
  4. private int weight;
  5. // constructor etc..
  6. }
  7.  
  8. public Monster getMonsterSpecial() {
  9. List<Monster> monsters = new ArrayList<>();
  10.  
  11. for(Monster monsterType : Monster.values()) {
  12. monsters.addAll(Collections.nCopies(monsterType.getWeight(),monsterType));
  13. }
  14.  
  15. int winIndex = random.nextInt(monsters.length);
  16. return monsters.get(winIndex);
  17. }

你也许可以使枚举怪物复数,并让它指向一个类<?延伸怪物>如果你还想实例化怪物类.我只是想让这个例子更加清晰.

猜你在找的Java相关文章