Skip to content

feat: battle nearby trainers with a team of up to six - #362

Open
thomasblom wants to merge 12 commits into
chattymin:mainfrom
thomasblom:feat/network-battle
Open

thomasblom wants to merge 12 commits into
chattymin:mainfrom
thomasblom:feat/network-battle

Conversation

@thomasblom

Copy link
Copy Markdown

Summary

Adds Pokémon battles to PokeTokenBar: pick a team of up to six from the Pokémon you have collected, then battle a CPU trainer for practice or challenge another PokeTokenBar user nearby (Mac to Mac, over Wi-Fi / peer-to-peer via MultipeerConnectivity).

The design goals were:

  • Your real Pokémon. Levels, stats, natures, shininess and learned moves come from your save. Nothing is scaled or normalized.
  • Nothing at stake. A battle never changes your collection, levels or items. The only thing it records is a win/loss/draw count.
  • Pokémon-accurate. The engine follows the Gen V (Black/White) singles rules: damage formula, STAB, type chart, crits, accuracy and evasion, stat stages, priority, speed ties, status effects, weather, screens, entry hazards and ~99.6% of the moves Pokémon learn by level-up in Gen I–V.
  • Fair over the network. Each turn has 60 seconds. Both Macs run the same deterministic engine in lockstep, and every turn is checked with a state digest. When the timer runs out, a random legal move is chosen for the idle player.
  • Private by default. You are not discoverable until you turn on Visible to trainers nearby. Only a trainer name that you choose is shown, and the connection is always encrypted.

What's new for users

  1. Battle tab (new popover tab): shows your team of up to six (click to add or remove, right-click to set the lead), the Practice battle button, your W/L/D record and the nearby-trainers lobby.
  2. Practice battle against a CPU trainer. Its team is generated to match your team's size and levels.
  3. Trainers nearby: a visibility toggle, a trainer name, a list of trainers found nearby with a Challenge button, and an Other version label for peers on an incompatible battle protocol.
  4. Incoming challenge prompt with Accept and Decline, shown even while the popover is closed.
  5. Battle window with sprites, HP bars, party indicators, status badges (PSN/BRN/PAR/SLP/FRZ), a weather banner, side-condition chips (Reflect, Light Screen, Spikes, …), a move grid with PP, and a 60-second turn timer. It also has Switch and Forfeit buttons, a replacement picker after a faint or U-turn, and a result screen.

How it works

Engine (Core/BattleEngine.swift, BattleMoveRules.swift)

  • The engine is a pure, deterministic value type (BattleState). All math is integer-only, and randomness comes from an app-owned SplitMix64 RNG (BattleRNG), never SystemRandomNumberGenerator. The same seed and the same choices always give the same battle, on every Mac.
  • Moves are fetched from PokéAPI (BattleMoveClient, a 30-day disk cache in battle-moves-v1). They are classified by BattleMoveKind through a name table for the moves whose effects PokéAPI does not describe in machine-readable form. This covers:
    • Variable power and fixed damage: Low Kick, Heavy Slam, Gyro Ball, Reversal, Seismic Toss, Super Fang, Psywave and others.
    • Protection: Protect, Detect, Endure, and success chances that halve on consecutive use.
    • Status and volatiles: burn, poison, badly poisoned, paralysis, sleep, freeze, confusion, flinch, leech seed, trapping, Taunt, Encore, Disable, Torment and others.
    • Field and side effects: rain, sun, sandstorm, hail, Reflect, Light Screen, Safeguard, Mist, Tailwind, Spikes, Toxic Spikes, Stealth Rock, Trick Room and others.
    • Special moves: two-turn and recharge moves, multi-hit, Rollout and Outrage-style locks, U-turn, Baton Pass, Transform, Counter and Mirror Coat, Destiny Bond, Explosion, Pain Split, Belly Drum and others.
  • Five moves are not supported yet: Metronome, Nature Power, Substitute, Snatch and Sky Drop. They show a NOT YET label and cannot be selected. If a Pokémon has no usable move left, it uses Struggle, as in the games.

Session (Core/BattleSession.swift, BattleCPU.swift)

  • BattleSession drives the UI. It handles prompts, event playback (BattleDisplay), the turn timer, forfeits and results. The opponent is abstracted as a BattleOpponent: CPUOpponent for practice and NetworkOpponent for nearby battles, so both modes share one code path.
  • The CPU scores moves by expected damage, type matchups and simple status and setup heuristics.
  • Forced turns are chosen automatically: charging, recharging and locked moves such as Outrage.

