Job terrain #12

Merged
erns6604 merged 16 commits from job_terrain into main 2025-10-28 11:21:35 +01:00
3 changed files with 27 additions and 8 deletions
Showing only changes of commit d72e0a8765 - Show all commits

View File

@ -0,0 +1,4 @@
package Shared;
public record LootEntry<T>(T item, int weight) {
}

View File

@ -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;
}
}

View File

@ -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();