/
battleclient.py
2119 lines (1851 loc) · 89 KB
/
battleclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
import string
import traceback
import AI
from AI.actions import MoveAction, SwitchAction
from battle.battlefield import BattleSide, BattleField
from battle.battlepokemon import BattlePokemon
from bot.foeside import FoeBattleSide, FoePokemon, UnrevealedPokemon, UNREVEALED
from bot.battlecalculator import BattleCalculator
from showdowndata import pokedex
from showdowndata.rbstats import rbstats, rbstats_key
from misc.functions import normalize_name, clamp_int
from battle import effects, statuses
from battle.abilities import abilitydex
from battle.enums import (Status, Weather, Volatile, ITEM, ABILITY, Type, SideCondition, Hazard,
PseudoWeather, Decision)
from battle.items import itemdex
from battle.moves import movedex
from battle.types import type_effectiveness, HPivs
from battle.stats import Boosts, PokemonStats
from _logging import log
class BattleClient(object):
"""
Maintains a model of a battle (self.battlefield) and handles Showdown messages that modify
the state of the battle. Responds to |request| messages via its send method.
See PROTOCOL.md in the Showdown repo for documentation on the client/server communication
protocol.
Purposefully unimplemented message types (because they don't occur in randbats):
{-swapboost, -copyboost, -invertboost, -ohko, -mustrecharge}
"""
def __init__(self, name, room, send, show_calcs=False, ai_strategy=None):
"""
name: (str) client's username
room: (str) the showdown room that battle messages should be sent to
send: a callable that takes a str param, and sends messages to the showdown server
"""
self.name = name # str
self.room = room # str
self.foe_name = None # str
self.my_side = None # BattleSide
self.foe_side = None # FoeBattleSide
self.battlefield = None # BattleField
self.is_active = True
self.last_sent = None
self.request = None
self.rqid = None
self.crit = False
self.hiddenpower_trigger = None
self.previous_msg = ['']
self.switch_choice = None
self.bench_order = None
self.show_calcs = show_calcs
self.battle = BattleCalculator.from_battlefield(None)
self.AI = AI.Agent(ai_strategy) if ai_strategy else None
def _send(msg):
self.last_sent = msg
send(msg)
self.send = _send
@property
def win(self):
return None if self.battlefield is None else self.battlefield.win
def get_side_from_msg(self, msg, index=1):
"""
All `POKEMON` in messages are formatted 'p2a: Goodra' or '[of] p2a: Goodra'
e.g. |-unboost|p2a: Goodra|spa|2
"""
identifier = msg[index].replace('[of] ', '')
side = self.my_side if int(identifier[1]) - 1 == self.my_side.index else self.foe_side
assert side is not None, side
return side
def get_pokemon_from_msg(self, msg, index=1):
"""
All `POKEMON` in messages are formatted 'p2a: Vaporeon'
Returning None is allowed when the pokemon is one of the foe's unrevealed pokemon
A different index may be passed, e.g. index=3 to get Weezing from
`|-sethp|p2a: Emboar|55/100|p1a: Weezing|166/238|[from] move: Pain Split`
If getting a foe pokemon and foe_side.active_illusion is set, then return the foe's
zoroark instead of that pokemon.
"""
side = self.get_side_from_msg(msg, index)
name = normalize_name(msg[index])
# is it referring to an illusioned zoroark?
if side == self.my_side:
if msg[0] == 'switch':
if self.switch_choice is None:
if self.get_zoroark(side) is not None and self.battlefield.turns > 0:
log.w('My switch choice was not recorded and I have a zoroark')
else:
name = self.switch_choice
elif msg[0] == 'drag':
my_zoroark = self.get_zoroark(side)
if (my_zoroark is not None and
not my_zoroark.is_fainted() and
side.remaining_pokemon > 1 and
normalize_name(self.request['side']['pokemon'][0]['ident']) == 'zoroark'
):
name = 'zoroark'
else:
active = side.active_pokemon
if active is not None and active.base_species == 'zoroark':
name = 'zoroark'
elif side.active_illusion:
return self.get_zoroark(side)
for pokemon in side.team:
if pokemon.base_species.startswith(name):
if pokemon.is_fainted():
continue
return pokemon
def get_move(self, move_name, pokemon):
"""
Get the move object corresponding to a name sent by the server. If it's a hiddenpower move,
then return the correct one for the pokemon or hiddenpowernotype if the type can't be
determined.
"""
move_name = normalize_name(move_name)
if move_name == 'hiddenpower':
hp_moves = [hp_move for hp_move in pokemon.moves if hp_move.is_hiddenpower]
if hp_moves:
assert len(hp_moves) == 1, (hp_moves, pokemon)
move = hp_moves[0]
else:
assert pokemon.side == self.foe_side, pokemon
move, _ = self.get_possible_hiddenpowers(pokemon)
else:
move = movedex[move_name]
return move
def is_ally(self, pokemon):
return pokemon.side == self.my_side
def is_foe(self, pokemon):
return pokemon.side == self.foe_side
def set_hp_status(self, pokemon, hp_msg):
"""
hp_msg is a str of the form "201/219" (my pokemon) or "76/100" (foe pokemon).
It may also have a status, e.g. "88/100 brn".
If the pokemon is fainted, it will be "0 fnt"
"""
msg = hp_msg.split()
if len(msg) > 1:
if msg[1] == 'fnt':
pokemon.hp = 0
pokemon.status = Status.FNT
return
else:
status = self.STATUS_MAP[msg[1]][0]
if not pokemon.has_effect(status):
self.set_status(pokemon, status)
else:
pokemon.status = None
hp, max_hp = map(int, msg[0].split('/'))
if self.is_foe(pokemon):
# We do some estimation here, since information on the opponent's HP is always a
# percentage.
assert max_hp == 100, max_hp
if hp == 100:
pokemon.hp = pokemon.max_hp # probably
elif hp == 1:
pokemon.hp = 1 # probably, because of focus sash, sturdy, etc.
else:
pokemon.hp = int(round(pokemon.max_hp * hp / 100.0)) # best estimate
else:
assert max_hp == pokemon.max_hp != 100, (max_hp, pokemon.max_hp)
pokemon.hp = hp
def build_my_side(self, json):
index = int(json['side']['id'][1]) - 1
j_team = json['side']['pokemon']
team = [self.my_pokemon_from_json(j_pokemon) for j_pokemon in j_team]
self.my_side = BattleSide(team, index, self.name)
return self.my_side
def my_pokemon_from_json(self, j_pokemon):
details = j_pokemon['details'].split(', ')
species = normalize_name(details[0])
level = int(details[1].lstrip('L'))
gender = details[2] if len(details) > 2 else None
hp, max_hp = map(int, j_pokemon['condition'].split('/'))
stats = j_pokemon['stats']
stats['max_hp'] = max_hp
moves = [movedex[move.rstrip(string.digits)] for move in j_pokemon['moves']]
ability = abilitydex[j_pokemon['baseAbility']]
item = itemdex[j_pokemon['item']]
pokemon = BattlePokemon(pokedex[species], level, moves, ability, item, gender)
pokemon.hp, pokemon.max_hp = hp, max_hp
self._warn_if_stats_discrepancy(pokemon, stats)
pokemon.stats = PokemonStats.from_dict(stats)
return pokemon
def handle(self, msg_type, msg):
handle_method = 'handle_%s' % msg_type.lstrip('-')
if self.hiddenpower_trigger is not None:
self.deduce_hiddenpower(self.hiddenpower_trigger, msg)
log.d('%s called with %s', handle_method, msg)
getattr(self, handle_method)(msg)
if self.crit and msg_type != '-crit':
self.crit = False
self.previous_msg = msg
handle_supereffective = handle_resisted = handle_miss = lambda self, msg: None
def deduce_hiddenpower(self, trigger, msg):
"""
Try to deduce, from the message following a move, what type of hiddenpower `pokemon` has.
e.g.:
|move|p2a: Gothitelle|Hidden Power|p1a: Ambipom
|-supereffective|p1a: Ambipom <-- called for this message
Since Gothitelle gets either fire-type or fighting-type hiddenpower, we can deduce that this
gothitelle has hiddenpowerfighting, and so we adjust its moveset and IVs.
The possible messages following a |move||Hidden Power| are:
Typical:
|-supereffective|p2a: Graveler
|-resisted|p2a: Azumarill
|-immune|p2a: Haunter|[msg]
|-damage|p2a: Grovyle|161/241
|-miss|p2a: Durant|p1a: Yveltal
Ability-based: flashfire,voltabsorb/waterabsorb/dryskin,lightningrod/motordrive/stormdrain,
levitate,primordialsea,desolateland,wonderguard,protean,deltastream
|-start|p2a: Caterpie|ability: Flash Fire
|-immune|p2a: Caterpie|[msg]|[from] ability: Flash Fire
|-heal|p2a: Azumarill|341/341|[from] ability: Volt Absorb|[of] p1a: Clefable
|-immune|p2a: Azumarill|[msg]|[from] ability: Volt Absorb
|-ability|p2a: Plusle|Lightning Rod|boost
|-ability|p2a: Leafeon|Storm Drain|boost
|-ability|p2a: Electivire|Motor Drive|boost
|-immune|p2a: Eelektross|[msg]|[from] ability: Levitate
|-fail|p2a: Caterpie|Hidden Power|[from] Primordial Sea
|-activate|p1a: Shedinja|ability: Wonder Guard
|-start|p1a: Kecleon|typechange|Rock|[from] Protean
|-activate||deltastream
"""
if msg[0] in ('-crit', 'replace', '-end'):
return # expect information in the next message instead
self.hiddenpower_trigger = None
if msg[0] == '-miss': # no information
return
pokemon, possible = trigger
hiddenpower = None
hp_notype = movedex['hiddenpowernotype']
pp = pokemon.pp[hp_notype]
del pokemon.moves[hp_notype]
if msg[0] == '-start' and msg[2] == 'typechange': # reveals type in msg[3]
pokemon.moves['hiddenpower' + normalize_name(msg[3])] = pp
return
defender = self.get_pokemon_from_msg(msg, 1) if msg[1] else None
msg_to_eff = {'-supereffective': (2, 4),
'-resisted': (0.5, 0.25),
'-immune': (0,),
'-damage': (1,)}
if msg[0] in msg_to_eff and len(msg) <= 3:
reduced = [move for move in possible if
(self.battle.get_effectiveness(pokemon, move, defender) *
(not defender.is_immune_to_move(pokemon, move))) in msg_to_eff[msg[0]]]
if len(reduced) == 1:
hiddenpower = reduced[0]
elif len(reduced) == 0:
log.w('Error deducing hiddenpower type (no candidates): '
'%s, %s: %s', pokemon, possible, msg)
# handle all the abilities and other effects that could reveal the hiddenpower type
elif msg[0] == '-start' and normalize_name(msg[2]) == 'flashfire':
hiddenpower = movedex['hiddenpowerfire']
elif msg[0] == '-immune':
effect = normalize_name(msg[3])
if effect == 'flashfire':
hiddenpower = movedex['hiddenpowerfire']
elif effect == 'voltabsorb':
hiddenpower = movedex['hiddenpowerelectric']
elif effect in ('waterabsorb', 'dryskin'):
hiddenpower = movedex['hiddenpowerwater']
elif effect == 'levitate':
hiddenpower = movedex['hiddenpowerground']
elif msg[0] == '-heal':
effect = normalize_name(msg[3])
if effect == 'voltabsorb':
hiddenpower = movedex['hiddenpowerelectric']
elif effect in ('waterabsorb', 'dryskin'):
hiddenpower = movedex['hiddenpowerwater']
elif msg[0] == '-ability':
effect = normalize_name(msg[3])
if effect in ('lightningrod', 'motordrive'):
hiddenpower = movedex['hiddenpowerelectric']
elif effect == 'stormdrain':
hiddenpower = movedex['hiddenpowerwater']
elif msg[0] == '-fail':
effect = normalize_name(msg[3])
if effect == 'primordialsea':
hiddenpower = movedex['hiddenpowerfire']
if effect == 'desolateland':
hiddenpower = movedex['hiddenpowerwater']
elif msg[0] == '-activate':
effect = normalize_name(msg[2])
if effect == 'wonderguard':
reduced = [move for move in possible if
self.battle.get_effectiveness(pokemon, move, defender) < 2]
if len(reduced) == 1:
hiddenpower = reduced[0]
elif effect == 'deltastream':
reduced = [move for move in possible if
type_effectiveness(move.type, Type.FLYING) > 1]
if len(reduced) == 1:
hiddenpower = reduced[0]
else:
log.e('Unhandled deduce_hiddenpower message for %s: %s', pokemon, msg)
if hiddenpower is None:
pokemon.moves[hp_notype] = pp
else:
pokemon.moves[hiddenpower] = pp
self.recalculate_stats_hiddenpower(pokemon, hiddenpower.type)
if hiddenpower is None:
log.i("Unable to deduce %s's hiddenpower type vs %s from %s",
pokemon, defender, msg)
elif hiddenpower in possible:
log.i("Deduced %s's hiddenpower type to be %s", pokemon, hiddenpower)
else:
log.w("Setting %s's hiddenpower type to %s: "
"but possible choices were %s", pokemon, hiddenpower, possible)
def recalculate_stats_hiddenpower(self, pokemon, hp_type):
log.i("Recalculating %s's stats for hp_type=%s", pokemon, hp_type)
pokemon.ivs = HPivs[hp_type]
pokemon.stats = pokemon.calculate_initial_stats(pokemon.evs, pokemon.ivs)
def handle_inactive(self, msg):
if self.last_sent is not None:
self.send(self.last_sent)
def handle_turn(self, msg):
"""
|turn|1
This is the last message that will be received before a move must be chosen. Will be sent
after a fainted pokemon is replaced.
"""
assert self.battlefield.turns == int(msg[1]) - 1, (self.battlefield.turns, msg)
self.battlefield.turns = turn = int(msg[1])
my_active = self.my_side.active_pokemon
foe_active = self.foe_side.active_pokemon
assert (my_active and foe_active), (my_active, foe_active)
my_active.item_used_this_turn = None
my_active.will_move_this_turn = True
my_active.turns_out += 1
foe_active.item_used_this_turn = None
foe_active.will_move_this_turn = True
foe_active.turns_out += 1
if turn > 1:
for thing in filter(None, (my_active, foe_active, my_active.side, foe_active.side,
self.battlefield)):
for effect in thing.effects:
if effect.duration is not None and effect.source not in Weather.values:
if (effect.duration <= 1 and effect.source in (
SideCondition.WISH, Volatile.STALL, Volatile.TWOTURNMOVE,
Volatile.LOCKEDMOVE)):
# remove automatically, since there's no notification in protocol
thing.remove_effect(effect.source)
continue
elif effect.duration == 0:
log.w("%s's effect %s has a duration of 0, cannot "
"decrement", thing, effect)
continue
effect.duration -= 1
self.update_foe_inferences()
abilities = (my_active.ability, foe_active.ability)
# update ability-based field effects
if abilitydex['airlock'] in abilities or abilitydex['cloudnine'] in abilities:
self.battlefield.suppress_weather()
else:
self.battlefield.unsuppress_weather()
if abilitydex['darkaura'] in abilities:
self.battlefield.set_effect(effects.DarkAuraFieldEffect())
elif self.battlefield.has_effect(PseudoWeather.DARKAURA):
self.battlefield.remove_effect(PseudoWeather.DARKAURA)
if abilitydex['fairyaura'] in abilities:
self.battlefield.set_effect(effects.FairyAuraFieldEffect())
elif self.battlefield.has_effect(PseudoWeather.FAIRYAURA):
self.battlefield.remove_effect(PseudoWeather.FAIRYAURA)
if abilitydex['aurabreak'] in abilities:
self.battlefield.set_effect(effects.AuraBreakFieldEffect())
elif self.battlefield.has_effect(PseudoWeather.AURABREAK):
self.battlefield.remove_effect(PseudoWeather.AURABREAK)
def update_foe_inferences(self):
for pokemon in self.foe_side.team:
if pokemon.is_fainted() or pokemon.name == UNREVEALED or pokemon.is_transformed:
continue
log.d("Updating foe: %s" % pokemon)
known_attrs, all_known = pokemon.known_attrs()
if all_known:
continue
rb_index = rbstats_key(pokemon)
if pokemon.item == itemdex['_unrevealed_']:
for item in rbstats[rb_index]['item']:
if rbstats.attr_probability(rb_index, item, known_attrs) == 1:
log.i("%s must have %s, given %s", pokemon.name, item, known_attrs)
self.reveal_foe_original_item(pokemon, itemdex[item])
self.set_item(pokemon, itemdex[item])
if pokemon.ability == abilitydex['_unrevealed_']:
for ability in rbstats[rb_index]['ability']:
if rbstats.attr_probability(rb_index, ability, known_attrs) == 1:
log.i("%s must have %s, given %s", pokemon.name, ability, known_attrs)
self.set_ability(pokemon, abilitydex[ability])
if len(pokemon.moves) < 4:
for move in rbstats[rb_index]['moves']:
if (move not in known_attrs and
rbstats.attr_probability(rb_index, move, known_attrs) == 1
):
log.i("%s must have %s, given %s", pokemon.name, move, known_attrs)
self.reveal_move(pokemon, movedex[move])
assert len(pokemon.moves) <= 4, (pokemon, pokemon.moves)
active = self.my_side.active_pokemon
foe = self.foe_side.active_pokemon
if active.is_transformed and active.name == foe.name:
if (foe.ability != abilitydex['_unrevealed_'] and
active.ability == abilitydex['_unrevealed_']):
self.set_ability(active, foe.ability)
elif (active.ability != abilitydex['_unrevealed_'] and
foe.ability == abilitydex['_unrevealed_']):
self.set_ability(foe, active.ability)
def handle_player(self, msg):
"""
`|player|PLAYER|USERNAME|AVATAR` e.g. `|player|p1|1BillsPC|294`
"""
if len(msg) > 2: # ignore msgs of the form `|player|p1`
if msg[2] != self.name:
if self.foe_name is None:
foe_index = int(msg[1][1]) - 1
if self.my_side is not None:
assert foe_index != self.my_side.index
self.foe_name = msg[2]
self.foe_side = FoeBattleSide([UnrevealedPokemon() for _ in range(6)],
foe_index, self.foe_name)
else:
log.w('Received a second (foe) player registration (%s); '
'foe already named as (%s)', msg[2], self.foe_name)
if self.battlefield is None and self.my_side and self.foe_side:
self.battlefield = BattleField(*sorted([self.my_side, self.foe_side],
key=lambda side: side.index))
self.battle.battlefield = self.battlefield
if self.AI is not None:
self.AI.set_my_player(self.my_side.index)
def handle_request(self, request):
"""
|request|
{"active":[{"moves":[1-4 moves], "maybeTrapped":true, "trapped":true}],
"rqid": 1
"wait": true (or undefined)
"side": {
"name": str
"id": "p1"
"pokemon": [{
"ident": "p1: Vaporeon"
"details": "Vaporeon, L77, M[, shiny]"
"condition": "401/401"
"active": true
"stats": {"atk", "def", "spa", "spd", "spe"}
"moves": ["scald", "toxic", "wish", "protect"]
"baseAbility": "waterabsorb"
"item": "leftovers"
"canMegaEvo": false
} ... ]}}
or
{"forceSwitch": [true],
"side"...,
"rqid": 2}
If this is the first request (beginning of game), "active" and "rqid" are omitted
"""
self.rqid = request.get('rqid')
my_active = self.my_side.active_pokemon
foe_active = self.foe_side.active_pokemon
req_active = request.get('active')
if req_active is not None:
if req_active[0].get('maybeTrapped'):
my_active.set_effect(effects.Trapped())
if len(req_active[0]['moves']) > 1 and my_active.has_effect(Volatile.LOCKEDMOVE):
my_active.remove_effect(Volatile.LOCKEDMOVE)
self._validate_my_team()
log.i('\n'+repr(self.battlefield))
if request.get('wait'): # The opponent has more decisions to make
return
if self.show_calcs and not my_active.is_fainted() and not foe_active.is_fainted():
self.battle.show_my_moves(my_active, foe_active)
self.battle.show_foe_moves(my_active, foe_active)
if self.AI:
self.make_move(request)
else:
self.bench_order = [normalize_name(p['ident']) for p in self.request['side']['pokemon']]
self.request = request
def make_move(self, request, switch_rejected=False):
moves, switches, can_mega = self.get_action_choices(request, switch_rejected)
action, mega = self.AI.select_action(self.battlefield, moves, switches, can_mega)
log.i('Selected action: %s%s', action, ' + mega' if mega else '')
if mega and action.action_type == Decision.SWITCH:
log.w("%s chose to switch and mega-evolve on the same turn; removing 'mega'", self.AI)
mega = False
command = '%s|%s%s' % (self.room, action.command_string, ' mega' if mega else '')
if self.rqid:
command += '|%d' % self.rqid
self.send(command)
if action.action_type == Decision.SWITCH:
self.switch_choice = action.incoming_name
else:
self.switch_choice = None
def get_action_choices(self, request, switch_rejected):
moves = None
switches = []
can_mega = False
force_switch = request.get('forceSwitch', False)
if not switch_rejected and (force_switch or
self.my_side.active_pokemon.get_switch_choices()):
switches = [SwitchAction(normalize_name(p['ident']), i)
for i, p in enumerate(request['side']['pokemon'], 1)
if not p['condition'] == '0 fnt' and not p['active']]
if not force_switch:
can_mega = bool(request['active'][0].get('canMegaEvo'))
moves = [MoveAction(normalize_name(move['move']), i)
for i, move in enumerate(request['active'][0]['moves'], 1)
if not move.get('disabled')]
log.d('Choosing from: %s %s, can_mega=%s', moves, switches, can_mega)
assert moves or switches, (request, self.my_side.active_pokemon.get_switch_choices())
return moves, switches, can_mega
def handle_choice(self, msg):
"""
In case moves are being made manually, we need to watch for |choice| messages to know what
switch was requested by the player. This is required if the player has a zoroark to
determine whether the zoroark or its decoy is being switched in.
If the move was made by the AI module via self.make_move, then we already track this choice.
|choice|switch 2|
"""
if self.AI:
return
if msg[1].startswith('switch'):
bench_index = int(msg[1][-1]) - 1
self.switch_choice = self.bench_order[bench_index]
log.i('set switch = %s', self.switch_choice)
def handle_move(self, msg):
"""
`|move|POKEMON|MOVE|TARGET[|FROM]`
|move|p1a: Groudon|Aerial Ace|p2a: Fraxure|[from]Copycat
|move|p1a: Kyurem|Outrage|p2a: Glalie|[from]lockedmove
|move|p2a: Stunfisk|Earth Power|p1a: Swalot|[from]Sleep Talk
|move|p1a: Haxorus|Outrage|p2: Zoroark|[notarget]
Just subtract pp for MOVE from POKEMON
Start autotomize from here, since there's no -start message when incrementing the multiplier
"""
pokemon = self.get_pokemon_from_msg(msg)
assert pokemon.is_active, pokemon
foe = (self.foe_side.active_pokemon if self.is_ally(pokemon)
else self.my_side.active_pokemon)
if len(msg) > 4 and msg[4].startswith('[from]'):
# if hiddenpower is used, then for the purposes of copycat (the consumer of
# battlefield.last_move_used), it is the default hiddenpowerdark
called_move = movedex['hiddenpowerdark' if msg[2] == 'Hidden Power' else
normalize_name(msg[2])]
self.battlefield.last_move_used = called_move
if msg[4].endswith('Sleep Talk'):
self.reveal_move(pokemon, called_move)
else:
pokemon.last_move_used = called_move
return # this move is called by another (copycat, sleeptalk, lockedmove)
if msg[2] == 'Hidden Power':
hp_moves = [move for move in pokemon.moves if
move.is_hiddenpower and move != movedex['hiddenpowernotype']]
if hp_moves:
assert len(hp_moves) == 1, hp_moves
move = hp_moves[0]
else:
assert pokemon.side == self.foe_side, (pokemon, pokemon.side)
move, possible = self.get_possible_hiddenpowers(pokemon)
if len(possible) > 1:
self.hiddenpower_trigger = (pokemon, possible)
else:
move = movedex[normalize_name(msg[2])]
if move != movedex['struggle']:
if (not foe.is_fainted() and
foe.ability == abilitydex['pressure'] and
not move.targets_user):
pp_sub = 2
else:
pp_sub = 1
if move in pokemon.pp:
pokemon.pp[move] -= pp_sub
elif self.is_foe(pokemon): # Add move to foe's moveset
if (move.name not in rbstats[rbstats_key(pokemon)]['moves'] and
move.name in rbstats['zoroark']['moves']
):
log.i('Detected zoroark based on move %s', move)
pokemon = self.detect_illusioned_foe(pokemon, break_illusion=False)
else:
if self.reveal_move(pokemon, move):
pokemon.pp[move] = max(0, move.max_pp - pp_sub)
else:
log.w("Handling a move (%s) not in %r's moveset", normalize_name(msg[2]), pokemon)
pokemon.last_move_used = move
self.battlefield.last_move_used = move
pokemon.will_move_this_turn = False
if pokemon.has_effect(Volatile.TWOTURNMOVE):
pokemon.remove_effect(Volatile.TWOTURNMOVE, force=True)
if move in (movedex['outrage'], movedex['petaldance']) and not msg[-1] == '[notarget]':
pokemon.set_effect(effects.LockedMove(move))
elif move == movedex['autotomize']:
effect = pokemon.get_effect(Volatile.AUTOTOMIZE)
if effect is None:
pokemon.set_effect(effects.Autotomize())
else:
effect.multiplier += 1
elif move == movedex['wish']:
pokemon.side.set_effect(effects.Wish(pokemon.max_hp / 2))
elif move == movedex['healingwish']:
pokemon.side.set_effect(effects.HealingWish())
elif move == movedex['batonpass']:
pokemon.set_effect(effects.BatonPass())
if pokemon.item in (itemdex['choiceband'], itemdex['choicescarf'], itemdex['choicespecs']):
pokemon.set_effect(effects.ChoiceLock(move))
def get_possible_hiddenpowers(self, pokemon):
possible = [movedex[move] for move in rbstats[rbstats_key(pokemon)]['moves']
if move.startswith('hiddenpower')]
move = possible[0] if len(possible) == 1 else movedex['hiddenpowernotype']
return move, possible
def reveal_move(self, pokemon, move):
"""
Reveal a move that a foe pokemon definitely has (i.e. was not called via copycat, etc.)
Return success.
"""
if (move in pokemon.moves or
move == movedex['struggle'] or
(move.is_hiddenpower and any(known.is_hiddenpower for known in pokemon.moves))):
return False
if len(pokemon.moves) >= 4:
log.i('Revealing %s when %s already has a full moveset: %s',
move, pokemon, pokemon.moves)
for name in rbstats['zoroark']['moves']:
known_move = movedex[name]
if known_move in pokemon.moves:
log.i('Forgetting possible zoroark move: %s', known_move)
del pokemon.moves[known_move]
# reset assumed item, because item could have been revealed due to faulty assumptions
pokemon.item = itemdex['_unrevealed_']
pokemon.original_item = itemdex['_unrevealed_']
if move.name in rbstats['zoroark']['moves']:
log.i('Rejected learning %s due to possibility of zoroark', move)
return False
if len(pokemon.moves) >= 4: # if the above handling didn't fix it, something's gone wrong
log.w("%s's moveset %s is full; cannot reveal %s. Clearing moveset as a last resort.",
pokemon, pokemon.moves, move)
pokemon.moves.clear()
pokemon.moves[move] = move.max_pp
log.i("%s's %s was revealed!", pokemon, move)
if move.is_hiddenpower and move.type != Type.NOTYPE:
self.recalculate_stats_hiddenpower(pokemon, move.type)
return True
def handle_fail(self, msg):
"""
Ignore:
|-fail|p1a: Hitmontop
|-fail|p2a: Accelgor|tox
|-fail|p2a: Kyogre|Flare Blitz|[from] Primordial Sea
|-fail|p1a: Kyurem|move: Substitute|[weak]
Reveal ability:
|-fail|p2a: Registeel|unboost|[from] ability: Clear Body|[of] p2a: Registeel
|-fail|p2a: Graveler|unboost|Attack|[from] ability: Hyper Cutter|[of] p2a: Graveler
|-fail|p2a: Haunter|unboost|accuracy|[from] ability: Keen Eye|[of] p2a: Haunter
Fail - Healing Wish
|move|p2a: Latias|Healing Wish|p2a: Latias
|-fail|p2a: Latias
"""
for i in range(3, len(msg)):
if msg[i].startswith('[from] ability:'):
pokemon = self.get_pokemon_from_msg(msg, i+1)
ability = abilitydex[normalize_name(msg[i])]
self.set_ability(pokemon, ability)
failmon = self.get_pokemon_from_msg(msg)
if failmon is not None:
failmon.remove_effect(Volatile.BATONPASS)
if failmon.last_move_used == movedex['healingwish']:
failmon.side.remove_effect(SideCondition.HEALINGWISH)
def handle_immune(self, msg):
"""
|-immune|p2a: Drifblim|[msg]
|-immune|p2a: Quagsire|[msg]|[from] ability: Water Absorb
|-immune|p1a: Uxie|[msg]|[from] ability: Levitate
etc.
|-immune|p2a: Muk|[msg]|[from] ability: Synchronize|[of] p1a: Umbreon
"""
pokemon = self.get_pokemon_from_msg(msg)
if len(msg) > 3:
ability = normalize_name(msg[3])
if ability == 'synchronize':
pokemon = self.get_pokemon_from_msg(msg, 4)
self.set_ability(pokemon, abilitydex[ability])
attacker = self.battlefield.get_foe(pokemon)
if (attacker is not None and
attacker.last_move_used in (movedex['outrage'], movedex['petaldance'])
):
attacker.remove_effect(Volatile.LOCKEDMOVE)
foe = self.foe_side.active_pokemon
if pokemon is foe:
if (self.previous_msg[0] == 'move' and
self.battlefield.last_move_used.type == Type.PSYCHIC and
not Type.DARK in foe.types and
not foe.ability == abilitydex['wonderguard']
):
log.i('Detected foe zoroark based on psychic immunity')
self.detect_illusioned_foe(foe, break_illusion=False)
def handle_damage(self, msg):
"""
`|-damage|POKEMON|HP STATUS`, with optionally `|[from] EFFECT|[of] SOURCE`,
`|[still]` (suppress animation), `|[silent]` (suppress message).
|-damage|p2a: Goodra|62/100 brn|[from] brn
|-damage|p1a: Phione|252/268 tox|[from] psn
|-damage|p1a: Garchomp|35/286|[from] ability: Iron Barbs|[of] p2a: Ferrothorn
|-damage|p2a: Gengar|50/208 slp|[from] ability: Bad Dreams|[of] p1a: Darkrai
|-damage|p2a: Mightyena|136/252|[from] ability: Aftermath|[of] p1a: Electrode
|-damage|p2a: Cresselia|311/381|[from] ability: Dry Skin|[of] p2a: Cresselia
|-damage|p1a: Arceus|350/381|[from] ability: Liquid Ooze|[of] p2a: Graveler
|-damage|p2a: Porygon-Z|30/100|[from] item: Life Orb
|-damage|p2a: Electivire|35/100|[from] item: Rocky Helmet|[of] p1a: Ferrothorn
|-damage|p2a: Cresselia|264/381|[from] item: Black Sludge
|-damage|p1a: Throh|169/331|[from] Leech Seed|[of] p2a: Venusaur
|-damage|p1a: Haxorus|119/244|[from] confusion
"""
pokemon = self.get_pokemon_from_msg(msg)
assert pokemon.is_active, pokemon
if len(msg) > 3:
if msg[3].startswith('[from] item'):
item = itemdex[normalize_name(msg[3])]
holder = self.get_pokemon_from_msg(msg, 4) if len(msg) > 4 else pokemon
if holder is not None: # may be fainted e.g. from move that triggered rockyhelmet
self.reveal_foe_original_item(holder, item)
self.set_item(holder, item)
elif msg[3].startswith('[from] ability'):
who = self.get_pokemon_from_msg(msg, 4)
self.set_ability(who, abilitydex[normalize_name(msg[3])])
elif normalize_name(msg[3]) == 'leechseed':
if not pokemon.has_effect(Volatile.LEECHSEED):
log.e("%s damaged by leechseed; no Volatile.LEECHSEED present", pokemon, msg)
elif msg[2].endswith('tox') and msg[3] == '[from] psn':
tox = pokemon.get_effect(Status.TOX)
if tox is None:
log.e("%s damaged by tox but has no Status.TOX effect: %s", pokemon, msg)
else:
tox.stage += 1
elif msg[3].endswith('confusion'):
pokemon.remove_effect(Volatile.LOCKEDMOVE)
self.set_hp_status(pokemon, msg[2])
def handle_heal(self, msg):
"""
Same as damage; check for revealed abilities/items first
|-heal|p2a: Tyranitar|330/341|[from] ability: Rain Dish
|-heal|p2a: Moltres|253/267|[from] item: Leftovers
|-heal|p2a: Blissey|87/100 tox|[from] move: Wish|[wisher] Blissey
|-heal|p1a: Tyranitar|341/341|[from] move: Healing Wish
|-enditem|p1a: Exeggutor|Sitrus Berry|[eat]
|-heal|p1a: Exeggutor|205/288|[from] item: Sitrus Berry
"""
pokemon = self.get_pokemon_from_msg(msg)
assert pokemon.is_active, pokemon
if len(msg) > 3:
if msg[3].startswith('[from] item') and 'Berry' not in msg[3]:
item = itemdex[normalize_name(msg[3])]
self.reveal_foe_original_item(pokemon, item)
self.set_item(pokemon, item)
elif msg[3].startswith('[from] ability'):
self.set_ability(pokemon, abilitydex[normalize_name(msg[3])])
elif msg[3] == '[from] move: Wish':
pokemon.side.remove_effect(SideCondition.WISH)
elif msg[3] == '[from] move: Healing Wish':
pokemon.side.remove_effect(SideCondition.HEALINGWISH)
self.set_hp_status(pokemon, msg[2])
def handle_faint(self, msg):
"""
`|faint|POKEMON`
|faint|p1a: Hitmonchan
"""
pokemon = self.get_pokemon_from_msg(msg)
if pokemon is None:
return # pokemon was already fainted, probably from `|-damage|POKEMON|0 fnt|`
pokemon.hp = 0
pokemon.status = Status.FNT
def handle_status(self, msg):
"""
`|-status|POKEMON|STATUS[|FROM]`
|-status|p2a: Goodra|brn
|-status|p2a: Stunfisk|slp|[from] move: Rest
|-status|p1a: Raticate|tox|[from] item: Toxic Orb
|-status|p2a: Blissey|tox|[from] ability: Synchronize|[of] p1a: Musharna
"""
pokemon = self.get_pokemon_from_msg(msg)
pokemon.cure_status()
if len(msg) > 3 and msg[3] == '[from] move: Rest':
pokemon.is_resting = True
pokemon.status = Status.SLP
pokemon.set_effect(statuses.Sleep(pokemon, rest=True))
return
self.set_status(pokemon, msg[2])
if len(msg) > 3:
if msg[3].startswith('[from] item'):
item = itemdex[normalize_name(msg[3])]
self.reveal_foe_original_item(pokemon, item)
self.set_item(pokemon, item)
elif msg[3].startswith('[from] ability'):
other = self.get_pokemon_from_msg(msg, 4)
self.set_ability(other, abilitydex[normalize_name(msg[3])])
else:
log.w('Unhandled part of -status msg: %s', msg)
def handle_cant(self, msg):
"""
`|cant|POKEMON|REASON` or `|cant|POKEMON|REASON|MOVE`
|cant|p2a: Omastar|flinch
Increment pokemon.turns_slept if its sleeping:
|cant|p2a: Alomomola|slp
Reveal a move if shown:
|cant|p2a: Corsola|move: Taunt|Recover
|cant|p2a: Ditto|Disable|Bug Bite
|cant|p2a: Aerodactyl|Focus Punch|Focus Punch
"""
pokemon = self.get_pokemon_from_msg(msg)
pokemon.remove_effect(Volatile.LOCKEDMOVE)
if msg[2] == 'slp':
assert pokemon.status is Status.SLP, (pokemon, pokemon.status)
if pokemon.turns_slept < 3:
pokemon.turns_slept += 1
elif len(msg) > 3:
self.reveal_move(pokemon, self.get_move(msg[3], pokemon))
def handle_curestatus(self, msg):
"""
`|-curestatus|POKEMON|STATUS`
|-curestatus|p1a: Regirock|slp
|-curestatus|p1a: Chansey|tox|[from] ability: Natural Cure
"""
pokemon = self.get_pokemon_from_msg(msg)
assert pokemon.status is not None, (pokemon, pokemon.status)
if len(msg) > 3 and msg[3].startswith('[from] ability:'):
if msg[3] == '[from] ability: Natural Cure':
self.set_ability(pokemon, abilitydex['naturalcure'])
else:
log.e('Unhandled -curestatus msg: %s', msg)
pokemon.cure_status()
def handle_cureteam(self, msg):
"""
`|-cureteam|POKEMON`
|-cureteam|p1a: Granbull|[from] move: HealBell
After -cureteam, -curestatus is now sent for every pokemon that was actually cured, so there
is nothing to do for this message.
"""
pass
def set_status(self, pokemon, status):
assert status in self.STATUS_MAP, status
pokemon.status = self.STATUS_MAP[status][0]
pokemon.set_effect(self.STATUS_MAP[status][1](pokemon), override_immunity=True)
STATUS_MAP = {
'brn': (Status.BRN, statuses.Burn),
'slp': (Status.SLP, statuses.Sleep),
'frz': (Status.FRZ, statuses.Freeze),
'psn': (Status.PSN, statuses.Poison),
'tox': (Status.TOX, statuses.Toxic),
'par': (Status.PAR, statuses.Paralyze),
Status.BRN: (Status.BRN, statuses.Burn),
Status.SLP: (Status.SLP, statuses.Sleep),
Status.FRZ: (Status.FRZ, statuses.Freeze),
Status.PSN: (Status.PSN, statuses.Poison),
Status.TOX: (Status.TOX, statuses.Toxic),
Status.PAR: (Status.PAR, statuses.Paralyze),
}
def handle_weather(self, msg):
"""
`|-weather|WEATHER`
|-weather|RainDance or |-weather|RainDance|[upkeep] or |-weather|none
|-weather|Sandstorm|[from] ability: Sand Stream|[of] p2a: Tyranitar
"""
if msg[1] == 'none':
self.battlefield.clear_weather()
return
weather = Weather.values[msg[1].upper()]
pokemon = None
if len(msg) > 2 and msg[2] == '[upkeep]':
if msg[1].lower() not in ('desolateland', 'primordialsea', 'deltastream'):
assert self.battlefield._weather is not None, \