Network (Core/BattleLink.swift, NearbyBattleService.swift)

  • Transport: MultipeerConnectivity. The Bonjour service type is _ptb-battle, and encryptionPreference: .required.
  • Discovery info: only the battle protocol version is advertised. Peers on a different version are listed as Other version and cannot be challenged.
  • Handshake (BattleHandshake):
    • Both sides exchange hello messages (protocol version and trainer name), then teams and nonces. The battle seed mixes both nonces. This is not tamper-proof, because a peer could wait for our nonce before sending its own. With nothing at stake, that is acceptable.
    • Incoming teams are validated on decode (BattleTeam.isPlausible): level, stat, move, PP, power and name bounds. A malformed or implausible team is rejected.
  • Lockstep:
    • Each turn, both sides send their choice together with a SHA-256 digest of the battle state. A digest mismatch ends the battle as a desync instead of letting the two Macs diverge silently.
    • A mid-turn replacement after U-turn or Baton Pass is sent before it is applied locally.
  • Delivery order: MultipeerConnectivity callbacks reach the main actor through DispatchQueue.main.async + MainActor.assumeIsolated, which keeps them FIFO; Task { @MainActor } does not guarantee order.
  • Version gate: BattleWireMessage.protocolVersion (currently 3) must be bumped on every rule change. BattleEngineVersionTests pins the digest of a reference battle together with the version, so a rule change fails CI until both are updated on purpose.
  • Invitation rules (invitationIsAcceptable): one battle at a time, only while visible, only with a ready team, and only when the invitation's hello matches our protocol version.
  • Interrupts: a peer's forfeit or disconnect during a turn is recorded and applied once the turn finishes, so it is never lost.

Save data

  • CompanionState gains two fields:
    • battleTeam: up to six instance IDs, cleaned up with reconcileBattleTeam() when a Pokémon leaves the dex.
    • battleRecord: wins, losses and draws.
  • Both decode with defaults, so existing saves load unchanged.
  • SaveTransfer classifies both fields as progress, clamps the record to non-negative values and reconciles the team on import.

App bundle

scripts/build-app.sh adds these Info.plist keys, which macOS needs for local-network discovery:

  • NSLocalNetworkUsageDescription: "PokeTokenBar finds trainers nearby so you can challenge them to a Pokémon battle."
  • NSBonjourServices: _ptb-battle._tcp, _ptb-battle._udp

Localization

All new text is available in all 7 app languages. The status badges match the in-game abbreviations for each language. Badly poisoned uses the same label as poison (PSN / ENV / GIF / 독 / どく), with a darker color, as in Gen V.

Korean text uses KoreanParticle instead of written-out 이(가) forms. I extended it with:

  • .topic (은/는) and .comitative (과/와)
  • number-aware particles that follow how the number is read aloud ("Trainer 4821과", "v2.5.4를"). As a side effect, the existing skippedVersion text now reads naturally too. A #123 name placeholder keeps the written-out form.

Small fixes along the way

  • The Battle tab reserves the scroller lane (.reservesScrollerLane()), so it passes the ScrollerLaneTests added on main.

Type of change

  • Bug fix
  • New feature
  • Refactor / cleanup
  • Documentation
  • Other:

UI changes

All screenshots are rendered from this branch with real PokéAPI data (dark mode, @2x).

Before After
No Battle tab. Battle tab: team of up to six, lead badge, practice button, record and your Pokémon to pick from.
Battle tab
— Trainers nearby (visible): trainer name, discovered trainers with Challenge, and an incompatible peer shown as Other version.
Nearby lobby
— Incoming challenge prompt.
Challenge prompt
— Nearby battle: choosing a move with the 60-second turn timer.
Battle turn
— Waiting for the other trainer after locking in a move.
Waiting for opponent
— Status badge: a paralyzed Hariyama (PAR).
Status badge
— Field effects: rain banner, a Reflect chip and a Ditto that transformed into Politoed (copied moves with 5 PP each).
Weather, screen and Transform
— Replacement picker after a faint.
Choose next Pokémon
— Result.
Result

Tests

  • New test suites cover the whole feature: data and snapshots (BattleDataTests, BattleTeamTests), engine and mechanics (BattleEngineTests, BattleMechanicsTests, BattleSpecialMoveTests, BattleEffectCoverageTests), sessions (BattleSessionTests), the network protocol (BattleLinkTests) and nearby discovery (NearbyBattleTests). KoreanParticleTests is extended.
  • Network battles are tested end to end over an in-process LoopbackTransport: handshake, lockstep, diverged state, illegal or garbage messages from the peer, silent peers, turn-timer expiry, U-turn across the network, forfeits arriving mid-turn, disconnects and the version gate.
  • scripts/test-gate.sh adds every Battle*.swift core file to the logic-core set.
  • Local result: 1552 tests, 0 failures, logic-core line coverage 94.76% (threshold 75%). New branches were also checked with llvm-cov --show-regions, as CLAUDE.md asks, so the result does not rely on line coverage alone.
  • docs/reference/defect-log.md gains a Battle engine section and two concurrency entries, based on bugs found while building this feature:
    • bump the protocol version on every rule change
    • keep lockstep state to String-keyed dictionaries only (hash order differs per process)
    • send a mid-turn choice before applying it
    • deliver in order through the main queue
    • never drop an interrupt because "the pending await will throw it"
    • test modifiers against a bound
    • take game labels from a game source

