Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/battles/frlg-pokeguy-chain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# PokeGuy's League setup as one chain

`python3 -m pokesim.cli.frlg_league_pokeguy` plays PokeGuy's setup from Lorelei to the Champion with
HP, PP and bag carried over (500 chains, seed `f1`, the engine and table of `frlg_league_plan eval`).
Full tables: `~/BDSPLab/notes/e4-sim/pokeguy-chain/tables.txt`.

| Scenario | League |
|---|---:|
| Each fight alone from his recorded entry (C2 + his goals) | 71.8% all five (per fight 90-96%) |
| A: his Blastoise, bag and between-fight healing, C2 + his goals | 23.2% |
| B: his Blastoise and bag, our planned policy | 13.2% |
| C: our Blastoise Lv54 and bag, no held item, C2 + his goals | 7.6% |
| E: C + Black Glasses | 15.8% |
| P: our Blastoise Lv54 and bag, no held item, planned policy | 23.0% |
| D: P + Black Glasses (= #111's planned Lv54 result) | 21.2% |

Why ~95% per fight becomes ~23% as a chain:

- The per-fight numbers start every fight from his recorded entry, bag included. Even played in one seed,
the five isolated fights all win only 72-77% of the time.
- Items: C2 spends ~2.9 X Accuracy at Agatha chasing Gengar's Double Team (he spent none on video), so
Lance and the Champion get ~0 of the 3 and 2 his recorded bags gave them; the Champion falls from 95% to
36%. His on-video setup (policy `video`) keeps them (Champion 61%) but loses more at Bruno (63%).
- Full Restores: Lance alone takes ~5 in the chain. In our item sweep, Full Restore +5 is worth +19pp.
- PP: Surf runs out at Lance (Elixir 0.6 per Lance), so the Champion gets less Elixir help.

The League cases carry his Black Glasses (`held_item`), so every earlier chain on our Blastoise held them
too; `run_chain(..., held_item='')` now models our console Blastoise. The engine's Gen 3 Black Glasses is
1.1x Sp. Atk on Dark moves (Showdown's gen3 mod; Bite on Dewgong 28.2 -> 30.9 mean), and the policy's
`@smogon/calc` previews see it too.
181 changes: 181 additions & 0 deletions src/pokesim/cli/frlg_league_pokeguy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
"""PokeGuy's League setup as one chain (Lorelei -> Champion, HP/PP/bag carried over).

PYTHONPATH=src python3 -m pokesim.cli.frlg_league_pokeguy --chains 500 --seed f1 --out-dir /tmp/pokeguy-chain

Scenarios (same engine, seeds and table as frlg_league_plan eval):
isolated each fight alone from PokeGuy's recorded entry (HP, PP, bag), C2 with his strategies.json goals
A his Blastoise (recorded Lv51-55 stats), his bag at Lorelei, his between-fight healing, C2 + his goals
B his Blastoise and bag, our planned policy (plan.json) and its between-fight top-ups
C our Blastoise at Lv54 and our bag (BAG_NOW), C2 + his goals, his between-fight healing, no held item
E C with Black Glasses held
P our Blastoise at Lv54, our bag, planned policy (plan.json), no held item
D P with Black Glasses held (the #111 planned-54 table: those runs inherited his glasses)
V A with policy 'video' (his on-video setup, X Accuracy ignores Double Team) in place of C2
W C with policy 'video'

A and B keep his Black Glasses. Gen 3 Black Glasses: 1.1x Sp. Atk for Dark moves (Showdown's gen3 mod;
@smogon/calc previews the same).
"""

import argparse
import json
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

from pokesim.cli.frlg_league_chain import BAG_NOW, league_cases
from pokesim.cli.frlg_league_plan import render, table
from pokesim.games.frlg.battle.engine import Engine
from pokesim.games.frlg.battle.npc_ai import NPCTrainerAI
from pokesim.games.frlg.league import planned
from pokesim.games.frlg.league.chain import FIGHTS, MOVE_PP, fight_scenario, play, run_chain, POLICIES


def pokeguy_bag():
"""His bag at Lorelei (state-history.json via the case): Full Restore 13 bought at the Plateau."""
cases, _ = league_cases()
return dict(cases['lorelei']['bag'])


def isolated(engine, cases, pret, ai, seed, bench):
"""Each fight from his recorded entry state; a record shaped like run_chain's."""
record = {'seed': seed, 'fights': [], 'outcome': 'win'}
for fight in FIGHTS:
player = cases[fight]['player']
pp = {m['name'].upper(): m['pp'] for m in player['moves']}
carry = {'hp': player['hp'], 'status': player.get('status', ''),
'pp': {k: pp.get(k, 0) for k in MOVE_PP}, 'bag': dict(cases[fight]['bag'])}
scenario = fight_scenario(cases[fight], pret, carry, None, None, bench=bench)
state, _ = play(engine, scenario, ai, POLICIES['c2'], '{}:{}'.format(seed, fight), fight=fight)
won = state['winner'] == 'Player'
record['fights'].append({'fight': fight, 'won': won, 'used': dict(state['items_used']), 'between_used': {}})
if not won and record['outcome'] == 'win':
record['outcome'] = 'loss@' + fight
return record


SCENARIOS = {
'A': dict(policy='c2', bag='pokeguy', levels=None, between='pokeguy', held=None),
'B': dict(policy='planned', bag='pokeguy', levels=None, between=None, held=None),
'C': dict(policy='c2', bag='ours', levels=54, between='pokeguy', held=''),
'E': dict(policy='c2', bag='ours', levels=54, between='pokeguy', held='BLACK_GLASSES'),
'P': dict(policy='planned', bag='ours', levels=54, between=None, held=''),
'D': dict(policy='planned', bag='ours', levels=54, between=None, held='BLACK_GLASSES'),
# His setup as seen on video (replica.VIDEO_GOALS): no X Accuracy chase of Gengar's Double Team.
'V': dict(policy='video', bag='pokeguy', levels=None, between='pokeguy', held=None),
'W': dict(policy='video', bag='ours', levels=54, between='pokeguy', held=''),
}


# One change at a time from P (our bag, Lv54, planned policy, no held item): (label, bag additions, level, held).
SWEEP = [
('base (P)', {}, 54, ''),
('Full Restore +1', {'fullrestore': 1}, 54, ''),
('Full Restore +3', {'fullrestore': 3}, 54, ''),
('Full Restore +5', {'fullrestore': 5}, 54, ''),
('Full Heal +1', {'fullheal': 1}, 54, ''),
('Full Heal +3', {'fullheal': 3}, 54, ''),
('Full Heal +5', {'fullheal': 5}, 54, ''),
('Awakening +1', {'awakening': 1}, 54, ''),
('Awakening +3', {'awakening': 3}, 54, ''),
('Black Glasses', {}, 54, 'BLACK_GLASSES'),
('Elixir +1', {'elixir': 1}, 54, ''),
('Max Elixir +1', {'maxelixir': 1}, 54, ''),
('X Accuracy +2', {'xaccuracy': 2}, 54, ''),
('Guard Spec +1', {'guardspec': 1}, 54, ''),
('Super Potion +4', {'superpotion': 4}, 54, ''),
('Hyper Potion +4 (costs money; reference)', {'hyperpotion': 4}, 54, ''),
('Lv55 (reference)', {}, 55, ''),
('Lv57 (reference)', {}, 57, ''),
]


def sweep_scenario(label):
_, add, level, held = next(row for row in SWEEP if row[0] == label)
bag = dict(BAG_NOW)
for k, v in add.items():
bag[k] = bag.get(k, 0) + v
return dict(policy='planned', bag=bag, levels=level, between=None, held=held)


def _worker(job):
name, seeds, bench = job
cases, pret = league_cases()
ai = NPCTrainerAI(pret)
out = []
with Engine() as engine:
for seed in seeds:
if name == 'isolated':
out.append(isolated(engine, cases, pret, ai, seed, bench))
continue
s = SCENARIOS.get(name) or sweep_scenario(name)
bag = dict(cases['lorelei']['bag']) if s['bag'] == 'pokeguy' else dict(BAG_NOW if s['bag'] == 'ours' else s['bag'])
levels = {f: s['levels'] for f in FIGHTS} if s['levels'] else None
plan = planned.load_plan() if s['policy'] == 'planned' else None
record = run_chain(engine, cases, pret, ai, s['policy'], bag, levels, seed, plan=plan, bench=bench,
between=s['between'], held_item=s['held'])
for fight in record['fights']:
fight.pop('decisions')
out.append(record)
return out


def isolated_table(records):
"""Per fight won/total: every fight is played in every record."""
t = table([{'fights': r['fights'], 'outcome': 'win'} for r in records])
t['wins'] = sum(all(f['won'] for f in r['fights']) for r in records)
t['items_per_win'] = None
return t


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--scenarios', default='isolated,A,B,C')
parser.add_argument('--chains', type=int, default=500)
parser.add_argument('--workers', type=int, default=8)
parser.add_argument('--seed', default='f1')
parser.add_argument('--no-bench', action='store_true', help='Blastoise alone: Roar/Whirlwind fail')
parser.add_argument('--sweep', action='store_true', help='the one-change item sweep from P (sweep.txt)')
parser.add_argument('--out-dir', type=Path, required=True)
args = parser.parse_args(argv)
args.out_dir.mkdir(parents=True, exist_ok=True)
seeds = ['{}:{}'.format(args.seed, i) for i in range(args.chains)]
if args.sweep:
return sweep(args, seeds)
suffix = '-solo' if args.no_bench else ''
with ProcessPoolExecutor(args.workers) as pool:
for name in args.scenarios.split(','):
jobs = [(name, seeds[i::args.workers], not args.no_bench) for i in range(args.workers)]
records = [r for part in pool.map(_worker, jobs) for r in part]
t = isolated_table(records) if name == 'isolated' else table(records)
title = name + suffix
if name == 'isolated':
title += ' (each fight from his recorded entry; "League" = all five won in one seed)'
text = render(title, t)
print(text, flush=True)
(args.out_dir / (name + suffix + '.txt')).write_text(text + '\n')
(args.out_dir / (name + suffix + '.json')).write_text(json.dumps(t) + '\n')


def sweep(args, seeds):
rows = []
with ProcessPoolExecutor(args.workers) as pool:
for label, *_ in SWEEP:
jobs = [(label, seeds[i::args.workers], not args.no_bench) for i in range(args.workers)]
t = table([r for part in pool.map(_worker, jobs) for r in part])
champ = t['per_fight']['champion']
rows.append((label, t['wins'], t['chains'], champ['won'], champ['reached']))
print('{:44s} League {:4d}/{} champion {}/{}'.format(*rows[-1]), flush=True)
base = rows[0][1]
lines = ['Item sweep from P: our bag (BAG_NOW), Lv54, planned policy (plan.json), no held item; '
'{} chains, seed {}; one change per row, sorted by gain.'.format(args.chains, args.seed),
' {:44s} {:>14s} {:>7s} {:>17s}'.format('change', 'League', 'gain', 'champion won/reached')]
for label, wins, n, cw, cr in sorted(rows, key=lambda r: -r[1]):
lines.append(' {:44s} {:4d}/{} {:5.1%} {:+6.1f}pp {:6d}/{:<4d} {:4.0%}'.format(
label, wins, n, wins / n, 100 * (wins - base) / n, cw, cr, cw / max(1, cr)))
text = '\n'.join(lines)
print(text)
(args.out_dir / 'sweep.txt').write_text(text + '\n')


if __name__ == '__main__':
main()
57 changes: 52 additions & 5 deletions src/pokesim/games/frlg/league/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,15 @@ def ours_at(level, measured=True):
'spd': 140 + round(3.5 * d), 'spe': 111 + 2 * d}


def fight_scenario(case, pret, carry, stats, level, only_foe=None, bench=True):
def fight_scenario(case, pret, carry, stats, level, only_foe=None, bench=True, held_item=None):
"""held_item None keeps the case's (PokeGuy's Black Glasses); '' holds nothing."""
scenario = copy.deepcopy(case)
if bench:
scenario['bench'] = copy.deepcopy(BENCH)
scenario.pop('progression', None)
player = scenario['player']
if held_item is not None:
player['held_item'] = held_item
if stats is not None:
player['stats'] = dict(stats)
player['level'] = level
Expand Down Expand Up @@ -186,10 +189,48 @@ def use(item):
return used


def pokeguy_between(carry, max_hp, next_fight):
"""PokeGuy's out-of-battle play on video (state-history.json): no HP top-up before Bruno (130/162)
or Agatha (45/165); a Full Restore to full before Lance and the Champion (his Super Potions stayed 4);
his one Elixir before the Champion. A status is cured first (he had none; dedicated cure, Full Heal,
Full Restore)."""
used = Counter()
bag = carry['bag']

def use(item):
bag[item] -= 1
used[item] += 1

if carry['status']:
cure = {'par': 'parlyzheal', 'psn': 'antidote', 'tox': 'antidote', 'slp': 'awakening'}.get(carry['status'])
for item in (cure, 'fullheal', 'fullrestore'):
if item and bag.get(item):
use(item)
carry['status'] = ''
if item == 'fullrestore':
carry['hp'] = max_hp
break
if next_fight in ('lance', 'champion') and carry['hp'] < max_hp and bag.get('fullrestore'):
use('fullrestore')
carry['hp'] = max_hp
pp = carry['pp']
if next_fight == 'champion' and any(pp[name] < MOVE_PP[name] for name in pp):
item = next((i for i in ('elixir', 'maxelixir') if bag.get(i)), None)
if item:
use(item)
for name in pp:
pp[name] = MOVE_PP[name] if item == 'maxelixir' else min(MOVE_PP[name], pp[name] + 10)
return used


def run_chain(engine, cases, pret, ai, policy_name, bag, levels, seed, entry_hp=None, fights=FIGHTS, only_foe=None,
budget=None, plan=None, bench=True):
budget=None, plan=None, bench=True, between=None, held_item=None):
"""budget: per-fight item budgets {fight: {item: n}} in place of the planner's split (autostory only).
plan: the League plan (policy 'planned'); bench: our HM users in the party (Roar/Whirlwind work)."""
plan: the League plan (policy 'planned'); bench: our HM users in the party (Roar/Whirlwind work).
levels None: each fight's recorded stats from the case (PokeGuy's Lv51-55).
between: 'pokeguy' for PokeGuy's out-of-battle healing in place of the policy's own.
held_item: None keeps each case's (PokeGuy's Black Glasses, so our-Blastoise runs held them too);
'' for none (our console Blastoise holds nothing)."""
policy = POLICIES[policy_name]
carry = {'hp': entry_hp, 'status': '', 'pp': dict(MOVE_PP), 'bag': dict(bag)}
record = {'seed': seed, 'fights': [], 'outcome': 'win'}
Expand All @@ -204,9 +245,15 @@ def run_chain(engine, cases, pret, ai, policy_name, bag, levels, seed, entry_hp=
max_hp = stats['hp'] if stats else cases[fight]['player']['stats']['hp']
if carry['hp'] is None:
carry['hp'] = max_hp
top = between_fights(carry, max_hp, policy_name, fight, extra and extra.get('_league_plan')) if index else Counter()
if not index:
top = Counter()
elif between == 'pokeguy':
top = pokeguy_between(carry, max_hp, fight)
else:
top = between_fights(carry, max_hp, policy_name, fight, extra and extra.get('_league_plan'))
entry = {'hp': carry['hp'], 'max_hp': max_hp, 'pp': dict(carry['pp']), 'bag': dict(carry['bag'])}
scenario = fight_scenario(cases[fight], pret, carry, stats, levels[fight] if levels else None, only_foe, bench)
scenario = fight_scenario(cases[fight], pret, carry, stats, levels[fight] if levels else None, only_foe, bench,
held_item)
state, decisions = play(engine, scenario, ai, policy, '{}:{}'.format(seed, fight), fight=fight,
extra_goals=dict(extra) if extra else None)
won = state['winner'] == 'Player'
Expand Down
57 changes: 57 additions & 0 deletions src/pokesim/games/frlg/league/test_pokeguy_chain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""PokeGuy's League chain: his out-of-battle healing and the held-item override."""

