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
+864 -153

No files matched your search

@@ -14,5 +14,6 @@ data class ParsedTrainer(
val name: String, val name: String,
val trainerClass: Int, val trainerClass: Int,
val doubleBattle: Boolean, val doubleBattle: Boolean,
val prizeRate: Int,
val party: List<ParsedTrainerMon>, val party: List<ParsedTrainerMon>,
) )
@@ -5,7 +5,7 @@ object RenderUtil {
fun trainer(region: String, t: ParsedTrainer): String { fun trainer(region: String, t: ParsedTrainer): String {
val party = t.party.joinToString(", ", "listOf(", ")") { mon(it) } val party = t.party.joinToString(", ", "listOf(", ")") { mon(it) }
return "reg.register(Region.${region.uppercase()}, TrainerDef(${t.id}, \"${escape(t.name)}\", " + return "reg.register(Region.${region.uppercase()}, TrainerDef(${t.id}, \"${escape(t.name)}\", " +
"${t.trainerClass}, ${t.doubleBattle}, $party))" "${t.trainerClass}, ${t.doubleBattle}, ${t.prizeRate}, $party))"
} }
private fun mon(m: ParsedTrainerMon): String { private fun mon(m: ParsedTrainerMon): String {
@@ -18,6 +18,7 @@ class TrainerParser(private val rootDir: File) {
fun parseAll(): List<ParsedTrainer> { fun parseAll(): List<ParsedTrainer> {
val parties = readParties() val parties = readParties()
val (prizeRates, defaultPrizeRate) = readPrizeRates()
return readTrainers() return readTrainers()
.mapNotNull { entry -> .mapNotNull { entry ->
val id = trainerIds[entry.constant] val id = trainerIds[entry.constant]
@@ -37,6 +38,7 @@ class TrainerParser(private val rootDir: File) {
name = entry.name, name = entry.name,
trainerClass = classIds[entry.trainerClass] ?: 0, trainerClass = classIds[entry.trainerClass] ?: 0,
doubleBattle = entry.doubleBattle, doubleBattle = entry.doubleBattle,
prizeRate = prizeRates[entry.trainerClass] ?: defaultPrizeRate,
party = party, party = party,
) )
} }
@@ -103,6 +105,18 @@ class TrainerParser(private val rootDir: File) {
} }
} }
/**
* gTrainerMoneyTable, which pays a trainer class this much per level of its last monster. The
* table ends with a 0xFF row that every class it does not list falls through to.
*/
private fun readPrizeRates(): Pair<Map<String, Int>, Int> {
val table = MONEY_TABLE.find(read("src/battle_main.c"))?.groupValues?.get(1).orEmpty()
val byClass =
MONEY_ENTRY.findAll(table).associate { it.groupValues[1] to it.groupValues[2].toInt() }
val fallback = MONEY_FALLBACK.find(table)?.groupValues?.get(1)?.toInt() ?: 0
return byClass to fallback
}
private fun fields(body: String): Map<String, String> = private fun fields(body: String): Map<String, String> =
FIELD.findAll(body).associate { it.groupValues[1] to it.groupValues[2].trim() } FIELD.findAll(body).associate { it.groupValues[1] to it.groupValues[2].trim() }
@@ -133,5 +147,9 @@ class TrainerParser(private val rootDir: File) {
val MEMBER = Regex("""\{((?:[^{}]|\{[^{}]*})*)}""", RegexOption.DOT_MATCHES_ALL) val MEMBER = Regex("""\{((?:[^{}]|\{[^{}]*})*)}""", RegexOption.DOT_MATCHES_ALL)
val FIELD = Regex("""\.(\w+)\s*=\s*(\{[^}]*}|[^,}]+)""") val FIELD = Regex("""\.(\w+)\s*=\s*(\{[^}]*}|[^,}]+)""")
val MOVE = Regex("""MOVE_\w+""") val MOVE = Regex("""MOVE_\w+""")
val MONEY_TABLE =
Regex("""gTrainerMoneyTable\[]\s*=\s*\{(.*?)};""", RegexOption.DOT_MATCHES_ALL)
val MONEY_ENTRY = Regex("""\{\s*(TRAINER_CLASS_\w+)\s*,\s*(\d+)\s*}""")
val MONEY_FALLBACK = Regex("""\{\s*0xFF\s*,\s*(\d+)\s*}""")
} }
} }
@@ -21,6 +21,8 @@ data class TrainerDef(
val name: String, val name: String,
val trainerClass: Int, val trainerClass: Int,
val doubleBattle: Boolean, val doubleBattle: Boolean,
/** What the class pays per level of its last monster. */
val prizeRate: Int,
val party: List<TrainerMon>, val party: List<TrainerMon>,
) )
@@ -180,12 +180,12 @@ data class BattleBulkStatePacket(
/** /**
* Terminal marker sent when a wild encounter resolves, telling the client to leave the scene. * 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( BattleBulkStatePacket(
phase = 0, phase = 0,
firstGroup = listOf(NullSerializedEntry), firstGroup = listOf(NullSerializedEntry),
secondGroup = listOf(NullSerializedEntry), secondGroup = listOf(NullSerializedEntry),
prizeMoney = 0, prizeMoney = prizeMoney,
valueB = 0, valueB = 0,
flag = 2, flag = 2,
thirdGroup = emptyList(), thirdGroup = emptyList(),
@@ -18,9 +18,7 @@ sealed interface BattleEventBody {
/** Event 5, BattlePokemonFainted. [playFaintAnimation] plays the faint-in-place animation. */ /** Event 5, BattlePokemonFainted. [playFaintAnimation] plays the faint-in-place animation. */
data class Faint(val playFaintAnimation: Boolean) : BattleEventBody data class Faint(val playFaintAnimation: Boolean) : BattleEventBody
/** /** Event 4, meaning unknown. It carries no body. Effectiveness rides in the outcome word. */
* Event 4, BattleEffectivenessMessage. No body: the client derives the message from the types.
*/
data object EffectivenessMessage : BattleEventBody data object EffectivenessMessage : BattleEventBody
/** Event 0x40, BattleMoveFailed. [moveId] names the move in the "it failed" message. */ /** 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> = private val StatChangeBodyCodec: Codec<BattleEventBody> =
object : PacketCodec<BattleEventBody>() { object : PacketCodec<BattleEventBody>() {
override fun CodecScope<BattleEventBody>.body(): BattleEventBody { override fun CodecScope<BattleEventBody>.body(): BattleEventBody {
val changeType = field(S8) { (it as BattleEventBody.StatChange).changeType } 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 stat = field(S8) { (it as BattleEventBody.StatChange).stat }
val stageDelta = field(S16LE) { (it as BattleEventBody.StatChange).stageDelta } val stages = field(S8) { (it as BattleEventBody.StatChange).stageDelta.toByte() }
return BattleEventBody.StatChange(stat, stageDelta, changeType) // 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.bytecodec.*
import de.fiereu.openmmo.common.utils.hexToBytes 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 field state that opens a battle (opcode 0x30). Each side sends a monster count that sizes the
* the client's slot array followed by that many monster blocks. The player side closes with the * client's slot array followed by that many blocks. The player side closes with its active
* active monster's detail, the wild side carries a single wild block. * 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( data class BattleFieldStatePacket(
val playerName: String, val playerName: String,
val playerId: Long, 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 playerParty: List<BattleMonBlock>,
val activeSlot: Int, 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() // ByteArray breaks the generated equals, and the fixtures compare whole packets.
private val APPEARANCE = "ff00024c031aac0f00038001a400040000000000".hexToBytes() 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>() { object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
override fun CodecScope<BattleFieldStatePacket>.body(): 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 } val playerName = field(Utf16LeNullTerminated) { it.playerName }
reserved(0) reserved(0)
val playerId = field(S64LE) { it.playerId } val playerId = field(S64LE) { it.playerId }
constant(APPEARANCE) field(S8) { it.opposing.wireValue }
constant(1) // player side marker val appearance =
field(fixedBytes(BattleFieldStatePacket.APPEARANCE_SIZE)) { it.playerAppearance }
padding(5)
constant(1)
val partyCount = field(U8) { it.playerParty.size } val partyCount = field(U8) { it.playerParty.size }
reserved(0) reserved(0)
val party = val party =
@@ -40,14 +112,43 @@ object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
field(BattleActiveDetailCodec) { field(BattleActiveDetailCodec) {
BattleActiveDetail.of(it.activeSlot, it.playerParty[it.activeSlot]) BattleActiveDetail.of(it.activeSlot, it.playerParty[it.activeSlot])
} }
// Closes the player side after the active detail: [01][active level][00 x5].
constant(1) // Opens the opposing side. A trainer adds its id and two more halfwords here.
field(S8) { it.playerParty[it.activeSlot].level } field(S8) { if (it.opposing == OpposingSide.TRAINER) 2.toByte() else 1.toByte() }
padding(5) constant(6)
constant(1) // wild side marker
val wildCount = field(U8) { it.wildParty.size }
reserved(0) reserved(0)
val wildParty = List(wildCount) { i -> field(BattleWildBlockCodec) { it.wildParty[i] } } val trainerId =
return BattleFieldStatePacket(playerName, playerId, party, active.slot, wildParty) 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. // Captured constant that precedes the moves-present flag, meaning still unknown.
private val MOVES_HEADER = seg("000000ff03") 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 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. */ /** The active monster's detail block, naming only species, level, and gender. */
internal data class BattleActiveDetail( internal data class BattleActiveDetail(
val slot: Int, val slot: Int,
@@ -86,18 +82,38 @@ internal object BattleFullBlockCodec : PacketCodec<BattleMonBlock>() {
val maxHp = field(S16LE) { it.maxHp } val maxHp = field(S16LE) { it.maxHp }
constant(MOVES_HEADER) constant(MOVES_HEADER)
val movesPresent = field(Bool) { it.movesPresent } val movesPresent = field(Bool) { it.movesPresent }
val abilityId = field(S16LE) { it.abilityId } val abilityId = if (movesPresent) field(S16LE) { it.abilityId } else 0
val moveIds = field(S16LE.repeat(BattleMonBlock.MOVE_SLOTS)) { it.moveIds } val moveIds =
if (movesPresent) field(S16LE.repeat(BattleMonBlock.MOVE_SLOTS)) { it.moveIds }
else List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
return BattleMonBlock( return BattleMonBlock(
slot, entityId, species, level, gender, abilityId, maxHp, currentHp, movesPresent, moveIds) 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>() { * One monster on the opposing side. A monster the player has not been shown yet rides as a stub
override fun CodecScope<BattleMonBlock>.body(): BattleMonBlock { * 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() 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 entityId = field(S64LE) { it.entityId }
val species = field(S16LE) { it.species } val species = field(S16LE) { it.species }
val level = field(S8) { it.level } val level = field(S8) { it.level }
@@ -106,10 +122,9 @@ internal object BattleWildBlockCodec : PacketCodec<BattleMonBlock>() {
padding(3) padding(3)
val currentHp = field(S16LE) { it.currentHp } val currentHp = field(S16LE) { it.currentHp }
val maxHp = field(S16LE) { it.maxHp } val maxHp = field(S16LE) { it.maxHp }
constant(WILD_MOVES_SEGMENT) constant(MOVES_HEADER)
field(BattleActiveDetailCodec) { BattleActiveDetail.of(it.slot, it) } // The opposing side never carries a moveset, so the client cannot read the enemy's moves.
padding(4) constant(0)
return BattleMonBlock( return BattleOpponentBlock(slot, true, entityId, species, level, gender, maxHp, currentHp)
slot, entityId, species, level, gender, 0, maxHp, currentHp, false, NO_MOVES)
} }
} }
@@ -13,6 +13,8 @@ data class BattleSwitchInPacket(
val oldSlot: Int, val oldSlot: Int,
val mon: BattleMonBlock, val mon: BattleMonBlock,
val fullBlock: Boolean, 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() } private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() }
@@ -56,10 +58,11 @@ private val SwitchInMonCodec: Codec<SwitchInMon> =
object BattleSwitchInPacketCodec : PacketCodec<BattleSwitchInPacket>() { object BattleSwitchInPacketCodec : PacketCodec<BattleSwitchInPacket>() {
override fun CodecScope<BattleSwitchInPacket>.body(): BattleSwitchInPacket { override fun CodecScope<BattleSwitchInPacket>.body(): BattleSwitchInPacket {
padding(2) val side = field(S8) { it.side }
reserved(0)
val newSlot = field(U8) { it.newSlot } val newSlot = field(U8) { it.newSlot }
val oldSlot = field(U8) { it.oldSlot } val oldSlot = field(U8) { it.oldSlot }
val section = field(SwitchInMonCodec) { SwitchInMon(it.mon, it.fullBlock) } 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.decodeBytes
import de.fiereu.openmmo.common.test.encodeToBytes 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.BattleActionEvent
import de.fiereu.openmmo.net.game.packets.battle.BattleEffectTarget import de.fiereu.openmmo.net.game.packets.battle.BattleEffectTarget
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket
@@ -12,6 +14,19 @@ import io.kotest.matchers.shouldBe
class BattleEntityMoveEventPacketTest : class BattleEntityMoveEventPacketTest :
FunSpec({ 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") { test("round-trips every body type and entity-flag combination") {
val packet = val packet =
BattleEntityMoveEventPacket( 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.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacketCodec 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.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.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe 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 : class BattleFieldStatePacketTest :
FunSpec({ FunSpec({
test("round-trips a two-party wild field state byte for byte") { 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) val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
decoded.playerName shouldBe "Test" decoded.playerName shouldBe "Test"
decoded.playerParty.size shouldBe 2 decoded.playerParty.size shouldBe 2
decoded.activeSlot shouldBe 0 decoded.activeSlot shouldBe 0
decoded.opposing shouldBe OpposingSide.WILD
BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes
} }
test("decodes the structured mon fields from the capture") { test("decodes the structured mon fields from the capture") {
val bytes = fixture("game/s2c/30/wild_two_party_scrubbed.bin") val decoded = BattleFieldStatePacketCodec.decodeBytes(fixture(WILD))
val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes)
val snivy = decoded.playerParty[0] val snivy = decoded.playerParty[0]
snivy.slot shouldBe 0 snivy.slot shouldBe 0
@@ -43,12 +48,42 @@ class BattleFieldStatePacketTest :
patrat.abilityId shouldBe 50.toShort() patrat.abilityId shouldBe 50.toShort()
patrat.moveIds shouldBe listOf<Short>(33, 0, 0, 0) 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.species shouldBe 504.toShort()
wild.level shouldBe 2.toByte() wild.level shouldBe 2.toByte()
wild.maxHp shouldBe 14.toShort() wild.maxHp shouldBe 14.toShort()
wild.currentHp 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") { test("round-trips a synthetic field state for a species without a capture") {
@@ -65,26 +100,28 @@ class BattleFieldStatePacketTest :
movesPresent = true, movesPresent = true,
moveIds = listOf(33, 39, 45, 98), moveIds = listOf(33, 39, 45, 98),
) )
val wild = val geodude =
BattleMonBlock( BattleOpponentBlock(
slot = 0, slot = 0,
revealed = true,
entityId = 0x456C000L, entityId = 0x456C000L,
species = 74, species = 74,
level = 9, level = 9,
gender = 0,
abilityId = 0,
maxHp = 26, maxHp = 26,
currentHp = 26, currentHp = 26,
movesPresent = false,
moveIds = listOf(0, 0, 0, 0),
) )
val packet = val packet =
BattleFieldStatePacket( BattleFieldStatePacket(
playerName = "Ash", playerName = "Ash",
playerId = 0x19000L, playerId = 0x19000L,
playerAppearance = ByteArray(BattleFieldStatePacket.APPEARANCE_SIZE),
background = 0,
opposing = OpposingSide.WILD,
trainerId = 0,
playerParty = listOf(rattata), playerParty = listOf(rattata),
activeSlot = 0, activeSlot = 0,
wildParty = listOf(wild), opponentParty = listOf(geodude),
opponentActiveSlot = 0,
) )
val decoded = val decoded =
BattleFieldStatePacketCodec.decodeBytes( BattleFieldStatePacketCodec.decodeBytes(
@@ -52,6 +52,18 @@ class BattleSwitchInPacketTest :
bytes.toHex() shouldBe fixture("game/s2c/35/return_switch_in.bin").toHex() 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 // 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. // matches the captured Patrat bytes now built from structured fields.
test("round-trips a full-block switch-in") { test("round-trips a full-block switch-in") {
@@ -2,6 +2,7 @@ package de.fiereu.openmmo.server.game.battle
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.server.game.world.interest.BattleInterestKey import de.fiereu.openmmo.server.game.world.interest.BattleInterestKey
import de.fiereu.openmmo.trainer.TrainerDef
import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CompletableDeferred
enum class BattleResult { enum class BattleResult {
@@ -13,24 +14,35 @@ enum class BattleResult {
FAILED, FAILED,
} }
/** One running wild battle. Trainer battles later add more participants to the same key. */ /** What kind of battle this is, beyond the two teams. A [trainer] owns the opposing side. */
data class BattleRules(
val catchable: Boolean = true,
val escapable: Boolean = true,
val trainer: TrainerDef? = null,
)
/** One running battle. A wild encounter is the case where [opponent] holds a single monster. */
class BattleInstance( class BattleInstance(
val battleId: Long, val battleId: Long,
val charId: Long, val charId: Long,
val session: SessionContext, val session: SessionContext,
val party: List<BattleMonState>, val party: List<BattleMonState>,
val wild: BattleMonState, val opponent: List<BattleMonState>,
val rng: BattleRng, val rng: BattleRng,
val catchable: Boolean = true, val catchable: Boolean = true,
val escapable: Boolean = true, val escapable: Boolean = true,
/** The trainer who owns [opponent], or null for a wild encounter. */
val trainer: TrainerDef? = null,
) { ) {
val key: BattleInterestKey = BattleInterestKey(battleId) val key: BattleInterestKey = BattleInterestKey(battleId)
var turn: Int = 1 var turn: Int = 1
var activeSlot: Int = 0 var activeSlot: Int = 0
var opponentSlot: Int = 0
// Which party slots have been sent out as active. A monster's first appearance carries its // Which slots have been sent out as active. A monster's first appearance carries its full block,
// full block, a return only its active detail. // a return only its active detail.
val seenActive: MutableSet<Int> = mutableSetOf(0) val seenActive: MutableSet<Int> = mutableSetOf(0)
val opponentSeen: MutableSet<Int> = mutableSetOf(0)
/** Completes when the battle leaves the registry. */ /** Completes when the battle leaves the registry. */
val completion = CompletableDeferred<BattleResult>() val completion = CompletableDeferred<BattleResult>()
@@ -39,4 +51,8 @@ class BattleInstance(
var pendingResult: BattleResult? = null var pendingResult: BattleResult? = null
fun activeMon(): BattleMonState = party[activeSlot] fun activeMon(): BattleMonState = party[activeSlot]
fun opponentMon(): BattleMonState = opponent[opponentSlot]
fun isPlayerSide(entityId: Long): Boolean = party.any { it.entityId == entityId }
} }
@@ -3,6 +3,7 @@ package de.fiereu.openmmo.server.game.battle
import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock
import de.fiereu.openmmo.net.game.packets.battle.BattleOpponentBlock
import de.fiereu.openmmo.pokemon.SpeciesDef import de.fiereu.openmmo.pokemon.SpeciesDef
import java.util.EnumMap import java.util.EnumMap
@@ -14,8 +15,9 @@ class BattleMonState(
val entityId: Long, val entityId: Long,
val species: SpeciesDef, val species: SpeciesDef,
val partyIndex: Int?, val partyIndex: Int?,
val source: Pokemon, // Both move on when a reward lands, so a second reward in the same battle builds on the first.
val stats: ComputedStats, var source: Pokemon,
var stats: ComputedStats,
val gender: Byte = 0, val gender: Byte = 0,
) { ) {
var currentHp: Int = source.hp.toInt().coerceIn(0, stats.hp) var currentHp: Int = source.hp.toInt().coerceIn(0, stats.hp)
@@ -53,6 +55,18 @@ class BattleMonState(
fun effective(stat: BattleStat): Int = StatStages.scaleStat(unstaged(stat), stage(stat)) fun effective(stat: BattleStat): Int = StatStages.scaleStat(unstaged(stat), stage(stat))
fun toOpponentBlock(slot: Int): BattleOpponentBlock =
BattleOpponentBlock(
slot = slot,
revealed = true,
entityId = entityId,
species = species.id.toShort(),
level = source.level,
gender = gender,
maxHp = stats.hp.toShort(),
currentHp = currentHp.toShort(),
)
fun toBlock(slot: Int, movesPresent: Boolean): BattleMonBlock = fun toBlock(slot: Int, movesPresent: Boolean): BattleMonBlock =
BattleMonBlock( BattleMonBlock(
slot = slot, slot = slot,
@@ -5,6 +5,7 @@ import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.EVs import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.Language import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket
import de.fiereu.openmmo.net.game.packets.EntityPresencePacket import de.fiereu.openmmo.net.game.packets.EntityPresencePacket
@@ -16,6 +17,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleEntityDeltaPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEventBody import de.fiereu.openmmo.net.game.packets.battle.BattleEventBody
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleOpponentBlock
import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket 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.BattleSidePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSlotEventEnumPacket import de.fiereu.openmmo.net.game.packets.battle.BattleSlotEventEnumPacket
@@ -25,6 +27,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket
import de.fiereu.openmmo.net.game.packets.battle.Experience import de.fiereu.openmmo.net.game.packets.battle.Experience
import de.fiereu.openmmo.net.game.packets.battle.MoveSlots import de.fiereu.openmmo.net.game.packets.battle.MoveSlots
import de.fiereu.openmmo.net.game.packets.battle.OpposingSide
import de.fiereu.openmmo.server.game.world.interest.InterestManager import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.typechart.TypeChart import de.fiereu.openmmo.typechart.TypeChart
import javax.inject.Inject import javax.inject.Inject
@@ -43,10 +46,20 @@ private const val PRESENCE_OVERWORLD: Byte = 0
// The active battle side reported to the client so the bag knows which monster an item targets. // The active battle side reported to the client so the bag knows which monster an item targets.
private const val PLAYER_SIDE: Byte = 1 private const val PLAYER_SIDE: Byte = 1
// The target move short the live server sends for each event. Meaning unknown, but it is fixed per // The side byte a switch-in carries, which is not the same numbering as BattleSidePacket.
// event type in every capture: a hit carries 0x0200, other events carry 0. private const val OPPONENT_SIDE: Byte = 1
private val CAPTURED_APPEARANCE = "00024c031aac0f00038001a40004".hexToBytes()
// The target's outcome word, which picks the line the client prints for that target. A damaging
// hit is 0x0200, a miss 1, a failure 4, and a status move that only moves a stat carries none of
// them. The events under the target are read either way.
private const val HP_TARGET_MOVE: Short = 0x0200 private const val HP_TARGET_MOVE: Short = 0x0200
private const val MISSED_TARGET_MOVE: Short = 1
private const val FAILED_TARGET_MOVE: Short = 4
private const val DEFAULT_TARGET_MOVE: Short = 0 private const val DEFAULT_TARGET_MOVE: Short = 0
private const val SUPER_EFFECTIVE_BIT = 0x20
private const val NOT_VERY_EFFECTIVE_BIT = 0x10
/** /**
* Turns battle state and [BattleEvent]s into packets. Everything battle wide goes through the * Turns battle state and [BattleEvent]s into packets. Everything battle wide goes through the
@@ -67,9 +80,21 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
BattleFieldStatePacket( BattleFieldStatePacket(
playerName = playerName, playerName = playerName,
playerId = battle.charId, playerId = battle.charId,
// TODO Send the player's own appearance and the map's battle backdrop
// These are the captured values, so every player appears as the captured character.
playerAppearance = CAPTURED_APPEARANCE,
background = 0,
opposing = if (battle.trainer == null) OpposingSide.WILD else OpposingSide.TRAINER,
// TODO Check whether Hoenn needs a region tag, both decomps number trainers from 1
trainerId = (battle.trainer?.id ?: 0).toShort(),
playerParty = battle.party.mapIndexed { slot, mon -> mon.toBlock(slot, true) }, playerParty = battle.party.mapIndexed { slot, mon -> mon.toBlock(slot, true) },
activeSlot = battle.activeSlot, activeSlot = battle.activeSlot,
wildParty = listOf(battle.wild.toBlock(slot = 0, movesPresent = false)), opponentParty =
battle.opponent.mapIndexed { slot, mon ->
if (slot in battle.opponentSeen) mon.toOpponentBlock(slot)
else BattleOpponentBlock(slot = slot, revealed = false)
},
opponentActiveSlot = battle.opponentSlot,
), ),
) )
sendPrompt(battle) sendPrompt(battle)
@@ -81,7 +106,7 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
val event = events[i] val event = events[i]
when (event) { when (event) {
is BattleEvent.MoveUsed -> { is BattleEvent.MoveUsed -> {
if (event.attackerId != battle.wild.entityId) { if (battle.isPlayerSide(event.attackerId)) {
battle.session.send( battle.session.send(
EntityMovePpPacket( EntityMovePpPacket(
event.attackerId, event.moveSlot.toByte(), event.ppLeft.toByte())) event.attackerId, event.moveSlot.toByte(), event.ppLeft.toByte()))
@@ -93,18 +118,30 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
when (val next = events.getOrNull(i + 1)) { when (val next = events.getOrNull(i + 1)) {
is BattleEvent.DamageDealt -> { is BattleEvent.DamageDealt -> {
i++ i++
// The client faints the target on hp reaching 0, as the real server does, so no
// faint sub-event is sent here.
val subEvents = val subEvents =
mutableListOf( mutableListOf(
BattleActionEvent( BattleActionEvent(
null, null, BattleEventBody.HpUpdate(next.newHp.toShort()))) null, null, BattleEventBody.HpUpdate(next.newHp.toShort())))
// Type 4 is assumed to be the "super effective" line. Not very effective and no // A secondary stage change rides under the same target as the damage, the way
// effect ride other event ids we have not identified yet. // the captured Rock Tomb does. One aimed elsewhere gets a target of its own.
if (next.effectiveness > TypeChart.NEUTRAL) { var elsewhere = emptyList<BattleEffectTarget>()
subEvents += BattleActionEvent(null, null, BattleEventBody.EffectivenessMessage) val secondary = events.getOrNull(i + 1)
if (secondary is BattleEvent.StageChanged && !secondary.failed) {
i++
val body =
BattleEventBody.StatChange(
statIndex(secondary.stat), secondary.delta.toShort())
if (secondary.targetId == next.targetId) {
subEvents += BattleActionEvent(null, null, body)
} else {
elsewhere = listOf(target(secondary.targetId, DEFAULT_TARGET_MOVE, body))
} }
// The client faints the target on hp reaching 0, as the real server does, so no }
// faint sub-event is sent here. val outcome = HP_TARGET_MOVE.toInt() or effectivenessBit(next.effectiveness)
listOf(BattleEffectTarget(next.targetId, HP_TARGET_MOVE, subEvents)) listOf(BattleEffectTarget(next.targetId, outcome.toShort(), subEvents)) +
elsewhere
} }
is BattleEvent.StageChanged -> is BattleEvent.StageChanged ->
if (!next.failed) { if (!next.failed) {
@@ -120,7 +157,7 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
} }
is BattleEvent.MoveWithoutTarget -> { is BattleEvent.MoveWithoutTarget -> {
i++ i++
listOf(failTarget(battle, event.attackerId, next.moveId)) listOf(failTarget(battle, event.attackerId, next))
} }
else -> emptyList() else -> emptyList()
} }
@@ -137,20 +174,32 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
} }
} }
fun sendSwitchIn(battle: BattleInstance, fullBlock: Boolean) { fun sendSwitchIn(battle: BattleInstance, oldSlot: Int, fullBlock: Boolean) {
broadcast( broadcast(
battle, battle,
BattleSwitchInPacket( BattleSwitchInPacket(
// These are field positions, not party slots: a newly revealed mon enters at field slot newSlot = battle.activeSlot,
// 1, one already seen returns to slot 0. The party slot itself rides in the block. oldSlot = oldSlot,
newSlot = if (fullBlock) 1 else 0,
oldSlot = if (fullBlock) 0 else 1,
mon = battle.activeMon().toBlock(slot = battle.activeSlot, movesPresent = true), mon = battle.activeMon().toBlock(slot = battle.activeSlot, movesPresent = true),
fullBlock = fullBlock, fullBlock = fullBlock,
), ),
) )
} }
/** The opposing side sends out its next monster. Its moves stay hidden from the player. */
fun sendOpponentSwitchIn(battle: BattleInstance, oldSlot: Int, fullBlock: Boolean) {
broadcast(
battle,
BattleSwitchInPacket(
newSlot = battle.opponentSlot,
oldSlot = oldSlot,
mon = battle.opponentMon().toBlock(battle.opponentSlot, movesPresent = false),
fullBlock = fullBlock,
side = OPPONENT_SIDE,
),
)
}
fun sendPrompt(battle: BattleInstance) { fun sendPrompt(battle: BattleInstance) {
broadcast(battle, BattleTileMapPacket(groupId = battle.turn.toShort(), slotTiles = null)) broadcast(battle, BattleTileMapPacket(groupId = battle.turn.toShort(), slotTiles = null))
broadcast(battle, BattleQueuedEventPacket(packed = ACTION_PROMPT)) broadcast(battle, BattleQueuedEventPacket(packed = ACTION_PROMPT))
@@ -172,8 +221,8 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD)) battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD))
} }
fun sendBattleEnd(battle: BattleInstance, party: List<Pokemon>) { fun sendBattleEnd(battle: BattleInstance, party: List<Pokemon>, prizeMoney: Int = 0) {
broadcast(battle, BattleBulkStatePacket.battleEnd()) broadcast(battle, BattleBulkStatePacket.battleEnd(prizeMoney))
battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD)) battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD))
battle.session.send( battle.session.send(
PokemonContainerPacket( PokemonContainerPacket(
@@ -228,15 +277,28 @@ class BattlePacketEmitter @Inject constructor(private val interestManager: Inter
BattleEffectTarget(entityId, targetMove, listOf(BattleActionEvent(null, null, body))) BattleEffectTarget(entityId, targetMove, listOf(BattleActionEvent(null, null, body)))
// A missed or failed move carries no target of its own, so it lands on the attacker's opponent. // A missed or failed move carries no target of its own, so it lands on the attacker's opponent.
// A miss is the target move word on its own with no events under it. The client writes the miss
// line from that, so sending an event as well makes it print an unrelated message.
private fun failTarget( private fun failTarget(
battle: BattleInstance, battle: BattleInstance,
attackerId: Long, attackerId: Long,
moveId: Short event: BattleEvent.MoveWithoutTarget,
): BattleEffectTarget { ): BattleEffectTarget {
val opponent = val defender =
if (attackerId == battle.wild.entityId) battle.activeMon().entityId if (battle.isPlayerSide(attackerId)) battle.opponentMon().entityId
else battle.wild.entityId else battle.activeMon().entityId
return target(opponent, DEFAULT_TARGET_MOVE, BattleEventBody.MoveFailed(moveId)) return when (event) {
is BattleEvent.MoveMissed -> BattleEffectTarget(defender, MISSED_TARGET_MOVE, emptyList())
is BattleEvent.MoveFailed -> BattleEffectTarget(defender, FAILED_TARGET_MOVE, emptyList())
}
}
/** The effectiveness line rides in the outcome word rather than in an event of its own. */
private fun effectivenessBit(effectiveness: Int): Int =
when {
effectiveness > TypeChart.NEUTRAL -> SUPER_EFFECTIVE_BIT
effectiveness in 1..<TypeChart.NEUTRAL -> NOT_VERY_EFFECTIVE_BIT
else -> 0
} }
fun broadcast(battle: BattleInstance, packet: Any) { fun broadcast(battle: BattleInstance, packet: Any) {
@@ -17,10 +17,9 @@ class BattleRegistry @Inject constructor() {
charId: Long, charId: Long,
session: SessionContext, session: SessionContext,
party: List<BattleMonState>, party: List<BattleMonState>,
wild: BattleMonState, opponent: List<BattleMonState>,
rng: BattleRng, rng: BattleRng,
catchable: Boolean = true, rules: BattleRules = BattleRules(),
escapable: Boolean = true,
): BattleInstance { ): BattleInstance {
val battle = val battle =
BattleInstance( BattleInstance(
@@ -28,10 +27,11 @@ class BattleRegistry @Inject constructor() {
charId, charId,
session, session,
party, party,
wild, opponent,
rng, rng,
catchable, rules.catchable,
escapable, rules.escapable,
rules.trainer,
) )
byChar[charId] = battle byChar[charId] = battle
return battle return battle
@@ -3,12 +3,16 @@ package de.fiereu.openmmo.server.game.battle
import de.fiereu.openmmo.common.enums.EVs import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.PokemonStat import de.fiereu.openmmo.common.enums.PokemonStat
import de.fiereu.openmmo.pokemon.SpeciesDef import de.fiereu.openmmo.pokemon.SpeciesDef
import de.fiereu.openmmo.trainer.TrainerDef
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
private const val EV_STAT_CAP = 252 private const val EV_STAT_CAP = 252
private const val EV_TOTAL_CAP = 510 private const val EV_TOTAL_CAP = 510
// The flat multiplier the decomp applies on top of the class rate.
private const val PRIZE_PER_LEVEL = 4
data class RewardResult( data class RewardResult(
val xpGained: Int, val xpGained: Int,
val newXp: Int, val newXp: Int,
@@ -23,11 +27,28 @@ data class RewardResult(
@Singleton @Singleton
class BattleRewards @Inject constructor() { class BattleRewards @Inject constructor() {
/** The Gen 3 wild battle experience: base yield times level over seven. */ /**
* The Gen 3 wild battle experience. The live server is on a later formula and pays more, and
* staying on Gen 3 is deliberate.
*/
fun wildXp(defeated: SpeciesDef, defeatedLevel: Int): Int = defeated.expYield * defeatedLevel / 7 fun wildXp(defeated: SpeciesDef, defeatedLevel: Int): Int = defeated.expYield * defeatedLevel / 7
fun apply(winner: BattleMonState, defeated: SpeciesDef, defeatedLevel: Int): RewardResult { /** The Gen 3 payout for beating a trainer, off the level of the last monster it sent out. */
val gained = wildXp(defeated, defeatedLevel) fun trainerPrize(trainer: TrainerDef, lastLevel: Int): Int =
PRIZE_PER_LEVEL * lastLevel * trainer.prizeRate
/** A trainer's monster is worth half again as much, the way Gen 3 pays it. */
fun trainerXp(defeated: SpeciesDef, defeatedLevel: Int): Int =
wildXp(defeated, defeatedLevel) * 3 / 2
fun apply(
winner: BattleMonState,
defeated: SpeciesDef,
defeatedLevel: Int,
fromTrainer: Boolean = false,
): RewardResult {
val gained =
if (fromTrainer) trainerXp(defeated, defeatedLevel) else wildXp(defeated, defeatedLevel)
val rate = winner.species.growthRate val rate = winner.species.growthRate
val cap = ExpCurves.totalXpFor(rate, ExpCurves.MAX_LEVEL) val cap = ExpCurves.totalXpFor(rate, ExpCurves.MAX_LEVEL)
val newXp = minOf(winner.source.xp + gained, cap) val newXp = minOf(winner.source.xp + gained, cap)
@@ -35,7 +56,9 @@ class BattleRewards @Inject constructor() {
val leveled = newLevel > winner.level val leveled = newLevel > winner.level
val newEvs = addYields(winner.source.eVs, defeated) val newEvs = addYields(winner.source.eVs, defeated)
val grown = winner.source.copy(level = newLevel.toByte(), eVs = newEvs) val grown = winner.source.copy(level = newLevel.toByte(), eVs = newEvs)
val newStats = StatCalculator.computeAll(winner.species, grown) // Stats only move on a level up. New EVs are banked until then, as Gen 3 does, and the client
// is only told about stats when it is told about the level, so moving them apart desyncs it.
val newStats = if (leveled) StatCalculator.computeAll(winner.species, grown) else winner.stats
// A level up raises the maximum, the missing hp stays missing. // A level up raises the maximum, the missing hp stays missing.
val newCurrentHp = val newCurrentHp =
(winner.currentHp + maxOf(0, newStats.hp - winner.stats.hp)).coerceAtMost(newStats.hp) (winner.currentHp + maxOf(0, newStats.hp - winner.stats.hp)).coerceAtMost(newStats.hp)
@@ -69,30 +69,31 @@ constructor(
fun resolveTurn(battle: BattleInstance, playerMoveId: Short): List<BattleEvent> { fun resolveTurn(battle: BattleInstance, playerMoveId: Short): List<BattleEvent> {
val events = mutableListOf<BattleEvent>() val events = mutableListOf<BattleEvent>()
val player = battle.activeMon() val player = battle.activeMon()
val wild = battle.wild val enemy = battle.opponentMon()
val playerAction = TurnAction(player, wild, moves.get(playerMoveId.toInt())) val playerAction = TurnAction(player, enemy, moves.get(playerMoveId.toInt()))
val wildAction = TurnAction(wild, player, pickWildMove(battle)) val enemyAction = TurnAction(enemy, player, pickEnemyMove(battle, enemy))
for (action in order(battle, playerAction, wildAction)) { for (action in order(battle, playerAction, enemyAction)) {
if (action.attacker.fainted) continue if (action.attacker.fainted) continue
execute(battle, action, events) execute(battle, action, events)
if (player.fainted || wild.fainted) break if (player.fainted || enemy.fainted) break
} }
return events return events
} }
/** A voluntary switch spends the player's turn, so the wild attacks the incoming monster. */ /** A voluntary switch spends the player's turn, so the enemy attacks the incoming monster. */
fun resolveSwitchTurn(battle: BattleInstance): List<BattleEvent> { fun resolveSwitchTurn(battle: BattleInstance): List<BattleEvent> {
val events = mutableListOf<BattleEvent>() val events = mutableListOf<BattleEvent>()
if (battle.wild.fainted) return events val enemy = battle.opponentMon()
execute(battle, TurnAction(battle.wild, battle.activeMon(), pickWildMove(battle)), events) if (enemy.fainted) return events
execute(battle, TurnAction(enemy, battle.activeMon(), pickEnemyMove(battle, enemy)), events)
return events return events
} }
/** The wild AI picks a random usable move, falling back to Tackle with no pp left. */ /** The enemy AI picks a random usable move, falling back to Tackle with no pp left. */
private fun pickWildMove(battle: BattleInstance): MoveDef? { private fun pickEnemyMove(battle: BattleInstance, enemy: BattleMonState): MoveDef? {
val usable = battle.wild.moves.filter { it.id.toInt() != 0 && it.pp > 0 } val usable = enemy.moves.filter { it.id.toInt() != 0 && it.pp > 0 }
if (usable.isEmpty()) return moves.get(TACKLE_ID) if (usable.isEmpty()) return moves.get(TACKLE_ID)
return moves.get(usable[battle.rng.pick(usable.size)].id.toInt()) return moves.get(usable[battle.rng.pick(usable.size)].id.toInt())
} }
@@ -4,6 +4,7 @@ import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.DynamicWarp import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.dialog.DialogLine import de.fiereu.openmmo.common.dialog.DialogLine
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.net.game.packets.dialog.TextPokemonSpeciesArg import de.fiereu.openmmo.net.game.packets.dialog.TextPokemonSpeciesArg
import de.fiereu.openmmo.server.game.battle.BattleResult import de.fiereu.openmmo.server.game.battle.BattleResult
import de.fiereu.openmmo.server.game.services.BattleService import de.fiereu.openmmo.server.game.services.BattleService
@@ -138,6 +139,16 @@ internal constructor(
checkNotNull(battles) { "Battle service is unavailable" } checkNotNull(battles) { "Battle service is unavailable" }
.startScriptedBattle(session, dexId, level, moveIds.toList()) .startScriptedBattle(session, dexId, level, moveIds.toList())
/** Fight the decomp trainer with this id, using the region the player is standing in. */
suspend fun trainerBattle(trainerId: Int): BattleResult {
val region =
checkNotNull(Region.byWireValue(state.regionId.toByte())) {
"Scene ran in unknown region ${state.regionId}"
}
return checkNotNull(battles) { "Battle service is unavailable" }
.startTrainerBattle(session, region, trainerId)
}
/** /**
* Walk the map npc with decomp local id [localId] (its entityIdx) through [steps] and wait for * Walk the map npc with decomp local id [localId] (its entityIdx) through [steps] and wait for
* the whole path to finish. This is applymovement plus waitmovement for an npc. * the whole path to finish. This is applymovement plus waitmovement for an npc.
@@ -4,7 +4,9 @@ import de.fiereu.network.PacketEvent
import de.fiereu.network.SessionContext import de.fiereu.network.SessionContext
import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.BattleAction import de.fiereu.openmmo.common.enums.BattleAction
import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket
import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket
@@ -22,6 +24,7 @@ import de.fiereu.openmmo.server.game.battle.BattleRegistry
import de.fiereu.openmmo.server.game.battle.BattleResult import de.fiereu.openmmo.server.game.battle.BattleResult
import de.fiereu.openmmo.server.game.battle.BattleRewards import de.fiereu.openmmo.server.game.battle.BattleRewards
import de.fiereu.openmmo.server.game.battle.BattleRng import de.fiereu.openmmo.server.game.battle.BattleRng
import de.fiereu.openmmo.server.game.battle.BattleRules
import de.fiereu.openmmo.server.game.battle.MoveLearner import de.fiereu.openmmo.server.game.battle.MoveLearner
import de.fiereu.openmmo.server.game.battle.StatCalculator import de.fiereu.openmmo.server.game.battle.StatCalculator
import de.fiereu.openmmo.server.game.battle.TurnEngine import de.fiereu.openmmo.server.game.battle.TurnEngine
@@ -31,6 +34,8 @@ import de.fiereu.openmmo.server.game.battle.notice
import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.world.interest.InterestManager import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.trainer.TrainerDef
import de.fiereu.openmmo.trainer.TrainerRegistry
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
@@ -51,13 +56,20 @@ private const val MAX_WILD_LEVEL = 100
private const val POKE_BALL_ITEM: Short = 5004 private const val POKE_BALL_ITEM: Short = 5004
/** A prompt waiting for its answer, kept after the battle ends. */ /**
private data class PendingMoveLearn(val entityId: Long, val offered: List<Short>) * A prompt waiting for its answer, kept after the battle ends. A trainer battle can raise one
* monster past a level more than once, so these are held per monster rather than per player.
*/
private data class PendingMoveLearn(
val charId: Long,
val entityId: Long,
val offered: List<Short>,
)
/** /**
* Orchestrates wild battles: builds the battle state from the party and a rolled wild monster, * Orchestrates battles: builds the battle state from the party and the opposing side, routes client
* routes client actions through the [TurnEngine], and persists the outcome. Packets go out through * actions through the [TurnEngine], and persists the outcome. Packets go out through the
* the [BattlePacketEmitter] over the battle's interest key. * [BattlePacketEmitter] over the battle's interest key.
*/ */
@Singleton @Singleton
class BattleService class BattleService
@@ -73,6 +85,7 @@ constructor(
private val interestManager: InterestManager, private val interestManager: InterestManager,
private val speciesRegistry: SpeciesRegistry, private val speciesRegistry: SpeciesRegistry,
private val moveRegistry: MoveRegistry, private val moveRegistry: MoveRegistry,
private val trainers: TrainerRegistry,
) { ) {
private val pendingLearns = ConcurrentHashMap<Long, PendingMoveLearn>() private val pendingLearns = ConcurrentHashMap<Long, PendingMoveLearn>()
@@ -101,9 +114,9 @@ constructor(
fun onMoveLearnReply(event: PacketEvent<MoveLearnReplyPacket>) { fun onMoveLearnReply(event: PacketEvent<MoveLearnReplyPacket>) {
val charId = event.session.attributes[PLAYER_STATE]?.characterId ?: return val charId = event.session.attributes[PLAYER_STATE]?.characterId ?: return
val reply = event.packet val reply = event.packet
val pending = pendingLearns[charId] ?: return val pending = pendingLearns[reply.entityId] ?: return
if (pending.entityId != reply.entityId) return if (pending.charId != charId) return
pendingLearns.remove(charId) pendingLearns.remove(reply.entityId)
val stored = val stored =
characterStore.getCharacter(charId)?.pokemon?.firstOrNull { it.id == reply.entityId } characterStore.getCharacter(charId)?.pokemon?.firstOrNull { it.id == reply.entityId }
?: return ?: return
@@ -115,6 +128,17 @@ constructor(
if (moves == stored.moves) return if (moves == stored.moves) return
characterStore.updatePokemon(charId, stored.copy(moves = moves)) characterStore.updatePokemon(charId, stored.copy(moves = moves))
characterStore.flushCharacterAsync(charId) characterStore.flushCharacterAsync(charId)
// A battle still running holds its own copy, and the next reward writes that copy back over
// the store. Move the live one across so the pick survives the rest of the battle.
battles
.byChar(charId)
?.party
?.firstOrNull { it.entityId == reply.entityId }
?.let { live ->
live.moves.clear()
live.moves.addAll(moves.map { PokemonMove(it.id, it.pp) })
live.source = live.source.copy(moves = moves)
}
event.session.send(emitter.moveSlotsDelta(reply.entityId, moves.map { it.id to it.pp }, 0)) event.session.send(emitter.moveSlotsDelta(reply.entityId, moves.map { it.id to it.pp }, 0))
} }
@@ -140,7 +164,7 @@ constructor(
/** Ends a running battle when the player disconnects, keeping the last hp and pp state. */ /** Ends a running battle when the player disconnects, keeping the last hp and pp state. */
fun onDisconnect(session: SessionContext) { fun onDisconnect(session: SessionContext) {
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
pendingLearns.remove(charId) pendingLearns.values.removeIf { it.charId == charId }
val battle = battles.byChar(charId) ?: return val battle = battles.byChar(charId) ?: return
persistParty(battle) persistParty(battle)
finishBattle(battle, BattleResult.DISCONNECTED) finishBattle(battle, BattleResult.DISCONNECTED)
@@ -181,6 +205,41 @@ constructor(
return battle.completion.await() return battle.completion.await()
} }
/** Runs a battle against the decomp trainer with this id and waits for its scene. */
suspend fun startTrainerBattle(
session: SessionContext,
region: Region,
trainerId: Int,
): BattleResult {
val trainer = trainers.get(region, trainerId)
if (trainer == null) {
log.warn { "No $region trainer with id $trainerId" }
return BattleResult.FAILED
}
return startTrainerBattle(session, trainer)
}
/** Runs a battle against a trainer's whole team and waits for its scene. */
suspend fun startTrainerBattle(session: SessionContext, trainer: TrainerDef): BattleResult {
val battle =
createBattle(
session,
trainer.party.map { OpponentSpec(it.dexId, it.level, it.moveIds, it.iv) },
catchable = false,
escapable = false,
trainer = trainer,
) ?: return BattleResult.FAILED
return battle.completion.await()
}
/** Empty [moveIds] keeps the level up moveset, a null [iv] rolls one like a wild encounter. */
private data class OpponentSpec(
val dexId: Int,
val level: Int,
val moveIds: List<Int>,
val iv: Int? = null,
)
private fun createWildBattle( private fun createWildBattle(
session: SessionContext, session: SessionContext,
dexId: Int, dexId: Int,
@@ -188,6 +247,15 @@ constructor(
catchable: Boolean, catchable: Boolean,
escapable: Boolean, escapable: Boolean,
moveIds: List<Int> = emptyList(), moveIds: List<Int> = emptyList(),
): BattleInstance? =
createBattle(session, listOf(OpponentSpec(dexId, level, moveIds)), catchable, escapable)
private fun createBattle(
session: SessionContext,
opponents: List<OpponentSpec>,
catchable: Boolean,
escapable: Boolean,
trainer: TrainerDef? = null,
): BattleInstance? { ): BattleInstance? {
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return null val charId = session.attributes[PLAYER_STATE]?.characterId ?: return null
if (battles.byChar(charId) != null) { if (battles.byChar(charId) != null) {
@@ -213,32 +281,47 @@ constructor(
return null return null
} }
val rng = BattleRng() val rng = BattleRng()
var wildPokemon = wildMons.create(dexId, level, rng) val enemies = mutableListOf<BattleMonState>()
if (wildPokemon == null) { for (spec in opponents) {
session.send(notice("Unknown species $dexId.")) var rolled = wildMons.create(spec.dexId, spec.level, rng)
if (rolled == null) {
session.send(notice("Unknown species ${spec.dexId}."))
return null return null
} }
if (moveIds.isNotEmpty()) { if (spec.moveIds.isNotEmpty()) {
wildPokemon = rolled =
wildPokemon.copy( rolled.copy(
moves = moves =
moveIds.take(4).map { id -> spec.moveIds.take(4).map { id ->
PokemonMove(id.toShort(), (moveRegistry.get(id)?.pp ?: 0).toByte()) PokemonMove(id.toShort(), (moveRegistry.get(id)?.pp ?: 0).toByte())
} + List((4 - moveIds.size).coerceAtLeast(0)) { PokemonMove(0, 0) }) } + List((4 - spec.moveIds.size).coerceAtLeast(0)) { PokemonMove(0, 0) })
}
val def = speciesRegistry.get(spec.dexId)!!
// A trainer's monsters are built to a fixed difficulty, so they must not keep the rolled
// IVs. Max hp moves with them, and the monster comes out full.
if (spec.iv != null) {
val ivs =
IVs().apply {
hp = spec.iv
atk = spec.iv
this.def = spec.iv
spAtk = spec.iv
spDef = spec.iv
spd = spec.iv
}
val fixed = rolled.copy(iVs = ivs)
rolled = fixed.copy(hp = StatCalculator.computeAll(def, fixed).hp.toShort())
}
enemies +=
BattleMonState(rolled.id, def, null, rolled, StatCalculator.computeAll(def, rolled))
} }
val wildDef = speciesRegistry.get(dexId)!!
val wild =
BattleMonState(
wildPokemon.id,
wildDef,
null,
wildPokemon,
StatCalculator.computeAll(wildDef, wildPokemon),
)
log.info { log.info {
"Starting wild battle for char=$charId (${stored.info.name}): ${wildDef.name} level $level" "Starting battle for char=$charId (${stored.info.name}) against " +
enemies.joinToString { "${it.species.name} level ${it.level}" }
} }
val battle = battles.create(charId, session, party, wild, rng, catchable, escapable) val battle =
battles.create(
charId, session, party, enemies, rng, BattleRules(catchable, escapable, trainer))
val firstAlive = party.indexOfFirst { !it.fainted } val firstAlive = party.indexOfFirst { !it.fainted }
battle.activeSlot = firstAlive battle.activeSlot = firstAlive
battle.seenActive.clear() battle.seenActive.clear()
@@ -256,17 +339,24 @@ constructor(
private fun afterTurn(battle: BattleInstance) { private fun afterTurn(battle: BattleInstance) {
when { when {
battle.wild.fainted -> endVictory(battle) battle.opponent.all { it.fainted } -> endVictory(battle)
battle.party.all { it.fainted } -> endDefeat(battle) battle.party.all { it.fainted } -> endDefeat(battle)
else -> {
if (battle.opponentMon().fainted) {
awardXp(battle, battle.opponentMon())
sendOutNextOpponent(battle)
}
// The active mon fainted with a live backup. Open the switch screen instead of the action // The active mon fainted with a live backup. Open the switch screen instead of the action
// prompt. The replacement arrives as a normal SWITCH action. // prompt. The replacement arrives as a normal SWITCH action.
battle.activeMon().fainted -> emitter.sendSwitchPrompt(battle) if (battle.activeMon().fainted) {
else -> { emitter.sendSwitchPrompt(battle)
} else {
battle.turn += 1 battle.turn += 1
emitter.sendPrompt(battle) emitter.sendPrompt(battle)
} }
} }
} }
}
private fun switchMon(battle: BattleInstance, partyIndex: Short) { private fun switchMon(battle: BattleInstance, partyIndex: Short) {
val target = partyIndex.toInt() val target = partyIndex.toInt()
@@ -297,13 +387,24 @@ constructor(
} }
} }
private fun sendOutNextOpponent(battle: BattleInstance) {
val next = battle.opponent.indexOfFirst { !it.fainted }
if (next < 0) return
val fullBlock = next !in battle.opponentSeen
val oldSlot = battle.opponentSlot
battle.opponentSlot = next
battle.opponentSeen.add(next)
log.info { "Opponent sends out slot $next for char=${battle.charId}" }
emitter.sendOpponentSwitchIn(battle, oldSlot, fullBlock)
}
private fun performSwitch(battle: BattleInstance, target: Int) { private fun performSwitch(battle: BattleInstance, target: Int) {
val oldSlot = battle.activeSlot val oldSlot = battle.activeSlot
val fullBlock = target !in battle.seenActive val fullBlock = target !in battle.seenActive
battle.activeSlot = target battle.activeSlot = target
battle.seenActive.add(target) battle.seenActive.add(target)
log.info { "Switch char=${battle.charId} slot $oldSlot -> $target (fullBlock=$fullBlock)" } log.info { "Switch char=${battle.charId} slot $oldSlot -> $target (fullBlock=$fullBlock)" }
emitter.sendSwitchIn(battle, fullBlock) emitter.sendSwitchIn(battle, oldSlot, fullBlock)
} }
private fun flee(battle: BattleInstance) { private fun flee(battle: BattleInstance) {
@@ -326,20 +427,23 @@ constructor(
val stored = characterStore.getCharacter(battle.charId) ?: return val stored = characterStore.getCharacter(battle.charId) ?: return
val nextSlot = ((stored.pokemon.maxOfOrNull { it.containerSlot } ?: -1) + 1).toShort() val nextSlot = ((stored.pokemon.maxOfOrNull { it.containerSlot } ?: -1) + 1).toShort()
val caught = val caught =
battle.wild.source.copy( battle
.opponentMon()
.source
.copy(
ownerId = battle.charId, ownerId = battle.charId,
container = PokemonContainer.PARTY, container = PokemonContainer.PARTY,
containerSlot = nextSlot, containerSlot = nextSlot,
ot = stored.info.name, ot = stored.info.name,
hp = battle.wild.currentHp.toShort(), hp = battle.opponentMon().currentHp.toShort(),
moves = battle.wild.moves.map { PokemonMove(it.id, it.pp) }, moves = battle.opponentMon().moves.map { PokemonMove(it.id, it.pp) },
caughtAt = LocalDateTime.now(), caughtAt = LocalDateTime.now(),
) )
log.info { "Caught wild ${battle.wild.species.name} for char=${battle.charId}" } log.info { "Caught wild ${battle.opponentMon().species.name} for char=${battle.charId}" }
// The caught monster is sent as a full 148-byte record on opcode 0x14 before the ball-throw // The caught monster is sent as a full 148-byte record on opcode 0x14 before the ball-throw
// event, so the client can resolve the monster when the throw lands. // event, so the client can resolve the monster when the throw lands.
battle.session.send(SocialListEntryAddPacket(caught)) battle.session.send(SocialListEntryAddPacket(caught))
battle.session.send(acquiredMonsterDelta(caught, battle.wild.species)) battle.session.send(acquiredMonsterDelta(caught, battle.opponentMon().species))
// "Player threw a Poke Ball" event. // "Player threw a Poke Ball" event.
battle.session.send( battle.session.send(
BattleListEventPacket( BattleListEventPacket(
@@ -354,8 +458,22 @@ constructor(
} }
private fun endVictory(battle: BattleInstance) { private fun endVictory(battle: BattleInstance) {
awardXp(battle, battle.opponentMon())
val prize = battle.trainer?.let { rewards.trainerPrize(it, battle.opponent.last().level) } ?: 0
if (prize > 0) {
characterStore.addMoney(battle.charId, prize)
log.info { "char=${battle.charId} won $prize from ${battle.trainer?.name}" }
}
endBattle(battle, BattleResult.VICTORY, battle.activeMon().entityId, prize)
}
/**
* Pays the active monster for knocking [defeated] out. A trainer's team is paid for one at a
* time, as each faints, which is when the captures show the delta going out.
*/
private fun awardXp(battle: BattleInstance, defeated: BattleMonState) {
val winner = battle.activeMon() val winner = battle.activeMon()
val reward = rewards.apply(winner, battle.wild.species, battle.wild.level) val reward = rewards.apply(winner, defeated.species, defeated.level, battle.trainer != null)
log.info { log.info {
"char=${battle.charId} won: +${reward.xpGained} xp, level ${winner.level} -> ${reward.newLevel}" "char=${battle.charId} won: +${reward.xpGained} xp, level ${winner.level} -> ${reward.newLevel}"
} }
@@ -368,20 +486,20 @@ constructor(
} }
if (outcome.offered.isNotEmpty()) { if (outcome.offered.isNotEmpty()) {
val offered = outcome.offered.map { it.moveId.toShort() } val offered = outcome.offered.map { it.moveId.toShort() }
pendingLearns[battle.charId] = PendingMoveLearn(winner.entityId, offered) pendingLearns[winner.entityId] = PendingMoveLearn(battle.charId, winner.entityId, offered)
battle.session.send(MoveLearnPromptPacket(winner.entityId, offered)) battle.session.send(MoveLearnPromptPacket(winner.entityId, offered))
} }
characterStore.updatePokemon( val grown =
battle.charId,
winner.source.copy( winner.source.copy(
level = reward.newLevel.toByte(), level = reward.newLevel.toByte(),
xp = reward.newXp, xp = reward.newXp,
hp = reward.newCurrentHp.toShort(), hp = reward.newCurrentHp.toShort(),
eVs = reward.newEvs, eVs = reward.newEvs,
moves = winner.moves.map { PokemonMove(it.id, it.pp) }, moves = winner.moves.map { PokemonMove(it.id, it.pp) },
),
) )
endBattle(battle, BattleResult.VICTORY, skip = winner.entityId) winner.source = grown
winner.stats = reward.newStats
characterStore.updatePokemon(battle.charId, grown)
} }
private fun endDefeat(battle: BattleInstance) { private fun endDefeat(battle: BattleInstance) {
@@ -393,10 +511,11 @@ constructor(
battle: BattleInstance, battle: BattleInstance,
result: BattleResult, result: BattleResult,
skip: Long? = null, skip: Long? = null,
prizeMoney: Int = 0,
) { ) {
persistParty(battle, skip) persistParty(battle, skip)
val party = characterStore.getCharacter(battle.charId)?.pokemon ?: emptyList() val party = characterStore.getCharacter(battle.charId)?.pokemon ?: emptyList()
emitter.sendBattleEnd(battle, party) emitter.sendBattleEnd(battle, party, prizeMoney)
battle.pendingResult = result battle.pendingResult = result
} }
@@ -0,0 +1,157 @@
package de.fiereu.openmmo.server.game.battle
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.net.game.packets.battle.BattleEntityMoveEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEventBody
import de.fiereu.openmmo.pokemon.SpeciesRegistry
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.typechart.TypeChart
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.shouldBe
import java.time.LocalDateTime
private const val BULBASAUR = 1
private const val TACKLE: Short = 33
private val species = SpeciesRegistry()
private fun mon(entityId: Long): BattleMonState {
val def = species.get(BULBASAUR)!!
val source =
Pokemon(
id = entityId,
ownerId = 2L,
container = PokemonContainer.PARTY,
containerSlot = 0,
dexId = BULBASAUR,
seed = 0,
ot = "Ash",
nickname = "",
level = 10,
hp = Short.MAX_VALUE,
xp = 0,
eVs = EVs(),
iVs = IVs(),
moves = listOf(PokemonMove(TACKLE, 35)),
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
return BattleMonState(entityId, def, 0, source, StatCalculator.computeAll(def, source))
}
class BattlePacketEmitterTest :
FunSpec({
// Capture 0x33 e6169246 is a missed Rock Tomb: one target, move word 1, no events under it.
test("a miss sends the target on its own with no events") {
val session = FakeSession(1L)
val interest = InterestManager()
val emitter = BattlePacketEmitter(interest)
val attacker = mon(10L)
val defender = mon(20L)
val battle =
BattleInstance(1L, 1L, session, listOf(attacker), listOf(defender), BattleRng())
interest.join(session, battle.key)
emitter.sendEvents(
battle,
listOf(
BattleEvent.MoveUsed(attacker.entityId, TACKLE, 0, 34),
BattleEvent.MoveMissed(attacker.entityId, TACKLE),
),
)
val target =
session.sent.filterIsInstance<BattleEntityMoveEventPacket>().single().targets.single()
target.entityId shouldBe defender.entityId
target.targetMove shouldBe 1.toShort()
target.subEvents.shouldBeEmpty()
}
// Capture 0x33 bf4d168c is a super effective Rock Tomb, outcome word 0x0220.
test("effectiveness rides in the outcome word next to the hit bit") {
val session = FakeSession(1L)
val interest = InterestManager()
val emitter = BattlePacketEmitter(interest)
val attacker = mon(10L)
val defender = mon(20L)
val battle =
BattleInstance(1L, 1L, session, listOf(attacker), listOf(defender), BattleRng())
interest.join(session, battle.key)
emitter.sendEvents(
battle,
listOf(
BattleEvent.MoveUsed(attacker.entityId, TACKLE, 0, 34),
BattleEvent.DamageDealt(defender.entityId, 21, false, TypeChart.NEUTRAL * 2),
),
)
val target =
session.sent.filterIsInstance<BattleEntityMoveEventPacket>().single().targets.single()
target.targetMove shouldBe 0x0220.toShort()
target.subEvents.single().body shouldBe BattleEventBody.HpUpdate(21)
}
// Capture 0x33 bf4d168c carries both, an hp update and a speed drop, under one target.
test("a move's secondary stat drop rides under the damage it dealt") {
val session = FakeSession(1L)
val interest = InterestManager()
val emitter = BattlePacketEmitter(interest)
val attacker = mon(10L)
val defender = mon(20L)
val battle =
BattleInstance(1L, 1L, session, listOf(attacker), listOf(defender), BattleRng())
interest.join(session, battle.key)
emitter.sendEvents(
battle,
listOf(
BattleEvent.MoveUsed(attacker.entityId, TACKLE, 0, 34),
BattleEvent.DamageDealt(defender.entityId, 21, false, TypeChart.NEUTRAL * 2),
BattleEvent.StageChanged(defender.entityId, BattleStat.SPEED, -1, 0, -1, false),
),
)
val target =
session.sent.filterIsInstance<BattleEntityMoveEventPacket>().single().targets.single()
target.targetMove shouldBe 0x0220.toShort()
target.subEvents.map { it.body } shouldBe
listOf(BattleEventBody.HpUpdate(21), BattleEventBody.StatChange(3, -1))
}
// Capture 0x33 6c1b3e8a is a Growl: outcome word 0, one stat event under it.
test("a stat change rides under an outcome word of its own") {
val session = FakeSession(1L)
val interest = InterestManager()
val emitter = BattlePacketEmitter(interest)
val attacker = mon(10L)
val defender = mon(20L)
val battle =
BattleInstance(1L, 1L, session, listOf(attacker), listOf(defender), BattleRng())
interest.join(session, battle.key)
emitter.sendEvents(
battle,
listOf(
BattleEvent.MoveUsed(attacker.entityId, TACKLE, 0, 34),
BattleEvent.StageChanged(defender.entityId, BattleStat.ACCURACY, -1, 0, -1, false),
),
)
val target =
session.sent.filterIsInstance<BattleEntityMoveEventPacket>().single().targets.single()
target.targetMove shouldBe 0.toShort()
target.subEvents.single().body shouldBe BattleEventBody.StatChange(6, -1)
}
})
@@ -6,10 +6,13 @@ import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.GrowthRate import de.fiereu.openmmo.common.enums.GrowthRate
import de.fiereu.openmmo.common.enums.IVs import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry
import de.fiereu.openmmo.trainer.TrainerRegistry
import io.kotest.core.spec.style.FunSpec import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldBe
import java.time.LocalDateTime import java.time.LocalDateTime
@@ -58,6 +61,33 @@ class BattleRewardsTest :
rewards.wildXp(rattata, 3) shouldBe rattata.expYield * 3 / 7 rewards.wildXp(rattata, 3) shouldBe rattata.expYield * 3 / 7
} }
// Camper LIAM, whose last monster is level 11, pays 220 on the live server too.
test("a trainer pays four times the class rate per level of its last monster") {
val liam = TrainerRegistry().get(Region.KANTO, 142).shouldNotBeNull()
liam.prizeRate shouldBe 5
rewards.trainerPrize(liam, liam.party.last().level) shouldBe 220
}
test("a trainer's monster pays half again as much as a wild one") {
val rattata = species.get(RATTATA)!!
rewards.trainerXp(rattata, 11) shouldBe rewards.wildXp(rattata, 11) * 3 / 2
}
test("ev gains alone move neither the stats nor the hp") {
val mon = winner(level = 50, xp = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 50))
val before = mon.stats
val hpBefore = mon.currentHp
val reward = rewards.apply(mon, species.get(RATTATA)!!, 2)
reward.leveled shouldBe false
reward.newStats shouldBe before
reward.newCurrentHp shouldBe hpBefore
reward.newEvs.spd shouldBe 1
}
test("a big win jumps several levels and recomputes stats") { test("a big win jumps several levels and recomputes stats") {
val start = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 5) val start = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 5)
val mon = winner(level = 5, xp = start) val mon = winner(level = 5, xp = start)
@@ -69,7 +69,7 @@ private fun battle(
wild: BattleMonState, wild: BattleMonState,
seed: Long, seed: Long,
): BattleInstance = ): BattleInstance =
BattleInstance(1L, 100L, FakeSession(100L), listOf(player), wild, BattleRng(seed)) BattleInstance(1L, 100L, FakeSession(100L), listOf(player), listOf(wild), BattleRng(seed))
private val engine = TurnEngine(MoveRegistry(), TypeChart()) private val engine = TurnEngine(MoveRegistry(), TypeChart())
@@ -20,6 +20,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleEntityDeltaPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket 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.BattleQueuedEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket
import de.fiereu.openmmo.pokemon.LearnsetRegistry import de.fiereu.openmmo.pokemon.LearnsetRegistry
import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry
@@ -34,20 +35,27 @@ import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import de.fiereu.openmmo.server.game.testsupport.FakeSession import de.fiereu.openmmo.server.game.testsupport.FakeSession
import de.fiereu.openmmo.server.game.world.interest.InterestManager import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.trainer.TrainerDef
import de.fiereu.openmmo.trainer.TrainerMon
import de.fiereu.openmmo.trainer.TrainerRegistry
import de.fiereu.openmmo.typechart.TypeChart import de.fiereu.openmmo.typechart.TypeChart
import io.kotest.core.spec.style.FunSpec import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.collections.shouldNotBeEmpty import io.kotest.matchers.collections.shouldNotBeEmpty
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldBe
import java.time.LocalDateTime import java.time.LocalDateTime
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
private const val TACKLE: Short = 33 private const val TACKLE: Short = 33
private const val RATTATA = 19
private fun bulbasaur(ownerId: Long, level: Byte, hp: Short): Pokemon = private fun bulbasaur(ownerId: Long, level: Byte, hp: Short): Pokemon =
Pokemon( Pokemon(
@@ -95,6 +103,7 @@ private class Fixture(scope: CoroutineScope) {
interestManager = interestManager, interestManager = interestManager,
speciesRegistry = SpeciesRegistry(), speciesRegistry = SpeciesRegistry(),
moveRegistry = MoveRegistry(), moveRegistry = MoveRegistry(),
trainers = TrainerRegistry(),
) )
suspend fun playerWithParty(level: Byte = 50, hp: Short = 999): Pair<FakeSession, Long> { suspend fun playerWithParty(level: Byte = 50, hp: Short = 999): Pair<FakeSession, Long> {
@@ -138,8 +147,8 @@ class BattleServiceTest :
// Bulbasaur base hp 45 at level 50 with empty IVs and EVs. // Bulbasaur base hp 45 at level 50 with empty IVs and EVs.
val field = session.sent.filterIsInstance<BattleFieldStatePacket>().single() val field = session.sent.filterIsInstance<BattleFieldStatePacket>().single()
field.playerParty.single().maxHp shouldBe 105.toShort() field.playerParty.single().maxHp shouldBe 105.toShort()
field.wildParty.single().level shouldBe 2.toByte() field.opponentParty.single().level shouldBe 2.toByte()
field.wildParty.single().currentHp shouldBe field.wildParty.single().maxHp field.opponentParty.single().currentHp shouldBe field.opponentParty.single().maxHp
} }
} }
@@ -233,6 +242,64 @@ class BattleServiceTest :
} }
} }
test("a trainer sends out its next monster instead of losing when one faints") {
runTest {
val fx = Fixture(backgroundScope)
val (session, charId) = fx.playerWithParty()
val terry =
TrainerDef(
id = 1,
name = "TERRY",
trainerClass = 0,
doubleBattle = false,
prizeRate = 5,
party =
listOf(
TrainerMon(RATTATA, 2, 0, 0, emptyList()),
TrainerMon(RATTATA, 2, 0, 0, emptyList()),
),
)
// The battle never ends in this test, so its await must not hold the test scope open.
backgroundScope.launch { fx.service.startTrainerBattle(session, terry) }
runCurrent()
val battle = fx.registry.byChar(charId).shouldNotBeNull()
battle.opponent.size shouldBe 2
val field = session.sent.filterIsInstance<BattleFieldStatePacket>().single()
field.opponentParty[0].revealed.shouldBeTrue()
field.opponentParty[1].revealed shouldBe false
var rounds = 0
while (battle.opponentSlot == 0 && rounds < 10) {
session.act(fx.service, BattleAction.MOVE, TACKLE)
rounds += 1
}
battle.opponentSlot shouldBe 1
battle.opponent[0].fainted.shouldBeTrue()
battle.pendingResult.shouldBeNull()
session.sent.filterIsInstance<BattleSwitchInPacket>().last().side shouldBe 1.toByte()
// The lead is paid for as it faints, not held back until the whole team is beaten.
val xpBefore = battle.activeMon().source.xp
xpBefore shouldBeGreaterThan 0
session.sent
.filterIsInstance<BattleEntityDeltaPacket>()
.any { it.experience != null }
.shouldBeTrue()
rounds = 0
while (battle.pendingResult == null && rounds < 10) {
session.act(fx.service, BattleAction.MOVE, TACKLE)
rounds += 1
}
// The second monster pays on top of the first, rather than replacing it.
battle.activeMon().source.xp shouldBeGreaterThan xpBefore
}
}
test("a disconnect persists and removes the battle") { test("a disconnect persists and removes the battle") {
runTest { runTest {
val fx = Fixture(this) val fx = Fixture(this)
@@ -29,6 +29,7 @@ import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.world.interest.InterestManager import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import de.fiereu.openmmo.trainer.TrainerRegistry
import de.fiereu.openmmo.typechart.TypeChart import de.fiereu.openmmo.typechart.TypeChart
/** /**
@@ -59,6 +60,7 @@ fun movementService(
interestManager = interest, interestManager = interest,
speciesRegistry = species, speciesRegistry = species,
moveRegistry = moves, moveRegistry = moves,
trainers = TrainerRegistry(),
) )
val registry = ScriptRegistry(emptyMap()) val registry = ScriptRegistry(emptyMap())
val runner = val runner =