Known limitations

  • Five moves are not supported yet: Metronome, Nature Power, Substitute, Snatch and Sky Drop. They are labeled NOT YET and cannot be selected.
  • Singles only, following Gen V rules. There are no abilities or held items; the save has no data for them.
  • Mac to Mac only. Both players need a build with the same protocolVersion.
  • Trust model: a peer's team is checked against plausible bounds, not against its real save. A modified client could send a strong but plausible team. Since a battle only changes a W/L counter, I think this trade-off is acceptable.
  • Real MultipeerConnectivity: discovery and challenges were checked manually between two local instances. The full battle flow is covered over the loopback transport. A battle between two physical Macs still needs a manual run.
  • Unverified labels: the French, Japanese, Korean and Portuguese status labels have not been checked against a game source yet (noted in the defect log).

How to test

  1. Build and run as usual (./scripts/build-app.sh, or swift build).
  2. Open the popover and go to the Battle tab. Add Pokémon to your team, then start a Practice battle.
  3. Nearby battle on one Mac: start two instances with separate state directories:
    swift build
    PTB_STATE_DIR=/tmp/ptb-a .build/debug/PokeTokenBar &
    PTB_STATE_DIR=/tmp/ptb-b .build/debug/PokeTokenBar &
    In both instances, build a team, turn on Visible to trainers nearby, then challenge one instance from the other and accept.
  4. Two Macs: use a bundled build on both (so the Info.plist local-network keys are present), on the same Wi-Fi or close to each other. The first time, allow the macOS local-network prompt.

Checklist

  • swift build and swift test pass locally
  • PR title and description are written in English
  • UI changes are described above (before/after — images optional)
  • No copyrighted assets, secrets, or private tooling references are committed (see CONTRIBUTING). Sprites and move data are loaded from PokéAPI at runtime, as elsewhere in the app.
  • Tests were added or updated for this change

🤖 Generated with Claude Code

thomasblom and others added 10 commits September 26, 2026 14:05
Add the data layer for nearby battles:

- BattleMove: battle-relevant move data from PokéAPI /move/{name},
  clamped at the trust boundary, with memory, 30-day disk cache and
  stale offline fallback. Concurrent requests share one fetch.
- BattleSnapshot: turns a catch-log entry into a fully resolved
  BattlePokemon (real level, computed stats, types, nature, ability,
  up to four moves). Stats use fixed fields so both peers iterate them
  in the same order. Hidden Power takes its type from the IVs.
- BattleTeam: 1-6 unique individuals.
- BattleTeamLoader: resolves a team and fails loudly on missing data
  instead of silently dropping a move.

Both files join the test gate's logic core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- New popover tab with the team slots (first slot is the lead) and a
  grid of every Pokémon that can battle: the one being raised plus the
  catch log, showing real levels.
- Click to add or remove, right-click a member to make it the lead.
- The tab checks that the team resolves into battle data and shows
  ready / preparing / failed with retry.
- The team is persisted as profile instance IDs, so a member keeps its
  slot after graduating. Load and import drop unknown, duplicate or
  overflowing IDs; the field is classified as progress for transfer.
- Copy in all seven app languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- BattleEngine: deterministic singles battle. Gen V damage formula,
  modern 18-type chart, STAB, crits, accuracy/evasion, priority and
  speed order, switching, stat-stage moves and secondary stat effects,
  drain, recoil, heal and Struggle. Illegal actions are rejected, so a
  remote peer cannot crash the engine. Same seed + actions always give
  the same state and events, which lockstep networking will rely on.
- BattleCPU: picks the best expected-damage move most turns; the
  opponent factory mirrors the player's team size and levels with
  random Gen I-V species.
- BattleSession: asks the opponent, resolves turns and plays events
  back line by line; forfeits, rematches and closing the window.
- Battle window with HP bars, typed move buttons, switch and
  replacement pickers, and a result screen. All battle lines in the
  seven app languages, with PokéAPI move, type and species names.
- Engine, CPU and session join the test gate's logic core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Lockstep protocol (BattleLink): after a handshake (hello, team,
  nonce) only choices travel, each with a digest of the state it was
  made in. A diverged digest, malformed message or illegal move ends
  the battle with no winner instead of crashing.
- Peer teams are validated on decode: size, duplicates and the value
  ranges the engine relies on.
