From 1ecfabaed59cd261e58a1fdde03b37fc3305c919 Mon Sep 17 00:00:00 2001 From: Fiereu Date: Wed, 5 Aug 2026 10:38:55 +0200 Subject: [PATCH] feat(game): give monsters their real level up moveset (#85) * feat(codegen): generate the level up learnsets from the decomp * feat(game): give monsters their real level up moveset --- codegen/build.gradle.kts | 5 ++ .../jte/learnset/LearnsetRegistry.jte | 26 ++++++ .../de/fiereu/openmmo/codegen/DecompTables.kt | 13 +++ .../codegen/learnset/LearnsetParser.kt | 67 ++++++++++++++++ .../codegen/learnset/LearnsetRenderer.kt | 39 +++++++++ .../fiereu/openmmo/codegen/learnset/Main.kt | 21 +++++ .../openmmo/codegen/learnset/ParsedModel.kt | 5 ++ .../openmmo/codegen/learnset/RenderUtil.kt | 9 +++ .../fiereu/openmmo/codegen/move/MoveParser.kt | 7 +- .../openmmo/codegen/pokemon/NationalDex.kt | 16 ++-- .../openmmo/codegen/pokemon/SpeciesParser.kt | 7 +- .../openmmo/pokemon/LearnsetRegistry.kt | 46 +++++++++++ .../openmmo/pokemon/LearnsetRegistryTest.kt | 79 +++++++++++++++++++ .../de/fiereu/openmmo/common/Pokemon.kt | 4 +- .../net/game/packets/LearnedMovesetPacket.kt | 5 ++ .../net/game/packets/battle/BattleMonBlock.kt | 3 +- .../openmmo/server/game/battle/MoveLearner.kt | 43 ++++++++++ .../server/game/battle/WildMonFactory.kt | 20 +++-- .../server/game/services/BattleService.kt | 7 ++ .../server/game/battle/MoveLearnerTest.kt | 79 +++++++++++++++++++ .../server/game/battle/WildMonFactoryTest.kt | 16 +++- .../server/game/services/BattleServiceTest.kt | 7 +- 22 files changed, 485 insertions(+), 39 deletions(-) create mode 100644 codegen/src/generator/jte/learnset/LearnsetRegistry.jte create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/DecompTables.kt create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetParser.kt create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetRenderer.kt create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/Main.kt create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/ParsedModel.kt create mode 100644 codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/RenderUtil.kt create mode 100644 codegen/src/main/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistry.kt create mode 100644 codegen/src/test/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistryTest.kt create mode 100644 server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearner.kt create mode 100644 server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearnerTest.kt diff --git a/codegen/build.gradle.kts b/codegen/build.gradle.kts index 6145d5e..d4db25c 100644 --- a/codegen/build.gradle.kts +++ b/codegen/build.gradle.kts @@ -52,6 +52,11 @@ jteCodegen { inputDirs.from(sourceDecompDir) extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath)) } + register("learnset") { + mainClass.set("de.fiereu.openmmo.codegen.learnset.Main") + inputDirs.from(sourceDecompDir) + extraArgs.set(listOf(sourceDecompDir.asFile.absolutePath)) + } // Per region flag and var key constants for scripts. Names come from each decomp, so this is by // region like maps. The generic story store in server.game does not depend on these, they are the // GBA adapter that gives ported scripts readable keys. diff --git a/codegen/src/generator/jte/learnset/LearnsetRegistry.jte b/codegen/src/generator/jte/learnset/LearnsetRegistry.jte new file mode 100644 index 0000000..8003098 --- /dev/null +++ b/codegen/src/generator/jte/learnset/LearnsetRegistry.jte @@ -0,0 +1,26 @@ +@import java.util.List +@import de.fiereu.openmmo.codegen.learnset.ParsedLearnset +@import de.fiereu.openmmo.codegen.learnset.RenderUtil + +@param List> chunks +package de.fiereu.openmmo.pokemon.generated + +import de.fiereu.openmmo.pokemon.LearnsetRegistry +import de.fiereu.openmmo.pokemon.LevelUpMove + +internal object GeneratedLearnsets { + fun loadInto(reg: LearnsetRegistry) { +@for(int i = 0; i < chunks.size(); i++) + registerChunk${i}(reg) +@endfor + } + +@for(int c = 0; c < chunks.size(); c++) + private fun registerChunk${c}(reg: LearnsetRegistry) { +@for(ParsedLearnset l : chunks.get(c)) + ${RenderUtil.INSTANCE.learnset(l)} +@endfor + } + +@endfor +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/DecompTables.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/DecompTables.kt new file mode 100644 index 0000000..cac8713 --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/DecompTables.kt @@ -0,0 +1,13 @@ +package de.fiereu.openmmo.codegen + +import java.io.File + +/** Reads a `#define ` block, keyed by the full constant name. */ +fun defineTable(file: File, prefix: String): Map { + if (!file.exists()) return emptyMap() + val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""") + return file + .readLines() + .mapNotNull { regex.find(it.trim()) } + .associate { it.groupValues[1] to it.groupValues[2].toInt() } +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetParser.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetParser.kt new file mode 100644 index 0000000..c114afb --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetParser.kt @@ -0,0 +1,67 @@ +package de.fiereu.openmmo.codegen.learnset + +import de.fiereu.openmmo.codegen.defineTable +import de.fiereu.openmmo.codegen.pokemon.NationalDex +import de.fiereu.openmmo.codegen.pokemon.SpeciesParser +import java.io.File + +class LearnsetParser(private val rootDir: File) { + + fun parseAll(): List { + val speciesIds = readDefineTable("include/constants/species.h", "SPECIES_") + val nationalDex = NationalDex.read(rootDir) + val moveIds = readDefineTable("include/constants/moves.h", "MOVE_") + val tables = readTables() + // The decomp keeps learnset pointers for placeholder species with no stats, drop those. + val known = SpeciesParser(rootDir).parseAll().mapTo(HashSet()) { it.id } + + return readPointers() + .mapNotNull { (constant, symbol) -> + // Same as the species data, the client keys by national dex. + val dexId = speciesIds[constant]?.let { nationalDex[it] } ?: return@mapNotNull null + if (dexId !in known) return@mapNotNull null + val entries = tables[symbol] ?: return@mapNotNull null + val moves = + entries.mapNotNull { (level, move) -> + moveIds[move]?.let { ParsedLevelUpMove(level, it) } + } + if (moves.isEmpty()) null else ParsedLearnset(dexId, moves) + } + .sortedBy { it.dexId } + } + + // static const u16 sLevelUpLearnset[] = { LEVEL_UP_MOVE(lvl, MOVE_X), ... }; + private fun readTables(): Map>> { + val file = File(rootDir, "src/data/pokemon/level_up_learnsets.h") + require(file.exists()) { + "Decomp not initialized at $rootDir (missing ${file.path}). " + + "Run: git submodule update --init --recursive" + } + val table = + Regex( + """static\s+const\s+u16\s+(\w+)\s*\[\s*]\s*=\s*\{(.*?)}""", + RegexOption.DOT_MATCHES_ALL, + ) + val move = Regex("""LEVEL_UP_MOVE\(\s*(\d+)\s*,\s*(MOVE_\w+)\s*\)""") + return table.findAll(file.readText()).associate { match -> + match.groupValues[1] to + move + .findAll(match.groupValues[2]) + .map { it.groupValues[1].toInt() to it.groupValues[2] } + .toList() + } + } + + private fun readPointers(): Map { + val file = File(rootDir, "src/data/pokemon/level_up_learnset_pointers.h") + require(file.exists()) { "Missing learnset pointer table at ${file.path}" } + val regex = Regex("""\[(SPECIES_\w+)]\s*=\s*(\w+)""") + return regex.findAll(file.readText()).associate { it.groupValues[1] to it.groupValues[2] } + } + + private fun readDefineTable(path: String, prefix: String): Map { + val file = File(rootDir, path) + require(file.exists()) { "Missing $prefix table at ${file.path}" } + return defineTable(file, prefix) + } +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetRenderer.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetRenderer.kt new file mode 100644 index 0000000..5acb855 --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/LearnsetRenderer.kt @@ -0,0 +1,39 @@ +package de.fiereu.openmmo.codegen.learnset + +import gg.jte.ContentType +import gg.jte.TemplateEngine +import gg.jte.output.FileOutput +import gg.jte.resolve.DirectoryCodeResolver +import java.io.File + +class LearnsetRenderer( + private val templatesDir: File, + private val outputDir: File, + private val classCacheDir: File, + private val registryChunkSize: Int = 50, +) { + + fun render(learnsets: List) { + classCacheDir.mkdirs() + val engine = + TemplateEngine.create( + DirectoryCodeResolver(templatesDir.toPath()), + classCacheDir.toPath(), + ContentType.Plain, + ) + + val packageRoot = File(outputDir, BASE_PACKAGE.replace('.', '/')) + if (packageRoot.exists()) packageRoot.deleteRecursively() + + val chunks = learnsets.sortedBy { it.dexId }.chunked(registryChunkSize) + val registry = File(outputDir, "${BASE_PACKAGE.replace('.', '/')}/GeneratedLearnsets.kt") + registry.parentFile.mkdirs() + FileOutput(registry.toPath()).use { out -> + engine.render("LearnsetRegistry.jte", mapOf("chunks" to chunks), out) + } + } + + companion object { + private const val BASE_PACKAGE = "de.fiereu.openmmo.pokemon.generated" + } +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/Main.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/Main.kt new file mode 100644 index 0000000..e8d65fe --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/Main.kt @@ -0,0 +1,21 @@ +@file:JvmName("Main") + +package de.fiereu.openmmo.codegen.learnset + +import java.io.File + +fun main(args: Array) { + require(args.size >= 4) { + "Usage: got ${args.toList()}" + } + val outputDir = File(args[0]) + val templatesDir = File(args[1]) + val classCacheDir = File(args[2]) + val decompDir = File(args[3]) + + println("[learnset] parsing from $decompDir") + val learnsets = LearnsetParser(decompDir).parseAll() + println("[learnset] parsed ${learnsets.size} learnsets. writing to $outputDir") + LearnsetRenderer(templatesDir, outputDir, classCacheDir).render(learnsets) + println("[learnset] done") +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/ParsedModel.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/ParsedModel.kt new file mode 100644 index 0000000..d89040b --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/ParsedModel.kt @@ -0,0 +1,5 @@ +package de.fiereu.openmmo.codegen.learnset + +data class ParsedLearnset(val dexId: Int, val moves: List) + +data class ParsedLevelUpMove(val level: Int, val moveId: Int) diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/RenderUtil.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/RenderUtil.kt new file mode 100644 index 0000000..7e81240 --- /dev/null +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/learnset/RenderUtil.kt @@ -0,0 +1,9 @@ +package de.fiereu.openmmo.codegen.learnset + +object RenderUtil { + + fun learnset(l: ParsedLearnset): String { + val moves = l.moves.joinToString(", ") { "LevelUpMove(${it.level}, ${it.moveId})" } + return "reg.register(${l.dexId}, listOf($moves))" + } +} diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/move/MoveParser.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/move/MoveParser.kt index 399812e..37d5fc1 100644 --- a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/move/MoveParser.kt +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/move/MoveParser.kt @@ -1,5 +1,6 @@ package de.fiereu.openmmo.codegen.move +import de.fiereu.openmmo.codegen.defineTable import java.io.File class MoveParser(private val rootDir: File) { @@ -35,11 +36,7 @@ class MoveParser(private val rootDir: File) { "Decomp not initialized at $rootDir (missing ${file.path}). " + "Run: git submodule update --init --recursive" } - val regex = Regex("""^#define\s+(MOVE_\w+)\s+(\d+)\s*$""") - return file - .readLines() - .mapNotNull { regex.find(it.trim()) } - .associate { it.groupValues[1] to it.groupValues[2].toInt() } + return defineTable(file, "MOVE_") } private fun readMoveNames(): Map { diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/NationalDex.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/NationalDex.kt index c237ecf..3f1561b 100644 --- a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/NationalDex.kt +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/NationalDex.kt @@ -1,5 +1,6 @@ package de.fiereu.openmmo.codegen.pokemon +import de.fiereu.openmmo.codegen.defineTable import java.io.File /** @@ -10,23 +11,16 @@ import java.io.File object NationalDex { fun read(rootDir: File): Map { - val internalBySuffix = defineTable(File(rootDir, "include/constants/species.h"), "SPECIES_") + val internalBySuffix = + defineTable(File(rootDir, "include/constants/species.h"), "SPECIES_").mapKeys { + it.key.removePrefix("SPECIES_") + } val nationalBySuffix = enumTable(File(rootDir, "include/constants/pokedex.h"), "NATIONAL_DEX_") return internalBySuffix .mapNotNull { (suffix, internal) -> nationalBySuffix[suffix]?.let { internal to it } } .toMap() } - // #define SPECIES_ - private fun defineTable(file: File, prefix: String): Map { - if (!file.exists()) return emptyMap() - val re = Regex("""^#define\s+$prefix(\w+)\s+(\d+)\s*$""") - return file - .readLines() - .mapNotNull { re.find(it.trim()) } - .associate { it.groupValues[1] to it.groupValues[2].toInt() } - } - // A plain enum where each NATIONAL_DEX_ takes the next value, starting at NONE = 0. private fun enumTable(file: File, prefix: String): Map { if (!file.exists()) return emptyMap() diff --git a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/SpeciesParser.kt b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/SpeciesParser.kt index 8d67f5c..adf6824 100644 --- a/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/SpeciesParser.kt +++ b/codegen/src/generator/kotlin/de/fiereu/openmmo/codegen/pokemon/SpeciesParser.kt @@ -1,5 +1,6 @@ package de.fiereu.openmmo.codegen.pokemon +import de.fiereu.openmmo.codegen.defineTable import java.io.File class SpeciesParser(private val rootDir: File) { @@ -86,11 +87,7 @@ class SpeciesParser(private val rootDir: File) { private fun readDefineTable(path: String, prefix: String): Map { val file = File(rootDir, path) require(file.exists()) { "Missing $prefix table at ${file.path}" } - val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""") - return file - .readLines() - .mapNotNull { regex.find(it.trim()) } - .associate { it.groupValues[1] to it.groupValues[2].toInt() } + return defineTable(file, prefix) } private fun braceList(value: String): List = diff --git a/codegen/src/main/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistry.kt b/codegen/src/main/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistry.kt new file mode 100644 index 0000000..e195a79 --- /dev/null +++ b/codegen/src/main/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistry.kt @@ -0,0 +1,46 @@ +package de.fiereu.openmmo.pokemon + +import de.fiereu.openmmo.common.MAX_MOVE_SLOTS +import de.fiereu.openmmo.pokemon.generated.GeneratedLearnsets +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +data class LevelUpMove(val level: Int, val moveId: Int) + +/** The level up learnsets from the decomp, keyed by national dex id and sorted by level. */ +@Singleton +class LearnsetRegistry @Inject constructor() { + + private val learnsets = ConcurrentHashMap>() + + init { + GeneratedLearnsets.loadInto(this) + } + + fun register(dexId: Int, moves: List) { + learnsets[dexId] = moves + } + + fun get(dexId: Int): List = learnsets[dexId] ?: emptyList() + + fun movesAt(dexId: Int, level: Int): List = + get(dexId).filter { it.level == level }.map { it.moveId } + + /** + * The moveset a monster generated at this level starts with. Like the games, the learnset is + * walked in order and a fifth move pushes out the oldest one. + */ + fun initialMoveset(dexId: Int, level: Int): List { + val slots = ArrayList(MAX_MOVE_SLOTS) + for (entry in get(dexId)) { + if (entry.level > level) break + if (entry.moveId in slots) continue + if (slots.size == MAX_MOVE_SLOTS) slots.removeAt(0) + slots += entry.moveId + } + return slots + } + + fun size(): Int = learnsets.size +} diff --git a/codegen/src/test/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistryTest.kt b/codegen/src/test/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistryTest.kt new file mode 100644 index 0000000..5a5a7e4 --- /dev/null +++ b/codegen/src/test/kotlin/de/fiereu/openmmo/pokemon/LearnsetRegistryTest.kt @@ -0,0 +1,79 @@ +package de.fiereu.openmmo.pokemon + +import de.fiereu.openmmo.common.MAX_MOVE_SLOTS +import de.fiereu.openmmo.moves.MoveRegistry +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.ints.shouldBeGreaterThan +import io.kotest.matchers.shouldBe + +private const val TACKLE = 33 +private const val GROWL = 45 +private const val LEECH_SEED = 73 +private const val VINE_WHIP = 22 +private const val POISON_POWDER = 77 +private const val SLEEP_POWDER = 79 +private const val SWEET_SCENT = 230 +private const val GROWTH = 74 +private const val SYNTHESIS = 235 +private const val SOLAR_BEAM = 76 + +class LearnsetRegistryTest : + FunSpec({ + val learnsets = LearnsetRegistry() + + test("every species with stats has a learnset") { + learnsets.size() shouldBe SpeciesRegistry().size() + } + + test("a learnset is sorted by level") { + for (dexId in 1..learnsets.size()) { + val levels = learnsets.get(dexId).map { it.level } + levels shouldBe levels.sorted() + } + } + + test("Bulbasaur learns the moves it does in the games") { + learnsets.get(1).take(4) shouldBe + listOf( + LevelUpMove(1, TACKLE), + LevelUpMove(4, GROWL), + LevelUpMove(7, LEECH_SEED), + LevelUpMove(10, VINE_WHIP), + ) + } + + test("two moves can share a level") { + learnsets.movesAt(1, 15) shouldBe listOf(POISON_POWDER, SLEEP_POWDER) + } + + test("a level with no move learns nothing") { learnsets.movesAt(1, 2).shouldBeEmpty() } + + test("the initial moveset stops at the given level") { + learnsets.initialMoveset(1, 1) shouldBe listOf(TACKLE) + learnsets.initialMoveset(1, 10) shouldBe listOf(TACKLE, GROWL, LEECH_SEED, VINE_WHIP) + } + + test("a fifth move pushes out the oldest one") { + learnsets.initialMoveset(1, 100) shouldBe listOf(SWEET_SCENT, GROWTH, SYNTHESIS, SOLAR_BEAM) + } + + test("no moveset is longer than four moves") { + for (dexId in 1..learnsets.size()) { + learnsets.initialMoveset(dexId, 100).size shouldBe + minOf(MAX_MOVE_SLOTS, learnsets.get(dexId).map { it.moveId }.distinct().size) + } + } + + test("an unknown species has no learnset") { + learnsets.get(9999).shouldBeEmpty() + learnsets.initialMoveset(9999, 50).shouldBeEmpty() + } + + test("every learned move is in the move registry") { + val moves = MoveRegistry() + val learned = (1..learnsets.size()).flatMap { learnsets.get(it) } + learned.size shouldBeGreaterThan 0 + learned.filter { moves.get(it.moveId) == null }.shouldBeEmpty() + } + }) diff --git a/common/src/main/kotlin/de/fiereu/openmmo/common/Pokemon.kt b/common/src/main/kotlin/de/fiereu/openmmo/common/Pokemon.kt index 8b85c8e..8cc5d66 100644 --- a/common/src/main/kotlin/de/fiereu/openmmo/common/Pokemon.kt +++ b/common/src/main/kotlin/de/fiereu/openmmo/common/Pokemon.kt @@ -6,6 +6,8 @@ import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonNature import java.time.LocalDateTime +const val MAX_MOVE_SLOTS = 4 + data class Pokemon( val id: Long, val ownerId: Long, @@ -36,7 +38,7 @@ data class Pokemon( PokemonNature.entries[((seed.toLong() and 0xFFFFFFFFL) % PokemonNature.entries.size).toInt()] init { - require(moves.size <= 4) { "A Pokemon can't have more than 4 moves" } + require(moves.size <= MAX_MOVE_SLOTS) { "A Pokemon can't have more than $MAX_MOVE_SLOTS moves" } } } diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/LearnedMovesetPacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/LearnedMovesetPacket.kt index cc2475a..5c26ab6 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/LearnedMovesetPacket.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/LearnedMovesetPacket.kt @@ -17,6 +17,11 @@ data class LearnedMoveSlot( val appearance: LearnedMoveAppearance?, ) +// TODO Decide how a monster stores the moves it has learned +// Nothing sends LearnedMovesetPacket (S2C 0x7A) or reads SetActiveMovesetPacket (C2S 0x3C), and +// ByteDex holds no capture of either. Both shapes suggest the client keeps every learned move and +// picks four active ones, which Pokemon cannot hold today because it caps moves at four. Capture +// the flow, then either move to a learned pool or drop the packets. data class LearnedMovesetPacket( val moves: List, ) diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt index ac0d1c2..012f212 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt @@ -1,6 +1,7 @@ package de.fiereu.openmmo.net.game.packets.battle import de.fiereu.bytecodec.* +import de.fiereu.openmmo.common.MAX_MOVE_SLOTS /** * One monster as the battle packets carry it, shared by the field state and the switch-in. The @@ -27,7 +28,7 @@ data class BattleMonBlock( } companion object { - const val MOVE_SLOTS = 4 + const val MOVE_SLOTS = MAX_MOVE_SLOTS } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearner.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearner.kt new file mode 100644 index 0000000..7b7513f --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearner.kt @@ -0,0 +1,43 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.MAX_MOVE_SLOTS +import de.fiereu.openmmo.common.PokemonMove +import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.LearnsetRegistry +import javax.inject.Inject +import javax.inject.Singleton + +/** A move learned on level up, ready to be announced to the player. */ +data class LearnedMove(val level: Int, val moveId: Int, val name: String) + +/** Teaches the level up moves a monster gained from a level range. */ +@Singleton +class MoveLearner +@Inject +constructor( + private val learnsets: LearnsetRegistry, + private val moves: MoveRegistry, +) { + + /** + * Adds every move learned above [fromLevel] up to [toLevel] that fits a free slot and returns + * them. A monster that already knows four moves learns nothing. + */ + // TODO Let the player replace a move when the moveset is full + // A monster with four moves silently skips every move it would learn on level up. The client's + // move learn prompt packets are unknown, ByteDex holds no capture of them. Capture the prompt + // and the answer, then apply the chosen slot here. + fun learn(known: MutableList, dexId: Int, fromLevel: Int, toLevel: Int) = buildList { + for (level in fromLevel + 1..toLevel) { + for (moveId in learnsets.movesAt(dexId, level)) { + if (known.any { it.id.toInt() == moveId }) continue + val def = moves.get(moveId) ?: continue + val slot = known.indexOfFirst { it.id.toInt() == 0 } + if (slot < 0 && known.size >= MAX_MOVE_SLOTS) continue + val learned = PokemonMove(moveId.toShort(), def.pp.toByte()) + if (slot < 0) known += learned else known[slot] = learned + add(LearnedMove(level, moveId, def.name)) + } + } + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt index 3d3d85b..bffc70f 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt @@ -1,11 +1,13 @@ package de.fiereu.openmmo.server.game.battle +import de.fiereu.openmmo.common.MAX_MOVE_SLOTS import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.enums.EVs import de.fiereu.openmmo.common.enums.IVs import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.LearnsetRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.server.game.storage.EntityIdService import java.time.LocalDateTime @@ -22,6 +24,7 @@ class WildMonFactory constructor( private val species: SpeciesRegistry, private val moves: MoveRegistry, + private val learnsets: LearnsetRegistry, private val entityIds: EntityIdService, ) { @@ -36,10 +39,11 @@ constructor( spDef = rng.ivRoll() spd = rng.ivRoll() } - // TODO Give wild monsters their real level up moveset - // Parse level_up_learnsets.h in a new codegen generator, use it here for wild movesets and - // for learning moves on level up, and capture the client's move learn prompt packets. - val tacklePp = (moves.get(TACKLE_ID)?.pp ?: FALLBACK_PP).toByte() + // Species without a learnset fall back to Tackle so the monster can still attack. + val moveIds = learnsets.initialMoveset(dexId, level).ifEmpty { listOf(TACKLE_ID) } + val moveset = + moveIds.map { PokemonMove(it.toShort(), (moves.get(it)?.pp ?: FALLBACK_PP).toByte()) } + + List(MAX_MOVE_SLOTS - moveIds.size) { PokemonMove(0, 0) } val mon = Pokemon( id = entityIds.newMonsterId(), @@ -55,13 +59,7 @@ constructor( xp = ExpCurves.totalXpFor(def.growthRate, level), eVs = EVs(), iVs = ivs, - moves = - listOf( - PokemonMove(TACKLE_ID.toShort(), tacklePp), - PokemonMove(0, 0), - PokemonMove(0, 0), - PokemonMove(0, 0), - ), + moves = moveset, isShiny = false, hasHiddenAbility = false, isAlpha = false, diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt index 4360fab..60f4828 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt @@ -20,6 +20,7 @@ import de.fiereu.openmmo.server.game.battle.BattleRegistry import de.fiereu.openmmo.server.game.battle.BattleResult import de.fiereu.openmmo.server.game.battle.BattleRewards import de.fiereu.openmmo.server.game.battle.BattleRng +import de.fiereu.openmmo.server.game.battle.MoveLearner import de.fiereu.openmmo.server.game.battle.StatCalculator import de.fiereu.openmmo.server.game.battle.TurnEngine import de.fiereu.openmmo.server.game.battle.WildMonFactory @@ -61,6 +62,7 @@ constructor( private val wildMons: WildMonFactory, private val emitter: BattlePacketEmitter, private val rewards: BattleRewards, + private val moveLearner: MoveLearner, private val interestManager: InterestManager, private val speciesRegistry: SpeciesRegistry, private val moveRegistry: MoveRegistry, @@ -326,7 +328,12 @@ constructor( "char=${battle.charId} won: +${reward.xpGained} xp, level ${winner.level} -> ${reward.newLevel}" } winner.currentHp = reward.newCurrentHp + val learned = + moveLearner.learn(winner.moves, winner.source.dexId, winner.level, reward.newLevel) emitter.sendVictoryDelta(battle, winner.entityId, reward) + for (move in learned) { + emitter.sendNotice(battle, "${winner.species.name} learned ${move.name}!") + } characterStore.updatePokemon( battle.charId, winner.source.copy( diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearnerTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearnerTest.kt new file mode 100644 index 0000000..940a4a0 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/MoveLearnerTest.kt @@ -0,0 +1,79 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.PokemonMove +import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.LearnsetRegistry +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.shouldBe + +private const val BULBASAUR = 1 +private const val TACKLE: Short = 33 +private const val GROWL: Short = 45 +private const val LEECH_SEED: Short = 73 +private const val VINE_WHIP: Short = 22 +private const val POISON_POWDER: Short = 77 + +private fun slots(vararg ids: Short) = ids.map { PokemonMove(it, 0) }.toMutableList() + +class MoveLearnerTest : + FunSpec({ + val moves = MoveRegistry() + val learner = MoveLearner(LearnsetRegistry(), moves) + + test("a move learned at the new level goes into a free slot") { + val known = slots(TACKLE, 0, 0, 0) + val learned = learner.learn(known, BULBASAUR, 3, 4) + learned.map { it.moveId } shouldBe listOf(GROWL.toInt()) + known.map { it.id } shouldBe listOf(TACKLE, GROWL, 0, 0) + } + + test("the new move gets its registry pp") { + val known = slots(TACKLE, 0, 0, 0) + learner.learn(known, BULBASAUR, 3, 4) + known[1].pp shouldBe moves.get(GROWL.toInt())!!.pp.toByte() + } + + test("skipping levels learns every move in between") { + val known = slots(TACKLE, 0, 0, 0) + val learned = learner.learn(known, BULBASAUR, 1, 10) + learned.map { it.moveId.toShort() } shouldBe listOf(GROWL, LEECH_SEED, VINE_WHIP) + known.map { it.id } shouldBe listOf(TACKLE, GROWL, LEECH_SEED, VINE_WHIP) + } + + test("a full moveset keeps its moves") { + val known = slots(TACKLE, GROWL, LEECH_SEED, VINE_WHIP) + learner.learn(known, BULBASAUR, 14, 15).shouldBeEmpty() + known.map { it.id } shouldBe listOf(TACKLE, GROWL, LEECH_SEED, VINE_WHIP) + } + + // Bulbasaur learns Poison Powder and Sleep Powder at 15, only the first one fits. + test("a partly full moveset learns until it runs out of slots") { + val known = slots(TACKLE, GROWL, LEECH_SEED, 0) + val learned = learner.learn(known, BULBASAUR, 14, 15) + learned.map { it.moveId.toShort() } shouldBe listOf(POISON_POWDER) + known.map { it.id } shouldBe listOf(TACKLE, GROWL, LEECH_SEED, POISON_POWDER) + } + + test("a known move is not learned twice") { + val known = slots(GROWL, 0, 0, 0) + learner.learn(known, BULBASAUR, 3, 4).shouldBeEmpty() + known.map { it.id } shouldBe listOf(GROWL, 0, 0, 0) + } + + test("no level up learns nothing") { + val known = slots(TACKLE, 0, 0, 0) + learner.learn(known, BULBASAUR, 5, 5).shouldBeEmpty() + } + + test("an unknown species learns nothing") { + val known = slots(TACKLE, 0, 0, 0) + learner.learn(known, 9999, 1, 100).shouldBeEmpty() + } + + test("a moveset shorter than four slots grows") { + val known = slots(TACKLE) + learner.learn(known, BULBASAUR, 3, 4) + known.map { it.id } shouldBe listOf(TACKLE, GROWL) + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt index cc505e3..e96b0be 100644 --- a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt @@ -1,6 +1,7 @@ package de.fiereu.openmmo.server.game.battle import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.LearnsetRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.server.game.storage.EntityIdService import io.kotest.core.spec.style.FunSpec @@ -11,7 +12,8 @@ import io.kotest.matchers.shouldBe class WildMonFactoryTest : FunSpec({ - val factory = WildMonFactory(SpeciesRegistry(), MoveRegistry(), EntityIdService()) + val factory = + WildMonFactory(SpeciesRegistry(), MoveRegistry(), LearnsetRegistry(), EntityIdService()) test("the same seed rolls the same monster") { val a = factory.create(19, 3, BattleRng(seed = 42))!! @@ -31,11 +33,17 @@ class WildMonFactoryTest : } } - test("the moveset is Tackle with its registry pp") { + test("the moveset is the level up moveset with registry pp") { + // Bulbasaur knows Tackle at level 1 and Growl at level 4. val mon = factory.create(1, 5, BattleRng(seed = 7))!! - mon.moves[0].id shouldBe 33.toShort() + mon.moves.map { it.id.toInt() } shouldBe listOf(33, 45, 0, 0) mon.moves[0].pp shouldBe MoveRegistry().get(33)!!.pp.toByte() - mon.moves.drop(1).all { it.id == 0.toShort() } shouldBe true + mon.moves[1].pp shouldBe MoveRegistry().get(45)!!.pp.toByte() + } + + test("a high level monster keeps only the last four moves") { + val mon = factory.create(1, 100, BattleRng(seed = 7))!! + mon.moves.map { it.id.toInt() } shouldBe listOf(230, 74, 235, 76) } test("xp matches the species growth curve at the rolled level") { diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt index c2d039d..9b4fda8 100644 --- a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt @@ -21,10 +21,12 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket +import de.fiereu.openmmo.pokemon.LearnsetRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.server.game.battle.BattlePacketEmitter import de.fiereu.openmmo.server.game.battle.BattleRegistry import de.fiereu.openmmo.server.game.battle.BattleRewards +import de.fiereu.openmmo.server.game.battle.MoveLearner import de.fiereu.openmmo.server.game.battle.TurnEngine import de.fiereu.openmmo.server.game.battle.WildMonFactory import de.fiereu.openmmo.server.game.storage.CharacterStore @@ -84,9 +86,12 @@ private class Fixture(scope: CoroutineScope) { characterStore = store, battles = registry, engine = TurnEngine(MoveRegistry(), TypeChart()), - wildMons = WildMonFactory(SpeciesRegistry(), MoveRegistry(), EntityIdService()), + wildMons = + WildMonFactory( + SpeciesRegistry(), MoveRegistry(), LearnsetRegistry(), EntityIdService()), emitter = BattlePacketEmitter(interestManager), rewards = BattleRewards(), + moveLearner = MoveLearner(LearnsetRegistry(), MoveRegistry()), interestManager = interestManager, speciesRegistry = SpeciesRegistry(), moveRegistry = MoveRegistry(),