Job terrain #12
4
src/main/java/Shared/LootEntry.java
Normal file
4
src/main/java/Shared/LootEntry.java
Normal file
@ -0,0 +1,4 @@
|
||||
package Shared;
|
||||
|
||||
public record LootEntry<T>(T item, int weight) {
|
||||
}
|
||||
@ -1,24 +1,35 @@
|
||||
package Shared;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class LootTable<T> {
|
||||
private Random random = new Random();
|
||||
private final List<T> items = new ArrayList<>();
|
||||
private final Random random;
|
||||
private final List<LootEntry<T>> entries = new ArrayList<>();
|
||||
|
||||
public LootTable() {
|
||||
this.random = new Random();
|
||||
}
|
||||
public LootTable(Random random) {
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
public void addEntry(T entry, int weight) {
|
||||
items.add(entry);
|
||||
entries.add(new LootEntry<>(entry,weight));
|
||||
}
|
||||
|
||||
public T roll() {
|
||||
return items.getFirst();
|
||||
int totalWeight = entries.stream().mapToInt(LootEntry::weight).sum();
|
||||
int roll = random.nextInt(totalWeight);
|
||||
int current = 0;
|
||||
for(LootEntry<T> entry : entries) {
|
||||
current += entry.weight();
|
||||
if (roll < current) {
|
||||
return entry.item();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -25,10 +25,14 @@ public class LootTableTest {
|
||||
assertThat(result, anyOf(equalTo("Stone"), equalTo("Iron")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void respects_weight_when_rolling() {
|
||||
var mockRandom = mock(Random.class);
|
||||
when(mockRandom.nextInt(anyInt())).thenReturn(94);
|
||||
LootTable<String> loot = new LootTable<>(mockRandom);
|
||||
LootTable<String> loot = new LootTable<>(new Random() {
|
||||
@Override
|
||||
public int nextInt(int bound) {
|
||||
return 94;
|
||||
}
|
||||
});
|
||||
loot.addEntry("Stone", 90);
|
||||
loot.addEntry("Iron", 10);
|
||||
String result = loot.roll();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user