feat(economy): add character coins and exact rewards
Release / release (push) Successful in 5m11s

This commit is contained in:
dmg committed 2026-09-21 00:56:09 -04:00
1 parent 0536d4c717
commit 5c5f774dea
30 files changed
+788 -95

No files matched your search

@@ -84,6 +84,11 @@ class DistributionTest {
assertTrue(defaults.contains(setting), "Missing packaged Inspire default: " + setting);
}
assertTrue(defaults.contains("admin-revive-selection-timeout-seconds: 60"));
for (String setting : java.util.List.of("starting-coins-min: 1", "starting-coins-max: 6",
"hostile-coin-drop-min: 1", "hostile-coin-drop-max: 5",
"boss-coin-drop-min: 25", "boss-coin-drop-max: 50")) {
assertTrue(defaults.contains(setting), "Missing packaged coin default: " + setting);
}
assertTrue(defaults.contains("sheet-resource-pack-url: ''"));
assertTrue(defaults.contains("sheet-resource-pack-sha1: ''"));
for (String setting : java.util.List.of("out-of-combat-healing-delay-seconds: 30",
@@ -25,6 +25,9 @@ class CharacterFactoryTest {
assertEquals(character.name(), replay.create(ProgressionRules.defaults()).name());
assertTrue(ids.add(character.id()));
assertEquals(BigInteger.valueOf(40), character.unspentPoints());
assertTrue(character.coinsInitialized());
assertTrue(character.coins().compareTo(BigInteger.ONE) >= 0 && character.coins().compareTo(BigInteger.valueOf(6)) <= 0);
assertTrue(character.rewardReceipts().isEmpty());
names.add(character.name());
}
assertTrue(names.size() > 1, "Names must use the supplied randomness, not a constant placeholder");
@@ -57,6 +60,9 @@ class CharacterFactoryTest {
assertEquals(Set.of(), record.learned());
assertEquals(List.of("", "", "", "", "", "", ""), record.loadout());
assertEquals(Map.of(), record.cooldowns());
assertTrue(record.coinsInitialized());
assertTrue(record.coins().compareTo(BigInteger.ONE) >= 0 && record.coins().compareTo(BigInteger.valueOf(6)) <= 0);
assertTrue(record.rewardReceipts().isEmpty());
assertFalse(record.dead());
assertNull(record.deathId());
assertNull(record.diedAt());
@@ -19,6 +19,31 @@ import org.junit.jupiter.api.io.TempDir;
class CharacterStorageTest {
@TempDir Path data;
@Test
void firstLoadPersistsExactlyOneConfiguredMigrationRollAndNeverRerollsZero() throws Exception {
var repository = new YamlCharacterRepository(data);
var sample = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
var legacy = new CharacterRecord(sample.id(), sample.name(), sample.revision(), sample.stats(), sample.level(),
sample.experience(), sample.unspentPoints(), sample.health(), sample.learned(), sample.loadout(), sample.passives(),
sample.cooldowns(), sample.restrictedKills(), sample.dead(), sample.deathId(), sample.diedAt(),
BigInteger.ZERO, false, java.util.Set.of());
repository.create(legacy);
var rules = new games.dmg.fantasystick.progression.CoinRules(4, 4, 1, 5, 25, 50);
try (var storage = new CharacterStorage(repository, Clock.systemUTC(), () -> rules, new java.util.Random(7))) {
var migrated = storage.find(legacy.id()).join().orElseThrow();
assertTrue(migrated.coinsInitialized());
assertEquals(BigInteger.valueOf(4), migrated.coins());
assertEquals(BigInteger.ONE, migrated.revision());
assertEquals(migrated, storage.find(legacy.id()).join().orElseThrow());
var spent = new CharacterRecord(migrated.id(), migrated.name(), migrated.revision().add(BigInteger.ONE),
migrated.stats(), migrated.level(), migrated.experience(), migrated.unspentPoints(), migrated.health(),
migrated.learned(), migrated.loadout(), migrated.passives(), migrated.cooldowns(), migrated.restrictedKills(),
migrated.dead(), migrated.deathId(), migrated.diedAt(), BigInteger.ZERO, true, migrated.rewardReceipts());
repository.replace(spent, migrated.revision());
assertEquals(BigInteger.ZERO, storage.find(legacy.id()).join().orElseThrow().coins());
}
}
@Test
void performsFileWritesOffTheCallerThreadAndAcknowledgesOnlyAfterCommit() throws Exception {
Thread caller = Thread.currentThread();
@@ -78,6 +103,38 @@ class CharacterStorageTest {
}
}
@Test
void combatRewardAtomicallyPersistsCoinsXpReceiptAndSpacingWithoutDuplicateApplication() throws Exception {
var repository = new YamlCharacterRepository(data);
var progression = new games.dmg.fantasystick.progression.ProgressionRules(BigInteger.ZERO, BigInteger.TEN, 30);
var rewards = games.dmg.fantasystick.progression.CombatRewardRules.defaults();
var base = new games.dmg.fantasystick.crafting.CharacterFactory().create(progression);
var live = new CharacterRecord(base.id(), base.name(), base.revision(), base.stats(), base.level(),
base.experience(), base.unspentPoints(), base.health(), base.learned(), base.loadout(), base.passives(),
base.cooldowns(), base.restrictedKills(), false, null, null, BigInteger.valueOf(3), true, java.util.Set.of());
var rewardId = UUID.randomUUID();
var world = UUID.randomUUID();
var location = new games.dmg.fantasystick.progression.CombatRewardRules.KillPosition(world,
java.math.BigDecimal.ZERO, java.math.BigDecimal.ZERO, java.math.BigDecimal.ZERO);
try (var storage = new CharacterStorage(repository, Clock.systemUTC())) {
storage.create(live).join();
var applied = storage.awardCombatReward(live.id(), live.revision(), rewardId, BigInteger.TEN,
BigInteger.valueOf(5), progression, rewards, location).join();
assertEquals(CharacterStorage.CombatAwardStatus.APPLIED, applied.status());
var saved = applied.record().orElseThrow();
assertEquals(BigInteger.valueOf(8), saved.coins());
assertEquals(BigInteger.TEN, saved.experience());
assertTrue(saved.rewardReceipts().contains(rewardId));
assertEquals(location, saved.restrictedKills().get(world));
var duplicate = storage.awardCombatReward(live.id(), live.revision(), rewardId, BigInteger.TEN,
BigInteger.valueOf(5), progression, rewards, location).join();
assertEquals(CharacterStorage.CombatAwardStatus.DUPLICATE, duplicate.status());
assertEquals(saved, duplicate.record().orElseThrow());
assertEquals(saved, repository.load(live.id()).orElseThrow());
}
}
@Test
void combatAwardsAtomicallyPersistXpPointsAndPerWorldRestrictedKillHistory() throws Exception {
var repository = new YamlCharacterRepository(data);
@@ -0,0 +1,25 @@
package games.dmg.fantasystick.persistence;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class CoinSettingsTest {
@TempDir Path data;
private static Map<String,String> defaults(){var values=new LinkedHashMap<String,String>();for(String key:CoinSettings.keys())values.put(key,CoinSettings.defaultValue(key));return values;}
@Test void validatesPairsAndPublishesOnlyAfterDurableSaveWhilePreservingUnrelatedKeys()throws Exception{
Files.writeString(data.resolve("config.yml"),"unrelated: keep\n");
try(var settings=new CoinSettings(data,defaults())){
assertEquals(1,settings.rules().startingMin());assertEquals(50,settings.rules().bossMax());
assertThrows(IllegalArgumentException.class,()->settings.set(CoinSettings.START_MIN,"7"));
assertThrows(IllegalArgumentException.class,()->settings.set(CoinSettings.BOSS_MAX,"2147483648"));
var update=settings.set(CoinSettings.START_MAX,"9").toCompletableFuture().get(5,TimeUnit.SECONDS);
assertEquals("6",settings.value(CoinSettings.START_MAX));
assertTrue(settings.publish(update));assertEquals("9",settings.value(CoinSettings.START_MAX));
assertTrue(Files.readString(data.resolve("config.yml")).contains("unrelated: keep"));
}
}
}
@@ -43,6 +43,38 @@ class YamlCharacterRepositoryTest {
original.loadout(), original.cooldowns(), original.dead(), original.deathId(), original.diedAt());
}
@Test
void freshCoinStateRoundTripsThroughTheYamlCodec() {
var fresh = new games.dmg.fantasystick.crafting.CharacterFactory().create(
games.dmg.fantasystick.progression.ProgressionRules.defaults());
assertEquals(fresh, CharacterYaml.decode(CharacterYaml.encode(fresh)));
}
@Test
void coinStateAndBoundedRewardReceiptsRoundTripWhileLegacyRecordsRemainUninitialized() throws Exception {
var original = sample(UUID.randomUUID());
var receipt = UUID.randomUUID();
var economy = new CharacterRecord(original.id(), original.name(), original.revision(), original.stats(),
original.level(), original.experience(), original.unspentPoints(), original.health(), original.learned(),
original.loadout(), original.passives(), original.cooldowns(), original.restrictedKills(), original.dead(),
original.deathId(), original.diedAt(), BigInteger.TEN.pow(200), true, Set.of(receipt));
var repository = new YamlCharacterRepository(data);
repository.create(economy);
assertEquals(economy, repository.load(economy.id()).orElseThrow());
String yaml = Files.readString(data.resolve("characters").resolve(economy.id() + ".yml"));
assertTrue(yaml.contains("coins: '" + BigInteger.TEN.pow(200) + "'"));
assertTrue(yaml.contains(receipt.toString()));
String legacy = CharacterYaml.encode(original)
.replace("coins-initialized: true\n", "")
.replace("coins: '0'\n", "")
.replace("reward-receipts: []\n", "");
var decoded = CharacterYaml.decode(legacy);
assertFalse(decoded.coinsInitialized());
assertEquals(BigInteger.ZERO, decoded.coins());
assertTrue(decoded.rewardReceipts().isEmpty());
}
@Test
void restrictedKillHistoryRoundTripsPerWorldAndOldRecordsRemainCompatible() throws Exception {
var original = sample(UUID.randomUUID());
@@ -0,0 +1,32 @@
package games.dmg.fantasystick.progression;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigInteger;
import java.util.random.RandomGenerator;
import org.junit.jupiter.api.Test;
class CoinRulesTest {
@Test void inclusiveConfiguredRollsAreDeterministicBoundedAndClassifiedIndependentlyFromXp() {
var rules = new CoinRules(1, 6, 1, 5, 25, 50);
var minimum = new FixedRandom(0);
var maximum = new FixedRandom(Long.MAX_VALUE);
assertEquals(BigInteger.ONE, rules.starting(minimum));
assertEquals(BigInteger.valueOf(6), rules.starting(maximum));
assertEquals(BigInteger.ONE, rules.mob(CoinRules.Target.HOSTILE, minimum));
assertEquals(BigInteger.valueOf(5), rules.mob(CoinRules.Target.HOSTILE, maximum));
assertEquals(BigInteger.valueOf(25), rules.mob(CoinRules.Target.BOSS, minimum));
assertEquals(BigInteger.valueOf(50), rules.mob(CoinRules.Target.BOSS, maximum));
assertEquals(BigInteger.ZERO, rules.mob(CoinRules.Target.PASSIVE, maximum));
assertEquals(BigInteger.ZERO, rules.mob(CoinRules.Target.NEUTRAL, maximum));
assertThrows(IllegalArgumentException.class, () -> new CoinRules(6, 1, 1, 5, 25, 50));
assertThrows(IllegalArgumentException.class, () -> new CoinRules(0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE + 1L));
}
private static final class FixedRandom implements RandomGenerator {
private final long value;
private FixedRandom(long value) { this.value = value; }
@Override public long nextLong() { return value; }
@Override public long nextLong(long bound) { return value == 0 ? 0 : bound - 1; }
}
}
@@ -0,0 +1,33 @@
package games.dmg.fantasystick.progression;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.junit.jupiter.api.Test;
class RewardAllocatorTest {
@Test void conservesExactPoolsAcrossSoloAndPartyUnitsWithDistinctRandomRemainders() {
var units = List.of(
new RewardAllocator.Unit<String>("solo", List.of("solo")),
new RewardAllocator.Unit<String>("party", List.of("a", "b", "c")));
var allocation = RewardAllocator.allocate(BigInteger.TEN, units, new Random(7));
assertEquals(BigInteger.valueOf(5), allocation.get("solo"));
assertEquals(BigInteger.valueOf(5), allocation.get("a").add(allocation.get("b")).add(allocation.get("c")));
assertEquals(BigInteger.TEN, allocation.values().stream().reduce(BigInteger.ZERO, BigInteger::add));
assertEquals(List.of(BigInteger.ONE, BigInteger.TWO, BigInteger.TWO),
allocation.entrySet().stream().filter(entry -> !entry.getKey().equals("solo"))
.map(Map.Entry::getValue).sorted().toList());
var one = RewardAllocator.allocate(BigInteger.ONE,
List.of(new RewardAllocator.Unit<>("p", List.of("a", "b", "c"))), new Random(11));
assertEquals(BigInteger.ONE, one.values().stream().reduce(BigInteger.ZERO, BigInteger::add));
assertEquals(1, one.values().stream().filter(BigInteger.ONE::equals).count());
assertEquals(2, one.values().stream().filter(BigInteger.ZERO::equals).count());
assertThrows(IllegalArgumentException.class, () -> RewardAllocator.allocate(BigInteger.ONE,
List.of(new RewardAllocator.Unit<>("x", List.of("same")),
new RewardAllocator.Unit<>("y", List.of("same"))), new Random(1)));
}
}