feat(battle): add the wild battle system with structured codecs (#58)

This commit is contained in:
Fiereu authored and GitHub committed 2026-07-25 17:28:48 +02:00
1 parent 214663531a
commit 651a1fbb67
30 files changed
+2429 -522

No files matched your search

@@ -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<BattleMonState>,
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<Int> = mutableSetOf(0)
fun activeMon(): BattleMonState = party[activeSlot]
}
@@ -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<PokemonMove> =
source.moves.map { PokemonMove(it.id, it.pp) }.toMutableList()
private val stages = EnumMap<BattleStat, Int>(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 },
)
}
@@ -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<BattleEvent>) {
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<Pokemon>) {
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<Short>? = 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<Short> =
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 = "",
)
@@ -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<Long, BattleInstance>()
private val ids = AtomicLong(1)
fun create(
charId: Long,
session: SessionContext,
party: List<BattleMonState>,
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)
}
@@ -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
}
}
@@ -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)
}
@@ -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]
}
}
@@ -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<BattleEvent> {
val events = mutableListOf<BattleEvent>()
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<BattleEvent> {
val events = mutableListOf<BattleEvent>()
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<TurnAction> {
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<BattleEvent>
) {
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<BattleEvent>,
) {
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<BattleEvent>,
) {
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
}
}
@@ -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())
}
}
@@ -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)
@@ -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<Long, Int>()
// 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<Long, Int>()
private val battleSeenActive = ConcurrentHashMap<Long, MutableSet<Int>>()
fun onBattlePacket(event: PacketEvent<*>) {
log.info { "Battle packet ${event.packet::class.simpleName} received: ${event.packet}" }
}
fun onBattleAction(event: PacketEvent<BattleActionSelectPacket>) {
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<ChatMessageSendPacket>) {
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<BattleMonState>()
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<ChatMessageSendPacket>) {
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)
}
}
@@ -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<Short>(33, 0, 0, 0)
}
})
@@ -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
}
})
@@ -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<Short>, 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<Short>, 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<BattleEvent> {
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<BattleEvent.MoveUsed>().first { it.attackerId == PLAYER_ID }
used.moveSlot shouldBe 0
used.ppLeft shouldBe 19
player.moves[0].pp shouldBe 19.toByte()
events.filterIsInstance<BattleEvent.DamageDealt>().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<BattleEvent.DamageDealt>().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<BattleEvent.DamageDealt>().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<BattleEvent.DamageDealt>().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<BattleEvent.MoveFailed>().first { it.attackerId == PLAYER_ID }
events
.filterIsInstance<BattleEvent.DamageDealt>()
.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<BattleEvent.StageChanged>().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<BattleEvent.StageChanged>().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<BattleEvent.MoveUsed>().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<BattleEvent.MoveUsed>().first().attackerId shouldBe WILD_ID
}
test("a speed tie falls to the rng and both orders appear") {
val leaders = mutableSetOf<Long>()
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<BattleEvent.MoveUsed>().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<BattleEvent.Fainted>().first().targetId shouldBe WILD_ID
events
.filterIsInstance<BattleEvent.MoveUsed>()
.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<BattleEvent.MoveFailed>().shouldNotBeEmpty()
wild.currentHp shouldBe before
wild.stage(BattleStat.ATTACK) shouldBe 0
}
})
@@ -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
}
})
@@ -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<FakeSession, Long> {
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<BattleFieldStatePacket>().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<EntityMovePpPacket>().shouldNotBeEmpty()
session.sent.filterIsInstance<BattleQueuedEventPacket>().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<BattleBulkStatePacket>().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<BattleEntityDeltaPacket>()
.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()
}
}
})