- MultipeerConnectivity transport (peer-to-peer Wi-Fi or the local
  network) with discovery, invitations and required encryption.
  Delegate callbacks reach the main actor through the main queue so
  messages keep their order.
- Battle tab: opt-in visibility under an anonymous trainer name, a list
  of trainers nearby with Challenge, and a win/loss record. Incoming
  challenges get their own small window, even with the popover closed.
- Battle window: works for either side, 60-second turn timer with a
  random pick on timeout, "waiting for" state, forfeit while waiting.
  Forfeit, disconnect and a silent peer give the other player the win.
- Info.plist declares the Bonjour service and a Local Network reason.
- BattleRecord in the save, classified as progress for transfer.
- Defect log: order-sensitive delivery and interrupts that arrive while
  a wait has already been satisfied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Engine (protocol version 3; older builds show as "Other version"):
- Status: burn, paralysis, poison, bad poison, sleep, freeze, confusion
  and flinch, primary and secondary, with type immunities, plus Rest,
  Swagger, Protect/Detect and Endure.
- Damage rules: multi-hit, HP/weight/speed/stat based power,
  conditional doubling (Brine, Hex, Facade, Revenge, ...), fixed damage
  (Seismic Toss, Counter, Endeavor, ...) and OHKO moves.
- Timing: charge turns and semi-invulnerability (Solar Beam, Fly, Dig,
  Dive), recharge, rampage/Rollout/Uproar locks, Bide, Future Sight,
  Explosion, crash damage, Fake Out, Sucker Punch, Feint, Focus Punch,
  Pursuit.
- Switching: U-turn and Baton Pass pause the turn for a mid-turn pick,
  Roar/Dragon Tail drag out, trapping and Ingrain.
- Field: weather, screens, Safeguard, Mist, Tailwind, Lucky Chant,
  Trick Room, Gravity, sports and entry hazards.
- Unique effects: Taunt, Encore, Disable, Torment, Leech Seed, Curse,
  Yawn, Perish Song, Transform, Copycat, Sleep Talk, Magic Coat and
  about forty more. Moves that only touch items or abilities succeed
  without effect. Metronome, Nature Power, Substitute, Snatch and
  Sky Drop stay unsupported and show "Not yet".
- Forced turns (charging, recharging, rampages) play themselves.

Also:
- Side conditions key dictionaries by String so the state digest is the
  same on every Mac (enum keys encode in per-process hash order).
- A mid-turn replacement is sent before it is applied, so the peer sees
  the turn it is waiting in.
- The battle window shows weather, screens, hazards and status badges.
- About 100 new battle lines in all seven app languages.
- BattleEngineVersionTests pins a reference battle to the protocol
  version; the defect log records the new rule classes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gen V shows badly poisoned with the poison label in darker colors;
"TOX" is a Pokémon Showdown convention. Every language now uses the
poison label for both, and the badge turns dark purple for bad poison.
A test pins the English labels to BRN/PAR/PSN/PSN/SLP/FRZ, and the
defect log asks for a game source for labels that mimic the games.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main now requires every vertical popover ScrollView to pad its content
for the overlay scroller; the Battle tab's right-aligned Practice and
Challenge buttons would otherwise sit under it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Battle lines wrote both forms ("이(가)", "은(는)", "을(를)") or hard-coded
"는" after names, which read "리자몽는" for names ending in a consonant.
They now use KoreanParticle, which gains the topic (은/는) and
comitative (과/와) particles and reads trailing numbers aloud
("3으로", "2로", "v2.5.4를"). "chattymin#123" stays a name placeholder with both
forms. The same fix corrects the update banner's "v2.5.4을".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Swift 6.1.2 (Xcode 16.4, used by CI) runs the nonisolated async closure off
the main actor, so returning an unconstrained T into the @mainactor session
failed to compile. Swift 6.3 accepted it, which is why the local gate passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Swift 6.1.2 (CI) treats XCTest's tearDown as nonisolated, so reading the
@mainactor test class's files array there failed to compile. Each state
file now registers its own teardown block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts: SaveTransfer field classification (pendingForm/representativeForm
renames plus battleTeam/battleRecord).

Semantic follow-ups from main:
- UnownForm became PokemonForm: battle snapshots carry `form`, names and
  sprites use PokemonForm, and peer forms are length-checked on decode.
  The snapshot is wire data, so BattleWireMessage.protocolVersion is now 4.
- Russian joined the app languages: all battle copy gains Russian text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@yuwet15 yuwet15 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@NachoJuanDev NachoJuanDev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@etejedaw etejedaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Resolve conflicts by keeping both sides: battle team/record fields alongside
dex completion tracking in CompanionState and the transfer field
classification, the local-network/Bonjour keys alongside the poketokenbar://
URL scheme in Info.plist, and the battle sources alongside AgentActivity in
the coverage gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants