diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt index 953251d..f7ac0d7 100644 --- a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt @@ -3,12 +3,23 @@ package de.fiereu.bytecodec interface CodecScope

{ fun field(codec: Codec, get: (P) -> T): T + /** + * A field present only when [present] is true, absent otherwise. [present] must be derivable the + * same way on both sides, typically from a flags field decoded just above, so encode and decode + * always agree on presence. Returns the decoded value, or the value from [get] on encode, and + * null when the field is absent. + */ + fun optionalField(present: Boolean, codec: Codec, get: (P) -> T?): T? + fun structural(codec: Codec) } internal class ReadingScope

(private val buf: ReadBuffer) : CodecScope

{ override fun field(codec: Codec, get: (P) -> T): T = codec.read(buf) + override fun optionalField(present: Boolean, codec: Codec, get: (P) -> T?): T? = + if (present) codec.read(buf) else null + override fun structural(codec: Codec) { codec.read(buf) } @@ -24,6 +35,13 @@ internal class WritingScope

( return v } + override fun optionalField(present: Boolean, codec: Codec, get: (P) -> T?): T? { + val v = get(value) + if (present) + codec.write(buf, requireNotNull(v) { "optional field is present but value is null" }) + return v + } + override fun structural(codec: Codec) { codec.write(buf, Unit) } diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/GameProtocol.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/GameProtocol.kt index 5153d97..e72860f 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/GameProtocol.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/GameProtocol.kt @@ -113,7 +113,7 @@ object GameProtocol : Protocol() { bidi(0x26u, DialogOptionPacketCodec) c2s(0x27u, PlayerStopMovingPacketCodec) - s2c(0x27u, BattlePromptSwitchPacketCodec) + s2c(0x27u, PcTogglePacketCodec) c2s(0x28u, TypedBinaryDataPacketCodec) s2c(0x28u, EntityInteractionFlagPacketCodec) @@ -407,7 +407,7 @@ object GameProtocol : Protocol() { s2c(0x94u, EntityAppearanceSyncPacketCodec) c2s(0x95u, MailComposeSendPacketCodec) - s2c(0x95u, BattleSwitchPromptTogglePacketCodec) + s2c(0x95u, MailTogglePacketCodec) c2s(0x96u, TeamPreviewRevealPickPacketCodec) s2c(0x96u, BattleEndDisconnectPacketCodec) diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleBulkStatePacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleBulkStatePacket.kt index 78a91c7..587ad24 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleBulkStatePacket.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleBulkStatePacket.kt @@ -36,12 +36,14 @@ internal val BattleMessageArgCodec: Codec = } val t = type.toInt() val payload: BattleMessageArgPayload = - when { - t == 5 -> StringArgPayload(Utf16LeNullTerminated.read(buf)) - t == 28 -> EmptyArgPayload - t == 30 -> LongArgPayload(S64LE.read(buf)) - t == 9 || t == 10 || t == 17 -> IntArgPayload(S32LE.read(buf)) - t == 18 -> StringArgPayload(Utf16LeNullTerminated.read(buf)) + when (t) { + 5 -> StringArgPayload(Utf16LeNullTerminated.read(buf)) + 28 -> EmptyArgPayload + 30 -> LongArgPayload(S64LE.read(buf)) + 9, + 10, + 17 -> IntArgPayload(S32LE.read(buf)) + 18 -> StringArgPayload(Utf16LeNullTerminated.read(buf)) else -> { val n = U8.read(buf) ShortListArgPayload((0 until n).map { S16LE.read(buf) }) @@ -56,12 +58,14 @@ internal val BattleMessageArgCodec: Codec = S8.write(buf, rawType) if (value.hasExtra) S8.write(buf, value.extra) val t = value.type.toInt() - when { - t == 5 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value) - t == 28 -> Unit - t == 30 -> S64LE.write(buf, (value.payload as LongArgPayload).value) - t == 9 || t == 10 || t == 17 -> S32LE.write(buf, (value.payload as IntArgPayload).value) - t == 18 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value) + when (t) { + 5 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value) + 28 -> Unit + 30 -> S64LE.write(buf, (value.payload as LongArgPayload).value) + 9, + 10, + 17 -> S32LE.write(buf, (value.payload as IntArgPayload).value) + 18 -> Utf16LeNullTerminated.write(buf, (value.payload as StringArgPayload).value) else -> { val values = (value.payload as ShortListArgPayload).values U8.write(buf, values.size) diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleEntityMoveEventPacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleEntityMoveEventPacket.kt index 135ff7d..0748f4e 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleEntityMoveEventPacket.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleEntityMoveEventPacket.kt @@ -2,35 +2,152 @@ package de.fiereu.openmmo.net.game.packets.battle import de.fiereu.bytecodec.* -data class BattleMoveDataEntry( - val entityId: Long, - val value: Short, - val actionCount: Int, -) +/** The body of a nested battle action event, selected by its [BattleEventType]. */ +sealed interface BattleEventBody { + /** Event 0, BattleHpUpdate: the entity's resulting hp. */ + data class HpUpdate(val currentHp: Short) : BattleEventBody -private val BattleMoveDataEntryCodec: Codec = - object : PacketCodec() { - override fun CodecScope.body(): BattleMoveDataEntry { - val entityId = field(S64LE) { it.entityId } - val value = field(S16LE) { it.value } - val actionCount = field(U8) { it.actionCount } - return BattleMoveDataEntry(entityId, value, actionCount) + /** + * Event 1, BattleStatChange. [stat] is the wire stat id (1 atk, 2 def, 3 spd, ...) and + * [stageDelta] the signed number of stages (-1 down one, +2 up two). [changeType] is 0 for a + * normal stage change. + */ + data class StatChange(val stat: Byte, val stageDelta: Short, val changeType: Byte = 0) : + 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. + */ + data object EffectivenessMessage : BattleEventBody + + /** Event 0x40, BattleMoveFailed. [moveId] names the move in the "it failed" message. */ + data class MoveFailed(val moveId: Short) : BattleEventBody +} + +private val HpUpdateBodyCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleEventBody { + val currentHp = field(S16LE) { (it as BattleEventBody.HpUpdate).currentHp } + return BattleEventBody.HpUpdate(currentHp) } } -data class BattleEntityMoveEventPacket( +private val StatChangeBodyCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleEventBody { + val changeType = field(S8) { (it as BattleEventBody.StatChange).changeType } + val stat = field(S8) { (it as BattleEventBody.StatChange).stat } + val stageDelta = field(S16LE) { (it as BattleEventBody.StatChange).stageDelta } + return BattleEventBody.StatChange(stat, stageDelta, changeType) + } + } + +private val FaintBodyCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleEventBody { + val playFaintAnimation = field(Bool) { (it as BattleEventBody.Faint).playFaintAnimation } + return BattleEventBody.Faint(playFaintAnimation) + } + } + +private val EffectivenessMessageBodyCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleEventBody = + BattleEventBody.EffectivenessMessage + } + +private val MoveFailedBodyCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleEventBody { + val moveId = field(S16LE) { (it as BattleEventBody.MoveFailed).moveId } + return BattleEventBody.MoveFailed(moveId) + } + } + +/** + * A nested battle action event's type, the client's event id. Each type holds the codec for its + * body. The enum grows as we capture more of the client's event types. + */ +enum class BattleEventType(val id: Int, val codec: Codec) { + HP_UPDATE(id = 0, codec = HpUpdateBodyCodec), + STAT_CHANGE(id = 1, codec = StatChangeBodyCodec), + EFFECTIVENESS_MESSAGE(id = 4, codec = EffectivenessMessageBodyCodec), + POKEMON_FAINTED(id = 5, codec = FaintBodyCodec), + MOVE_FAILED(id = 0x40, codec = MoveFailedBodyCodec); + + companion object { + fun ofId(id: Int): BattleEventType = entries.first { it.id == id } + + fun ofBody(body: BattleEventBody): BattleEventType = + when (body) { + is BattleEventBody.HpUpdate -> HP_UPDATE + is BattleEventBody.StatChange -> STAT_CHANGE + is BattleEventBody.EffectivenessMessage -> EFFECTIVENESS_MESSAGE + is BattleEventBody.Faint -> POKEMON_FAINTED + is BattleEventBody.MoveFailed -> MOVE_FAILED + } + } +} + +private const val FLAG_ENTITY_A = 0x01 +private const val FLAG_ENTITY_B = 0x02 + +/** + * One nested battle action event. The variable header is a type id, a presence-flags byte, then the + * entity ids the flags select. [entityA] and [entityB] are present only when their flag bit is set. + */ +data class BattleActionEvent(val entityA: Long?, val entityB: Long?, val body: BattleEventBody) + +private val BattleActionEventCodec: Codec = + object : PacketCodec() { + override fun CodecScope.body(): BattleActionEvent { + val typeId = field(U8) { BattleEventType.ofBody(it.body).id } + val aux = + field(U8) { + var flags = 0 + if (it.entityA != null) flags = flags or FLAG_ENTITY_A + if (it.entityB != null) flags = flags or FLAG_ENTITY_B + flags + } + val entityA = optionalField((aux and FLAG_ENTITY_A) != 0, S64LE) { it.entityA } + val entityB = optionalField((aux and FLAG_ENTITY_B) != 0, S64LE) { it.entityB } + val body = field(BattleEventType.ofId(typeId).codec) { it.body } + return BattleActionEvent(entityA, entityB, body) + } + } + +/** One mon a move affected: its entity, its move short, and the events applied to it. */ +data class BattleEffectTarget( val entityId: Long, - val value: Short, + val targetMove: Short, + val subEvents: List, +) + +object BattleEffectTargetCodec : PacketCodec() { + override fun CodecScope.body(): BattleEffectTarget { + val entityId = field(S64LE) { it.entityId } + val targetMove = field(S16LE) { it.targetMove } + val subEvents = field(BattleActionEventCodec.listPrefixed(U8)) { it.subEvents } + return BattleEffectTarget(entityId, targetMove, subEvents) + } +} + +data class BattleEntityMoveEventPacket( + val sourceEntity: Long, + val sourceMove: Short, val kind: Byte, - val entries: List, + val targets: List, ) object BattleEntityMoveEventPacketCodec : PacketCodec() { override fun CodecScope.body(): BattleEntityMoveEventPacket { - val entityId = field(S64LE) { it.entityId } - val value = field(S16LE) { it.value } + val sourceEntity = field(S64LE) { it.sourceEntity } + val sourceMove = field(S16LE) { it.sourceMove } val kind = field(S8) { it.kind } - val entries = field(BattleMoveDataEntryCodec.listPrefixed(U8)) { it.entries } - return BattleEntityMoveEventPacket(entityId, value, kind, entries) + val targets = field(BattleEffectTargetCodec.listPrefixed(U8)) { it.targets } + return BattleEntityMoveEventPacket(sourceEntity, sourceMove, kind, targets) } } diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleFieldStatePacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleFieldStatePacket.kt index 49b1a72..29cfce6 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleFieldStatePacket.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleFieldStatePacket.kt @@ -2,146 +2,54 @@ package de.fiereu.openmmo.net.game.packets.battle import de.fiereu.bytecodec.* -data class BattleFieldMon( - val entityId: Long, - val species: Short, - val hp: Short, -) - /** * 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. A player block carries a - * per-species stat and move block with its hp and party slot filled in, so a benched monster goes - * in its own slot instead of overwriting the active one. + * 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. */ data class BattleFieldStatePacket( val playerName: String, val playerId: Long, - val playerParty: List, - val wildMon: BattleFieldMon, + val playerParty: List, + val activeSlot: Int, + val wildParty: List, ) private fun seg(hex: String): ByteArray = ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() } private val PREAMBLE = seg("02000000000000000000000000ff000000000016000000ff00200006") -private val AFTER_NAME = seg("00") private val APPEARANCE = seg("ff00024c031aac0f00038001a400040000000000") -private val SIDE_HEADER = seg("01") -private val SIDE_MID = seg("00") -// A monster block starts with its slot index then a constant 01. -private val MON_CONST = seg("01") -private val ACTIVE_DETAIL = seg("0000ef010600000000000003ff000000006666666601060000000000") -private val WILD_DATA_A = seg("020000010000000e00") -private val WILD_DATA_B = seg("000000ff0300010000f8010200000000010003ff000000006666666600000000") - -private const val WILD_COUNT = 1 - -// Per-species blocks captured from a real field state. The 9-byte stat segment is -// [prefix (7)][max hp][00] and the 17-byte move segment is [move body (16)][party slot]. Hp and -// slot are spliced in per monster. -private class SpeciesBlock(val statPrefix: ByteArray, val moveBody: ByteArray) - -private val SPECIES_BLOCKS = - mapOf( - 495 to SpeciesBlock(seg("06000000000000"), seg("000000ff0301410021002b0000000000")), - 504 to SpeciesBlock(seg("02000001000000"), seg("000000ff030132002100000000000000")), - ) -private val DEFAULT_SPECIES_BLOCK = SPECIES_BLOCKS.getValue(504) - -private fun speciesBlock(species: Short): SpeciesBlock = - SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SPECIES_BLOCK - -private val BattleFieldStateBody: Codec = - object : Codec { - override fun read(buf: ReadBuffer): BattleFieldStatePacket { - buf.readBytes(ByteArray(PREAMBLE.size)) - val playerName = Utf16LeNullTerminated.read(buf) - buf.readBytes(ByteArray(AFTER_NAME.size)) - val playerId = S64LE.read(buf) - buf.readBytes(ByteArray(APPEARANCE.size)) - buf.readBytes(ByteArray(SIDE_HEADER.size)) - val playerCount = U8.read(buf) - buf.readBytes(ByteArray(SIDE_MID.size)) - val party = List(playerCount) { readMon(buf) } - buf.readBytes(ByteArray(ACTIVE_DETAIL.size)) - buf.readBytes(ByteArray(SIDE_HEADER.size)) - U8.read(buf) // opponent count - buf.readBytes(ByteArray(SIDE_MID.size)) - val wild = readWild(buf) - return BattleFieldStatePacket(playerName, playerId, party, wild) - } - - override fun write(buf: WriteBuffer, value: BattleFieldStatePacket) { - buf.writeBytes(PREAMBLE) - Utf16LeNullTerminated.write(buf, value.playerName) - buf.writeBytes(AFTER_NAME) - S64LE.write(buf, value.playerId) - buf.writeBytes(APPEARANCE) - buf.writeBytes(SIDE_HEADER) - U8.write(buf, value.playerParty.size) - buf.writeBytes(SIDE_MID) - value.playerParty.forEachIndexed { slot, mon -> writeMon(buf, slot, mon) } - buf.writeBytes(ACTIVE_DETAIL) - buf.writeBytes(SIDE_HEADER) - U8.write(buf, WILD_COUNT) - buf.writeBytes(SIDE_MID) - writeWild(buf, value.wildMon) - } - - private fun readMon(buf: ReadBuffer): BattleFieldMon { - S8.read(buf) // slot index - buf.readBytes(ByteArray(MON_CONST.size)) - val entityId = S64LE.read(buf) - val species = S16LE.read(buf) - val block = speciesBlock(species) - buf.readBytes(ByteArray(block.statPrefix.size)) - S8.read(buf) // max hp - S8.read(buf) // stat tail - val hp = S16LE.read(buf) - buf.readBytes(ByteArray(block.moveBody.size)) - S8.read(buf) // slot trailer - return BattleFieldMon(entityId, species, hp) - } - - private fun writeMon(buf: WriteBuffer, slot: Int, mon: BattleFieldMon) { - S8.write(buf, slot.toByte()) - buf.writeBytes(MON_CONST) - S64LE.write(buf, mon.entityId) - S16LE.write(buf, mon.species) - val block = speciesBlock(mon.species) - buf.writeBytes(block.statPrefix) - S8.write(buf, mon.hp.toByte()) // max hp - S8.write(buf, 0) - S16LE.write(buf, mon.hp) - buf.writeBytes(block.moveBody) - S8.write(buf, slot.toByte()) // slot trailer - } - - private fun readWild(buf: ReadBuffer): BattleFieldMon { - S8.read(buf) // slot index - buf.readBytes(ByteArray(MON_CONST.size)) - val entityId = S64LE.read(buf) - val species = S16LE.read(buf) - buf.readBytes(ByteArray(WILD_DATA_A.size)) - val hp = S16LE.read(buf) - buf.readBytes(ByteArray(WILD_DATA_B.size)) - return BattleFieldMon(entityId, species, hp) - } - - private fun writeWild(buf: WriteBuffer, mon: BattleFieldMon) { - S8.write(buf, 0) - buf.writeBytes(MON_CONST) - S64LE.write(buf, mon.entityId) - S16LE.write(buf, mon.species) - buf.writeBytes(WILD_DATA_A) - S16LE.write(buf, mon.hp) - buf.writeBytes(WILD_DATA_B) - } - } object BattleFieldStatePacketCodec : PacketCodec() { override fun CodecScope.body(): BattleFieldStatePacket { - return field(BattleFieldStateBody) { it } + constant(PREAMBLE) + val playerName = field(Utf16LeNullTerminated) { it.playerName } + reserved(0) + val playerId = field(S64LE) { it.playerId } + constant(APPEARANCE) + constant(1) // player side marker + val partyCount = field(U8) { it.playerParty.size } + reserved(0) + val party = + List(partyCount) { i -> + val block = field(BattleFullBlockCodec) { it.playerParty[i] } + // The trailing byte flags the last party block; 0 says another block follows. + field(S8) { if (i == it.playerParty.lastIndex) 1.toByte() else 0.toByte() } + block + } + val active = + 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 } + reserved(0) + val wildParty = List(wildCount) { i -> field(BattleWildBlockCodec) { it.wildParty[i] } } + return BattleFieldStatePacket(playerName, playerId, party, active.slot, wildParty) } } diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt new file mode 100644 index 0000000..ac0d1c2 --- /dev/null +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleMonBlock.kt @@ -0,0 +1,114 @@ +package de.fiereu.openmmo.net.game.packets.battle + +import de.fiereu.bytecodec.* + +/** + * One monster as the battle packets carry it, shared by the field state and the switch-in. The + * values are server computed and the client displays them as sent. A full block carries hp, + * ability, and moves. The 21-byte active detail names only species, level, and gender. + * + * [movesPresent] is the wire flag that guards the ability and move ids. The wild block clears it so + * the client never learns the enemy moveset. + */ +data class BattleMonBlock( + val slot: Int, + val entityId: Long, + val species: Short, + val level: Byte, + val gender: Byte, + val abilityId: Short, + val maxHp: Short, + val currentHp: Short, + val movesPresent: Boolean, + val moveIds: List, +) { + init { + require(moveIds.size == MOVE_SLOTS) { "A battle mon block carries exactly $MOVE_SLOTS moves" } + } + + companion object { + const val MOVE_SLOTS = 4 + } +} + +private fun seg(hex: String): ByteArray = + ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + +// 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, + val species: Short, + val level: Byte, + val gender: Byte, +) { + companion object { + fun of(slot: Int, mon: BattleMonBlock): BattleActiveDetail = + BattleActiveDetail(slot, mon.species, mon.level, mon.gender) + } +} + +internal object BattleActiveDetailCodec : PacketCodec() { + const val WIRE_SIZE = 21 + + override fun CodecScope.body(): BattleActiveDetail { + reserved(0) + val slot = field(S8) { it.slot.toByte() }.toInt() + val species = field(S16LE) { it.species } + val level = field(S8) { it.level } + padding(4) + val gender = field(S8) { it.gender } + reserved(0) + constant(ACTIVE_TAIL) + return BattleActiveDetail(slot, species, level, gender) + } +} + +internal object BattleFullBlockCodec : PacketCodec() { + override fun CodecScope.body(): BattleMonBlock { + val slot = field(S8) { it.slot.toByte() }.toInt() + constant(1) + val entityId = field(S64LE) { it.entityId } + val species = field(S16LE) { it.species } + val level = field(S8) { it.level } + padding(2) + val gender = field(S8) { it.gender } + padding(3) + val currentHp = field(S16LE) { it.currentHp } + 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 } + 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() { + override fun CodecScope.body(): BattleMonBlock { + val slot = field(S8) { it.slot.toByte() }.toInt() + constant(1) + val entityId = field(S64LE) { it.entityId } + val species = field(S16LE) { it.species } + val level = field(S8) { it.level } + padding(2) + val gender = field(S8) { it.gender } + 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) + } +} diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattlePromptSwitchPacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattlePromptSwitchPacket.kt deleted file mode 100644 index fe338d5..0000000 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattlePromptSwitchPacket.kt +++ /dev/null @@ -1,16 +0,0 @@ -package de.fiereu.openmmo.net.game.packets.battle - -import de.fiereu.bytecodec.Bool -import de.fiereu.bytecodec.CodecScope -import de.fiereu.bytecodec.PacketCodec - -data class BattlePromptSwitchPacket( - val enabled: Boolean, -) - -object BattlePromptSwitchPacketCodec : PacketCodec() { - override fun CodecScope.body(): BattlePromptSwitchPacket { - val enabled = field(Bool) { it.enabled } - return BattlePromptSwitchPacket(enabled) - } -} diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchInPacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchInPacket.kt index fa7d148..126fa51 100644 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchInPacket.kt +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchInPacket.kt @@ -2,126 +2,64 @@ package de.fiereu.openmmo.net.game.packets.battle import de.fiereu.bytecodec.* -data class BattleSwitchInMon( - val entityId: Long, - val species: Short, - val hp: Short, -) - /** * Brings a monster onto the field after a switch (opcode 0x35). The header names the new and * previous active party slots. A monster coming out for the first time carries its full block, the * same layout as the field state. One already seen active is sent as just its 21-byte active - * detail. When [fullBlock] is false the incoming hp and entity id are left at zero on decode. + * detail. When [fullBlock] is false the decode fills only species, level, and gender. */ data class BattleSwitchInPacket( val newSlot: Int, val oldSlot: Int, - val mon: BattleSwitchInMon, + val mon: BattleMonBlock, val fullBlock: Boolean, ) -private fun switchSeg(hex: String): ByteArray = - ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() } +private val NO_MOVES = List(BattleMonBlock.MOVE_SLOTS) { 0.toShort() } -private val SWITCH_HEADER = switchSeg("0000") -private val SWITCH_MON_CONST = switchSeg("01") +private data class SwitchInMon(val mon: BattleMonBlock, val fullBlock: Boolean) -// A species carries a full-block stat prefix and move body (as in the field state) plus a distinct -// active-detail stat used by the switch-in and active-mon segments. -private class SwitchSpeciesBlock( - val statPrefix: ByteArray, - val moveBody: ByteArray, - val activeStat: ByteArray, -) - -private val SWITCH_SPECIES_BLOCKS = - mapOf( - 495 to - SwitchSpeciesBlock( - switchSeg("06000000000000"), - switchSeg("000000ff0301410021002b0000000000"), - switchSeg("06000000000000"), - ), - 504 to - SwitchSpeciesBlock( - switchSeg("02000001000000"), - switchSeg("000000ff030132002100000000000000"), - switchSeg("02000000000100"), - ), - ) -private val DEFAULT_SWITCH_BLOCK = SWITCH_SPECIES_BLOCKS.getValue(504) - -private fun switchBlock(species: Short): SwitchSpeciesBlock = - SWITCH_SPECIES_BLOCKS[species.toInt()] ?: DEFAULT_SWITCH_BLOCK - -// [00][slot][species][active stat (7)] then this constant tail. -private val SWITCH_ACTIVE_TAIL = switchSeg("03ff0000000066666666") -private const val SWITCH_STAT_PREFIX_SIZE = 7 -private const val SWITCH_MOVE_BODY_SIZE = 16 -private const val SWITCH_ACTIVE_STAT_SIZE = 7 -private const val SWITCH_ACTIVE_DETAIL_SIZE = 21 - -private val BattleSwitchInBody: Codec = - object : Codec { - override fun read(buf: ReadBuffer): BattleSwitchInPacket { - buf.readBytes(ByteArray(SWITCH_HEADER.size)) - val newSlot = U8.read(buf) - val oldSlot = U8.read(buf) - val fullBlock = buf.remaining() > SWITCH_ACTIVE_DETAIL_SIZE - var entityId = 0L - var blockHp: Short = 0 - var blockSpecies: Short = 0 - if (fullBlock) { - S8.read(buf) // slot index - buf.readBytes(ByteArray(SWITCH_MON_CONST.size)) - entityId = S64LE.read(buf) - blockSpecies = S16LE.read(buf) - buf.readBytes(ByteArray(SWITCH_STAT_PREFIX_SIZE)) - S8.read(buf) // max hp - S8.read(buf) // stat tail - blockHp = S16LE.read(buf) - buf.readBytes(ByteArray(SWITCH_MOVE_BODY_SIZE)) - S8.read(buf) // slot trailer - } - // active detail - S8.read(buf) // constant 00 - S8.read(buf) // slot - val activeSpecies = S16LE.read(buf) - buf.readBytes(ByteArray(SWITCH_ACTIVE_STAT_SIZE)) - buf.readBytes(ByteArray(SWITCH_ACTIVE_TAIL.size)) - val species = if (fullBlock) blockSpecies else activeSpecies - return BattleSwitchInPacket( - newSlot, oldSlot, BattleSwitchInMon(entityId, species, blockHp), fullBlock) +// Whether the full block precedes the active detail is not flagged on the wire. Only the +// remaining length tells the two shapes apart, so this section cannot go through the scope. +private val SwitchInMonCodec: Codec = + object : Codec { + override fun read(buf: ReadBuffer): SwitchInMon { + val fullBlock = buf.remaining() > BattleActiveDetailCodec.WIRE_SIZE + val block = if (fullBlock) BattleFullBlockCodec.read(buf) else null + if (fullBlock) S8.read(buf) // last-block flag before the active detail + val active = BattleActiveDetailCodec.read(buf) + val mon = + block + ?: BattleMonBlock( + slot = active.slot, + entityId = 0, + species = active.species, + level = active.level, + gender = active.gender, + abilityId = 0, + maxHp = 0, + currentHp = 0, + movesPresent = false, + moveIds = NO_MOVES, + ) + return SwitchInMon(mon, fullBlock) } - override fun write(buf: WriteBuffer, value: BattleSwitchInPacket) { - buf.writeBytes(SWITCH_HEADER) - U8.write(buf, value.newSlot) - U8.write(buf, value.oldSlot) - val block = switchBlock(value.mon.species) + override fun write(buf: WriteBuffer, value: SwitchInMon) { if (value.fullBlock) { - S8.write(buf, value.newSlot.toByte()) - buf.writeBytes(SWITCH_MON_CONST) - S64LE.write(buf, value.mon.entityId) - S16LE.write(buf, value.mon.species) - buf.writeBytes(block.statPrefix) - S8.write(buf, value.mon.hp.toByte()) // max hp - S8.write(buf, 0) - S16LE.write(buf, value.mon.hp) - buf.writeBytes(block.moveBody) - S8.write(buf, value.newSlot.toByte()) // slot trailer + BattleFullBlockCodec.write(buf, value.mon) + S8.write(buf, 1) // last-block flag before the active detail } - S8.write(buf, 0) - S8.write(buf, value.newSlot.toByte()) - S16LE.write(buf, value.mon.species) - buf.writeBytes(block.activeStat) - buf.writeBytes(SWITCH_ACTIVE_TAIL) + BattleActiveDetailCodec.write(buf, BattleActiveDetail.of(value.mon.slot, value.mon)) } } object BattleSwitchInPacketCodec : PacketCodec() { override fun CodecScope.body(): BattleSwitchInPacket { - return field(BattleSwitchInBody) { it } + padding(2) + 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) } } diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchPromptTogglePacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchPromptTogglePacket.kt deleted file mode 100644 index 64a8f51..0000000 --- a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/BattleSwitchPromptTogglePacket.kt +++ /dev/null @@ -1,16 +0,0 @@ -package de.fiereu.openmmo.net.game.packets.battle - -import de.fiereu.bytecodec.Bool -import de.fiereu.bytecodec.CodecScope -import de.fiereu.bytecodec.PacketCodec - -data class BattleSwitchPromptTogglePacket( - val shown: Boolean, -) - -object BattleSwitchPromptTogglePacketCodec : PacketCodec() { - override fun CodecScope.body(): BattleSwitchPromptTogglePacket { - val shown = field(Bool) { it.shown } - return BattleSwitchPromptTogglePacket(shown) - } -} diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/MailTogglePacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/MailTogglePacket.kt new file mode 100644 index 0000000..118d95e --- /dev/null +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/MailTogglePacket.kt @@ -0,0 +1,16 @@ +package de.fiereu.openmmo.net.game.packets.battle + +import de.fiereu.bytecodec.Bool +import de.fiereu.bytecodec.CodecScope +import de.fiereu.bytecodec.PacketCodec + +data class MailTogglePacket( + val shown: Boolean, +) + +object MailTogglePacketCodec : PacketCodec() { + override fun CodecScope.body(): MailTogglePacket { + val shown = field(Bool) { it.shown } + return MailTogglePacket(shown) + } +} diff --git a/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/PcTogglePacket.kt b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/PcTogglePacket.kt new file mode 100644 index 0000000..05b35cf --- /dev/null +++ b/protocols.game/src/main/kotlin/de/fiereu/openmmo/net/game/packets/battle/PcTogglePacket.kt @@ -0,0 +1,16 @@ +package de.fiereu.openmmo.net.game.packets.battle + +import de.fiereu.bytecodec.Bool +import de.fiereu.bytecodec.CodecScope +import de.fiereu.bytecodec.PacketCodec + +data class PcTogglePacket( + val shown: Boolean, +) + +object PcTogglePacketCodec : PacketCodec() { + override fun CodecScope.body(): PcTogglePacket { + val shown = field(Bool) { it.shown } + return PcTogglePacket(shown) + } +} diff --git a/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleEntityMoveEventPacketTest.kt b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleEntityMoveEventPacketTest.kt new file mode 100644 index 0000000..8aacc30 --- /dev/null +++ b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleEntityMoveEventPacketTest.kt @@ -0,0 +1,40 @@ +package de.fiereu.openmmo.net.game + +import de.fiereu.bytecodec.test.decodeBytes +import de.fiereu.bytecodec.test.encodeToBytes +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 +import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacketCodec +import de.fiereu.openmmo.net.game.packets.battle.BattleEventBody +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +class BattleEntityMoveEventPacketTest : + FunSpec({ + test("round-trips every body type and entity-flag combination") { + val packet = + BattleEntityMoveEventPacket( + sourceEntity = 0x1122334455667788L, + sourceMove = 0x0200, + kind = 1, + targets = + listOf( + BattleEffectTarget( + entityId = 10L, + targetMove = 0x0200, + subEvents = + listOf( + BattleActionEvent(null, null, BattleEventBody.HpUpdate(14)), + BattleActionEvent(20L, null, BattleEventBody.StatChange(1, -2)), + BattleActionEvent(null, 30L, BattleEventBody.Faint(true)), + BattleActionEvent( + 40L, 50L, BattleEventBody.EffectivenessMessage), + BattleActionEvent(null, null, BattleEventBody.MoveFailed(33)))), + BattleEffectTarget( + entityId = 60L, targetMove = 0, subEvents = emptyList()))) + + val bytes = BattleEntityMoveEventPacketCodec.encodeToBytes(packet) + BattleEntityMoveEventPacketCodec.decodeBytes(bytes) shouldBe packet + } + }) diff --git a/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleFieldStatePacketTest.kt b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleFieldStatePacketTest.kt index 8b7dc24..3aa8ed2 100644 --- a/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleFieldStatePacketTest.kt +++ b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleFieldStatePacketTest.kt @@ -2,14 +2,14 @@ package de.fiereu.openmmo.net.game import de.fiereu.bytecodec.test.decodeBytes import de.fiereu.bytecodec.test.encodeToBytes +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 io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.util.Base64 -// A two-monster party wild encounter (Snivy active, Patrat benched), scrubbed of capture data. The -// player side carries a per-species stat and move block and a per-slot trailer, all reproduced by -// the codec. +// A two-monster party wild encounter (Snivy active, Patrat benched), scrubbed of capture data. private const val CAPTURED_TWO_PARTY = "AgAAAAAAAAAAAAAAAP8AAAAAABYAAAD/ACAABlQAZQBzAHQAAAAAAJABAAAAAAD/AAJMAxqsDwADgAGkAAQAAAAAAAECAAABAMABAAAAAADvAQYAAAAAAAAWABYAAAAA/wMBQQAhACsAAAAAAAABAQDAAgAAAAAA+AECAAABAAAADgAOAAAAAP8DATIAIQAAAAAAAAABAADvAQYAAAAAAAAD/wAAAABmZmZmAQYAAAAAAAEBAAABAMADAAAAAAD4AQIAAAEAAAAOAA4AAAAA/wMAAQAA+AECAAAAAAEAA/8AAAAAZmZmZgAAAAA=" @@ -20,9 +20,79 @@ class BattleFieldStatePacketTest : val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes) decoded.playerName shouldBe "Test" decoded.playerParty.size shouldBe 2 - decoded.playerParty[0].species shouldBe 495.toShort() - decoded.playerParty[1].species shouldBe 504.toShort() - decoded.wildMon.species shouldBe 504.toShort() + decoded.activeSlot shouldBe 0 BattleFieldStatePacketCodec.encodeToBytes(decoded) shouldBe bytes } + + test("decodes the structured mon fields from the capture") { + val bytes = Base64.getDecoder().decode(CAPTURED_TWO_PARTY) + val decoded = BattleFieldStatePacketCodec.decodeBytes(bytes) + + val snivy = decoded.playerParty[0] + snivy.slot shouldBe 0 + snivy.species shouldBe 495.toShort() + snivy.level shouldBe 6.toByte() + snivy.gender shouldBe 0.toByte() + snivy.abilityId shouldBe 65.toShort() + snivy.maxHp shouldBe 22.toShort() + snivy.currentHp shouldBe 22.toShort() + snivy.movesPresent shouldBe true + snivy.moveIds shouldBe listOf(33, 43, 0, 0) + + val patrat = decoded.playerParty[1] + patrat.slot shouldBe 1 + patrat.species shouldBe 504.toShort() + patrat.level shouldBe 2.toByte() + patrat.gender shouldBe 1.toByte() + patrat.abilityId shouldBe 50.toShort() + patrat.moveIds shouldBe listOf(33, 0, 0, 0) + + val wild = decoded.wildParty.single() + 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 synthetic field state for a species without a capture") { + val rattata = + BattleMonBlock( + slot = 0, + entityId = 0x123C000L, + species = 19, + level = 7, + gender = 1, + abilityId = 50, + maxHp = 21, + currentHp = 17, + movesPresent = true, + moveIds = listOf(33, 39, 45, 98), + ) + val wild = + BattleMonBlock( + slot = 0, + 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, + playerParty = listOf(rattata), + activeSlot = 0, + wildParty = listOf(wild), + ) + val decoded = + BattleFieldStatePacketCodec.decodeBytes( + BattleFieldStatePacketCodec.encodeToBytes(packet)) + decoded shouldBe packet + } }) diff --git a/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleSwitchInPacketTest.kt b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleSwitchInPacketTest.kt index 577cb67..406612c 100644 --- a/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleSwitchInPacketTest.kt +++ b/protocols.game/src/test/kotlin/de/fiereu/openmmo/net/game/BattleSwitchInPacketTest.kt @@ -2,7 +2,7 @@ package de.fiereu.openmmo.net.game import de.fiereu.bytecodec.test.decodeBytes import de.fiereu.bytecodec.test.encodeToBytes -import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInMon +import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacketCodec import io.kotest.core.spec.style.FunSpec @@ -10,39 +10,59 @@ import io.kotest.matchers.shouldBe private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) } +private fun patrat(): BattleMonBlock = + BattleMonBlock( + slot = 1, + entityId = 0x000000000003C000L, + species = 504, + level = 2, + gender = 1, + abilityId = 50, + maxHp = 14, + currentHp = 14, + movesPresent = true, + moveIds = listOf(33, 0, 0, 0), + ) + class BattleSwitchInPacketTest : FunSpec({ // Switching back to an already-active monster sends only the 21-byte active detail. - // Reproduced - // byte for byte from a real capture (Snivy, slot 0, previous slot 1). + // Reproduced byte for byte from a real capture (Snivy, slot 0, previous slot 1). test("encodes a return switch-in as just the active detail") { val packet = BattleSwitchInPacket( newSlot = 0, oldSlot = 1, - mon = BattleSwitchInMon(entityId = 0, species = 495, hp = 0), + mon = + BattleMonBlock( + slot = 0, + entityId = 0, + species = 495, + level = 6, + gender = 0, + abilityId = 0, + maxHp = 0, + currentHp = 0, + movesPresent = false, + moveIds = listOf(0, 0, 0, 0), + ), fullBlock = false, ) val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet) bytes.hex() shouldBe "000000010000ef010600000000000003ff0000000066666666" } - // A benched monster coming out carries its full block then its active detail. + // 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") { val packet = - BattleSwitchInPacket( - newSlot = 1, - oldSlot = 0, - mon = BattleSwitchInMon(entityId = 0x000000000003C000L, species = 504, hp = 14), - fullBlock = true, - ) + BattleSwitchInPacket(newSlot = 1, oldSlot = 0, mon = patrat(), fullBlock = true) val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet) bytes.size shouldBe 65 val decoded = BattleSwitchInPacketCodec.decodeBytes(bytes) decoded.newSlot shouldBe 1 decoded.oldSlot shouldBe 0 decoded.fullBlock shouldBe true - decoded.mon.species shouldBe 504.toShort() - decoded.mon.hp shouldBe 14.toShort() + decoded.mon shouldBe patrat() } }) diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleInstance.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleInstance.kt new file mode 100644 index 0000000..c28c095 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleInstance.kt @@ -0,0 +1,24 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.network.SessionContext +import de.fiereu.openmmo.server.game.world.interest.BattleInterestKey + +/** One running wild battle. Trainer battles later add more participants to the same key. */ +class BattleInstance( + val battleId: Long, + val charId: Long, + val session: SessionContext, + val party: List, + val wild: BattleMonState, + val rng: BattleRng, +) { + val key: BattleInterestKey = BattleInterestKey(battleId) + var turn: Int = 1 + var activeSlot: Int = 0 + + // Which party slots have been sent out as active. A monster's first appearance carries its + // full block, a return only its active detail. + val seenActive: MutableSet = mutableSetOf(0) + + fun activeMon(): BattleMonState = party[activeSlot] +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonState.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonState.kt new file mode 100644 index 0000000..f30ea4b --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonState.kt @@ -0,0 +1,69 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.Pokemon +import de.fiereu.openmmo.common.PokemonMove +import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock +import de.fiereu.openmmo.pokemon.SpeciesDef +import java.util.EnumMap + +/** + * One monster's live state inside a battle. [source] is the snapshot the battle started from. + * [currentHp] and the move PP are the live values written back when the battle ends. + */ +class BattleMonState( + val entityId: Long, + val species: SpeciesDef, + val partyIndex: Int?, + val source: Pokemon, + val stats: ComputedStats, + val gender: Byte = 0, +) { + var currentHp: Int = source.hp.toInt().coerceIn(0, stats.hp) + val moves: MutableList = + source.moves.map { PokemonMove(it.id, it.pp) }.toMutableList() + + private val stages = EnumMap(BattleStat::class.java) + + val level: Int + get() = source.level.toInt() + + val fainted: Boolean + get() = currentHp <= 0 + + fun stage(stat: BattleStat): Int = stages[stat] ?: 0 + + /** Clamp to the stage limits and return the delta that was actually applied. */ + fun changeStage(stat: BattleStat, delta: Int): Int { + val old = stage(stat) + val new = (old + delta).coerceIn(StatStages.MIN, StatStages.MAX) + stages[stat] = new + return new - old + } + + fun unstaged(stat: BattleStat): Int = + when (stat) { + BattleStat.ATTACK -> stats.atk + BattleStat.DEFENSE -> stats.def + BattleStat.SP_ATTACK -> stats.spAtk + BattleStat.SP_DEFENSE -> stats.spDef + BattleStat.SPEED -> stats.spd + BattleStat.ACCURACY, + BattleStat.EVASION -> error("$this has no base stat to stage") + } + + fun effective(stat: BattleStat): Int = StatStages.scaleStat(unstaged(stat), stage(stat)) + + fun toBlock(slot: Int, movesPresent: Boolean): BattleMonBlock = + BattleMonBlock( + slot = slot, + entityId = entityId, + species = species.id.toShort(), + level = source.level, + gender = gender, + abilityId = species.ability1.ordinal.toShort(), + maxHp = stats.hp.toShort(), + currentHp = currentHp.toShort(), + movesPresent = movesPresent, + moveIds = List(BattleMonBlock.MOVE_SLOTS) { moves.getOrNull(it)?.id ?: 0 }, + ) +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattlePacketEmitter.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattlePacketEmitter.kt new file mode 100644 index 0000000..c2f8175 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattlePacketEmitter.kt @@ -0,0 +1,297 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.Pokemon +import de.fiereu.openmmo.common.enums.ChatType +import de.fiereu.openmmo.common.enums.Language +import de.fiereu.openmmo.common.enums.PokemonContainer +import de.fiereu.openmmo.net.game.packets.ChatMessagePacket +import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket +import de.fiereu.openmmo.net.game.packets.EntityPresencePacket +import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleActionEvent +import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket +import de.fiereu.openmmo.net.game.packets.battle.BattleEffectTarget +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.BattleEventBody +import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket +import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket +import de.fiereu.openmmo.net.game.packets.battle.BattleSlotEventEnumPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleSlotFlagEventPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket +import de.fiereu.openmmo.server.game.world.interest.InterestManager +import de.fiereu.openmmo.typechart.TypeChart +import javax.inject.Inject +import javax.inject.Singleton + +private const val ACTION_PROMPT: Byte = -128 // 0x80 +private const val MOVE_EVENT_KIND: Byte = 1 +// Slot-event type shown when the player gets away from a wild battle. +private const val FLED_EVENT: Byte = 0 + +// The player's overworld entity is hidden while the battle scene is up and shown again when it +// ends. +private const val PRESENCE_IN_BATTLE: Byte = 1 +private const val PRESENCE_OVERWORLD: Byte = 0 + +// The active battle side reported to the client so the bag knows which monster an item targets. +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 +// event type in every capture: a hit carries 0x0200, other events carry 0. +private const val HP_TARGET_MOVE: Short = 0x0200 +private const val DEFAULT_TARGET_MOVE: Short = 0 + +/** + * Turns battle state and [BattleEvent]s into packets. Everything battle wide goes through the + * battle's interest key, so spectators and later trainer opponents receive it too. Packets tied to + * one viewer (side, bag, party sync) go to that session directly. + */ +@Singleton +class BattlePacketEmitter @Inject constructor(private val interestManager: InterestManager) { + + fun sendStart(battle: BattleInstance, playerName: String) { + battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_IN_BATTLE)) + // Tell the client which side is local so the battle bag knows which monster an item targets. + // Without it, opening the bag crashes. Opcode 0x40 is left alone here, since re-sending it + // would wipe the balls out of the battle bag. + battle.session.send(BattleSidePacket(side = PLAYER_SIDE)) + broadcast( + battle, + BattleFieldStatePacket( + playerName = playerName, + playerId = battle.charId, + playerParty = battle.party.mapIndexed { slot, mon -> mon.toBlock(slot, true) }, + activeSlot = battle.activeSlot, + wildParty = listOf(battle.wild.toBlock(slot = 0, movesPresent = false)), + ), + ) + sendPrompt(battle) + } + + fun sendEvents(battle: BattleInstance, events: List) { + var i = 0 + while (i < events.size) { + val event = events[i] + when (event) { + is BattleEvent.MoveUsed -> { + if (event.attackerId != battle.wild.entityId) { + battle.session.send( + EntityMovePpPacket( + event.attackerId, event.moveSlot.toByte(), event.ppLeft.toByte())) + } + // The move's outcome rides inside the move event so the client animates it. A hit carries + // the target's resulting hp, a stat change carries the affected stat and its signed stage + // delta. A capped change reports no delta, so it stays unanimated. + val targets = + when (val next = events.getOrNull(i + 1)) { + is BattleEvent.DamageDealt -> { + i++ + val subEvents = + mutableListOf( + BattleActionEvent( + null, null, BattleEventBody.HpUpdate(next.newHp.toShort()))) + // Type 4 is assumed to be the "super effective" line. Not very effective and no + // effect ride other event ids we have not identified yet. + if (next.effectiveness > TypeChart.NEUTRAL) { + subEvents += BattleActionEvent(null, null, BattleEventBody.EffectivenessMessage) + } + // The client faints the target on hp reaching 0, as the real server does, so no + // faint sub-event is sent here. + listOf(BattleEffectTarget(next.targetId, HP_TARGET_MOVE, subEvents)) + } + is BattleEvent.StageChanged -> + if (!next.failed) { + i++ + listOf( + target( + next.targetId, + DEFAULT_TARGET_MOVE, + BattleEventBody.StatChange( + statIndex(next.stat), next.delta.toShort()))) + } else { + emptyList() + } + is BattleEvent.MoveWithoutTarget -> { + i++ + listOf(failTarget(battle, event.attackerId, next.moveId)) + } + else -> emptyList() + } + broadcast( + battle, + BattleEntityMoveEventPacket(event.attackerId, event.moveId, MOVE_EVENT_KIND, targets)) + } + is BattleEvent.DamageDealt -> Unit + is BattleEvent.StageChanged -> Unit + is BattleEvent.Fainted -> Unit + is BattleEvent.MoveWithoutTarget -> Unit + } + i++ + } + } + + fun sendSwitchIn(battle: BattleInstance, fullBlock: Boolean) { + broadcast( + battle, + BattleSwitchInPacket( + // These are field positions, not party slots: a newly revealed mon enters at field slot + // 1, one already seen returns to slot 0. The party slot itself rides in the block. + newSlot = if (fullBlock) 1 else 0, + oldSlot = if (fullBlock) 0 else 1, + mon = battle.activeMon().toBlock(slot = battle.activeSlot, movesPresent = true), + fullBlock = fullBlock, + ), + ) + } + + fun sendPrompt(battle: BattleInstance) { + broadcast(battle, BattleTileMapPacket(groupId = battle.turn.toShort(), slotTiles = null)) + broadcast(battle, BattleQueuedEventPacket(packed = ACTION_PROMPT)) + } + + /** Opens the party switch screen after the active mon faints, in place of the action prompt. */ + fun sendSwitchPrompt(battle: BattleInstance) { + broadcast(battle, BattleSlotFlagEventPacket(slot = 0, flag = false, immediate = false)) + } + + /** Confirms the forced replacement choice just before its switch-in. */ + fun sendSwitchConfirm(battle: BattleInstance) { + broadcast(battle, BattleSlotFlagEventPacket(slot = 0, flag = false, immediate = true)) + } + + fun sendFled(battle: BattleInstance) { + broadcast(battle, BattleSlotEventEnumPacket(slot = 0, eventType = FLED_EVENT)) + broadcast(battle, BattleBulkStatePacket.fled()) + battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD)) + } + + fun sendBattleEnd(battle: BattleInstance, party: List) { + broadcast(battle, BattleBulkStatePacket.battleEnd()) + battle.session.send(EntityPresencePacket(entityId = battle.charId, status = PRESENCE_OVERWORLD)) + battle.session.send( + PokemonContainerPacket( + container = PokemonContainer.PARTY, + hasChange = true, + delete = false, + pokemon = party, + ), + ) + } + + fun sendVictoryDelta(battle: BattleInstance, entityId: Long, reward: RewardResult) { + var mask = 0x1 + if (reward.leveled) mask = mask or 0x2 or 0x8 + broadcast( + battle, + delta( + entityId = entityId, + mask = mask, + experienceLevel = reward.newLevel.toByte(), + experiencePoints = reward.newXp, + statValues = if (reward.leveled) reward.newStats.asWireList() else null, + currentHp = if (reward.leveled) reward.newCurrentHp.toShort() else null, + ), + ) + } + + fun sendNotice(battle: BattleInstance, message: String) { + battle.session.send(notice(message)) + } + + private fun target(entityId: Long, targetMove: Short, body: BattleEventBody): BattleEffectTarget = + 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. + private fun failTarget( + battle: BattleInstance, + attackerId: Long, + moveId: Short + ): BattleEffectTarget { + val opponent = + if (attackerId == battle.wild.entityId) battle.activeMon().entityId + else battle.wild.entityId + return target(opponent, DEFAULT_TARGET_MOVE, BattleEventBody.MoveFailed(moveId)) + } + + fun broadcast(battle: BattleInstance, packet: Any) { + interestManager.broadcast(battle.key, packet) + } + + fun delta( + entityId: Long, + mask: Int, + experienceLevel: Byte? = null, + experiencePoints: Int? = null, + statValues: List? = null, + currentHp: Short? = null, + faintFlag: Byte? = null, + ): BattleEntityDeltaPacket = + BattleEntityDeltaPacket( + entityId = entityId, + fieldMask = mask, + experienceLevel = experienceLevel, + experiencePoints = experiencePoints, + statValues = statValues, + moveSlots = null, + ppUps = null, + currentHp = currentHp, + faintFlag = faintFlag, + speciesId = null, + forme = null, + listType = null, + sortKey = null, + evValues = null, + level = null, + happiness = null, + shininessSeed = null, + experience = null, + flagA = null, + flagB = null, + encounterType = null, + statusFlagsValue = null, + warnA = null, + warnB = null, + natureId = null, + ribbons = null, + packedIvs = null, + effortValues = null, + originalSpecies = null, + originalTrainerName = null, + originalTrainerId = null, + shininessType = null, + gender = null, + ivs = null, + caughtBall = null, + statusFlags2 = null, + statusList = null, + status = null, + ) + + // The decomp battle stat order. Not verified against the live client yet. + private fun statIndex(stat: BattleStat): Byte = + when (stat) { + BattleStat.ATTACK -> 1 + BattleStat.DEFENSE -> 2 + BattleStat.SPEED -> 3 + BattleStat.SP_ATTACK -> 4 + BattleStat.SP_DEFENSE -> 5 + BattleStat.ACCURACY -> 6 + BattleStat.EVASION -> 7 + } +} + +// The decomp in-game stat order. Not verified against the live client yet. +private fun ComputedStats.asWireList(): List = + listOf( + hp.toShort(), atk.toShort(), def.toShort(), spd.toShort(), spAtk.toShort(), spDef.toShort()) + +fun notice(message: String): ChatMessagePacket = + ChatMessagePacket( + type = ChatType.GAME_NOTIFICATIONS, + language = Language.EN, + message = message, + sender = "", + ) diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRegistry.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRegistry.kt new file mode 100644 index 0000000..726e245 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRegistry.kt @@ -0,0 +1,31 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.network.SessionContext +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicLong +import javax.inject.Inject +import javax.inject.Singleton + +/** The running battles, one per character. */ +@Singleton +class BattleRegistry @Inject constructor() { + + private val byChar = ConcurrentHashMap() + private val ids = AtomicLong(1) + + fun create( + charId: Long, + session: SessionContext, + party: List, + wild: BattleMonState, + rng: BattleRng, + ): BattleInstance { + val battle = BattleInstance(ids.getAndIncrement(), charId, session, party, wild, rng) + byChar[charId] = battle + return battle + } + + fun byChar(charId: Long): BattleInstance? = byChar[charId] + + fun remove(charId: Long): BattleInstance? = byChar.remove(charId) +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewards.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewards.kt new file mode 100644 index 0000000..4247427 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewards.kt @@ -0,0 +1,89 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.enums.EVs +import de.fiereu.openmmo.common.enums.PokemonStat +import de.fiereu.openmmo.pokemon.SpeciesDef +import javax.inject.Inject +import javax.inject.Singleton + +private const val EV_STAT_CAP = 252 +private const val EV_TOTAL_CAP = 510 + +data class RewardResult( + val xpGained: Int, + val newXp: Int, + val newLevel: Int, + val leveled: Boolean, + val newStats: ComputedStats, + val newCurrentHp: Int, + val newEvs: EVs, +) + +/** Experience and EV rewards for a won wild battle. */ +@Singleton +class BattleRewards @Inject constructor() { + + /** The Gen 3 wild battle experience: base yield times level over seven. */ + fun wildXp(defeated: SpeciesDef, defeatedLevel: Int): Int = defeated.expYield * defeatedLevel / 7 + + fun apply(winner: BattleMonState, defeated: SpeciesDef, defeatedLevel: Int): RewardResult { + val gained = wildXp(defeated, defeatedLevel) + val rate = winner.species.growthRate + val cap = ExpCurves.totalXpFor(rate, ExpCurves.MAX_LEVEL) + val newXp = minOf(winner.source.xp + gained, cap) + val newLevel = maxOf(winner.level, ExpCurves.levelFor(rate, newXp)) + val leveled = newLevel > winner.level + val newEvs = addYields(winner.source.eVs, defeated) + val grown = winner.source.copy(level = newLevel.toByte(), eVs = newEvs) + val newStats = StatCalculator.computeAll(winner.species, grown) + // A level up raises the maximum, the missing hp stays missing. + val newCurrentHp = + (winner.currentHp + maxOf(0, newStats.hp - winner.stats.hp)).coerceAtMost(newStats.hp) + return RewardResult(gained, newXp, newLevel, leveled, newStats, newCurrentHp, newEvs) + } + + private fun addYields(current: EVs, defeated: SpeciesDef): EVs { + val result = EVs() + for (stat in PokemonStat.entries) { + result.assign(stat, current.value(stat)) + } + val yields = + listOf( + PokemonStat.HP to defeated.evYieldHp, + PokemonStat.ATTACK to defeated.evYieldAttack, + PokemonStat.DEFENSE to defeated.evYieldDefense, + PokemonStat.SP_ATTACK to defeated.evYieldSpAttack, + PokemonStat.SP_DEFENSE to defeated.evYieldSpDefense, + PokemonStat.SPEED to defeated.evYieldSpeed, + ) + for ((stat, yield) in yields) { + if (yield <= 0) continue + val value = result.value(stat) + val room = minOf(EV_STAT_CAP - value, EV_TOTAL_CAP - result.total) + if (room <= 0) continue + result.assign(stat, value + minOf(yield, room)) + } + return result + } +} + +private fun EVs.value(stat: PokemonStat): Int = + when (stat) { + PokemonStat.HP -> hp + PokemonStat.ATTACK -> atk + PokemonStat.DEFENSE -> def + PokemonStat.SP_ATTACK -> spAtk + PokemonStat.SP_DEFENSE -> spDef + PokemonStat.SPEED -> spd + } + +private fun EVs.assign(stat: PokemonStat, value: Int) { + when (stat) { + PokemonStat.HP -> hp = value + PokemonStat.ATTACK -> atk = value + PokemonStat.DEFENSE -> def = value + PokemonStat.SP_ATTACK -> spAtk = value + PokemonStat.SP_DEFENSE -> spDef = value + PokemonStat.SPEED -> spd = value + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRng.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRng.kt new file mode 100644 index 0000000..7f6c6df --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleRng.kt @@ -0,0 +1,23 @@ +package de.fiereu.openmmo.server.game.battle + +import kotlin.random.Random + +/** All battle randomness goes through one seedable source, so turns replay in tests. */ +class BattleRng(seed: Long = Random.nextLong()) { + // Game randomness, not security sensitive. It is seedable on purpose so turns replay in tests. + @Suppress("kotlin:S2245") private val random = Random(seed) + + fun natureSeed(): Int = random.nextInt() + + fun ivRoll(): Int = random.nextInt(32) + + fun accuracyRoll(): Int = random.nextInt(1, 101) + + fun damageRoll(): Int = random.nextInt(85, 101) + + fun critRoll(denominator: Int): Boolean = random.nextInt(denominator) == 0 + + fun coinFlip(): Boolean = random.nextBoolean() + + fun pick(bound: Int): Int = random.nextInt(bound) +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleStat.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleStat.kt new file mode 100644 index 0000000..d3bb355 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/BattleStat.kt @@ -0,0 +1,35 @@ +package de.fiereu.openmmo.server.game.battle + +/** The stats a battle can stage up or down. HP has no stage. */ +enum class BattleStat { + ATTACK, + DEFENSE, + SP_ATTACK, + SP_DEFENSE, + SPEED, + ACCURACY, + EVASION, +} + +/** The Gen 3 stage ratio tables for stages -6 to +6. */ +object StatStages { + const val MIN = -6 + const val MAX = 6 + + private val STAT_NUM = intArrayOf(10, 10, 10, 10, 10, 10, 10, 15, 20, 25, 30, 35, 40) + private val STAT_DEN = intArrayOf(40, 35, 30, 25, 20, 15, 10, 10, 10, 10, 10, 10, 10) + + // Applied to a move's accuracy for the combined accuracy minus evasion stage. + private val ACC_NUM = intArrayOf(33, 36, 43, 50, 60, 75, 1, 133, 166, 2, 233, 133, 3) + private val ACC_DEN = intArrayOf(100, 100, 100, 100, 100, 100, 1, 100, 100, 1, 100, 50, 1) + + fun scaleStat(value: Int, stage: Int): Int { + val i = stage.coerceIn(MIN, MAX) - MIN + return value * STAT_NUM[i] / STAT_DEN[i] + } + + fun scaleAccuracy(accuracy: Int, stage: Int): Int { + val i = stage.coerceIn(MIN, MAX) - MIN + return accuracy * ACC_NUM[i] / ACC_DEN[i] + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngine.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngine.kt new file mode 100644 index 0000000..01bba9b --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngine.kt @@ -0,0 +1,273 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.common.enums.MoveEffect +import de.fiereu.openmmo.moves.MoveDef +import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.typechart.TypeChart +import javax.inject.Inject +import javax.inject.Singleton + +private const val CRIT_DENOMINATOR = 16 +private const val TACKLE_ID = 33 + +sealed interface BattleEvent { + data class MoveUsed(val attackerId: Long, val moveId: Short, val moveSlot: Int, val ppLeft: Int) : + BattleEvent + + /** A move that reached no target of its own, so its message lands on the opponent. */ + sealed interface MoveWithoutTarget : BattleEvent { + val attackerId: Long + val moveId: Short + } + + data class MoveMissed(override val attackerId: Long, override val moveId: Short) : + MoveWithoutTarget + + data class MoveFailed(override val attackerId: Long, override val moveId: Short) : + MoveWithoutTarget + + data class DamageDealt( + val targetId: Long, + val newHp: Int, + val crit: Boolean, + val effectiveness: Int, + ) : BattleEvent + + data class StageChanged( + val targetId: Long, + val stat: BattleStat, + val stage: Int, + val effectiveValue: Int, + val delta: Int, + val failed: Boolean, + ) : BattleEvent + + data class Fainted(val targetId: Long) : BattleEvent +} + +private data class TurnAction( + val attacker: BattleMonState, + val defender: BattleMonState, + val move: MoveDef?, +) + +private data class StageEffect(val stat: BattleStat, val delta: Int, val onSelf: Boolean) + +/** + * Resolves one wild battle turn with the Gen 3 core rules: priority and speed order, accuracy + * stages, the damage formula with crit, STAB, and type chart, and stat stage moves. Effects outside + * that core fail gracefully without touching state. + */ +@Singleton +class TurnEngine +@Inject +constructor( + private val moves: MoveRegistry, + private val typeChart: TypeChart, +) { + + fun resolveTurn(battle: BattleInstance, playerMoveId: Short): List { + val events = mutableListOf() + val player = battle.activeMon() + val wild = battle.wild + + val playerAction = TurnAction(player, wild, moves.get(playerMoveId.toInt())) + val wildAction = TurnAction(wild, player, pickWildMove(battle)) + + for (action in order(battle, playerAction, wildAction)) { + if (action.attacker.fainted) continue + execute(battle, action, events) + if (player.fainted || wild.fainted) break + } + return events + } + + /** A voluntary switch spends the player's turn, so the wild attacks the incoming monster. */ + fun resolveSwitchTurn(battle: BattleInstance): List { + val events = mutableListOf() + if (battle.wild.fainted) return events + execute(battle, TurnAction(battle.wild, battle.activeMon(), pickWildMove(battle)), events) + return events + } + + /** The wild AI picks a random usable move, falling back to Tackle with no pp left. */ + private fun pickWildMove(battle: BattleInstance): MoveDef? { + val usable = battle.wild.moves.filter { it.id.toInt() != 0 && it.pp > 0 } + if (usable.isEmpty()) return moves.get(TACKLE_ID) + return moves.get(usable[battle.rng.pick(usable.size)].id.toInt()) + } + + private fun order( + battle: BattleInstance, + a: TurnAction, + b: TurnAction, + ): List { + val pa = a.move?.priority ?: 0 + val pb = b.move?.priority ?: 0 + if (pa != pb) return if (pa > pb) listOf(a, b) else listOf(b, a) + val sa = a.attacker.effective(BattleStat.SPEED) + val sb = b.attacker.effective(BattleStat.SPEED) + if (sa != sb) return if (sa > sb) listOf(a, b) else listOf(b, a) + return if (battle.rng.coinFlip()) listOf(a, b) else listOf(b, a) + } + + private fun execute( + battle: BattleInstance, + action: TurnAction, + events: MutableList + ) { + val attacker = action.attacker + val move = action.move + if (move == null) { + events += BattleEvent.MoveFailed(attacker.entityId, 0) + return + } + val moveId = move.id.toShort() + val slot = attacker.moves.indexOfFirst { it.id == moveId } + if (slot >= 0 && attacker.moves[slot].pp > 0) { + attacker.moves[slot].pp = (attacker.moves[slot].pp - 1).toByte() + } + events += + BattleEvent.MoveUsed( + attacker.entityId, + moveId, + slot.coerceAtLeast(0), + attacker.moves.getOrNull(slot)?.pp?.toInt() ?: 0) + + if (!accuracyCheck(battle, action, move)) { + events += BattleEvent.MoveMissed(attacker.entityId, moveId) + return + } + + val stage = stageEffect(move.effect) + when { + move.power > 0 -> damage(battle, action, move, events) + stage != null -> applyStage(action, stage, events) + else -> events += BattleEvent.MoveFailed(attacker.entityId, moveId) + } + } + + private fun accuracyCheck(battle: BattleInstance, action: TurnAction, move: MoveDef): Boolean { + if (move.accuracy == 0) return true + val stage = + action.attacker.stage(BattleStat.ACCURACY) - action.defender.stage(BattleStat.EVASION) + val threshold = StatStages.scaleAccuracy(move.accuracy, stage) + return battle.rng.accuracyRoll() <= threshold + } + + private fun damage( + battle: BattleInstance, + action: TurnAction, + move: MoveDef, + events: MutableList, + ) { + val attacker = action.attacker + val defender = action.defender + val eff = typeChart.effectiveness(move.type, defender.species.type1, defender.species.type2) + if (eff == 0) { + events += BattleEvent.MoveFailed(attacker.entityId, move.id.toShort()) + return + } + val physical = MoveCategory.isPhysical(move.type) + val atkStat = if (physical) BattleStat.ATTACK else BattleStat.SP_ATTACK + val defStat = if (physical) BattleStat.DEFENSE else BattleStat.SP_DEFENSE + val crit = battle.rng.critRoll(CRIT_DENOMINATOR) + // A crit ignores the attacker's negative stages and the defender's positive stages. + val atk = + if (crit && attacker.stage(atkStat) < 0) attacker.unstaged(atkStat) + else attacker.effective(atkStat) + val def = + if (crit && defender.stage(defStat) > 0) defender.unstaged(defStat) + else defender.effective(defStat) + + var dmg = (2 * attacker.level / 5 + 2) * move.power * atk / def / 50 + 2 + if (crit) dmg *= 2 + if (attacker.species.hasType(move.type)) dmg = dmg * 3 / 2 + dmg = dmg * eff / TypeChart.NEUTRAL + dmg = dmg * battle.rng.damageRoll() / 100 + if (dmg < 1) dmg = 1 + + defender.currentHp = (defender.currentHp - dmg).coerceAtLeast(0) + events += BattleEvent.DamageDealt(defender.entityId, defender.currentHp, crit, eff) + if (defender.fainted) { + events += BattleEvent.Fainted(defender.entityId) + return + } + secondaryEffect(move.effect)?.let { secondary -> + if (move.secondaryEffectChance > 0 && + battle.rng.accuracyRoll() <= move.secondaryEffectChance) { + applyStage(action, secondary, events) + } + } + } + + private fun applyStage( + action: TurnAction, + effect: StageEffect, + events: MutableList, + ) { + val target = if (effect.onSelf) action.attacker else action.defender + val applied = target.changeStage(effect.stat, effect.delta) + val value = + when (effect.stat) { + BattleStat.ACCURACY, + BattleStat.EVASION -> 0 + else -> target.effective(effect.stat) + } + events += + BattleEvent.StageChanged( + target.entityId, + effect.stat, + target.stage(effect.stat), + value, + effect.delta, + applied == 0) + } + + private fun stageEffect(effect: MoveEffect): StageEffect? = + when (effect) { + MoveEffect.ATTACK_UP -> StageEffect(BattleStat.ATTACK, 1, true) + MoveEffect.DEFENSE_UP -> StageEffect(BattleStat.DEFENSE, 1, true) + MoveEffect.SPEED_UP -> StageEffect(BattleStat.SPEED, 1, true) + MoveEffect.SPECIAL_ATTACK_UP -> StageEffect(BattleStat.SP_ATTACK, 1, true) + MoveEffect.SPECIAL_DEFENSE_UP -> StageEffect(BattleStat.SP_DEFENSE, 1, true) + MoveEffect.ACCURACY_UP -> StageEffect(BattleStat.ACCURACY, 1, true) + MoveEffect.EVASION_UP -> StageEffect(BattleStat.EVASION, 1, true) + MoveEffect.ATTACK_UP_2 -> StageEffect(BattleStat.ATTACK, 2, true) + MoveEffect.DEFENSE_UP_2 -> StageEffect(BattleStat.DEFENSE, 2, true) + MoveEffect.SPEED_UP_2 -> StageEffect(BattleStat.SPEED, 2, true) + MoveEffect.SPECIAL_ATTACK_UP_2 -> StageEffect(BattleStat.SP_ATTACK, 2, true) + MoveEffect.SPECIAL_DEFENSE_UP_2 -> StageEffect(BattleStat.SP_DEFENSE, 2, true) + MoveEffect.ACCURACY_UP_2 -> StageEffect(BattleStat.ACCURACY, 2, true) + MoveEffect.EVASION_UP_2 -> StageEffect(BattleStat.EVASION, 2, true) + MoveEffect.ATTACK_DOWN -> StageEffect(BattleStat.ATTACK, -1, false) + MoveEffect.DEFENSE_DOWN -> StageEffect(BattleStat.DEFENSE, -1, false) + MoveEffect.SPEED_DOWN -> StageEffect(BattleStat.SPEED, -1, false) + MoveEffect.SPECIAL_ATTACK_DOWN -> StageEffect(BattleStat.SP_ATTACK, -1, false) + MoveEffect.SPECIAL_DEFENSE_DOWN -> StageEffect(BattleStat.SP_DEFENSE, -1, false) + MoveEffect.ACCURACY_DOWN -> StageEffect(BattleStat.ACCURACY, -1, false) + MoveEffect.EVASION_DOWN -> StageEffect(BattleStat.EVASION, -1, false) + MoveEffect.ATTACK_DOWN_2 -> StageEffect(BattleStat.ATTACK, -2, false) + MoveEffect.DEFENSE_DOWN_2 -> StageEffect(BattleStat.DEFENSE, -2, false) + MoveEffect.SPEED_DOWN_2 -> StageEffect(BattleStat.SPEED, -2, false) + MoveEffect.SPECIAL_ATTACK_DOWN_2 -> StageEffect(BattleStat.SP_ATTACK, -2, false) + MoveEffect.SPECIAL_DEFENSE_DOWN_2 -> StageEffect(BattleStat.SP_DEFENSE, -2, false) + MoveEffect.ACCURACY_DOWN_2 -> StageEffect(BattleStat.ACCURACY, -2, false) + MoveEffect.EVASION_DOWN_2 -> StageEffect(BattleStat.EVASION, -2, false) + else -> null + } + + private fun secondaryEffect(effect: MoveEffect): StageEffect? = + when (effect) { + MoveEffect.ATTACK_DOWN_HIT -> StageEffect(BattleStat.ATTACK, -1, false) + MoveEffect.DEFENSE_DOWN_HIT -> StageEffect(BattleStat.DEFENSE, -1, false) + MoveEffect.SPEED_DOWN_HIT -> StageEffect(BattleStat.SPEED, -1, false) + MoveEffect.SPECIAL_ATTACK_DOWN_HIT -> StageEffect(BattleStat.SP_ATTACK, -1, false) + MoveEffect.SPECIAL_DEFENSE_DOWN_HIT -> StageEffect(BattleStat.SP_DEFENSE, -1, false) + MoveEffect.ACCURACY_DOWN_HIT -> StageEffect(BattleStat.ACCURACY, -1, false) + MoveEffect.EVASION_DOWN_HIT -> StageEffect(BattleStat.EVASION, -1, false) + MoveEffect.ATTACK_UP_HIT -> StageEffect(BattleStat.ATTACK, 1, true) + MoveEffect.DEFENSE_UP_HIT -> StageEffect(BattleStat.DEFENSE, 1, true) + else -> null + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt new file mode 100644 index 0000000..3d3d85b --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactory.kt @@ -0,0 +1,75 @@ +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.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import de.fiereu.openmmo.server.game.storage.EntityIdService +import java.time.LocalDateTime +import javax.inject.Inject +import javax.inject.Singleton + +private const val TACKLE_ID = 33 +private const val FALLBACK_PP = 35 + +/** Rolls a wild monster: random nature seed, random IVs, computed stats, full hp. */ +@Singleton +class WildMonFactory +@Inject +constructor( + private val species: SpeciesRegistry, + private val moves: MoveRegistry, + private val entityIds: EntityIdService, +) { + + fun create(dexId: Int, level: Int, rng: BattleRng): Pokemon? { + val def = species.get(dexId) ?: return null + val ivs = + IVs().apply { + hp = rng.ivRoll() + atk = rng.ivRoll() + this.def = rng.ivRoll() + spAtk = rng.ivRoll() + spDef = rng.ivRoll() + spd = rng.ivRoll() + } + // TODO Give wild monsters their real level up moveset + // Parse level_up_learnsets.h in a new codegen generator, use it here for wild movesets and + // for learning moves on level up, and capture the client's move learn prompt packets. + val tacklePp = (moves.get(TACKLE_ID)?.pp ?: FALLBACK_PP).toByte() + val mon = + Pokemon( + id = entityIds.newMonsterId(), + ownerId = 0, + container = PokemonContainer.PARTY, + containerSlot = 0, + dexId = dexId, + seed = rng.natureSeed(), + ot = "", + nickname = "", + level = level.toByte(), + hp = 0, + xp = ExpCurves.totalXpFor(def.growthRate, level), + eVs = EVs(), + iVs = ivs, + moves = + listOf( + PokemonMove(TACKLE_ID.toShort(), tacklePp), + PokemonMove(0, 0), + PokemonMove(0, 0), + PokemonMove(0, 0), + ), + isShiny = false, + hasHiddenAbility = false, + isAlpha = false, + isSecret = false, + isFatefulEncounter = false, + isRaidEncounter = false, + caughtAt = LocalDateTime.now(), + ) + return mon.copy(hp = StatCalculator.computeAll(def, mon).hp.toShort()) + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt index 1057c73..fbf6e3e 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt @@ -159,6 +159,8 @@ constructor( log.info { "Player ${state.characterId} disconnected." } val charId = state.characterId if (charId != null) { + // The battle flush must land before the unload evicts the character from the cache. + battleService.onDisconnect(session) presenceService.leave(session) sessionRegistry.unbindCharacter(charId) characterStore.unloadCharacterAsync(charId) diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt index 25fae4c..2ab00ca 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt @@ -2,36 +2,30 @@ package de.fiereu.openmmo.server.game.services import de.fiereu.network.PacketEvent import de.fiereu.network.SessionContext -import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.enums.BattleAction -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.ChatMessageSendPacket -import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket -import de.fiereu.openmmo.net.game.packets.EntityPresencePacket -import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket import de.fiereu.openmmo.net.game.packets.SocialListEntryAddPacket import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket -import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket -import de.fiereu.openmmo.net.game.packets.battle.BattleEntityMoveEventPacket -import de.fiereu.openmmo.net.game.packets.battle.BattleFieldMon -import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket import de.fiereu.openmmo.net.game.packets.battle.BattleListEventDetail import de.fiereu.openmmo.net.game.packets.battle.BattleListEventPacket -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.BattleSlotEventEnumPacket -import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInMon -import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket -import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import de.fiereu.openmmo.server.game.battle.BattleInstance +import de.fiereu.openmmo.server.game.battle.BattleMonState +import de.fiereu.openmmo.server.game.battle.BattlePacketEmitter +import de.fiereu.openmmo.server.game.battle.BattleRegistry +import de.fiereu.openmmo.server.game.battle.BattleRewards +import de.fiereu.openmmo.server.game.battle.BattleRng +import de.fiereu.openmmo.server.game.battle.StatCalculator +import de.fiereu.openmmo.server.game.battle.TurnEngine +import de.fiereu.openmmo.server.game.battle.WildMonFactory +import de.fiereu.openmmo.server.game.battle.notice import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.storage.CharacterStore -import de.fiereu.openmmo.server.game.storage.EntityIdService +import de.fiereu.openmmo.server.game.world.interest.InterestManager import io.github.oshai.kotlinlogging.KotlinLogging import java.time.LocalDateTime -import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Singleton @@ -42,122 +36,212 @@ private const val TEST_BATTLE_COMMAND = "/testbattle" // even though a ball can now be thrown from the UI. private const val CATCH_COMMAND = "/catch" -private const val PATRAT: Short = 504 -private const val WILD_MON_ID = 0x000000000003C000L -private const val WILD_PATRAT_HP: Short = 14 -private const val CAUGHT_PATRAT_LEVEL: Byte = 2 -private const val CAUGHT_PATRAT_HP: Short = 8 -private const val CAUGHT_PATRAT_XP = 8 -private const val PATRAT_TACKLE: Short = 33 -private const val PATRAT_TACKLE_PP: Byte = 35 -private const val ACTION_PROMPT: Byte = -128 // 0x80 +private const val DEFAULT_WILD_DEX = 19 +private const val DEFAULT_WILD_LEVEL = 3 +private const val MIN_WILD_LEVEL = 2 +private const val MAX_WILD_LEVEL = 100 -private const val ENEMY_MOVE: Short = 33 -private const val MOVE_EVENT_KIND: Byte = 1 private const val POKE_BALL_ITEM: Short = 5004 -// Slot-event type shown when the player gets away from a wild battle. -private const val FLED_EVENT: Byte = 0 - -// The player's overworld entity is hidden while the battle scene is up and shown again when it -// ends. -private const val PRESENCE_IN_BATTLE: Byte = 1 -private const val PRESENCE_OVERWORLD: Byte = 0 - -// The active battle side reported to the client so the bag knows which monster an item targets. -private const val PLAYER_SIDE: Byte = 1 +/** + * Orchestrates wild battles: builds the battle state from the party and a rolled wild monster, + * routes client actions through the [TurnEngine], and persists the outcome. Packets go out through + * the [BattlePacketEmitter] over the battle's interest key. + */ @Singleton class BattleService @Inject constructor( private val characterStore: CharacterStore, - private val entityIds: EntityIdService, + private val battles: BattleRegistry, + private val engine: TurnEngine, + private val wildMons: WildMonFactory, + private val emitter: BattlePacketEmitter, + private val rewards: BattleRewards, + private val interestManager: InterestManager, + private val speciesRegistry: SpeciesRegistry, ) { - private val battleTurn = ConcurrentHashMap() - // The active party slot per battle, and which slots have been sent out as active. A monster's - // first appearance carries its full block, a return only its active detail. - private val battleActiveSlot = ConcurrentHashMap() - private val battleSeenActive = ConcurrentHashMap>() - fun onBattlePacket(event: PacketEvent<*>) { log.info { "Battle packet ${event.packet::class.simpleName} received: ${event.packet}" } } fun onBattleAction(event: PacketEvent) { - val session = event.session - val charId = session.attributes[PLAYER_STATE]?.characterId ?: return + val charId = event.session.attributes[PLAYER_STATE]?.characterId ?: return + val battle = battles.byChar(charId) ?: return val action = event.packet log.info { "Battle action char=$charId: $action" } + // While the active mon is fainted the player owes a replacement and may only switch. + if (battle.activeMon().fainted && action.action != BattleAction.SWITCH) return when (action.action) { - BattleAction.MOVE -> { - playMoveAnimations(session, charId, action.moveOrItemId) - advanceTurn(session, charId) + BattleAction.MOVE -> resolveTurn(battle, action.moveOrItemId) + BattleAction.ITEM -> catchWild(battle) + BattleAction.SWITCH -> switchMon(battle, action.moveOrItemId) + BattleAction.RUN -> flee(battle) + } + } + + fun onChatSend(event: PacketEvent) { + val session = event.session + val text = (event.packet.message ?: event.packet.target).trim() + val parts = text.split(Regex("\\s+")) + when { + parts[0].equals(TEST_BATTLE_COMMAND, ignoreCase = true) -> { + val dexId = parts.getOrNull(1)?.toIntOrNull() ?: DEFAULT_WILD_DEX + val level = + (parts.getOrNull(2)?.toIntOrNull() ?: DEFAULT_WILD_LEVEL).coerceIn( + MIN_WILD_LEVEL, MAX_WILD_LEVEL) + startWildBattle(session, dexId, level) + } + text.equals(CATCH_COMMAND, ignoreCase = true) -> { + val charId = session.attributes[PLAYER_STATE]?.characterId ?: return + battles.byChar(charId)?.let { catchWild(it) } } - BattleAction.ITEM -> catchWildMon(session, charId) - BattleAction.SWITCH -> switchMon(session, charId, action.moveOrItemId) - BattleAction.RUN -> fleeBattle(session, charId) } } - // The client picked a party slot to switch to. The switch-in packet (opcode 0x35) brings the new - // monster onto the field: the first time a monster comes out it carries its full block, otherwise - // just its active detail. The turn then advances and re-prompts for the next action. - private fun switchMon(session: SessionContext, charId: Long, partyIndex: Short) { + /** Ends a running battle when the player disconnects, keeping the last hp and pp state. */ + fun onDisconnect(session: SessionContext) { + val charId = session.attributes[PLAYER_STATE]?.characterId ?: return + val battle = battles.byChar(charId) ?: return + persistParty(battle) + finishBattle(battle) + } + + private fun startWildBattle(session: SessionContext, dexId: Int, level: Int) { + val charId = session.attributes[PLAYER_STATE]?.characterId ?: return + if (battles.byChar(charId) != null) { + session.send(notice("You are already in a battle.")) + return + } val stored = characterStore.getCharacter(charId) ?: return + if (stored.pokemon.isEmpty()) { + session.send(notice("You need a monster in your party to battle.")) + return + } + val party = mutableListOf() + for ((index, mon) in stored.pokemon.withIndex()) { + val def = speciesRegistry.get(mon.dexId) + if (def == null) { + session.send(notice("Your party has a species the battle data does not cover yet.")) + return + } + party += BattleMonState(mon.id, def, index, mon, StatCalculator.computeAll(def, mon)) + } + if (party.all { it.fainted }) { + session.send(notice("All of your monsters have fainted.")) + return + } + val rng = BattleRng() + val wildPokemon = wildMons.create(dexId, level, rng) + if (wildPokemon == null) { + session.send(notice("Unknown species $dexId.")) + return + } + val wildDef = speciesRegistry.get(dexId)!! + val wild = + BattleMonState( + wildPokemon.id, + wildDef, + null, + wildPokemon, + StatCalculator.computeAll(wildDef, wildPokemon), + ) + log.info { + "Starting wild battle for char=$charId (${stored.info.name}): ${wildDef.name} level $level" + } + val battle = battles.create(charId, session, party, wild, rng) + val firstAlive = party.indexOfFirst { !it.fainted } + battle.activeSlot = firstAlive + battle.seenActive.clear() + battle.seenActive.add(firstAlive) + interestManager.join(session, battle.key) + emitter.sendStart(battle, stored.info.name) + } + + private fun resolveTurn(battle: BattleInstance, moveId: Short) { + val events = engine.resolveTurn(battle, moveId) + emitter.sendEvents(battle, events) + afterTurn(battle) + } + + private fun afterTurn(battle: BattleInstance) { + when { + battle.wild.fainted -> endVictory(battle) + battle.party.all { it.fainted } -> endDefeat(battle) + // 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. + battle.activeMon().fainted -> emitter.sendSwitchPrompt(battle) + else -> { + battle.turn += 1 + emitter.sendPrompt(battle) + } + } + } + + private fun switchMon(battle: BattleInstance, partyIndex: Short) { val target = partyIndex.toInt() - val mon = stored.pokemon.getOrNull(target) - if (mon == null) { - log.warn { "Switch to invalid party index $partyIndex for char=$charId" } - advanceTurn(session, charId) + val mon = battle.party.getOrNull(target) + val forced = battle.activeMon().fainted + if (mon == null || mon.fainted || target == battle.activeSlot) { + // Reopen the switch screen on an invalid forced choice, otherwise re-prompt for an action. + if (forced) { + emitter.sendSwitchPrompt(battle) + } else { + battle.turn += 1 + emitter.sendPrompt(battle) + } return } - val oldSlot = battleActiveSlot[charId] ?: 0 - if (target == oldSlot) { - advanceTurn(session, charId) - return + // A forced switch confirms the choice before the switch-in. The captures pair the confirm with + // a full block for a new mon and with a return block for a mon that was already active. + if (forced) emitter.sendSwitchConfirm(battle) + performSwitch(battle, target) + if (forced) { + // Replacing a fainted mon does not spend a turn, the new mon acts next. + battle.turn += 1 + emitter.sendPrompt(battle) + } else { + // A voluntary switch spends the turn, so the wild attacks the incoming mon. + emitter.sendEvents(battle, engine.resolveSwitchTurn(battle)) + afterTurn(battle) } - val seen = battleSeenActive.getOrPut(charId) { mutableSetOf(0) } - val fullBlock = target !in seen - log.info { "Switch char=$charId slot $oldSlot -> $target (fullBlock=$fullBlock)" } - session.send( - BattleSwitchInPacket( - newSlot = target, - oldSlot = oldSlot, - mon = BattleSwitchInMon(mon.id, mon.dexId.toShort(), mon.hp), - fullBlock = fullBlock, - ), - ) - seen.add(target) - battleActiveSlot[charId] = target - advanceTurn(session, charId) } - // The player fled. The slot event shows the got-away text, the flee end marker closes the battle - // scene, and the presence toggle restores the overworld player. - private fun fleeBattle(session: SessionContext, charId: Long) { - battleTurn.remove(charId) - battleActiveSlot.remove(charId) - battleSeenActive.remove(charId) - session.send(BattleSlotEventEnumPacket(slot = 0, eventType = FLED_EVENT)) - session.send(BattleBulkStatePacket.fled()) - session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_OVERWORLD)) + private fun performSwitch(battle: BattleInstance, target: Int) { + val oldSlot = battle.activeSlot + val fullBlock = target !in battle.seenActive + battle.activeSlot = target + battle.seenActive.add(target) + log.info { "Switch char=${battle.charId} slot $oldSlot -> $target (fullBlock=$fullBlock)" } + emitter.sendSwitchIn(battle, fullBlock) } - private fun catchWildMon(session: SessionContext, charId: Long) { - log.info { "Ball thrown, catching wild Patrat for char=$charId" } - battleTurn.remove(charId) - battleActiveSlot.remove(charId) - battleSeenActive.remove(charId) - val stored = characterStore.getCharacter(charId) - val ot = stored?.info?.name ?: "" - val nextSlot = ((stored?.pokemon?.maxOfOrNull { it.containerSlot } ?: -1) + 1).toShort() - val patrat = caughtPatrat(charId, ot, nextSlot) - // The caught Patrat is sent as a full 148-byte record on opcode 0x14 before the ball-throw + private fun flee(battle: BattleInstance) { + emitter.sendFled(battle) + persistParty(battle) + finishBattle(battle) + } + + private fun catchWild(battle: BattleInstance) { + val stored = characterStore.getCharacter(battle.charId) ?: return + val nextSlot = ((stored.pokemon.maxOfOrNull { it.containerSlot } ?: -1) + 1).toShort() + val caught = + battle.wild.source.copy( + ownerId = battle.charId, + container = PokemonContainer.PARTY, + containerSlot = nextSlot, + ot = stored.info.name, + hp = battle.wild.currentHp.toShort(), + moves = battle.wild.moves.map { PokemonMove(it.id, it.pp) }, + caughtAt = LocalDateTime.now(), + ) + log.info { "Caught wild ${battle.wild.species.name} for char=${battle.charId}" } + // 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. - session.send(SocialListEntryAddPacket(patrat)) + battle.session.send(SocialListEntryAddPacket(caught)) // "Player threw a Poke Ball" event. - session.send( + battle.session.send( BattleListEventPacket( kind = 0, value = POKE_BALL_ITEM, @@ -165,124 +249,59 @@ constructor( detail = BattleListEventDetail(listType = 1, value = 1), ), ) - endBattle(session, charId, patrat) + characterStore.addPokemon(battle.charId, caught) + endBattle(battle) } - // The wild encounter is over. The bulk-state end marker tells the client to leave the battle - // scene, the presence toggle shows the overworld player again, and the party is persisted and - // resynced so the caught monster stays after the battle. - // TODO: the caught monster does not show up in the party after the battle closes. - private fun endBattle(session: SessionContext, charId: Long, caught: Pokemon) { - val stored = characterStore.getCharacter(charId) ?: return - if (stored.pokemon.none { it.id == caught.id }) { - characterStore.addPokemon(charId, caught) - } - session.send(BattleBulkStatePacket.battleEnd()) - session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_OVERWORLD)) - session.send( - PokemonContainerPacket( - container = PokemonContainer.PARTY, - hasChange = true, - delete = false, - pokemon = characterStore.getCharacter(charId)?.pokemon ?: emptyList(), - ), - ) - } - - private fun caughtPatrat(ownerId: Long, ot: String, slot: Short): Pokemon = - Pokemon( - id = entityIds.newMonsterId(), - ownerId = ownerId, - container = PokemonContainer.PARTY, - containerSlot = slot, - dexId = PATRAT.toInt(), - seed = 0, - ot = ot, - nickname = "", - level = CAUGHT_PATRAT_LEVEL, - hp = CAUGHT_PATRAT_HP, - xp = CAUGHT_PATRAT_XP, - eVs = EVs(), - iVs = IVs(), - moves = - listOf( - PokemonMove(PATRAT_TACKLE, PATRAT_TACKLE_PP), - PokemonMove(0, 0), - PokemonMove(0, 0), - PokemonMove(0, 0), - ), - isShiny = false, - hasHiddenAbility = false, - isAlpha = false, - isSecret = false, - isFatefulEncounter = false, - isRaidEncounter = false, - caughtAt = LocalDateTime.now(), - ) - - private fun playMoveAnimations(session: SessionContext, charId: Long, playerMove: Short) { - // The move comes from whichever monster is currently on the field, not always the lead. - val activeSlot = battleActiveSlot[charId] ?: 0 - val partyMon = characterStore.getCharacter(charId)?.pokemon?.getOrNull(activeSlot) ?: return - // Decrement the used move's PP before the animation, matching the real turn order. - val slot = partyMon.moves.indexOfFirst { it.id == playerMove } - if (slot >= 0) { - val newPp = (partyMon.moves[slot].pp - 1).coerceAtLeast(0).toByte() - session.send(EntityMovePpPacket(partyMon.id, slot.toByte(), newPp)) - } - session.send(BattleEntityMoveEventPacket(partyMon.id, playerMove, MOVE_EVENT_KIND, emptyList())) - session.send(BattleEntityMoveEventPacket(WILD_MON_ID, ENEMY_MOVE, MOVE_EVENT_KIND, emptyList())) - } - - private fun advanceTurn(session: SessionContext, charId: Long) { - val turn = battleTurn.merge(charId, 1) { a, b -> a + b } ?: 1 - session.send(BattleTileMapPacket(groupId = turn.toShort(), slotTiles = null)) - session.send(BattleQueuedEventPacket(packed = ACTION_PROMPT)) - } - - fun onChatSend(event: PacketEvent) { - val session = event.session - val text = (event.packet.message ?: event.packet.target).trim() - when { - text.equals(TEST_BATTLE_COMMAND, ignoreCase = true) -> startTestBattle(session) - text.equals(CATCH_COMMAND, ignoreCase = true) -> { - val charId = session.attributes[PLAYER_STATE]?.characterId ?: return - catchWildMon(session, charId) - } - } - } - - private fun startTestBattle(session: SessionContext) { - val state = session.attributes[PLAYER_STATE] ?: return - val charId = state.characterId ?: return - val stored = characterStore.getCharacter(charId) ?: return - val partyMon = stored.pokemon.firstOrNull() - if (partyMon == null) { - log.warn { "Cannot start test battle: char=$charId has no party monster" } - return - } + private fun endVictory(battle: BattleInstance) { + val winner = battle.activeMon() + val reward = rewards.apply(winner, battle.wild.species, battle.wild.level) log.info { - "Starting test battle for char=$charId (${stored.info.name}): dex=${partyMon.dexId} vs wild Patrat" + "char=${battle.charId} won: +${reward.xpGained} xp, level ${winner.level} -> ${reward.newLevel}" } - battleTurn[charId] = 1 - battleActiveSlot[charId] = 0 - battleSeenActive[charId] = mutableSetOf(0) - // Hide the overworld player entity while the battle scene is up, matching the real enter order. - session.send(EntityPresencePacket(entityId = charId, status = PRESENCE_IN_BATTLE)) - // Tell the client which side is local so the battle bag knows which monster an item targets. - // Without it, opening the bag crashes. Opcode 0x40 is left alone here, since re-sending it - // would - // wipe the balls out of the battle bag. - session.send(BattleSidePacket(side = PLAYER_SIDE)) - session.send( - BattleFieldStatePacket( - playerName = stored.info.name, - playerId = charId, - playerParty = stored.pokemon.map { BattleFieldMon(it.id, it.dexId.toShort(), it.hp) }, - wildMon = BattleFieldMon(WILD_MON_ID, PATRAT, WILD_PATRAT_HP), + winner.currentHp = reward.newCurrentHp + emitter.sendVictoryDelta(battle, winner.entityId, reward) + characterStore.updatePokemon( + battle.charId, + winner.source.copy( + level = reward.newLevel.toByte(), + xp = reward.newXp, + hp = reward.newCurrentHp.toShort(), + eVs = reward.newEvs, + moves = winner.moves.map { PokemonMove(it.id, it.pp) }, ), ) - session.send(BattleTileMapPacket(groupId = 1, slotTiles = null)) - session.send(BattleQueuedEventPacket(packed = ACTION_PROMPT)) + endBattle(battle, skip = winner.entityId) + } + + private fun endDefeat(battle: BattleInstance) { + endBattle(battle) + } + + // Known issue: the caught monster does not show up in the party until the client reopens it. + private fun endBattle(battle: BattleInstance, skip: Long? = null) { + persistParty(battle, skip) + val party = characterStore.getCharacter(battle.charId)?.pokemon ?: emptyList() + emitter.sendBattleEnd(battle, party) + finishBattle(battle) + } + + /** Write the battle's live hp and pp back into the party and flush the character. */ + private fun persistParty(battle: BattleInstance, skip: Long? = null) { + for (state in battle.party) { + if (state.entityId == skip) continue + val updated = + state.source.copy( + hp = state.currentHp.toShort(), + moves = state.moves.map { PokemonMove(it.id, it.pp) }, + ) + characterStore.updatePokemon(battle.charId, updated) + } + characterStore.flushCharacterAsync(battle.charId) + } + + private fun finishBattle(battle: BattleInstance) { + interestManager.leave(battle.session, battle.key) + battles.remove(battle.charId) } } diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonStateTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonStateTest.kt new file mode 100644 index 0000000..5016857 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleMonStateTest.kt @@ -0,0 +1,88 @@ +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.pokemon.SpeciesRegistry +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import java.time.LocalDateTime + +private fun rattata(level: Byte = 3, hp: Short = 14): Pokemon = + Pokemon( + id = 1L, + ownerId = 2L, + container = PokemonContainer.PARTY, + containerSlot = 0, + dexId = 19, + seed = 0, + ot = "Ash", + nickname = "", + level = level, + hp = hp, + xp = 27, + eVs = EVs(), + iVs = IVs(), + moves = + listOf(PokemonMove(33, 35), PokemonMove(0, 0), PokemonMove(0, 0), PokemonMove(0, 0)), + isShiny = false, + hasHiddenAbility = false, + isAlpha = false, + isSecret = false, + isFatefulEncounter = false, + isRaidEncounter = false, + caughtAt = LocalDateTime.now(), + ) + +private fun state(): BattleMonState { + val species = SpeciesRegistry().get(19)!! + val mon = rattata() + return BattleMonState(mon.id, species, 0, mon, StatCalculator.computeAll(species, mon)) +} + +class BattleMonStateTest : + FunSpec({ + test("stages clamp at plus and minus six and report the applied delta") { + val mon = state() + mon.changeStage(BattleStat.ATTACK, -2) shouldBe -2 + mon.changeStage(BattleStat.ATTACK, -5) shouldBe -4 + mon.stage(BattleStat.ATTACK) shouldBe -6 + mon.changeStage(BattleStat.ATTACK, -1) shouldBe 0 + + mon.changeStage(BattleStat.SPEED, 7) shouldBe 6 + mon.stage(BattleStat.SPEED) shouldBe 6 + } + + test("effective stats follow the gen 3 stage ratios") { + val mon = state() + val base = mon.unstaged(BattleStat.ATTACK) + mon.effective(BattleStat.ATTACK) shouldBe base + + mon.changeStage(BattleStat.ATTACK, 2) + mon.effective(BattleStat.ATTACK) shouldBe base * 2 + + mon.changeStage(BattleStat.ATTACK, -4) + mon.effective(BattleStat.ATTACK) shouldBe base * 10 / 20 + } + + test("current hp starts clamped to the computed maximum") { + val species = SpeciesRegistry().get(19)!! + val mon = rattata(hp = 999) + val stats = StatCalculator.computeAll(species, mon) + BattleMonState(1L, species, 0, mon, stats).currentHp shouldBe stats.hp + } + + test("the block carries the computed stats and the live hp") { + val mon = state() + mon.currentHp = 9 + val block = mon.toBlock(slot = 2, movesPresent = true) + block.slot shouldBe 2 + block.species shouldBe 19.toShort() + block.maxHp shouldBe mon.stats.hp.toShort() + block.currentHp shouldBe 9.toShort() + block.movesPresent shouldBe true + block.moveIds shouldBe listOf(33, 0, 0, 0) + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewardsTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewardsTest.kt new file mode 100644 index 0000000..ada07b5 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/BattleRewardsTest.kt @@ -0,0 +1,116 @@ +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.GrowthRate +import de.fiereu.openmmo.common.enums.IVs +import de.fiereu.openmmo.common.enums.PokemonContainer +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.booleans.shouldBeTrue +import io.kotest.matchers.ints.shouldBeGreaterThan +import io.kotest.matchers.shouldBe +import java.time.LocalDateTime + +private val species = SpeciesRegistry() +private val rewards = BattleRewards() + +private const val BULBASAUR = 1 +private const val RATTATA = 19 +private const val CHANSEY = 113 + +private fun winner(level: Int, xp: Int, evs: EVs = EVs(), damage: Int = 0): BattleMonState { + val def = species.get(BULBASAUR)!! + val mon = + Pokemon( + id = 1L, + ownerId = 2L, + container = PokemonContainer.PARTY, + containerSlot = 0, + dexId = BULBASAUR, + seed = 0, + ot = "Ash", + nickname = "", + level = level.toByte(), + hp = Short.MAX_VALUE, + xp = xp, + eVs = evs, + iVs = IVs(), + moves = listOf(PokemonMove(33, 35)), + isShiny = false, + hasHiddenAbility = false, + isAlpha = false, + isSecret = false, + isFatefulEncounter = false, + isRaidEncounter = false, + caughtAt = LocalDateTime.now(), + ) + val state = BattleMonState(1L, def, 0, mon, StatCalculator.computeAll(def, mon)) + state.currentHp -= damage + return state +} + +class BattleRewardsTest : + FunSpec({ + test("wild xp follows yield times level over seven") { + val rattata = species.get(RATTATA)!! + rewards.wildXp(rattata, 3) shouldBe rattata.expYield * 3 / 7 + } + + test("a big win jumps several levels and recomputes stats") { + val start = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 5) + val mon = winner(level = 5, xp = start) + val chansey = species.get(CHANSEY)!! + + val reward = rewards.apply(mon, chansey, 100) + + reward.xpGained shouldBe chansey.expYield * 100 / 7 + reward.newXp shouldBe start + reward.xpGained + reward.newLevel shouldBe ExpCurves.levelFor(GrowthRate.MEDIUM_SLOW, reward.newXp) + reward.newLevel shouldBeGreaterThan 6 + reward.leveled.shouldBeTrue() + reward.newStats.hp shouldBe StatCalculator.maxHp(45, 0, reward.newEvs.hp, reward.newLevel) + } + + test("the hp gained on level up keeps the missing hp missing") { + val start = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 5) + val mon = winner(level = 5, xp = start, damage = 9) + val reward = rewards.apply(mon, species.get(CHANSEY)!!, 100) + + reward.newCurrentHp shouldBe reward.newStats.hp - 9 + } + + test("ev yields clamp at the per stat cap") { + val evs = EVs().apply { hp = 251 } + val mon = + winner(level = 50, xp = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 50), evs = evs) + val reward = rewards.apply(mon, species.get(CHANSEY)!!, 10) + + reward.newEvs.hp shouldBe 252 + } + + test("ev yields respect the total cap") { + val evs = + EVs().apply { + hp = 252 + atk = 252 + def = 6 + } + val mon = + winner(level = 50, xp = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 50), evs = evs) + val reward = rewards.apply(mon, species.get(RATTATA)!!, 10) + + reward.newEvs.spd shouldBe 0 + reward.newEvs.total shouldBe 510 + } + + test("xp and level cap at 100") { + val cap = ExpCurves.totalXpFor(GrowthRate.MEDIUM_SLOW, 100) + val mon = winner(level = 99, xp = cap - 1) + val reward = rewards.apply(mon, species.get(CHANSEY)!!, 100) + + reward.newXp shouldBe cap + reward.newLevel shouldBe 100 + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngineTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngineTest.kt new file mode 100644 index 0000000..050d051 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/TurnEngineTest.kt @@ -0,0 +1,250 @@ +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.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import de.fiereu.openmmo.server.game.testsupport.FakeSession +import de.fiereu.openmmo.typechart.TypeChart +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.booleans.shouldBeTrue +import io.kotest.matchers.collections.shouldNotBeEmpty +import io.kotest.matchers.ints.shouldBeGreaterThan +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import java.time.LocalDateTime + +private const val PLAYER_ID = 0x1C000L +private const val WILD_ID = 0x3C000L + +private const val TACKLE: Short = 33 +private const val GROWL: Short = 45 +private const val SWIFT: Short = 129 +private const val QUICK_ATTACK: Short = 98 +private const val SPLASH: Short = 150 +private const val PECK: Short = 64 + +private val speciesRegistry = SpeciesRegistry() + +private fun pokemon(dexId: Int, level: Int, moves: List, id: Long): Pokemon { + val moveRegistry = MoveRegistry() + val padded = List(4) { i -> moves.getOrNull(i) ?: 0 } + return Pokemon( + id = id, + ownerId = 0, + container = PokemonContainer.PARTY, + containerSlot = 0, + dexId = dexId, + seed = 0, + ot = "", + nickname = "", + level = level.toByte(), + hp = Short.MAX_VALUE, + xp = 0, + eVs = EVs(), + iVs = IVs(), + moves = padded.map { PokemonMove(it, (moveRegistry.get(it.toInt())?.pp ?: 0).toByte()) }, + isShiny = false, + hasHiddenAbility = false, + isAlpha = false, + isSecret = false, + isFatefulEncounter = false, + isRaidEncounter = false, + caughtAt = LocalDateTime.now(), + ) +} + +private fun state(dexId: Int, level: Int, moves: List, id: Long): BattleMonState { + val def = speciesRegistry.get(dexId)!! + val mon = pokemon(dexId, level, moves, id) + return BattleMonState( + id, def, if (id == PLAYER_ID) 0 else null, mon, StatCalculator.computeAll(def, mon)) +} + +private fun battle( + player: BattleMonState, + wild: BattleMonState, + seed: Long, +): BattleInstance = + BattleInstance(1L, 100L, FakeSession(100L), listOf(player), wild, BattleRng(seed)) + +private val engine = TurnEngine(MoveRegistry(), TypeChart()) + +class TurnEngineTest : + FunSpec({ + test("the same seed replays the same turn") { + fun run(): List { + val player = state(1, 5, listOf(TACKLE, GROWL), PLAYER_ID) + val wild = state(19, 3, listOf(TACKLE), WILD_ID) + return engine.resolveTurn(battle(player, wild, seed = 7), TACKLE) + } + run() shouldBe run() + } + + test("swift always hits and pp decrements to the event value") { + val player = state(1, 20, listOf(SWIFT), PLAYER_ID) + val wild = state(19, 3, listOf(TACKLE), WILD_ID) + val events = engine.resolveTurn(battle(player, wild, seed = 1), SWIFT) + + val used = + events.filterIsInstance().first { it.attackerId == PLAYER_ID } + used.moveSlot shouldBe 0 + used.ppLeft shouldBe 19 + player.moves[0].pp shouldBe 19.toByte() + events.filterIsInstance().first { it.targetId == WILD_ID } + } + + test("damage stays inside the gen 3 bounds for the setup") { + // Bulbasaur level 20 Swift versus Snorlax level 20. Swift is Normal, so the gen 3 type + // split makes it physical, and the target is bulky enough that no roll can faint it and + // clamp the damage. + repeat(30) { i -> + val player = state(1, 20, listOf(SWIFT), PLAYER_ID) + val wild = state(143, 20, listOf(TACKLE), WILD_ID) + val before = wild.currentHp + val events = engine.resolveTurn(battle(player, wild, seed = i.toLong()), SWIFT) + val hit = + events.filterIsInstance().first { it.targetId == WILD_ID } + val dealt = before - hit.newHp + val base = (2 * 20 / 5 + 2) * 60 * player.stats.atk / wild.stats.def / 50 + 2 + val bound = if (hit.crit) base * 2 else base + dealt shouldBeGreaterThan bound * 85 / 100 - 1 + (dealt <= bound).shouldBeTrue() + } + } + + test("a critical hit deals more than any normal roll") { + var critMin = Int.MAX_VALUE + var normalMax = 0 + for (seed in 0L until 200L) { + val player = state(1, 50, listOf(SWIFT), PLAYER_ID) + val wild = state(19, 30, listOf(TACKLE), WILD_ID) + val before = wild.currentHp + val events = engine.resolveTurn(battle(player, wild, seed), SWIFT) + val hit = + events.filterIsInstance().firstOrNull { + it.targetId == WILD_ID + } ?: continue + val dealt = before - hit.newHp + if (hit.crit) critMin = minOf(critMin, dealt) else normalMax = maxOf(normalMax, dealt) + } + critMin shouldNotBe Int.MAX_VALUE + normalMax shouldBeGreaterThan 0 + critMin shouldBeGreaterThan normalMax + } + + test("STAB outdamages an equal power move without it") { + // Rattata uses Tackle (Normal, 35, STAB) or Peck (Flying, 35, no STAB) into Snorlax. + fun maxDealt(moveId: Short): Int { + var best = 0 + for (seed in 0L until 100L) { + val player = state(19, 30, listOf(moveId), PLAYER_ID) + val wild = state(143, 30, listOf(SPLASH), WILD_ID) + val before = wild.currentHp + val events = engine.resolveTurn(battle(player, wild, seed), moveId) + val hit = + events.filterIsInstance().firstOrNull { + it.targetId == WILD_ID + } ?: continue + best = maxOf(best, before - hit.newHp) + } + return best + } + maxDealt(TACKLE) shouldBeGreaterThan maxDealt(PECK) + } + + test("an immune target takes no damage and the move fails") { + // Tackle into Gastly (Ghost/Poison) is a Normal immunity. + val player = state(1, 20, listOf(TACKLE), PLAYER_ID) + val wild = state(92, 5, listOf(SPLASH), WILD_ID) + val before = wild.currentHp + val events = engine.resolveTurn(battle(player, wild, seed = 3), TACKLE) + + events.filterIsInstance().first { it.attackerId == PLAYER_ID } + events + .filterIsInstance() + .none { it.targetId == WILD_ID } + .shouldBeTrue() + wild.currentHp shouldBe before + } + + test("growl drops the enemy attack stage") { + val player = state(1, 5, listOf(GROWL), PLAYER_ID) + val wild = state(19, 3, listOf(TACKLE), WILD_ID) + val events = engine.resolveTurn(battle(player, wild, seed = 5), GROWL) + + val change = + events.filterIsInstance().first { it.targetId == WILD_ID } + change.stat shouldBe BattleStat.ATTACK + change.stage shouldBe -1 + change.failed shouldBe false + wild.stage(BattleStat.ATTACK) shouldBe -1 + } + + test("a stage already at the limit reports a failed change") { + val player = state(1, 5, listOf(GROWL), PLAYER_ID) + val wild = state(19, 3, listOf(TACKLE), WILD_ID) + wild.changeStage(BattleStat.ATTACK, -6) + val events = engine.resolveTurn(battle(player, wild, seed = 5), GROWL) + + val change = + events.filterIsInstance().first { it.targetId == WILD_ID } + change.failed shouldBe true + wild.stage(BattleStat.ATTACK) shouldBe -6 + } + + test("priority beats speed") { + // Level 5 Bulbasaur is far slower than a level 30 Rattata, Quick Attack still goes first. + val player = state(1, 5, listOf(QUICK_ATTACK), PLAYER_ID) + val wild = state(19, 30, listOf(TACKLE), WILD_ID) + val events = engine.resolveTurn(battle(player, wild, seed = 11), QUICK_ATTACK) + + events.filterIsInstance().first().attackerId shouldBe PLAYER_ID + } + + test("the faster monster acts first without priority") { + val player = state(1, 5, listOf(TACKLE), PLAYER_ID) + val wild = state(19, 30, listOf(TACKLE), WILD_ID) + val events = engine.resolveTurn(battle(player, wild, seed = 11), TACKLE) + + events.filterIsInstance().first().attackerId shouldBe WILD_ID + } + + test("a speed tie falls to the rng and both orders appear") { + val leaders = mutableSetOf() + for (seed in 0L until 40L) { + val player = state(19, 10, listOf(TACKLE), PLAYER_ID) + val wild = state(19, 10, listOf(TACKLE), WILD_ID) + val events = engine.resolveTurn(battle(player, wild, seed), TACKLE) + leaders += events.filterIsInstance().first().attackerId + } + leaders shouldBe setOf(PLAYER_ID, WILD_ID) + } + + test("a faint ends the turn before the loser acts") { + val player = state(1, 50, listOf(SWIFT), PLAYER_ID) + val wild = state(19, 2, listOf(TACKLE), WILD_ID) + wild.currentHp = 1 + val events = engine.resolveTurn(battle(player, wild, seed = 2), SWIFT) + + events.filterIsInstance().first().targetId shouldBe WILD_ID + events + .filterIsInstance() + .none { it.attackerId == WILD_ID } + .shouldBeTrue() + } + + test("an effect outside the core fails gracefully") { + val player = state(1, 5, listOf(SPLASH), PLAYER_ID) + val wild = state(19, 3, listOf(TACKLE), WILD_ID) + val before = wild.currentHp + val events = engine.resolveTurn(battle(player, wild, seed = 9), SPLASH) + + events.filterIsInstance().shouldNotBeEmpty() + wild.currentHp shouldBe before + wild.stage(BattleStat.ATTACK) shouldBe 0 + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt new file mode 100644 index 0000000..cc505e3 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/battle/WildMonFactoryTest.kt @@ -0,0 +1,56 @@ +package de.fiereu.openmmo.server.game.battle + +import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import de.fiereu.openmmo.server.game.storage.EntityIdService +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.ints.shouldBeInRange +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.nulls.shouldNotBeNull +import io.kotest.matchers.shouldBe + +class WildMonFactoryTest : + FunSpec({ + val factory = WildMonFactory(SpeciesRegistry(), MoveRegistry(), EntityIdService()) + + test("the same seed rolls the same monster") { + val a = factory.create(19, 3, BattleRng(seed = 42))!! + val b = factory.create(19, 3, BattleRng(seed = 42))!! + a.seed shouldBe b.seed + a.iVs shouldBe b.iVs + a.nature shouldBe b.nature + } + + test("IVs stay in the legal range and hp equals the computed maximum") { + val species = SpeciesRegistry() + repeat(50) { i -> + val mon = factory.create(19, 5, BattleRng(seed = i.toLong()))!! + mon.iVs.values.forEach { it.toInt() shouldBeInRange 0..31 } + val stats = StatCalculator.computeAll(species.get(19)!!, mon) + mon.hp shouldBe stats.hp.toShort() + } + } + + test("the moveset is Tackle with its registry pp") { + val mon = factory.create(1, 5, BattleRng(seed = 7))!! + mon.moves[0].id shouldBe 33.toShort() + mon.moves[0].pp shouldBe MoveRegistry().get(33)!!.pp.toByte() + mon.moves.drop(1).all { it.id == 0.toShort() } shouldBe true + } + + test("xp matches the species growth curve at the rolled level") { + val mon = factory.create(19, 7, BattleRng(seed = 1))!! + mon.xp shouldBe ExpCurves.totalXpFor(SpeciesRegistry().get(19)!!.growthRate, 7) + } + + test("an unknown species returns null") { + factory.create(9999, 5, BattleRng(seed = 1)).shouldBeNull() + factory.create(495, 5, BattleRng(seed = 1)).shouldBeNull() + } + + test("the wild id carries the monster tag") { + val mon = factory.create(19, 3, BattleRng(seed = 3))!! + mon.shouldNotBeNull() + (mon.id and 0xFFFF) shouldBe 0xC000L + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt new file mode 100644 index 0000000..c94033a --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/BattleServiceTest.kt @@ -0,0 +1,231 @@ +package de.fiereu.openmmo.server.game.services + +import de.fiereu.network.PacketEvent +import de.fiereu.openmmo.common.Pokemon +import de.fiereu.openmmo.common.PokemonMove +import de.fiereu.openmmo.common.enums.BattleAction +import de.fiereu.openmmo.common.enums.EVs +import de.fiereu.openmmo.common.enums.IVs +import de.fiereu.openmmo.common.enums.PokemonContainer +import de.fiereu.openmmo.moves.MoveRegistry +import de.fiereu.openmmo.net.game.packets.ChatMessageSendPacket +import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket +import de.fiereu.openmmo.net.game.packets.EntityPresencePacket +import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket +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.BattleQueuedEventPacket +import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket +import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket +import de.fiereu.openmmo.pokemon.SpeciesRegistry +import de.fiereu.openmmo.server.game.battle.BattlePacketEmitter +import de.fiereu.openmmo.server.game.battle.BattleRegistry +import de.fiereu.openmmo.server.game.battle.BattleRewards +import de.fiereu.openmmo.server.game.battle.TurnEngine +import de.fiereu.openmmo.server.game.battle.WildMonFactory +import de.fiereu.openmmo.server.game.storage.CharacterStore +import de.fiereu.openmmo.server.game.storage.EntityIdService +import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository +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.booleans.shouldBeTrue +import io.kotest.matchers.collections.shouldNotBeEmpty +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.nulls.shouldNotBeNull +import io.kotest.matchers.shouldBe +import java.time.LocalDateTime +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest + +private const val TACKLE: Short = 33 + +private fun bulbasaur(ownerId: Long, level: Byte, hp: Short): Pokemon = + Pokemon( + id = EntityIdService().newMonsterId(), + ownerId = ownerId, + container = PokemonContainer.PARTY, + containerSlot = 0, + dexId = 1, + seed = 0, + ot = "Ash", + nickname = "", + level = level, + hp = hp, + xp = 0, + eVs = EVs(), + iVs = IVs(), + moves = + listOf( + PokemonMove(TACKLE, 35), PokemonMove(0, 0), PokemonMove(0, 0), PokemonMove(0, 0)), + isShiny = false, + hasHiddenAbility = false, + isAlpha = false, + isSecret = false, + isFatefulEncounter = false, + isRaidEncounter = false, + caughtAt = LocalDateTime.now(), + ) + +private class Fixture(scope: CoroutineScope) { + val repo = FakeCharacterRepository() + val store = CharacterStore(repo, EntityIdService(), scope) + val interestManager = InterestManager() + val registry = BattleRegistry() + val service = + BattleService( + characterStore = store, + battles = registry, + engine = TurnEngine(MoveRegistry(), TypeChart()), + wildMons = WildMonFactory(SpeciesRegistry(), MoveRegistry(), EntityIdService()), + emitter = BattlePacketEmitter(interestManager), + rewards = BattleRewards(), + interestManager = interestManager, + speciesRegistry = SpeciesRegistry(), + ) + + suspend fun playerWithParty(level: Byte = 50, hp: Short = 999): Pair { + val created = store.createCharacter(1, "Ash") + store.addPokemon(created.info.id, bulbasaur(created.info.id, level, hp)) + return FakeSession(created.info.id) to created.info.id + } +} + +private fun FakeSession.startBattle(service: BattleService, command: String = "/testbattle 19 2") { + service.onChatSend(PacketEvent(ChatMessageSendPacket(0, "", command), this)) +} + +private fun FakeSession.act(service: BattleService, action: BattleAction, value: Short = 0) { + service.onBattleAction(PacketEvent(BattleActionSelectPacket(0, action, value, 0L, 0), this)) +} + +@OptIn(ExperimentalCoroutinesApi::class) +class BattleServiceTest : + FunSpec({ + test("the start sequence arrives in the proven order") { + runTest { + val fx = Fixture(backgroundScope) + val (session, _) = fx.playerWithParty() + + session.startBattle(fx.service) + + val types = session.sent.map { it::class } + types shouldBe + listOf( + EntityPresencePacket::class, + BattleSidePacket::class, + BattleFieldStatePacket::class, + BattleTileMapPacket::class, + BattleQueuedEventPacket::class, + ) + // Bulbasaur base hp 45 at level 50 with empty IVs and EVs. + val field = session.sent.filterIsInstance().single() + field.playerParty.single().maxHp shouldBe 105.toShort() + field.wildParty.single().level shouldBe 2.toByte() + field.wildParty.single().currentHp shouldBe field.wildParty.single().maxHp + } + } + + test("an unknown species aborts with a chat notice") { + runTest { + val fx = Fixture(backgroundScope) + val (session, charId) = fx.playerWithParty() + + session.startBattle(fx.service, "/testbattle 9999 5") + + fx.registry.byChar(charId).shouldBeNull() + session.sent.none { it is BattleFieldStatePacket }.shouldBeTrue() + } + } + + test("a session joined to the battle key receives the broadcasts") { + runTest { + val fx = Fixture(backgroundScope) + val (session, charId) = fx.playerWithParty() + session.startBattle(fx.service) + val battle = fx.registry.byChar(charId).shouldNotBeNull() + + val spectator = FakeSession(200L) + fx.interestManager.join(spectator, battle.key) + + session.act(fx.service, BattleAction.MOVE, TACKLE) + + spectator.sent.shouldNotBeEmpty() + } + } + + test("a move resolves the turn and re-prompts while both sides stand") { + runTest { + val fx = Fixture(backgroundScope) + // A bulky matchup, so neither side can faint inside one turn. + val (session, charId) = fx.playerWithParty(level = 30, hp = 999) + session.startBattle(fx.service, "/testbattle 143 10") + session.sent.clear() + + session.act(fx.service, BattleAction.MOVE, TACKLE) + + fx.registry.byChar(charId).shouldNotBeNull() + session.sent.filterIsInstance().shouldNotBeEmpty() + session.sent.filterIsInstance().shouldNotBeEmpty() + } + } + + test("fleeing sends the flee markers and clears the battle") { + runTest { + val fx = Fixture(backgroundScope) + val (session, charId) = fx.playerWithParty() + session.startBattle(fx.service) + + session.act(fx.service, BattleAction.RUN) + + fx.registry.byChar(charId).shouldBeNull() + session.sent.filterIsInstance().shouldNotBeEmpty() + session.startBattle(fx.service) + fx.registry.byChar(charId).shouldNotBeNull() + } + } + + test("victory persists the party hp and pp through the store") { + runTest { + val fx = Fixture(this) + val (session, charId) = fx.playerWithParty() + session.startBattle(fx.service) + + var rounds = 0 + while (fx.registry.byChar(charId) != null && rounds < 10) { + session.act(fx.service, BattleAction.MOVE, TACKLE) + rounds += 1 + } + fx.registry.byChar(charId).shouldBeNull() + advanceUntilIdle() + + // The level 2 Rattata yields its base experience scaled by level over seven. + session.sent + .filterIsInstance() + .any { it.fieldMask and 0x1 != 0 } + .shouldBeTrue() + val saved = fx.repo.saved[charId].shouldNotBeNull() + saved.pokemon.single().moves[0].pp shouldBe (35 - rounds).toByte() + saved.pokemon.single().xp shouldBe 57 * 2 / 7 + } + } + + test("a disconnect persists and removes the battle") { + runTest { + val fx = Fixture(this) + val (session, charId) = fx.playerWithParty() + session.startBattle(fx.service) + session.act(fx.service, BattleAction.MOVE, TACKLE) + + fx.service.onDisconnect(session) + + fx.registry.byChar(charId).shouldBeNull() + advanceUntilIdle() + fx.repo.saved[charId].shouldNotBeNull() + } + } + })