feat(game): fight the decomp trainers for experience and prize money (#122)

* fix(protocol): decode the trainer form of the battle field state

* refactor(game): model the battle opponent as a party instead of one monster

* feat(game): let a script fight one of the decomp trainers

* fix(protocol): stop writing moves the opposing side's battle block leaves out

* feat(game): pay experience and prize money for a won trainer battle

* fix(game): send battle outcomes the way the client reads them

* fix(game): correct the reward and stat change defects the review found

* chore(game): tidy the battle comments

* fix(game): send real party slots on a switch and handle a double faint
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-09 00:26:27 +02:00
1 parent 299886ae19
commit abce0d6eb4
28 files changed
+878 -167

No files matched your search

@@ -180,12 +180,12 @@ data class BattleBulkStatePacket(
/**
* Terminal marker sent when a wild encounter resolves, telling the client to leave the scene.
*/
fun battleEnd(): BattleBulkStatePacket =
fun battleEnd(prizeMoney: Int = 0): BattleBulkStatePacket =
BattleBulkStatePacket(
phase = 0,
firstGroup = listOf(NullSerializedEntry),
secondGroup = listOf(NullSerializedEntry),
prizeMoney = 0,
prizeMoney = prizeMoney,
valueB = 0,
flag = 2,
thirdGroup = emptyList(),
@@ -18,9 +18,7 @@ sealed interface BattleEventBody {
/** Event 5, BattlePokemonFainted. [playFaintAnimation] plays the faint-in-place animation. */
data class Faint(val playFaintAnimation: Boolean) : BattleEventBody
/**
* Event 4, BattleEffectivenessMessage. No body: the client derives the message from the types.
*/
/** Event 4, meaning unknown. It carries no body. Effectiveness rides in the outcome word. */
data object EffectivenessMessage : BattleEventBody
/** Event 0x40, BattleMoveFailed. [moveId] names the move in the "it failed" message. */
@@ -35,13 +33,20 @@ private val HpUpdateBodyCodec: Codec<BattleEventBody> =
}
}
private const val STAT_INDEX_MASK = 0x7F
private val StatChangeBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val changeType = field(S8) { (it as BattleEventBody.StatChange).changeType }
// Only the low seven bits name the stat. The top bit is a separate emphasis flag, and the
// direction rides in the signed stage count rather than here.
val stat = field(S8) { (it as BattleEventBody.StatChange).stat }
val stageDelta = field(S16LE) { (it as BattleEventBody.StatChange).stageDelta }
return BattleEventBody.StatChange(stat, stageDelta, changeType)
val stages = field(S8) { (it as BattleEventBody.StatChange).stageDelta.toByte() }
// 0xFF in every capture.
reserved(0xFF)
return BattleEventBody.StatChange(
(stat.toInt() and STAT_INDEX_MASK).toByte(), stages.toShort(), changeType)
}
}
@@ -3,30 +3,102 @@ package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.utils.hexToBytes
/** Who the player is fighting. The byte rides twice, before the name and again after the id. */
enum class OpposingSide(val wireValue: Byte) {
WILD(0xFF.toByte()),
TRAINER(0x04);
companion object {
fun byWireValue(value: Byte): OpposingSide? = entries.find { it.wireValue == value }
}
}
/**
* The field state for a wild encounter (opcode 0x30). Each side sends a monster count that sizes
* the client's slot array followed by that many monster blocks. The player side closes with the
* active monster's detail, the wild side carries a single wild block.
* The field state that opens a battle (opcode 0x30). Each side sends a monster count that sizes the
* client's slot array followed by that many blocks. The player side closes with its active
* monster's detail, the opposing side closes with one shared detail for whichever monster is out.
*
* A trainer battle differs from a wild one in more than values: [opposing] flips two bytes, and the
* opposing side carries [trainerId] plus two extra halfwords that a wild battle leaves out.
*/
data class BattleFieldStatePacket(
val playerName: String,
val playerId: Long,
/** The player's own overworld appearance, the same bytes their 0x05 spawn carries. */
val playerAppearance: ByteArray,
/** Picks the battle backdrop. Outdoors is 0, forest 9, caves 12. */
val background: Byte,
val opposing: OpposingSide,
/** The decomp trainer id, which the client draws the name and sprite from. Zero on a wild. */
val trainerId: Short,
val playerParty: List<BattleMonBlock>,
val activeSlot: Int,
val wildParty: List<BattleMonBlock>,
)
val opponentParty: List<BattleOpponentBlock>,
val opponentActiveSlot: Int,
) {
init {
require(playerAppearance.size == APPEARANCE_SIZE) {
"A field state carries exactly $APPEARANCE_SIZE appearance bytes"
}
}
private val PREAMBLE = "02000000000000000000000000ff000000000016000000ff00200006".hexToBytes()
private val APPEARANCE = "ff00024c031aac0f00038001a400040000000000".hexToBytes()
// ByteArray breaks the generated equals, and the fixtures compare whole packets.
override fun equals(other: Any?): Boolean =
this === other ||
(other is BattleFieldStatePacket &&
playerName == other.playerName &&
playerId == other.playerId &&
playerAppearance.contentEquals(other.playerAppearance) &&
background == other.background &&
opposing == other.opposing &&
trainerId == other.trainerId &&
playerParty == other.playerParty &&
activeSlot == other.activeSlot &&
opponentParty == other.opponentParty &&
opponentActiveSlot == other.opponentActiveSlot)
override fun hashCode(): Int =
listOf<Any>(
playerName,
playerId,
playerAppearance.contentHashCode(),
background,
opposing,
trainerId,
playerParty,
activeSlot,
opponentParty,
opponentActiveSlot)
.hashCode()
companion object {
const val APPEARANCE_SIZE = 14
}
}
private val HEAD = "0200000000".hexToBytes()
private val AFTER_BACKGROUND = "00000000000000ff000000000016000000".hexToBytes()
private val AFTER_OPPOSING = "00200006".hexToBytes()
object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
override fun CodecScope<BattleFieldStatePacket>.body(): BattleFieldStatePacket {
constant(PREAMBLE)
constant(HEAD)
val background = field(S8) { it.background }
constant(AFTER_BACKGROUND)
val opposingByte = field(S8) { it.opposing.wireValue }
val opposing =
OpposingSide.byWireValue(opposingByte)
?: throw MalformedPacketException("Unknown opposing side $opposingByte")
constant(AFTER_OPPOSING)
val playerName = field(Utf16LeNullTerminated) { it.playerName }
reserved(0)
val playerId = field(S64LE) { it.playerId }
constant(APPEARANCE)
constant(1) // player side marker
field(S8) { it.opposing.wireValue }
val appearance =
field(fixedBytes(BattleFieldStatePacket.APPEARANCE_SIZE)) { it.playerAppearance }
padding(5)
constant(1)
val partyCount = field(U8) { it.playerParty.size }
reserved(0)
val party =
@@ -40,14 +112,43 @@ object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
field(BattleActiveDetailCodec) {
BattleActiveDetail.of(it.activeSlot, it.playerParty[it.activeSlot])
}
// Closes the player side after the active detail: [01][active level][00 x5].
constant(1)
field(S8) { it.playerParty[it.activeSlot].level }
padding(5)
constant(1) // wild side marker
val wildCount = field(U8) { it.wildParty.size }
// Opens the opposing side. A trainer adds its id and two more halfwords here.
field(S8) { if (it.opposing == OpposingSide.TRAINER) 2.toByte() else 1.toByte() }
constant(6)
reserved(0)
val wildParty = List(wildCount) { i -> field(BattleWildBlockCodec) { it.wildParty[i] } }
return BattleFieldStatePacket(playerName, playerId, party, active.slot, wildParty)
val trainerId =
if (opposing == OpposingSide.TRAINER) field(S16LE) { it.trainerId } else 0.toShort()
padding(4)
if (opposing == OpposingSide.TRAINER) padding(2)
constant(1)
val opponentCount = field(U8) { it.opponentParty.size }
reserved(0)
val opponents =
List(opponentCount) { i ->
val block = field(BattleOpponentBlockCodec) { it.opponentParty[i] }
field(S8) { if (i == it.opponentParty.lastIndex) 1.toByte() else 0.toByte() }
block
}
val opponentActive =
field(BattleActiveDetailCodec) {
val mon = it.opponentParty[it.opponentActiveSlot]
BattleActiveDetail(mon.slot, mon.species, mon.level, mon.gender)
}
padding(4)
return BattleFieldStatePacket(
playerName,
playerId,
appearance,
background,
opposing,
trainerId,
party,
active.slot,
opponents,
opponentActive.slot,
)
}
}
@@ -37,12 +37,8 @@ private fun seg(hex: String): ByteArray =
// Captured constant that precedes the moves-present flag, meaning still unknown.
private val MOVES_HEADER = seg("000000ff03")
// The wild block replaces the ability and move segment with this captured marker.
private val WILD_MOVES_SEGMENT = seg("000000ff030001")
private val ACTIVE_TAIL = seg("03ff0000000066666666")
private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
/** The active monster's detail block, naming only species, level, and gender. */
internal data class BattleActiveDetail(
val slot: Int,
@@ -86,18 +82,38 @@ internal object BattleFullBlockCodec : PacketCodec<BattleMonBlock>() {
val maxHp = field(S16LE) { it.maxHp }
constant(MOVES_HEADER)
val movesPresent = field(Bool) { it.movesPresent }
val abilityId = field(S16LE) { it.abilityId }
val moveIds = field(S16LE.repeat(BattleMonBlock.MOVE_SLOTS)) { it.moveIds }
val abilityId = if (movesPresent) field(S16LE) { it.abilityId } else 0
val moveIds =
if (movesPresent) field(S16LE.repeat(BattleMonBlock.MOVE_SLOTS)) { it.moveIds }
else List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
return BattleMonBlock(
slot, entityId, species, level, gender, abilityId, maxHp, currentHp, movesPresent, moveIds)
}
}
/** The wild side's block. The decode fills ability and moves with zero. */
internal object BattleWildBlockCodec : PacketCodec<BattleMonBlock>() {
override fun CodecScope<BattleMonBlock>.body(): BattleMonBlock {
/**
* One monster on the opposing side. A monster the player has not been shown yet rides as a stub
* with no body at all, which is how a trainer's benched team is hidden until it is sent out.
*/
data class BattleOpponentBlock(
val slot: Int,
val revealed: Boolean,
val entityId: Long = 0,
val species: Short = 0,
val level: Byte = 0,
val gender: Byte = 0,
val maxHp: Short = 0,
val currentHp: Short = 0,
)
private const val REVEALED: Byte = 1
private const val HIDDEN: Byte = 2
internal object BattleOpponentBlockCodec : PacketCodec<BattleOpponentBlock>() {
override fun CodecScope<BattleOpponentBlock>.body(): BattleOpponentBlock {
val slot = field(S8) { it.slot.toByte() }.toInt()
constant(1)
val kind = field(S8) { if (it.revealed) REVEALED else HIDDEN }
if (kind != REVEALED) return BattleOpponentBlock(slot, revealed = false)
val entityId = field(S64LE) { it.entityId }
val species = field(S16LE) { it.species }
val level = field(S8) { it.level }
@@ -106,10 +122,9 @@ internal object BattleWildBlockCodec : PacketCodec<BattleMonBlock>() {
padding(3)
val currentHp = field(S16LE) { it.currentHp }
val maxHp = field(S16LE) { it.maxHp }
constant(WILD_MOVES_SEGMENT)
field(BattleActiveDetailCodec) { BattleActiveDetail.of(it.slot, it) }
padding(4)
return BattleMonBlock(
slot, entityId, species, level, gender, 0, maxHp, currentHp, false, NO_MOVES)
constant(MOVES_HEADER)
// The opposing side never carries a moveset, so the client cannot read the enemy's moves.
constant(0)
return BattleOpponentBlock(slot, true, entityId, species, level, gender, maxHp, currentHp)
}
}
@@ -13,6 +13,8 @@ data class BattleSwitchInPacket(
val oldSlot: Int,
val mon: BattleMonBlock,
val fullBlock: Boolean,
/** 0 sends out one of the player's own, 1 one of the opponent's. */
val side: Byte = 0,
)
private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
@@ -56,10 +58,11 @@ private val SwitchInMonCodec: Codec<SwitchInMon> =
object BattleSwitchInPacketCodec : PacketCodec<BattleSwitchInPacket>() {
override fun CodecScope<BattleSwitchInPacket>.body(): BattleSwitchInPacket {
padding(2)
val side = field(S8) { it.side }
reserved(0)
val newSlot = field(U8) { it.newSlot }
val oldSlot = field(U8) { it.oldSlot }
val section = field(SwitchInMonCodec) { SwitchInMon(it.mon, it.fullBlock) }
return BattleSwitchInPacket(newSlot, oldSlot, section.mon, section.fullBlock)
return BattleSwitchInPacket(newSlot, oldSlot, section.mon, section.fullBlock, side)
}
}
@@ -2,6 +2,8 @@ package de.fiereu.openmmo.net.game
import de.fiereu.openmmo.common.test.decodeBytes
import de.fiereu.openmmo.common.test.encodeToBytes
import de.fiereu.openmmo.common.test.fixture
import de.fiereu.openmmo.common.utils.toHex
import de.fiereu.openmmo.net.game.packets.battle.BattleActionEvent
import de.fiereu.openmmo.net.game.packets.battle.BattleEffectTarget
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket
@@ -12,6 +14,19 @@ import io.kotest.matchers.shouldBe
class BattleEntityMoveEventPacketTest :
FunSpec({
// A captured Growl, which is a status move whose only effect is one stat drop.
test("round-trips a captured stat change byte for byte") {
val bytes = fixture("game/s2c/33/stat_change_growl.bin")
val decoded = BattleEntityMoveEventPacketCodec.decodeBytes(bytes)
decoded.sourceMove shouldBe 45.toShort()
val target = decoded.targets.single()
target.targetMove shouldBe 0.toShort()
target.subEvents.single().body shouldBe
BattleEventBody.StatChange(stat = 1, stageDelta = -1)
BattleEntityMoveEventPacketCodec.encodeToBytes(decoded).toHex() shouldBe bytes.toHex()
}
test("round-trips every body type and entity-flag combination") {
val packet =
BattleEntityMoveEventPacket(
@@ -6,23 +6,28 @@ import de.fiereu.openmmo.common.test.fixture
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacketCodec
import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock
import de.fiereu.openmmo.net.game.packets.battle.BattleOpponentBlock
import de.fiereu.openmmo.net.game.packets.battle.OpposingSide
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private const val WILD = "game/s2c/30/wild_two_party_scrubbed.bin"
private const val TRAINER = "game/s2c/30/trainer_one_opponent_scrubbed.bin"
class BattleFieldStatePacketTest :
FunSpec({
test("round-trips a two-party wild field state byte for byte") {
val bytes = fixture("game/s2c/30/wild_two_party_scrubbed.bin")
val bytes = fixture(WILD)
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
decoded.playerName shouldBe "Test"
decoded.playerParty.size shouldBe 2
decoded.activeSlot shouldBe 0
decoded.opposing shouldBe OpposingSide.WILD
BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("decodes the structured mon fields from the capture") {
val bytes = fixture("game/s2c/30/wild_two_party_scrubbed.bin")
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
val decoded = BattleFieldStatePacketCodec.decodeBytes(fixture(WILD))
val snivy = decoded.playerParty[0]
snivy.slot shouldBe 0
@@ -43,12 +48,42 @@ class BattleFieldStatePacketTest :
patrat.abilityId shouldBe 50.toShort()
patrat.moveIds shouldBe listOf<Short>(33, 0, 0, 0)
val wild = decoded.wildParty.single()
val wild = decoded.opponentParty.single()
wild.revealed shouldBe true
wild.species shouldBe 504.toShort()
wild.level shouldBe 2.toByte()
wild.maxHp shouldBe 14.toShort()
wild.currentHp shouldBe 14.toShort()
wild.movesPresent shouldBe false
}
test("round-trips a trainer field state byte for byte") {
val bytes = fixture(TRAINER)
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
decoded.opposing shouldBe OpposingSide.TRAINER
decoded.trainerId shouldBe 0x68.toShort()
decoded.playerParty.size shouldBe 3
val weedle = decoded.opponentParty.single()
weedle.revealed shouldBe true
weedle.species shouldBe 13.toShort()
weedle.level shouldBe 9.toByte()
weedle.currentHp shouldBe 26.toShort()
BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes
}
test("an unrevealed opponent rides as a stub and round-trips") {
val decoded = BattleFieldStatePacketCodec.decodeBytes(fixture(TRAINER))
val benched = BattleOpponentBlock(slot = 1, revealed = false)
val twoMon = decoded.copy(opponentParty = decoded.opponentParty + benched)
val reDecoded =
BattleFieldStatePacketCodec.decodeBytes(
BattleFieldStatePacketCodec.encodeToBytes(twoMon))
reDecoded.opponentParty.size shouldBe 2
reDecoded.opponentParty[1].revealed shouldBe false
reDecoded shouldBe twoMon
}
test("round-trips a synthetic field state for a species without a capture") {
@@ -65,26 +100,28 @@ class BattleFieldStatePacketTest :
movesPresent = true,
moveIds = listOf(33, 39, 45, 98),
)
val wild =
BattleMonBlock(
val geodude =
BattleOpponentBlock(
slot = 0,
revealed = true,
entityId = 0x456C000L,
species = 74,
level = 9,
gender = 0,
abilityId = 0,
maxHp = 26,
currentHp = 26,
movesPresent = false,
moveIds = listOf(0, 0, 0, 0),
)
val packet =
BattleFieldStatePacket(
playerName = "Ash",
playerId = 0x19000L,
playerAppearance = ByteArray(BattleFieldStatePacket.APPEARANCE_SIZE),
background = 0,
opposing = OpposingSide.WILD,
trainerId = 0,
playerParty = listOf(rattata),
activeSlot = 0,
wildParty = listOf(wild),
opponentParty = listOf(geodude),
opponentActiveSlot = 0,
)
val decoded =
BattleFieldStatePacketCodec.decodeBytes(
@@ -52,6 +52,18 @@ class BattleSwitchInPacketTest :
bytes.toHex() shouldBe fixture("game/s2c/35/return_switch_in.bin").toHex()
}
// The opposing block carries no moves, so this is 55 bytes where the player's own is 65.
test("round-trips a captured opponent switch-in") {
val bytes = fixture("game/s2c/35/opponent_switch_in.bin")
val decoded = BattleSwitchInPacketCodec.decodeBytes(bytes)
decoded.side shouldBe 1.toByte()
decoded.fullBlock shouldBe true
decoded.mon.species shouldBe 13.toShort()
decoded.mon.level shouldBe 7.toByte()
decoded.mon.movesPresent shouldBe false
BattleSwitchInPacketCodec.encodeToBytes(decoded).toHex() shouldBe bytes.toHex()
}
// A benched monster coming out carries its full block then its active detail. The block
// matches the captured Patrat bytes now built from structured fields.
test("round-trips a full-block switch-in") {