Repository navigation
feat: battle nearby trainers with a team of up to six - #362
Open
thomasblom wants to merge 12 commits into
Open
thomasblom wants to merge 12 commits into
thomasblom wants to merge 12 commits into
Conversation
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>
baseba
approved these changes
Oct 28, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
What's new for users
How it works
Engine (
Core/BattleEngine.swift,BattleMoveRules.swift)BattleState). All math is integer-only, and randomness comes from an app-owned SplitMix64 RNG (BattleRNG), neverSystemRandomNumberGenerator. The same seed and the same choices always give the same battle, on every Mac.BattleMoveClient, a 30-day disk cache inbattle-moves-v1). They are classified byBattleMoveKindthrough a name table for the moves whose effects PokéAPI does not describe in machine-readable form. This covers:Session (
Core/BattleSession.swift,BattleCPU.swift)BattleSessiondrives the UI. It handles prompts, event playback (BattleDisplay), the turn timer, forfeits and results. The opponent is abstracted as aBattleOpponent:CPUOpponentfor practice andNetworkOpponentfor nearby battles, so both modes share one code path.Network (
Core/BattleLink.swift,NearbyBattleService.swift)_ptb-battle, andencryptionPreference: .required.BattleHandshake):BattleTeam.isPlausible): level, stat, move, PP, power and name bounds. A malformed or implausible team is rejected.DispatchQueue.main.async+MainActor.assumeIsolated, which keeps them FIFO;Task { @MainActor }does not guarantee order.BattleWireMessage.protocolVersion(currently3) must be bumped on every rule change.BattleEngineVersionTestspins the digest of a reference battle together with the version, so a rule change fails CI until both are updated on purpose.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.Save data
CompanionStategains two fields:battleTeam: up to six instance IDs, cleaned up withreconcileBattleTeam()when a Pokémon leaves the dex.battleRecord: wins, losses and draws.SaveTransferclassifies both fields as progress, clamps the record to non-negative values and reconciles the team on import.App bundle
scripts/build-app.shadds 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._udpLocalization
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
KoreanParticleinstead of written-out 이(가) forms. I extended it with:.topic(은/는) and.comitative(과/와)skippedVersiontext now reads naturally too. A#123name placeholder keeps the written-out form.Small fixes along the way
.reservesScrollerLane()), so it passes theScrollerLaneTestsadded onmain.Type of change
UI changes
All screenshots are rendered from this branch with real PokéAPI data (dark mode, @2x).
Tests
BattleDataTests,BattleTeamTests), engine and mechanics (BattleEngineTests,BattleMechanicsTests,BattleSpecialMoveTests,BattleEffectCoverageTests), sessions (BattleSessionTests), the network protocol (BattleLinkTests) and nearby discovery (NearbyBattleTests).KoreanParticleTestsis extended.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.shadds everyBattle*.swiftcore file to the logic-core set.llvm-cov --show-regions, asCLAUDE.mdasks, so the result does not rely on line coverage alone.docs/reference/defect-log.mdgains a Battle engine section and two concurrency entries, based on bugs found while building this feature:Known limitations
protocolVersion.How to test
./scripts/build-app.sh, orswift build).Checklist
swift buildandswift testpass locally🤖 Generated with Claude Code