RuneHive-Tarnish
Neural OSRS Enhancement Framework
Loading...
Searching...
No Matches
Chance.java
1package com.osroyale.util.chance;
2
3import com.osroyale.game.world.items.Item;
4
5import java.util.LinkedList;
6import java.util.List;
7
38
39public class Chance<T> {
40
41public enum ChanceType {
42 ALWAYS(100),
43 COMMON(100),
44 UNCOMMON(75),
45 RARE(.6),
46 VERY_RARE(.2);
47
48 private final double weight;
49
50 ChanceType(double weight) {
51 this.weight = weight;
52 }
53
54 public double getWeight() {
55 return weight;
56 }
57 }
58
60 private final List<WeightedObject<T>> objects;
61
63 private double sum;
64
66 public Chance(List<WeightedObject<T>> objects) {
67 this.objects = objects;
68 sum = objects.stream().mapToDouble(WeightedObject::getWeight).sum();
69 objects.sort((first, second) -> (int) Math.signum(second.getWeight() - first.getWeight()));
70 }
71
73 public Chance() {
74 this.objects = new LinkedList<>();
75 sum = 0;
76 }
77
79 public final void add(double weight, T t) {
80 objects.add(new WeightedChance<>(weight, t));
81 sum += weight;
82 objects.sort((first, second) -> (int) Math.signum(second.getWeight() - first.getWeight()));
83 }
84
86 public final void add(ChanceType type, T t) {
87 add(type.getWeight(), t);
88 }
89
91 public T next() {
92 double rnd = Math.random() * sum;
93 double hit = 0;
94
95 for (WeightedObject<T> obj : objects) {
96 hit += obj.getWeight();
97
98 if (hit >= rnd) {
99 return obj.get();
100 }
101 }
102
103 throw new AssertionError("The random number [" + rnd + "] is too large!");
104 }
105
107 public WeightedObject<T> next(double boost) {
108 if (boost <= 0 || boost > 1) {
109 throw new IllegalArgumentException("Boost is outside of the domain: (0, 1]");
110 }
111
112 double rnd = Math.random() * sum;
113 double hit = 0;
114
115 for (WeightedObject<T> obj : objects) {
116 hit += obj.getWeight() + boost;
117
118 if ((int) (hit * (1 + boost)) >= (int) rnd) {
119 return obj;
120 }
121 }
122
123 throw new AssertionError("The random number [" + rnd + "] is too large!");
124 }
125
126 public Item[] toItemArray() {
127 int count = 0;
128 Item[] array = new Item[objects.size()];
129 for (WeightedObject<T> obj : objects) {
130 array[count] = (Item) obj.get();
131 count++;
132 }
133 return array;
134 }
135
136 @Override
137 public String toString() {
138 return objects.toString();
139 }
140
141}
WeightedObject< T > next(double boost)
Definition Chance.java:107
final void add(ChanceType type, T t)
Definition Chance.java:86
Chance(List< WeightedObject< T > > objects)
Definition Chance.java:66
final void add(double weight, T t)
Definition Chance.java:79