This repository has been archived by the owner on Dec 7, 2023. It is now read-only.
forked from 40Cakes/pokebot-bizhawk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
1496 lines (1228 loc) · 64.8 KB
/
bot.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
# Import modules
import io # https://docs.python.org/3/library/io.html
import os # https://docs.python.org/3/library/os.html
import re # https://docs.python.org/3/library/re.html
import sys # https://docs.python.org/3/library/sys.html
import glob # https://docs.python.org/3/library/glob.html
import json # https://docs.python.org/3/library/json.html
import math # https://docs.python.org/3/library/math.html
import mmap # https://docs.python.org/3/library/mmap.html
import time # https://docs.python.org/3/library/time.html
import atexit # https://docs.python.org/3/library/atexit.html
import random # https://docs.python.org/3/library/random.html
import argparse # https://docs.python.org/3/library/argparse.html
from pathlib import Path # https://docs.python.org/3/library/pathlib.html
from datetime import datetime # https://docs.python.org/3/library/datetime.html
from threading import Thread, Event # https://docs.python.org/3/library/threading.html
import logging # https://docs.python.org/3/library/logging.html
from logging.handlers import RotatingFileHandler # https://docs.python.org/3/library/logging.html
# Image processing and detection modules
import cv2 # https://pypi.org/project/opencv-python/
import numpy # https://pypi.org/project/numpy/
from PIL import Image, ImageGrab, ImageFile # https://pypi.org/project/Pillow/
# HTTP server/interface modules
from flask import Flask, abort, jsonify, request # https://pypi.org/project/Flask/
from flask_cors import CORS # https://pypi.org/project/Flask-Cors/
import webview # https://pypi.org/project/pywebview/
# Parsing modules
from ruamel.yaml import YAML # https://pypi.org/project/ruamel.yaml/
import fastjsonschema # https://pypi.org/project/fastjsonschema/
# Helper functions
from data.HiddenPower import calculate_hidden_power
from data.GameState import GameState
from data.MapData import MapBank, MapID
def player_on_map(map_bank: int, map_id: int):
on_map = trainer_info["mapBank"] == map_bank and trainer_info["mapId"] == map_id
if not on_map:
debug_log.info(f"Player was not on target map of {map_bank},{map_id}. Map was {trainer_info['mapBank']}, {trainer_info['mapId']}")
return on_map
def read_file(file: str): # Simple function to read data from a file, return False if file doesn't exist
try:
debug_log.debug(f"Reading file: {file}...")
with open(file, mode="r", encoding="utf-8") as open_file:
return open_file.read()
except Exception as e:
if args.d: debug_log.exception(str(e))
return False
def write_file(file: str, value: str): # Simple function to write data to a file, will create the file if doesn't exist
try:
debug_log.debug(f"Writing file: {file}...")
with open(file, mode="w", encoding="utf-8") as save_file:
save_file.write(value)
return True
except Exception as e:
if args.d: debug_log.exception(str(e))
return False
def load_json_mmap(size, file): # Function to load a JSON object from a memory mapped file
# BizHawk writes game information to memory mapped files every few frames (see bizhawk.lua)
# See https://tasvideos.org/Bizhawk/LuaFunctions (comm.mmfWrite)
try:
shmem = mmap.mmap(0, size, file)
if shmem:
if args.dm: debug_log.debug(f"Attempting to read {file} ({size} bytes) from memory...")
bytes_io = io.BytesIO(shmem)
byte_str = bytes_io.read()
if args.dm: debug_log.debug(f"Byte string: {byte_str}")
json_obj = json.loads(byte_str.decode("utf-8").split("\x00")[0]) # Only grab the data before \x00 null chars
if args.dm: debug_log.debug(f"JSON result: {json_obj}")
return json_obj
else: return False
except Exception as e:
if args.dm: debug_log.exception(str(e))
return False
def frames_to_ms(frames: float):
return max((frames/60.0) / emu_speed, 0.02)
# Pre-compile sleep pattern regex
sleep_pattern = re.compile("^\d*\.?\d*ms$")
def emu_combo(sequence: list): # Function to send a sequence of inputs and delays to the emulator
# Example: emu_combo(["B", "Up", "500ms", "Left"])
try:
for k in sequence:
if sleep_pattern.match(k):
delay = float(k[:-2]) # Remove "ms" from the string
time.sleep((delay/1000) / emu_speed)
elif k == "button_release:all":
release_all_inputs()
else: press_button(k)
except Exception as e:
if args.d: debug_log.exception(str(e))
def press_button(button: str): # Function to update the press_input object
global press_input
debug_log.debug(f"Pressing: {button}...")
press_input[button] = True
time.sleep(frames_to_ms(1))
press_input[button] = False
time.sleep(frames_to_ms(1))
def hold_button(button: str): # Function to update the hold_input object
global hold_input
debug_log.debug(f"Holding: {button}...")
hold_input[button] = True
def release_button(button: str): # Function to update the hold_input object
global hold_input
debug_log.debug(f"Releasing: {button}...")
hold_input[button] = False
def release_all_inputs(): # Function to release all keys in all input objects
global press_input, hold_input
debug_log.debug(f"Releasing all inputs...")
for button in ["A", "B", "L", "R", "Up", "Down", "Left", "Right", "Select", "Start", "Power"]:
press_input[button] = False
hold_input[button] = False
def opponent_changed(): # This function checks if there is a different opponent since last check, indicating the game state is probably now in a battle
try:
global last_opponent_personality
#debug_log.info(f"Checking if opponent has changed... Previous PID: {last_opponent_personality}, New PID: {opponent_info['personality']}")
# Fixes a bug where the bot checks the opponent for up to 20 seconds if it was last closed in a battle
if trainer_info["state"] == GameState.OVERWORLD:
return False
if opponent_info and last_opponent_personality != opponent_info["personality"]:
last_opponent_personality = opponent_info["personality"]
debug_log.info("Opponent has changed!")
return True
return False
except Exception as e:
if args.d: debug_log.exception(str(e))
return False
def mem_pollScreenshot():
global g_bizhawk_screenshot
while True:
hold_button("Screenshot")
time.sleep(max((1/max(emu_speed,1))*0.016,0.002)) # Give emulator time to produce a screenshot
try:
shmem = mmap.mmap(0, mmap_screenshot_size, mmap_screenshot_file)
screenshot = Image.open(io.BytesIO(shmem))
g_bizhawk_screenshot = cv2.cvtColor(numpy.array(screenshot), cv2.COLOR_BGR2RGB) # Convert screenshot to numpy array COLOR_BGR2RGB
screenshot.close()
except Exception as e:
if screenshot is not None:
screenshot.close()
if args.dm:
debug_log.exception(str(e))
continue
release_button("Screenshot")
if args.di:
cv2.imshow("pollScreenShotData",g_bizhawk_screenshot)
cv2.waitKey(1)
def find_image(file: str): # Function to find an image in a BizHawk screenshot
try:
profile_start = time.time() # Performance profiling
threshold = 0.999
if args.di: debug_log.debug(f"Searching for image {file} (threshold: {threshold})")
template = cv2.imread(f"data/templates/{language}/" + file, cv2.IMREAD_UNCHANGED)
hh, ww = template.shape[:2]
correlation = cv2.matchTemplate(g_bizhawk_screenshot, template[:,:,0:3], cv2.TM_CCORR_NORMED) # Do masked template matching and save correlation image
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(correlation)
max_val_corr = float('{:.6f}'.format(max_val))
if args.di:
debug_log.debug(f"Image detection took: {(time.time() - profile_start)*1000} ms")
cv2.imshow("screenshot", g_bizhawk_screenshot)
cv2.waitKey(1)
if max_val_corr > threshold:
if args.di:
loc = numpy.where(correlation >= threshold)
result = g_bizhawk_screenshot.copy()
for point in zip(*loc[::-1]):
cv2.rectangle(result, point, (point[0]+ww, point[1]+hh), (0,0,255), 1)
cv2.imshow(f"match", result)
cv2.waitKey(1)
if args.di: debug_log.debug(f"Maximum correlation value ({max_val_corr}) is above threshold ({threshold}), file {file} was on-screen!")
return True
else:
if args.di: debug_log.debug(f"Maximum correlation value ({max_val_corr}) is below threshold ({threshold}), file {file} was not detected on-screen.")
return False
except Exception as e:
if args.di: debug_log.exception(str(e))
return False
no_sleep_abilities = ["Shed Skin", "Insomnia", "Vital Spirit"]
def catch_pokemon(): # Function to catch pokemon
try:
while not find_image("battle/fight.png"):
emu_combo(["button_release:all", "B", "Up", "Left"]) # Press B + up + left until FIGHT menu is visible
if config["manual_catch"]:
input("Pausing bot for manual catch (don't forget to pause bizhawk.lua script so you can provide inputs). Press Enter to continue...")
return True
else:
debug_log.info("Attempting to catch Pokemon...")
if config["use_spore"]: # Use Spore to put opponent to sleep to make catches much easier
debug_log.info("Attempting to sleep the opponent...")
i, spore_pp = 0, 0
ability = opponent_info["ability"][opponent_info["altAbility"]]
can_sleep = ability not in no_sleep_abilities
if (opponent_info["status"] == 0) and can_sleep:
for move in party_info[0]["enrichedMoves"]:
if move["name"] == "Spore":
spore_pp = move["pp"]
spore_move_num = i
i += 1
if spore_pp != 0:
emu_combo(["A", "100ms"])
if spore_move_num == 0: seq = ["Up", "Left"]
elif spore_move_num == 1: seq = ["Up", "Right"]
elif spore_move_num == 2: seq = ["Left", "Down"]
elif spore_move_num == 3: seq = ["Right", "Down"]
while not find_image("spore.png"):
emu_combo(seq)
emu_combo(["A", "4000ms"]) # Select move and wait for animations
elif not can_sleep:
debug_log.info(f"Can't sleep the opponent! Ability is {ability}")
while not find_image("battle/bag.png"): emu_combo(["button_release:all", "B", "Up", "Right"]) # Press B + up + right until BAG menu is visible
while True:
if find_image("battle/bag.png"): press_button("A")
# TODO Safari Zone
#if opponent_info["metLocationName"] == "Safari Zone":
# while not find_image("battle/safari_zone/ball.png"):
# if trainer_info["state"] == GameState.OVERWORLD:
# return False
# emu_combo(["B", "Up", "Left"]) # Press B + up + left until BALL menu is visible
# Preferred ball order to catch wild mons + exceptions
# TODO read this data from memory instead
if trainer_info["state"] == GameState.BAG_MENU:
can_catch = False
# Check if current species has a preferred ball
foe_name = opponent_info["speciesName"]
if foe_name in config["pokeball_override"]:
species_rule = config["pokeball_override"][foe_name]
for ball in species_rule:
if bag_menu(category="pokeballs", item=ball):
can_catch = True
break
# Check global pokeball priority
if not can_catch:
for ball in config["pokeball_priority"]:
if bag_menu(category="pokeballs", item=ball):
can_catch = True
break
if not can_catch:
debug_log.info("No balls to catch the Pokemon found. Killing the script!")
os._exit(1)
if find_image("gotcha.png"): # Check for gotcha! text when a pokemon is successfully caught
debug_log.info("Pokemon caught!")
while trainer_info["state"] != GameState.OVERWORLD:
press_button("B")
time.sleep(frames_to_ms(120)) # Wait for animations
if config["save_game_after_catch"]:
save_game()
return True
if trainer_info["state"] == GameState.OVERWORLD:
return False
except Exception as e:
if args.di: debug_log.exception(str(e))
return False
def battle(): # Function to battle wild pokemon
# This will only battle with the lead pokemon of the party, and will run if it dies or runs out of PP
ally_fainted = False
foe_fainted = False
while not ally_fainted and not foe_fainted:
debug_log.info("Navigating to the FIGHT button...")
while not find_image("battle/fight.png"):
if trainer_info["state"] == GameState.OVERWORLD:
return True
emu_combo(["B", "Up", "Left"]) # Press B + up + left until FIGHT menu is visible
best_move = find_effective_move(party_info[0], opponent_info)
if best_move["power"] <= 10:
debug_log.info("Lead Pokemon has no effective moves to battle the foe!")
flee_battle()
return False
emu_combo(["A", "100ms"])
debug_log.info(f"Best move against foe is {best_move['name']} (Effective power is {best_move['power']})")
i = int(best_move["index"])
if i == 0:
emu_combo(["Up", "Left"])
elif i == 1:
emu_combo(["Up", "Right"])
elif i == 2:
emu_combo(["Down", "Left"])
elif i == 3:
emu_combo(["Down", "Right"])
emu_combo(["A", "4000ms"])
if opponent_info["hp"] == 0:
foe_fainted = True
elif party_info[0]["hp"] == 0:
debug_log.info("Lead Pokemon fainted!")
flee_battle()
return False
while trainer_info["state"] != GameState.OVERWORLD:
if find_image("stop_learning.png"): # Check if our Pokemon is trying to learn a move and skip learning
press_button("A")
press_button("B")
if foe_fainted:
debug_log.info("Battle won!")
return True
def is_valid_move(move: dict):
return not move["name"] in config["banned_moves"] and move["power"] > 0
def find_effective_move(ally: dict, foe: dict):
i = 0
move_power = []
for move in ally["enrichedMoves"]:
power = move["power"]
# Ignore banned moves and those with 0 PP
if not is_valid_move(move) or ally["pp"][i] == 0:
move_power.append(0)
i += 1
continue
# Calculate effectiveness against opponent's type(s)
matchups = type_list[move["type"]]
for foe_type in foe["type"]:
if foe_type in matchups["immunes"]:
power *= 0
elif foe_type in matchups["weaknesses"]:
power *= 0.5
elif foe_type in matchups["strengths"]:
power *= 2
# STAB
for ally_type in ally["type"]:
if ally_type == move["type"]:
power *= 1.5
move_power.append(power)
i += 1
# Return info on the best move
move_idx = move_power.index(max(move_power))
return {
"name": ally["enrichedMoves"][move_idx]["name"],
"index": move_idx,
"power": max(move_power)
}
def flee_battle(): # Function to run from wild pokemon
try:
debug_log.info("Running from battle...")
while trainer_info["state"] != GameState.OVERWORLD:
while not find_image("battle/run.png") and trainer_info["state"] != GameState.OVERWORLD:
emu_combo(["Right","Down", "B"])
while find_image("battle/run.png") and trainer_info["state"] != GameState.OVERWORLD:
press_button("A")
press_button("B")
time.sleep(frames_to_ms(30)) # Wait for battle fade animation
except Exception as e:
if args.d: debug_log.exception(str(e))
def run_until_obstructed(direction: str, run: bool = True): # Function to run until trainer position stops changing
try:
debug_log.info(f"Pathing {direction.lower()} until obstructed...")
press_button("B") # press and release B in case of a random pokenav call
hold_button(direction)
last_x = trainer_info["posX"]
last_y = trainer_info["posY"]
if run: move_speed = 8
else: move_speed = 16
dir_unchanged = 0
while dir_unchanged < move_speed:
if run: hold_button("B")
time.sleep(frames_to_ms(1))
if last_x == trainer_info["posX"] and last_y == trainer_info["posY"]:
dir_unchanged += 1
continue
last_x = trainer_info["posX"]
last_y = trainer_info["posY"]
dir_unchanged = 0
release_button(direction)
return [last_x, last_y]
except Exception as e:
if args.d: debug_log.exception(str(e))
def follow_path(coords: list):
def run_to_pos(x: int, y: int, map_data: tuple, run: bool = True):
try:
while True:
if x != trainer_info["posX"]:
axis = "posX"
directions = ["Left", "Right"]
end_pos = x
elif y != trainer_info["posY"]:
axis = "posY"
directions = ["Up", "Down"]
end_pos = y
else: return True
def target_pos():
if run:
hold_button("B")
if end_pos < trainer_info[axis]:
hold_button(directions[0])
return False
elif end_pos > trainer_info[axis]:
hold_button(directions[1])
return False
else: return True
stuck = 0
last_axis = 0
if map_data != []:
debug_log.info(f"Running to map: {map_data[0][0]}:{map_data[0][1]}")
while (trainer_info["mapBank"] != map_data[0][0] or trainer_info["mapId"] != map_data[0][1]):
if stuck > 25:
press_button("B")
stuck = 0
if trainer_info[axis] == last_axis: stuck += 1
else: stuck = 0
last_axis = trainer_info[axis]
time.sleep(frames_to_ms(1))
if not opponent_changed():
try: target_pos()
except Exception as e:
if args.dm: debug_log.exception(str(e))
else:
identify_pokemon()
return False
else: return True
else:
debug_log.info(f"Running to {axis}: {end_pos}")
while trainer_info[axis] != end_pos:
if stuck > 25:
press_button("B")
stuck = 0
if trainer_info[axis] == last_axis: stuck += 1
else: stuck = 0
last_axis = trainer_info[axis]
time.sleep(frames_to_ms(1))
if not opponent_changed():
try: target_pos()
except Exception as e:
if args.dm: debug_log.exception(str(e))
return False
else:
identify_pokemon()
return False
else:
release_all_inputs()
return True
except Exception as e:
if args.dm: debug_log.exception(str(e))
return False
try:
for x, y, *map_data in coords:
#debug_log.info(f"Current: X: {trainer_info['posX']}, Y: {trainer_info['posY']}, Map: [({trainer_info['mapBank']},{trainer_info['mapId']})]")
#debug_log.info(f"Pathing: X: {x}, Y: {y}, Map: {map_data}")
while not run_to_pos(x, y, map_data): continue
else: release_all_inputs()
except Exception as e:
if args.dm: debug_log.exception(str(e))
return False
menus = ["bag", "bot", "exit", "option", "pokedex", "pokemon", "pokenav", "save"]
def start_menu(entry: str): # Function to open any start menu item - presses START, finds the menu entry and opens it
try:
if entry in menus:
debug_log.info(f"Opening start menu entry: {entry}")
filename = f"start_menu/{entry.lower()}.png"
release_all_inputs()
# Press start until menu is visible
while True:
emu_combo(["Start", "200ms"])
if find_image(f"start_menu/select.png"):
break
while not find_image(filename): # Find menu entry
emu_combo(["Down", "150ms"])
while find_image(filename): # Press menu entry
emu_combo(["A", "200ms"])
else:
return False
except Exception as e:
if args.di: debug_log.exception(str(e))
return False
def bag_menu(category: str, item: str): # Function to find an item in the bag and use item in battle such as a pokeball
try:
if category in ["berries", "items", "key_items", "pokeballs", "tms&hms"]:
debug_log.info(f"Scrolling to bag category: {category}...")
while not find_image(f"start_menu/bag/{category.lower()}.png"):
emu_combo(["Right", "400ms"]) # Press right until the correct category is selected
time.sleep(frames_to_ms(60)) # Wait for animations
debug_log.info(f"Scanning for item: {item}...")
i = 0
while not find_image(f"start_menu/bag/items/{item}.png") and i < 50:
if i < 25: emu_combo(["Down", "50ms"])
else: emu_combo(["Up", "50ms"])
i += 1
if find_image(f"start_menu/bag/items/{item}.png"):
debug_log.info(f"Using item: {item}...")
while trainer_info["state"] == GameState.BAG_MENU: emu_combo(["A", "500ms"]) # Press A to use the item
return True
else:
return False
except Exception as e:
if args.di: debug_log.exception(str(e))
return False
pickup_pokemon = ["Meowth", "Aipom", "Phanpy", "Teddiursa", "Zigzagoon", "Linoone"]
def pickup_items(): # If using a team of Pokemon with the ability "pickup", this function will take the items from the pokemon in your party if 3 or more Pokemon have an item
try:
if trainer_info["state"] != GameState.OVERWORLD:
return
debug_log.info("Checking for pickup items...")
item_count = 0
pickup_mon_count = 0
for i in range(0, 6):
pokemon = party_info[i]
held_item = pokemon['heldItem']
if pokemon["speciesName"] in pickup_pokemon:
if held_item != 0:
item_count += 1
pickup_mon_count += 1
debug_log.info(f"Pokemon {i}: {pokemon['speciesName']} has item: {item_list[held_item]}")
if item_count < config["pickup_threshold"]:
return
time.sleep(frames_to_ms(60)) # Wait for animations
start_menu("pokemon") # Open Pokemon menu
time.sleep(frames_to_ms(60))
for i in range(0, 6):
pokemon = party_info[i]
if pokemon["speciesName"] in pickup_pokemon and pokemon["heldItem"] != 0:
# Take the item from the pokemon
emu_combo(["200ms", "A", "50ms", "Up", "50ms", "Up", "50ms", "A", "50ms", "Down", "50ms", "A", "1000ms", "B", "200ms"])
item_count -= 1
if item_count == 0:
break
emu_combo(["200ms", "Down"])
emu_combo(["50ms", "B", "300ms", "B", "50ms"]) # Close out of menus
except Exception as e:
if args.dm: debug_log.exception(str(e))
def save_game(): # Function to save the game via the save option in the start menu
try:
debug_log.info("Saving the game...")
i = 0
start_menu("save")
while i < 2:
while not find_image("start_menu/save/yes.png"):
time.sleep(frames_to_ms(10))
while find_image("start_menu/save/yes.png"):
emu_combo(["A", "500ms"])
i += 1
time.sleep(frames_to_ms(500)) # Wait for game to save
except Exception as e:
if args.dm: debug_log.exception(str(e))
def identify_pokemon(starter: bool = False): # Identify opponent pokemon and incremement statistics, returns True if shiny, else False
try:
def common_stats():
global stats, encounter_log
stats["pokemon"][pokemon["name"]]["encounters"] += 1
stats["pokemon"][pokemon["name"]]["phase_encounters"] += 1
phase_encounters = stats["totals"]["phase_encounters"]
total_encounters = stats["totals"]["encounters"] + stats["totals"]["shiny_encounters"]
total_shiny_encounters = stats["totals"]["shiny_encounters"]
if stats["pokemon"][pokemon["name"]]["phase_lowest_sv"] == "-": stats["pokemon"][pokemon["name"]]["phase_lowest_sv"] = pokemon["shinyValue"]
else:
if pokemon["shinyValue"] < stats["pokemon"][pokemon["name"]]["phase_lowest_sv"]: stats["pokemon"][pokemon["name"]]["phase_lowest_sv"] = pokemon["shinyValue"]
if stats["pokemon"][pokemon["name"]]["total_lowest_sv"] == "-": stats["pokemon"][pokemon["name"]]["total_lowest_sv"] = pokemon["shinyValue"]
else:
if pokemon["shinyValue"] < stats["pokemon"][pokemon["name"]]["total_lowest_sv"]: stats["pokemon"][pokemon["name"]]["total_lowest_sv"] = pokemon["shinyValue"]
if stats['pokemon'][pokemon['name']]['shiny_encounters'] > 0: shiny_average = f"1/{int(math.floor(stats['pokemon'][pokemon['name']]['encounters']/stats['pokemon'][pokemon['name']]['shiny_encounters'])):,}"
else: shiny_average = "-"
if total_shiny_encounters != 0 and stats['pokemon'][pokemon['name']]['encounters'] != 0: stats["totals"]["shiny_average"] = f"1/{int(math.floor(total_encounters/total_shiny_encounters)):,}"
else: stats["totals"]["shiny_average"] = "-"
log_obj = {
"time_encountered": str(datetime.now()),
"pokemon_obj": pokemon,
"snapshot_stats": {
"phase_encounters": stats["totals"]["phase_encounters"],
"species_encounters": stats['pokemon'][pokemon['name']]['encounters'],
"species_shiny_encounters": stats['pokemon'][pokemon['name']]['shiny_encounters'],
"total_encounters": total_encounters,
"total_shiny_encounters": total_shiny_encounters,
"shiny_average": shiny_average
}
}
if pokemon["shiny"]: shiny_log["shiny_log"].append(log_obj)
encounter_log["encounter_log"].append(log_obj)
stats["pokemon"][pokemon["name"]]["shiny_average"] = shiny_average
encounter_log["encounter_log"] = encounter_log["encounter_log"][-config["encounter_log_limit"]:]
if not args.n:
write_file("stats/totals.json", json.dumps(stats, indent=4, sort_keys=True)) # Save stats file
write_file("stats/encounter_log.json", json.dumps(encounter_log, indent=4, sort_keys=True)) # Save encounter log file
write_file("stats/shiny_log.json", json.dumps(shiny_log, indent=4, sort_keys=True)) # Save shiny log file
year, month, day, hour, minute, second = f"{datetime.now().year}", f"{(datetime.now().month):02}", f"{(datetime.now().day):02}", f"{(datetime.now().hour):02}", f"{(datetime.now().minute):02}", f"{(datetime.now().second):02}"
if not args.n and not pokemon["shiny"] and "all_encounters" in config["log"]: # Log all encounters to a file
path = f"stats/encounters/Phase {total_shiny_encounters}/{pokemon['metLocationName']}/{year}-{month}-{day}/{pokemon['name']}/"
os.makedirs(path, exist_ok=True)
write_file(f"{path}SV_{pokemon['shinyValue']} ({hour}-{minute}-{second}).json", json.dumps(pokemon, indent=4, sort_keys=True))
if pokemon["shiny"] and "shiny_encounters" in config["log"]: # Log shiny Pokemon to a file
path = f"stats/encounters/Shinies/"
os.makedirs(path, exist_ok=True)
write_file(f"{path}SV_{pokemon['shinyValue']} {pokemon['name']} ({hour}-{minute}-{second}).json", json.dumps(pokemon, indent=4, sort_keys=True))
debug_log.info(f"Phase encounters: {phase_encounters} | {pokemon['name']} Phase Encounters: {stats['pokemon'][pokemon['name']]['phase_encounters']}")
debug_log.info(f"{pokemon['name']} Encounters: {stats['pokemon'][pokemon['name']]['encounters']:,} | Lowest {pokemon['name']} SV seen this phase: {stats['pokemon'][pokemon['name']]['phase_lowest_sv']}")
debug_log.info(f"Shiny {pokemon['name']} Encounters: {stats['pokemon'][pokemon['name']]['shiny_encounters']:,} | {pokemon['name']} Shiny Average: {shiny_average}")
debug_log.info(f"Total Encounters: {total_encounters:,} | Total Shiny Encounters: {total_shiny_encounters:,} | Total Shiny Average: {stats['totals']['shiny_average']}")
debug_log.info(f"------------------ {pokemon['name']} ------------------")
debug_log.info("Identifying Pokemon...")
release_all_inputs()
if starter:
time.sleep(frames_to_ms(30))
else:
i = 0
while trainer_info["state"] not in [3, 255] and i < 250:
press_button("B")
i += 1
if trainer_info["state"] == GameState.OVERWORLD:
return False
if starter: pokemon = party_info[0]
else: pokemon = opponent_info
replace_battler = False
debug_log.info(f"------------------ {pokemon['name']} ------------------")
debug_log.debug(pokemon)
debug_log.info(f"Encountered a {pokemon['name']} at {pokemon['metLocationName']}")
debug_log.info(f"HP: {pokemon['hpIV']} | ATK: {pokemon['attackIV']} | DEF: {pokemon['defenseIV']} | SPATK: {pokemon['spAttackIV']} | SPDEF: {pokemon['spDefenseIV']} | SPE: {pokemon['speedIV']}")
debug_log.info(f"Shiny Value (SV): {pokemon['shinyValue']:,} (is {pokemon['shinyValue']:,} < 8 = {pokemon['shiny']})")
if not pokemon["name"] in stats["pokemon"]:
stats["pokemon"].update({pokemon["name"]: {"encounters": 0, "shiny_encounters": 0, "phase_lowest_sv": "-", "phase_encounters": 0, "shiny_average": "-", "total_lowest_sv": "-"}}) # Set up pokemon stats if first encounter
if pokemon["shiny"]:
debug_log.info("Shiny Pokemon detected!")
if stats["totals"]["shortest_phase_encounters"] == "-": stats["totals"]["shortest_phase_encounters"] = stats["totals"]["phase_encounters"]
elif stats["totals"]["shortest_phase_encounters"] > stats["totals"]["phase_encounters"]: stats["totals"]["shortest_phase_encounters"] = stats["totals"]["phase_encounters"]
stats["pokemon"][pokemon["name"]]["shiny_encounters"] += 1
stats["totals"]["shiny_encounters"] += 1
common_stats()
stats["totals"]["phase_encounters"] = 0
stats["totals"]["phase_lowest_sv"] = "-"
stats["totals"]["phase_lowest_sv_pokemon"] = ""
for mon_name in stats["pokemon"]: # Reset phase stats
stats["pokemon"][mon_name]["phase_lowest_sv"] = "-"
stats["pokemon"][mon_name]["phase_encounters"] = 0
if not args.n: write_file("stats/totals.json", json.dumps(stats, indent=4, sort_keys=True)) # Save stats file
if not starter and config["bot_mode"] not in ["manual", "rayquaza", "kyogre", "groudon", "mew"] and "shinies" in config["catch"]:
catch_pokemon()
if not args.n: write_file("stats/totals.json", json.dumps(stats, indent=4, sort_keys=True)) # Save stats file
return True
else:
debug_log.info("Non shiny Pokemon detected...")
stats["totals"]["encounters"] += 1
stats["totals"]["phase_encounters"] += 1
if stats["totals"]["phase_encounters"] > stats["totals"]["longest_phase_encounters"]: stats["totals"]["longest_phase_encounters"] = stats["totals"]["phase_encounters"]
if stats["totals"]["phase_lowest_sv"] == "-":
stats["totals"]["phase_lowest_sv"] = pokemon["shinyValue"]
stats["totals"]["phase_lowest_sv_pokemon"] = pokemon["name"]
elif pokemon["shinyValue"] <= stats["totals"]["phase_lowest_sv"]:
stats["totals"]["phase_lowest_sv"] = pokemon["shinyValue"]
stats["totals"]["phase_lowest_sv_pokemon"] = pokemon["name"]
common_stats()
if config["bot_mode"] == "manual":
while trainer_info["state"] != GameState.OVERWORLD:
time.sleep(frames_to_ms(100))
elif not starter:
if "perfect_ivs" in config["catch"] and mon_ivs_meets_threshold(pokemon, 31):
catch_pokemon()
elif "zero_ivs" in config["catch"] and not mon_ivs_meets_threshold(pokemon, 1):
catch_pokemon()
elif "good_ivs" in config["catch"] and mon_ivs_meets_threshold(pokemon, 25):
catch_pokemon()
elif "all" in config["catch"]:
catch_pokemon()
elif "mew" in config["bot_mode"]:
flee_battle()
time.sleep(frames_to_ms(60))
press_button("B")
release_button("B")
### Custom Filters ###
# Add custom filters here (make sure to uncomment the line), examples:
# If you want to pause the bot instead of automatically catching, replace `catch_pokemon()` with `input("Pausing bot for manual catch (don't forget to pause bizhawk.lua script so you can provide inputs). Press Enter to continue...")`
# --- Catch any species that the trainer has not already caught ---
#elif pokemon["hasSpecies"] == 0: catch_pokemon()
# --- Catch all Luvdisc with the held item "Heart Scale" ---
#elif pokemon["name"] == "Luvdisc" and pokemon["itemName"] == "Heart Scale": catch_pokemon()
# --- Catch Lonely natured Ralts with >25 attackIV and spAttackIV ---
#elif pokemon["name"] == "Ralts" and pokemon["attackIV"] > 25 and pokemon["spAttackIV"] > 25 and pokemon["nature"] == "Lonely": catch_pokemon()
elif config["battle_others"]:
battle_won = battle()
replace_battler = not battle_won
else:
flee_battle()
if config["pickup"]:
pickup_items()
if replace_battler:
if not config["cycle_lead_pokemon"]:
debug_log.info("Lead Pokemon can no longer battle. Ending the script!")
os._exit(1)
else:
start_menu("pokemon")
# Find another healthy battler
party_pp = [0, 0, 0, 0, 0, 0]
i = 0
for mon in party_info:
if mon["hp"] > 0 and i != 0:
for move in mon["enrichedMoves"]:
if is_valid_move(move):
party_pp[i] += move["pp"]
i += 1
highest_pp = max(party_pp)
lead_idx = party_pp.index(highest_pp)
if highest_pp == 0:
debug_log.info("Ran out of Pokemon to battle with. Ending the script!")
os._exit(1)
debug_log.info(f"Replacing lead battler with {party_info[lead_idx]['speciesName']} (Party slot {lead_idx})")
# Scroll to and select SWITCH
while not find_image("start_menu/select.png"):
emu_combo(["A", "100ms"])
emu_combo(["Up", "500ms", "Up", "500ms", "Up", "500ms", "A", "500ms"])
for i in range(0, lead_idx):
emu_combo(["Down", "100ms"])
# Select target Pokemon and close out menu
emu_combo(["A", "100ms"])
emu_combo(["50ms", "B", "300ms", "B", "50ms"])
return False
except Exception as e:
if args.dm: debug_log.exception(str(e))
def mon_ivs_meets_threshold(pokemon: dict, threshold: int):
return (pokemon["hpIV"] >= threshold and
pokemon["attackIV"] >= threshold and
pokemon["defenseIV"] >= threshold and
pokemon["speedIV"] >= threshold and
pokemon["spAttackIV"] >= threshold and
pokemon["spDefenseIV"] >= threshold)
def enrich_mon_data(pokemon: dict): # Function to add information to the pokemon data extracted from Bizhawk
try:
pokemon["name"] = pokemon["speciesName"].capitalize() # Capitalise name
pokemon["metLocationName"] = location_list[pokemon["metLocation"]] # Add a human readable location
pokemon["type"] = pokemon_list[pokemon["name"]]["type"] # Get pokemon types
pokemon["ability"] = pokemon_list[pokemon["name"]]["ability"] # Get pokemon abilities
pokemon["hiddenPowerType"] = calculate_hidden_power(pokemon)
pokemon["nature"] = nature_list[pokemon["personality"] % 25] # Get pokemon nature
pokemon["zeroPadNumber"] = f"{pokemon_list[pokemon['name']]['number']:03}" # Get zero pad number - e.g.: #5 becomes #005
pokemon["itemName"] = item_list[pokemon['heldItem']] # Get held item's name
pokemon["personalityBin"] = format(pokemon["personality"], "032b") # Convert personality ID to binary
pokemon["personalityF"] = int(pokemon["personalityBin"][:16], 2) # Get first 16 bits of binary PID
pokemon["personalityL"] = int(pokemon["personalityBin"][16:], 2) # Get last 16 bits of binary PID
pokemon["shinyValue"] = int(bin(pokemon["personalityF"] ^ pokemon["personalityL"] ^ trainer_info["tid"] ^ trainer_info["sid"])[2:], 2) # https://bulbapedia.bulbagarden.net/wiki/Personality_value#Shininess
if pokemon["shinyValue"] < 8: pokemon["shiny"] = True
else: pokemon["shiny"] = False
pokemon["enrichedMoves"] = []
for move in pokemon["moves"]:
pokemon["enrichedMoves"].append(move_list[move])
if pokemon["pokerus"] != 0: # TODO get number of days infectious, see - https://bulbapedia.bulbagarden.net/wiki/Pok%C3%A9rus#Technical_information
if pokemon["pokerus"] % 10: pokemon["pokerusStatus"] = "infected"
else: pokemon["pokerusStatus"] = "cured"
else: pokemon["pokerusStatus"] = "none"
return pokemon
except Exception as e:
if args.dm:
debug_log.exception(str(e))
moves = pokemon["moves"]
debug_log.info(f"Moves: {moves}")
def language_id_to_iso_639(lang: int):
match lang:
case 1: return "en"
case 2: return "jp"
case 3: return "fr"
case 4: return "es"
case 5: return "de"
case 6: return "it"
def mem_getEmuInfo(): # Loop repeatedly to read emulator info from memory
try:
global emu_info, emu_speed, language
while True:
try:
emu_info_mmap = load_json_mmap(4096, "bizhawk_emu_info")
if emu_info_mmap:
if validate_emu_info(emu_info_mmap["emu"]):
emu_info = emu_info_mmap["emu"]
if emu_info_mmap["emu"]["emuFPS"]: emu_speed = emu_info_mmap["emu"]["emuFPS"]/60
if language == None:
language = language_id_to_iso_639(emu_info["language"])
debug_log.info(f"Language was set to {language}")
except Exception as e:
if args.dm: debug_log.exception(str(e))
continue
time.sleep(max((1/max(emu_speed,1))*0.016,0.002))
except Exception as e:
if args.d: debug_log.exception(str(e))
def mem_getTrainerInfo(): # Loop repeatedly to read trainer info from memory
global trainer_info
while True:
try:
trainer_info_mmap = load_json_mmap(4096, "bizhawk_trainer_info")
if trainer_info_mmap:
if validate_trainer_info(trainer_info_mmap["trainer"]):
if trainer_info_mmap["trainer"]["posX"] < 0: trainer_info_mmap["trainer"]["posX"] = 0
if trainer_info_mmap["trainer"]["posY"] < 0: trainer_info_mmap["trainer"]["posY"] = 0
trainer_info = trainer_info_mmap["trainer"]
time.sleep(max((1/max(emu_speed,1))*0.016,0.002))
except Exception as e:
if args.dm: debug_log.exception(str(e))
continue
def mem_getPartyInfo(): # Loop repeatedly to read party info from memory
global party_info
while True:
try:
party_info_mmap = load_json_mmap(8192, "bizhawk_party_info")
if party_info_mmap:
enriched_party_obj = []
for pokemon in party_info_mmap["party"]:
if validate_pokemon(pokemon):
pokemon = enrich_mon_data(pokemon)
enriched_party_obj.append(pokemon)
else: continue
party_info = enriched_party_obj
time.sleep(max((1/max(emu_speed,1))*0.016,0.002))
except Exception as e:
if args.dm: debug_log.exception(str(e))
continue
def mem_getOpponentInfo(): # Loop repeatedly to read opponent info from memory
global opponent_info, last_opponent_personality
while True:
try:
opponent_info_mmap = load_json_mmap(4096, "bizhawk_opponent_info")
if config["bot_mode"] == "starters":
if party_info: opponent_info = party_info[0]
elif opponent_info_mmap:
if validate_pokemon(opponent_info_mmap):
enriched_opponent_obj = enrich_mon_data(opponent_info_mmap["opponent"])
if enriched_opponent_obj:
opponent_info = enriched_opponent_obj
elif not opponent_info: opponent_info = json.loads(read_file("data/placeholder_pokemon.json"))
time.sleep(max((1/max(emu_speed,1))*0.016,0.002))
except Exception as e:
if args.d: debug_log.exception(str(e))
continue
def mem_sendInputs():
while True:
try:
press_input_mmap.seek(0)
press_input_mmap.write(bytes(json.dumps(press_input), encoding="utf-8"))
hold_input_mmap.seek(0)
hold_input_mmap.write(bytes(json.dumps(hold_input), encoding="utf-8"))
except Exception as e:
if args.d: debug_log.exception(str(e))
continue
time.sleep(0.001) #The less sleep the better but without sleep it will hit CPU hard
def httpServer(): # Run HTTP server to make data available via HTTP GET
try:
log = logging.getLogger('werkzeug')
if not args.d: log.setLevel(logging.ERROR)
server = Flask(__name__)
CORS(server)
@server.route('/trainer_info', methods=['GET'])