import unittest

from pokesim.games.frlg.league import chain


def carry(hp, status='', pp=None, **bag):
return {'hp': hp, 'status': status, 'pp': dict(pp or chain.MOVE_PP), 'bag': dict(bag)}


class PokeguyBetweenTest(unittest.TestCase):
"""state-history.json: 130/162 into Bruno and 45/165 into Agatha untouched; a Full Restore to full
before Lance and the Champion with his Super Potions unused; his Elixir before the Champion."""

def test_no_top_up_before_agatha(self):
c = carry(45, fullrestore=12, superpotion=4)
self.assertEqual(chain.pokeguy_between(c, 165, 'agatha'), {})
self.assertEqual(c['hp'], 45)

def test_full_restore_before_lance(self):
c = carry(48, fullrestore=12, superpotion=4)
self.assertEqual(chain.pokeguy_between(c, 168, 'lance'), {'fullrestore': 1})
self.assertEqual((c['hp'], c['bag']['superpotion']), (168, 4))

def test_elixir_before_champion(self):
c = carry(37, pp={'BITE': 18, 'SURF': 3, 'BLIZZARD': 0, 'STRENGTH': 15}, fullrestore=10, elixir=1)
self.assertEqual(chain.pokeguy_between(c, 171, 'champion'), {'fullrestore': 1, 'elixir': 1})
self.assertEqual(c['pp'], {'BITE': 25, 'SURF': 13, 'BLIZZARD': 5, 'STRENGTH': 15})

def test_status_cured_with_its_own_cure(self):
c = carry(100, status='par', parlyzheal=1, fullrestore=5)
self.assertEqual(chain.pokeguy_between(c, 162, 'bruno'), {'parlyzheal': 1})
self.assertEqual((c['status'], c['hp']), ('', 100))


class HeldItemTest(unittest.TestCase):
"""The cases carry PokeGuy's Black Glasses; our console Blastoise holds nothing."""

@classmethod
def setUpClass(cls):
from pokesim.cli.frlg_league_chain import league_cases
cls.cases, cls.pret = league_cases()

def scenario(self, held_item):
return chain.fight_scenario(self.cases['lorelei'], self.pret, carry(None), chain.ours_at(54), 54,
held_item=held_item)

def test_case_keeps_his_black_glasses(self):
self.assertEqual(self.scenario(None)['player']['held_item'], 'BLACK_GLASSES')

def test_empty_string_holds_nothing(self):
self.assertEqual(self.scenario('')['player']['held_item'], '')


if __name__ == '__main__':
unittest.main()
Loading