-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathStockpiler.py
More file actions
2044 lines (1855 loc) · 79.4 KB
/
Stockpiler.py
File metadata and controls
2044 lines (1855 loc) · 79.4 KB
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 os
import os.path
import time
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, ImageGrab, Image
import logging
import datetime
from pynput.mouse import Controller
import glob
import cv2
import numpy as np
from global_hotkeys import *
import csv
import re
from requests.sessions import Request
import xlsxwriter
from tksheet import Sheet
import requests
import threading
import pygetwindow as gw
# import keyboard
bestTextScale = 1.0
bestIconScale = 1.0
global stockpilename
global PopupWindow
global NewStockpileName
global StockpileNameEntry
global IconEntry
global IconName
global CurrentStockpileName
global IconPickerWindow
global IndOrCrateWindow
global FilterFrame
global LastStockpile
global tempicon
foxhole_height = 1080
foxhole_width = 1920
width_ratio = 1.0
height_ratio = 1.0
class items(object):
data = []
numbers = (('CheckImages//num0.png', "0"), ('CheckImages//num1.png', "1"), ('CheckImages//num2.png', "2"),
('CheckImages//num3.png', "3"), ('CheckImages//num4.png', "4"), ('CheckImages//num5.png', "5"),
('CheckImages//num6.png', "6"), ('CheckImages//num7.png', "7"), ('CheckImages//num8.png', "8"),
('CheckImages//num9.png', "9"), ('CheckImages//numk.png', "k+"))
stockpilecontents = []
sortedcontents = []
slimcontents = []
ThisStockpileName = ""
FoundStockpileTypeName = ""
UIimages = []
mouse = Controller()
current_mouse_position = mouse.position
if not os.path.exists("./logs"):
os.makedirs("./logs")
logfilename = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
logfilename = "logs/Stockpiler-log-" + logfilename + ".txt"
logging.basicConfig(filename=logfilename, format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO)
print("Log file created: " + logfilename)
logging.info(str(datetime.datetime.now()) + ' Log Created')
def get_file_directory(file):
return os.path.dirname(os.path.abspath(file))
# Log cleanup of any contents of logs folder older than 7 days
now = time.time()
cutoff = now - (7 * 86400)
files = os.listdir(os.path.join(get_file_directory(__file__), "logs"))
file_path = os.path.join(get_file_directory(__file__), "logs/")
for xfile in files:
if os.path.isfile(str(file_path) + xfile):
t = os.stat(str(file_path) + xfile)
c = t.st_ctime
if c < cutoff:
os.remove(str(file_path) + xfile)
logging.info(str(datetime.datetime.now()) + " " + str(xfile) + " log file deleted")
Version = "1.6.3"
StockpilerWindow = Tk()
StockpilerWindow.title('Stockpiler ' + Version)
# Window width is based on generated UI. If buttons change, width should change here.
StockpilerWindow.geometry("537x600")
# Width locked since button array doesn't adjust dynamically
StockpilerWindow.resizable(width=False, height=False)
StockpilerWindow.iconbitmap(default='Bmat.ico')
class menu(object):
iconrow = 1
experimentalResizing = IntVar()
iconcolumn = 0
lastcat = 0
itembuttons = []
icons = []
category = [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]
faction = [0, 0]
topscroll = 0
BotHost = StringVar()
BotPassword = StringVar()
BotGuildID = StringVar()
CSVExport = IntVar()
updateBot = IntVar()
XLSXExport = IntVar()
ImgExport = IntVar()
debug = IntVar()
Set = IntVar()
Learning = IntVar()
PickerX = -1
PickerY = -1
bindings = list()
grabshift = IntVar()
grabctrl = IntVar()
grabalt = IntVar()
grabhotkey = StringVar()
scanshift = IntVar()
scanctrl = IntVar()
scanalt = IntVar()
scanhotkey = StringVar()
grabhotkeystring = "f2"
scanhotkeystring = "f3"
grabmods = "000"
scanmods = "000"
menu.grabshift.set(0)
menu.grabctrl.set(0)
menu.grabalt.set(0)
menu.scanshift.set(0)
menu.scanctrl.set(0)
menu.scanalt.set(0)
menu.debug.set(0)
menu.experimentalResizing.set(0)
s = ttk.Style()
s.theme_use('alt')
s.configure("EnabledButton.TButton", background="gray")
s.configure("DisabledButton.TButton", background="red2")
# Manually disabled button is different color because it is retained regardless of category/faction disable/enable
s.configure("ManualDisabledButton.TButton", background="red4")
s.configure("EnabledCategory.TButton", background="gray")
s.configure("DisabledCategory.TButton", background="red2")
s.configure("EnabledFaction.TButton", background="gray")
s.configure("DisabledFaction.TButton", background="red2")
s.configure("TScrollbar", troughcolor="grey20", arrowcolor="grey20", background="gray", bordercolor="grey15")
s.configure("TFrame", background="black")
s.configure("TCanvas", background="black")
s.configure("TCheckbutton", background="black", foreground="grey75")
s.configure("TWindow", background="black")
s.map("TCheckbutton", foreground=[('!active', 'grey75'),('pressed', 'black'),
('active', 'black'), ('selected', 'green'), ('alternate', 'purple')],
background=[ ('!active','black'),('pressed', 'grey75'), ('active', 'white'),
('selected', 'cyan'), ('alternate', 'pink')],
indicatorcolor=[('!active', 'black'),('pressed', 'black'), ('selected','grey75')],
indicatorbackground=[('!active', 'green'),('pressed', 'pink'), ('selected','red')])
s.configure('TNotebook', background="grey25", foreground="grey15", borderwidth=0)
s.map('TNotebook.Tab', foreground=[('active', 'black'), ('selected', 'black')],
background=[('active', 'grey80'), ('selected', 'grey65')])
s.configure("TNotebook.Tab", background="grey40", foreground="black", borderwidth=0)
s.configure('TRadiobutton', background='black', indicatorbackground='blue',
indicatorcolor='grey20', foreground='grey75', focuscolor='grey20')
s.map("TRadiobutton", foreground=[('!active', 'grey75'),('pressed', 'black'), ('active', 'black'),
('selected', 'green'), ('alternate', 'purple')],
background=[ ('!active','black'),('pressed', 'grey15'), ('active', 'white'),
('selected', 'cyan'), ('alternate', 'pink')])
s.configure("TLabel", background="black", foreground="grey75")
global hotkey
global listener
global vkclean
global vkorchar
global keyname
global justkey
global counter
global TargetDistanceEntry
global threadnum
counter = 1
threadnum = 1
filter = []
# Load contents of ItemNumbering.csv into items.data
# Adds all fields (columns) even though only a few are used
with open('ItemNumbering.csv', 'rt') as f_input:
csv_input = csv.reader(f_input, delimiter=',')
# Skips first line
header = next(csv_input)
# Skips reserved line
reserved = next(csv_input)
for rowdata in csv_input:
items.data.append(rowdata)
if os.path.exists("UI//" + str(rowdata[0]) + ".png"):
items.UIimages.append((rowdata[0], "UI//" + str(rowdata[0]) + ".png"))
# Load filter values into new array
with open('Filter.csv', 'rt') as f_input:
csv_input = csv.reader(f_input, delimiter=',')
# Skips first line
header = next(csv_input)
for rowdata in csv_input:
filter.append(rowdata)
# Matches up filter value with appropriate items in items.data
# for filteritem in range(len(filter)):
for item in range(len(items.data)):
items.data[item].append(0)
for filteritem in range(len(filter)):
# print(filter[filteritem])
try:
# print(filter[filteritem])
for item in range(len(items.data)):
if filter[filteritem][0] == items.data[item][0]:
items.data[item][19] = filter[filteritem][1]
# items.data[item].extend(filter[filteritem][1])
except Exception as e:
print("Exception: ", e)
print("failed to apply filters to items.data")
### For troubleshooting
# data[item].extend(filter[item][1])
# print(data)
# Names = [item[3] for item in data]
# print(Names)
class CreateToolTip(object):
"""
create a tooltip for a given widget
"""
def __init__(self, widget, text='widget info'):
self.waittime = 100 #miliseconds before popup appear
self.wraplength = 180 #pixels
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x, y = mouse.position
# have popup slightly offset from mouse
x += 15
y += 15
# creates a toplevel window
self.tw = Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = ttk.Label(self.tw, text=self.text, justify='left',
relief='ridge', borderwidth=5, background="grey25", foreground="white",
wraplength = self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw= None
if tw:
tw.destroy()
# Function used simply for grabbing cropped stockpile images
# Helpful for grabbing test images for assembling missing icons or new sets of icons (for modded icons)
def GrabStockpileImage():
global counter
global bestTextScale
global bestIconScale
global foxhole_height
global foxhole_width
global width_ratio
global height_ratio
# OKAY, so you'll have to grab the whole screen, detect that thing in the upper left, then use that as a basis
# for cropping that full screenshot down to just the foxhole window
threshold = .95
if (menu.experimentalResizing.get() == 1):
print("==============EXPERIMENTAL RESIZING==============")
window = gw.getWindowsWithTitle("War")
if (len(window) > 0):
foxhole_height = window[0].height - 39
foxhole_width = window[0].width - 16
else:
print("[Warning: !!!] Foxhole window not detected")
print(f"Foxhole screen size is: {foxhole_width}x{foxhole_height}")
width_ratio = foxhole_width / 1920
height_ratio = foxhole_height / 1080
print(f"Screen Ratio to original 1920x1080: {width_ratio}x{height_ratio}")
screen = np.array(ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=True))
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
numbox = cv2.imread('CheckImages//StateOf.png', cv2.IMREAD_GRAYSCALE)
best_score = None
res = None
if (menu.experimentalResizing.get() == 1):
if (foxhole_height == 1080): bestTextScale = 1.0
elif (not bestTextScale):
best_score, bestTextScale, res = matchTemplateBestScale(screen, numbox, numtimes=20)
else:
bestTextScale = 1.0
if (not best_score):
if (menu.experimentalResizing.get() == 1): numbox = cv2.resize(numbox, (int(numbox.shape[1]*bestTextScale), int(numbox.shape[0]*bestTextScale)))
res = cv2.matchTemplate(screen, numbox, cv2.TM_CCOEFF_NORMED)
best_score = np.amax(res)
print("Best scale for TEXT is: " + str(bestTextScale) + " with a score of: " + str(best_score))
threshold = .7
if best_score > threshold:
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
statex, statey = max_loc
margin_ratioed = 35 * height_ratio
if statey - margin_ratioed >= 0:
statey = statey - margin_ratioed
else:
statey = 0
if statex - margin_ratioed >= 0:
statex = statex - margin_ratioed
else:
statex = 0
screen = screen[int(statey):int(statey + (1079 * height_ratio)), int(statex):int(statex + (1919 * width_ratio))]
if menu.debug.get() == 1:
cv2.imshow("Grabbed in image GrabStockpileImage", screen)
cv2.waitKey(0)
if menu.Set.get() == 0:
findshirtC = cv2.imread('CheckImages//Default//86C.png', cv2.IMREAD_GRAYSCALE)
findshirt = cv2.imread('CheckImages//Default//86.png', cv2.IMREAD_GRAYSCALE)
else:
findshirtC = cv2.imread('CheckImages//Modded//86C.png', cv2.IMREAD_GRAYSCALE)
findshirt = cv2.imread('CheckImages//Modded//86.png', cv2.IMREAD_GRAYSCALE)
# Shirts are always in the same spot in every stockpile, but might be single or crates
if (menu.experimentalResizing.get() == 1):
if (bestIconScale == None):
if (foxhole_height == 1080):
bestIconScale = 1.0
print("Best scale for ITEM ICONS is: " + str(bestIconScale))
else:
best_score, bestIconScale, resC = matchTemplateBestScale(screen, findshirtC, numtimes=20)
print("Best scale for ITEM ICONS is: " + str(bestIconScale) + " with a score of: " + str(best_score))
else:
print("Best scale for ITEM ICONS is: " + str(bestIconScale))
findshirtC = cv2.resize(findshirtC, (int(findshirtC.shape[1]*bestIconScale), int(findshirtC.shape[0]*bestIconScale)))
findshirt = cv2.resize(findshirt, (int(findshirt.shape[1]*bestIconScale), int(findshirt.shape[0]*bestIconScale)))
try:
resC = cv2.matchTemplate(screen, findshirtC, cv2.TM_CCOEFF_NORMED)
except Exception as e:
print("Exception: ", e)
print("Maybe you don't have the shirt crate")
logging.info(str(datetime.datetime.now()) + " Exception loading shirt crate icon in GrabStockpileImage " + str(e))
try:
res = cv2.matchTemplate(screen, findshirt, cv2.TM_CCOEFF_NORMED)
except Exception as e:
print("Exception: ", e)
print("Maybe you don't have the individual shirt")
logging.info(str(datetime.datetime.now()) + " Exception loading individual shirt icon in GrabStockpileImage " + str(e))
threshold = .99
FoundShirt = False
try:
if np.amax(res) > threshold:
print("Found Shirts")
y, x = np.unravel_index(res.argmax(), res.shape)
FoundShirt = True
except Exception as e:
print("Exception: ", e)
print("Don't have the individual shirts icon or not looking at a stockpile")
logging.info(str(datetime.datetime.now()) + " Exception finding individual shirt icon in GrabStockpileImage " + str(e))
try:
if np.amax(resC) > threshold:
print("Found Shirt Crate")
y, x = np.unravel_index(resC.argmax(), resC.shape)
FoundShirt = True
except Exception as e:
print("Exception: ", e)
print("Don't have the shirt crate icon or not looking at a stockpile")
logging.info(str(datetime.datetime.now()) + " Exception finding shirt crate icon in GrabStockpileImage " + str(e))
if not FoundShirt:
print("Found nothing. Either don't have shirt icon(s) or not looking at a stockpile")
y = 0
x = 0
# If no stockpile was found, don't bother taking a screenshot, else crop based on where shirts were found
if x == 0 and y == 0:
print("Both 0's")
pass
else:
stockpile = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)
stockpile = stockpile[int(y) - 32:int(y) + 1080, int(x) - 11:int(x) + 589]
imagename = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
fullimagename = 'test_' + imagename + '.png'
cv2.imwrite(fullimagename, stockpile)
logging.info(str(datetime.datetime.now()) + " Saved image with GrabStockpileImage named " + fullimagename)
else:
print("No State of the War detected in top left corner. Either it is covered by something (Stockpiler maybe?)"
" or the map is not open")
def Learn(LearnInt, image):
global counter
global IconName
global LastStockpile
# grab whole screen and prepare for template matching
# COMMENT OUT THESE TWO LINES IF YOU ARE TESTING A SPECIFIC IMAGE
TestImage = False
# WHEN USING OTHER RESOLUTIONS, GRAB THEM HERE
resx = 1920
resy = 1080
try:
# OKAY, so you'll have to grab the whole screen, detect that thing in the upper left, then use that as a basis
# for cropping that full screenshot down to just the foxhole window
screen = np.array(ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=True))
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
numbox = cv2.imread('CheckImages//StateOf.png', cv2.IMREAD_GRAYSCALE)
res = cv2.matchTemplate(screen, numbox, cv2.TM_CCOEFF_NORMED)
threshold = .95
if np.amax(res) > threshold:
stateloc = np.where(res >= threshold)
if stateloc[0].astype(int) - 35 >= 0:
statey = stateloc[0].astype(int) - 35
else:
statey = 0
if stateloc[1].astype(int) - 35 >= 0:
statex = stateloc[1].astype(int) - 35
else:
statex = 0
# If/when it moves to multiple resolutions, these hardcoded sizes will need to be variables
screen = screen[int(statey):int(statey) + resy, int(statex):int(statex) + resx]
print("It thinks it found the window position in Learn and is grabbing location: X:", str(statex), " Y:", str(statey))
if menu.debug.get() == 1:
cv2.imshow('Grabbed in Learn, found State of War', screen)
cv2.waitKey(0)
else:
print("State of the War not found in Learn. It may be covered up or you're not on the map.")
if menu.debug.get() == 1:
cv2.imshow('Grabbed in Learn, did NOT find State of War', screen)
cv2.waitKey(0)
except Exception as e:
print("Exception: ", e)
print("Failed to grab the screen in Learn")
logging.info(str(datetime.datetime.now()) + " Failed Grabbing the screen in Learn " + str(e))
# UNCOMMENT AND MODIFY LINE BELOW IF YOU ARE TESTING A SPECIFIC IMAGE
# screen = cv2.cvtColor(np.array(Image.open("test_2021-11-25-110247.png")), cv2.COLOR_RGB2GRAY)
# TestImage = True
if LearnInt != "":
pass
else:
screen = LastStockpile
numbox = cv2.imread('CheckImages//NumBox.png', cv2.IMREAD_GRAYSCALE)
res = cv2.matchTemplate(screen, numbox, cv2.TM_CCOEFF_NORMED)
threshold = .99
if np.amax(res) > threshold:
numloc = np.where(res >= threshold)
print("found them here:", numloc)
print(len(numloc[0]))
for spot in range(len(numloc[0])):
# Stockpiles never displayed in upper left under State of the War area
# State of the War area throws false positives for icons
if numloc[1][spot] < (resx * .2) and numloc[0][spot] < (resy * .24) and not TestImage:
pass
else:
print("x:", numloc[1][spot], " y:",numloc[0][spot])
# cv2.imshow('icon', screen[int(numloc[0][spot]+2):int(numloc[0][spot]+36), int(numloc[1][spot]-38):numloc[1][spot]-4])
# cv2.waitKey(0)
currenticon = screen[int(numloc[0][spot]+2):int(numloc[0][spot]+36), int(numloc[1][spot]-38):numloc[1][spot]-4]
print("currenticon:", currenticon.shape)
if menu.Set.get() == 0:
folder = "CheckImages//Default//"
else:
folder = "CheckImages//Modded//"
Found = False
for imagefile in os.listdir(folder):
checkimage = cv2.imread(folder + imagefile, cv2.IMREAD_GRAYSCALE)
print("Checking for ", str(imagefile))
result = cv2.matchTemplate(currenticon, checkimage, cv2.TM_CCOEFF_NORMED)
threshold = .99
if np.amax(result) > threshold:
#print("Found:", imagefile)
Found = True
break
if not Found:
print("Not found, should launch IconPicker")
IconCatPicker(currenticon, 0)
# IconPicker(currenticon)
SearchImage(1, screen)
CreateButtons("blah")
else:
print("Found no numboxes, which is very strange")
if menu.debug.get() == 1:
cv2.imshow("No numboxes?", screen)
cv2.waitKey(0)
import numpy as np
import cv2
def matchTemplateBestScale(screen, icon, method=cv2.TM_CCOEFF_NORMED, numtimes=10):
print("Finding best scale to resize icons, this may take a while...")
best_score = -np.inf
best_scale = None
final_res = None
scales=None
if (foxhole_height < 1080):
scales = np.linspace(0.5, 1.0, numtimes)[::-1]
else:
scales = np.linspace(1.0, 2.0, numtimes)[::-1]
for scale in scales:
# resize the icon according to the scale
icon_resized = cv2.resize(icon, (int(icon.shape[1]*scale), int(icon.shape[0]*scale)))
# if the resized icon is larger than the screen, skip this scale
if icon_resized.shape[0] > screen.shape[0] or icon_resized.shape[1] > screen.shape[1]:
continue
res = cv2.matchTemplate(screen, icon_resized, method)
score = np.amax(res)
if score > best_score:
best_score = score
best_scale = scale
final_res = res
return best_score, best_scale, final_res
def SearchImage(Pass, LearnImage):
global stockpilename
global NewStockpileName
global PopupWindow
global CurrentStockpileName
global threadnum
global foxhole_height
global foxhole_width
global height_ratio
global width_ratio
global bestTextScale
screen = None
if Pass != "":
screen = LearnImage
else:
try:
if (menu.experimentalResizing.get() == 1):
print("==============EXPERIMENTAL RESIZING==============")
window = gw.getWindowsWithTitle("War")
if (len(window) > 0):
foxhole_height = window[0].height - 39
foxhole_width = window[0].width - 16
else:
print("[Warning: !!!] Foxhole window not detected")
print(f"Foxhole screen size is: {foxhole_width}x{foxhole_height}")
width_ratio = foxhole_width / 1920
height_ratio = foxhole_height / 1080
print(f"Screen Ratio to original 1920x1080: {width_ratio}x{height_ratio}")
# OKAY, so you'll have to grab the whole screen, detect that thing in the upper left, then use that as a basis
# for cropping that full screenshot down to just the foxhole window
screen = np.array(ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=True))
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
numbox = cv2.imread('CheckImages//StateOf.png', cv2.IMREAD_GRAYSCALE)
best_score = None
res = None
if (menu.experimentalResizing.get() == 1):
if (foxhole_height == 1080): bestTextScale = 1.0
elif (not bestTextScale):
best_score, bestTextScale, res = matchTemplateBestScale(screen, numbox, numtimes=20)
else:
bestTextScale = 1.0
if (not best_score):
if (menu.experimentalResizing.get() == 1): numbox = cv2.resize(numbox, (int(numbox.shape[1]*bestTextScale), int(numbox.shape[0]*bestTextScale)))
res = cv2.matchTemplate(screen, numbox, cv2.TM_CCOEFF_NORMED)
best_score = np.amax(res)
print("Best scale for TEXT is: " + str(bestTextScale) + " with a score of: " + str(best_score))
threshold = .7
if best_score > threshold:
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
statex, statey = max_loc
margin_ratioed = 35 * height_ratio
if statey - margin_ratioed >= 0:
statey = statey - margin_ratioed
else:
statey = 0
if statex - margin_ratioed >= 0:
statex = statex - margin_ratioed
else:
statex = 0
screen = screen[int(statey):int(statey + (1079 * height_ratio)), int(statex):int(statex + (1919 * width_ratio))]
print("It thinks it found the window position in SearchImage and is grabbing location: X:", str(statex),
" Y:", str(statey))
if menu.debug.get() == 1:
cv2.imshow('Grabbed in SearchImage', screen)
cv2.waitKey(0)
else:
print("State of the War not found in SearchImage. It may be covered up or you're not on the map.")
if menu.debug.get() == 1:
cv2.imshow('Grabbed in SearchImage, did NOT find State of War', screen)
cv2.waitKey(0)
except Exception as e:
print("Exception: ", e)
print("Failed to grab the screen in SearchImage")
logging.info(str(datetime.datetime.now()) + " Failed Grabbing the screen in SearchImage " + str(e))
garbage = "blah"
args = (screen, garbage)
# Threading commands are generated via text since each thread needs a distinct name, created using threadcounter
threadcounter = "t" + str(threadnum)
# print(threadcounter)
logging.info(str(datetime.datetime.now()) + " Starting scan thread: " + str(threadcounter))
threadingthread = threadcounter + " = threading.Thread(target = ItemScan, args = args)"
threadingdaemon = threadcounter + ".daemon = True"
threadingstart = threadcounter + ".start()"
# print(threadnum)
exec(threadingthread)
exec(threadingdaemon)
exec(threadingstart)
threadnum += 1
def ItemScan(screen, garbage):
global LastStockpile
global bestTextScale
global bestIconScale
resC = None
res = None
if menu.Set.get() == 0:
findshirtC = cv2.imread('CheckImages//Default//86C.png', cv2.IMREAD_GRAYSCALE)
findshirt = cv2.imread('CheckImages//Default//86.png', cv2.IMREAD_GRAYSCALE)
if (menu.experimentalResizing.get() == 1):
if (bestIconScale == None):
if (foxhole_height == 1080):
bestIconScale = 1.0
print("Best scale for ITEM ICONS is: " + str(bestIconScale))
else:
best_score, bestIconScale, resC = matchTemplateBestScale(screen, findshirtC, numtimes=20)
print("Best scale for ITEM ICONS is: " + str(bestIconScale) + " with a score of: " + str(best_score))
else:
print("Best scale for ITEM ICONS is: " + str(bestIconScale))
findshirtC = cv2.resize(findshirtC, (int(findshirtC.shape[1]*bestIconScale), int(findshirtC.shape[0]*bestIconScale)))
findshirt = cv2.resize(findshirt, (int(findshirt.shape[1]*bestIconScale), int(findshirt.shape[0]*bestIconScale)))
else:
try:
findshirtC = cv2.imread('CheckImages//Modded//86C.png', cv2.IMREAD_GRAYSCALE)
except Exception as e:
print("Exception: ", e)
print("You don't have the Shirt crate yet in ItemScan")
logging.info(str(datetime.datetime.now()) + " Failed loading modded shirt crate icon in ItemScan " + str(e))
try:
findshirt = cv2.imread('CheckImages//Modded//86.png', cv2.IMREAD_GRAYSCALE)
except Exception as e:
print("Exception: ", e)
print("You don't have the individual Shirt yet in ItemScan")
logging.info(str(datetime.datetime.now()) + " Failed loading modded individual shirt icon in ItemScan " + str(e))
try:
if (resC == None): resC = cv2.matchTemplate(screen, findshirtC, cv2.TM_CCOEFF_NORMED)
except Exception as e:
print("Exception: ", e)
print("Looks like you're missing the shirt crate in ItemScan")
logging.info(str(datetime.datetime.now()) + " Maybe missing shirt crate icon in ItemScan " + str(e))
try:
res = cv2.matchTemplate(screen, findshirt, cv2.TM_CCOEFF_NORMED)
except Exception as e:
print("Exception: ", e)
print("Looks like you're missing the individual shirts in ItemScan")
logging.info(str(datetime.datetime.now()) + " Maybe missing individual shirt icon in ItemScan " + str(e))
threshold = .9
FoundShirt = False
try:
if np.amax(res) > threshold:
print("Found Shirts")
y, x = np.unravel_index(res.argmax(), res.shape)
FoundShirt = True
except Exception as e:
print("Exception: ", e)
print("Don't have the individual shirts icon or not looking at a stockpile in ItemScan")
logging.info(str(datetime.datetime.now()) + " Don't have the individual shirts icon or not looking at a stockpile in ItemScan " + str(e))
try:
if np.amax(resC) > threshold:
print("Found Shirt Crate")
#print(np.amax(resC))
y, x = np.unravel_index(resC.argmax(), resC.shape)
FoundShirt = True
except Exception as e:
print("Exception: ", e)
print("Don't have the shirt crate icon or not looking at a stockpile in ItemScan")
logging.info(str(datetime.datetime.now()) + " Don't have the shirt crate icon or not looking at a stockpile in ItemScan " + str(e))
if not FoundShirt:
print("Found nothing. Either don't have shirt icon(s) or not looking at a stockpile in ItemScan")
y = 0
x = 0
# COMMENT OUT IF TESTING A SPECIFIC IMAGE
if y == x == 0:
stockpile = screen
else:
stockpile = screen[y - 32:1080, x - 11:x + 589]
if menu.debug.get() == 1:
cv2.imshow('Stockpile in this image in ItemScan?', stockpile)
cv2.waitKey(0)
# UNCOMMENT IF TESTING A SPECIFIC IMAGE
# stockpile = screen
# Grab this just in case you need to rerun the scan from Results tab
# LastStockpile = stockpile
LastStockpile = screen
# Image clips for each type of stockpile should be in this array below
StockpileTypes = (('CheckImages//Seaport.png', 'Seaport', 0), ('Checkimages//StorageDepot.png', 'Storage Depot', 1),
('Checkimages//Outpost.png', 'Outpost', 2), ('Checkimages//Townbase.png', 'Town Base', 3),
('Checkimages//RelicBase.png', 'Relic Base', 4),
('Checkimages//BunkerBase.png', 'Bunker Base', 5),
('Checkimages//Encampment.png', 'Encampment', 6),
('Checkimages//SafeHouse.png', 'Safe House', 7))
# Check cropped stockpile image for each location type image
FoundStockpileType = None
FoundStockpileTypeName = None
highestScore = 0
y = 0
x = 0
for image in StockpileTypes:
try:
findtype = cv2.imread(image[0], cv2.IMREAD_GRAYSCALE)
if menu.debug.get() == 1:
cv2.imshow("Looking for this", findtype)
cv2.waitKey(0)
if (menu.experimentalResizing.get() == 1): findtype = cv2.resize(findtype, (int(findtype.shape[1]*bestTextScale), int(findtype.shape[0]*bestTextScale)))
res = cv2.matchTemplate(stockpile, findtype, cv2.TM_CCOEFF_NORMED)
# Threshold is a bit lower for types as they are slightly see-thru
typethreshold = .65
score = np.amax(res)
#print("Checking:", image[1])
#print(score)
if (score > typethreshold and score > highestScore):
highestScore = score
y, x = np.unravel_index(res.argmax(), res.shape)
FoundStockpileType = image[2]
FoundStockpileTypeName = image[1]
except Exception as e:
print("Exception: ", e)
print("Probably not looking at a stockpile or don't have the game open. Looked for: ", str(image))
FoundStockpileType = None
ThisStockpileName = None
logging.info(str(datetime.datetime.now()) + " Probably not looking at a stockpile or don't have the game open.")
logging.info(str(datetime.datetime.now()) + " Looked for: ", str(image) + str(e))
pass
if (FoundStockpileType != None):
if FoundStockpileTypeName == "Seaport" or FoundStockpileTypeName == "Storage Depot":
findtab = cv2.imread('CheckImages//Tab.png', cv2.IMREAD_GRAYSCALE)
if (menu.experimentalResizing.get() == 1): findtab = cv2.resize(findtab, (int(findtab.shape[1]*bestTextScale), int(findtab.shape[0]*bestTextScale)))
res = cv2.matchTemplate(stockpile, findtab, cv2.TM_CCOEFF_NORMED)
tabthreshold = .6
cv2.imwrite('stockpile.jpg', stockpile)
if np.amax(res) > tabthreshold:
print("Found the Tab")
y, x = np.unravel_index(res.argmax(), res.shape)
# Seaports and Storage Depots have the potential to have named stockpiles, so grab the name
#print("bestTextScale:" + str(bestTextScale))
stockpilename = stockpile[int(y - 5*bestTextScale):int(y + 17*bestTextScale), int(x - 150*bestTextScale):int(x - 8*bestTextScale)]
# Make a list of all current stockpile name images
currentstockpiles = glob.glob("Stockpiles/*.png")
# print(currentstockpiles)
found = 0
for image in currentstockpiles:
stockpilelabel = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
if not image.endswith("image.png"):
res = cv2.matchTemplate(stockpilename, stockpilelabel, cv2.TM_CCOEFF_NORMED)
threshold = .97
flag = False
if np.amax(res) > threshold:
# Named stockpile is one already seen
found = 1
ThisStockpileName = (image[11:(len(image) - 4)])
if found != 1:
newstockpopup(stockpilename)
PopupWindow.wait_window()
if NewStockpileName == "" or NewStockpileName.lower() == "public":
popup("BlankName")
ThisStockpileName = "TheyLeftTheStockpileNameBlank"
else:
# NewStockpileFilename = 'Stockpiles//' + NewStockpileName + '.png'
# It's a new stockpile, so save an images of the name as well as the cropped stockpile itself
cv2.imwrite('Stockpiles//' + NewStockpileName + '.png', stockpilename)
if menu.ImgExport.get() == 1:
cv2.imwrite('Stockpiles//' + NewStockpileName + ' image.png', stockpile)
ThisStockpileName = NewStockpileName
else:
# It's not a named stockpile, so just call it by the type of location (Bunker Base, Encampment, etc)
print("Didn't find the Tab, so it looks like it's not a named stockpile")
ThisStockpileName = FoundStockpileTypeName
else:
# It's not a named stockpile, so just call it by the type of location (Bunker Base, Encampment, etc)
print("Not a named stockpile, it's a Bunker Base, Encampment, something like that")
ThisStockpileName = FoundStockpileTypeName
# StockpileName = StockpileNameEntry.get()
# cv2.imwrite('Stockpiles//' + StockpileName + '.png', stockpilename)
else:
# print("Didn't find",image[1])
print("Doesn't look like any known stockpile type")
FoundStockpileType = "None"
ThisStockpileName = "None"
pass
# These stockpile types allow for crates (ie: Seaport)
CrateList = [0, 1]
# These stockpile types only allow individual items (ie: Bunker Base)
SingleList = [2, 3, 4, 5, 6, 7]
start = datetime.datetime.now()
print(ThisStockpileName)
if ThisStockpileName == "TheyLeftTheStockpileNameBlank":
pass
else:
if menu.Set.get() == 0:
folder = "CheckImages//Default//"
else:
folder = "CheckImages//Modded//"
if ThisStockpileName != "None":
if menu.ImgExport.get() == 1:
cv2.imwrite('Stockpiles//' + ThisStockpileName + ' image.png', stockpile)
if FoundStockpileType in CrateList:
print("Crate Type")
# Grab all the crate CheckImages
#print(item)
#print(items.data[1])
StockpileImages = [(str(item[0]), folder + str(item[0]) + "C.png", (item[3] + " Crate"), item[8], item[12]) for item in items.data if str(item[19]) == "0"]
#print(StockpileImages)
# Grab all the individual vehicles and shippables, make sure the two if's are the right category. Was incorrectly set to 7 (uniforms) and 8 (vehicles) instead of 8 (vecicles) and 9 (shippables)
StockpileImagesAppend = [(str(item[0]), folder + str(item[0]) + ".png", item[3], item[8], item[11]) for item in items.data if (str(item[9]) == "8" and str(item[19]) == "0") or (str(item[9]) == "9" and str(item[19]) == "0")]
StockpileImages.extend(StockpileImagesAppend)
#print(StockpileImages)
#print("Checking for:", StockpileImages)
elif FoundStockpileType in SingleList:
print("Single Type")
# Grab all the individual items
# for item in range(len(items.data)):
# print(item)
StockpileImages = [(str(item[0]), folder + str(item[0]) + ".png", item[3], item[8], item[11]) for item in items.data]
#print("Checking for:", StockpileImages)
else:
print("No idea what type...")
stockpilecontents = []
checked = 0
#print("StockpileImages", StockpileImages)
numbers = {}
for number in items.numbers:
findnum = cv2.imread(number[0], cv2.IMREAD_GRAYSCALE)
if (menu.experimentalResizing.get() == 1 and bestIconScale != 1.0):
findnum = cv2.resize(findnum, (int(findnum.shape[1] * bestIconScale), int(findnum.shape[0] * bestIconScale)))
numbers[number[1]] = findnum
threshold = .98 if (menu.experimentalResizing.get() == 1 and foxhole_height != 1080) else .99
for image in StockpileImages:
checked += 1
if str(image[4]) == '1':
if os.path.exists(image[1]):
try:
findimage = cv2.imread(image[1], cv2.IMREAD_GRAYSCALE)
if (menu.experimentalResizing.get() == 1 and bestIconScale != 1.0): findimage = cv2.resize(findimage, (int(findimage.shape[1] * bestIconScale), int(findimage.shape[0] * bestIconScale)), interpolation=cv2.INTER_LANCZOS4)
res = cv2.matchTemplate(stockpile, findimage, cv2.TM_CCOEFF_NORMED)
#if (image[0] == "46"):
# print("Item" + repr(np.amax(res)))
#elif (image[0] == "92"):
# print("Item" + repr(np.amax(res)))
#elif (image[0] == "279"):
# print("Item" + repr(np.amax(res)))
flag = False
if np.amax(res) > threshold:
#print(image[1] + ": " + str(np.amax(res)))
flag = True
y, x = np.unravel_index(res.argmax(), res.shape)
# Found a thing, now find amount
numberlist = []
numberarea = stockpile[int(y+8*bestTextScale):int(y+28*bestTextScale), int(x+45*bestTextScale):int(x+87*bestTextScale)]
for number in items.numbers:
# Clip the area where the stock number will be
resnum = cv2.matchTemplate(numberarea, numbers[number[1]], cv2.TM_CCOEFF_NORMED)
threshold = .9
numloc = np.where(resnum >= threshold)
# It only looks for up to 3 of each number for each item, since after that it would be a "k+" scenario, which never happens in stockpiles
# This will need to be changed to allow for more digits whenever it does in-person looks at BB stockpiles and such, where it will show up to 5 digits
if len(numloc[1]) > 0:
numberlist.append(tuple([numloc[1][0],number[1]]))
if len(numloc[1]) > 1:
numberlist.append(tuple([numloc[1][1],number[1]]))
if len(numloc[1]) > 2:
numberlist.append(tuple([numloc[1][2],number[1]]))
# Sort the list of numbers by position closest to the left, putting the numbers in order by extension
numberlist.sort(key=lambda y: y[0])
# If the number ends in a K, it just adds 000 since you don't know if that's 1001 or 1999
# k+ never happens in stockpiles, so this only affects town halls, bunker bases, etc
quantity = 0
if len(numberlist) == 1:
quantity = int(str(numberlist[0][1]))
elif len(numberlist) == 2:
if numberlist[1][1] == "k+":
quantity = int(str(numberlist[0][1]) + "000")
else:
quantity = int(str(numberlist[0][1]) + (str(numberlist[1][1])))
elif len(numberlist) == 3:
if numberlist[2][1] == "k+":
quantity = int(str(numberlist[0][1]) + (str(numberlist[1][1])) + "000")
else:
quantity = int(str(numberlist[0][1]) + (str(numberlist[1][1])) + str(numberlist[2][1]))
elif len(numberlist) == 4:
if numberlist[3][1] == "k+":
quantity = int(str(numberlist[0][1]) + (str(numberlist[1][1])) + str(numberlist[2][1]) + "000")
else:
quantity = int(str(numberlist[0][1]) + (str(numberlist[1][1])) + str(numberlist[2][1]) + str(numberlist[3][1]))
# place shirts first, since they're always at the top of every stockpile
if image[0] == "86":
itemsort = 0
# bunker supplies next
elif image[0] == "93":
itemsort = 1
# garrison supplies last
elif image[0] == "90":
itemsort = 2
elif image[3] != "Vehicle" and image[3] != "Shippables":
itemsort = 5
elif image[3] == "Vehicle":
itemsort = 10
else:
itemsort = 15
if image[1][(len(image[1])-5):(len(image[1])-4)] == "C":
stockpilecontents.append(list((image[0], image[2], quantity, itemsort, 1)))
else:
stockpilecontents.append(list((image[0], image[2], quantity, itemsort, 0)))
except Exception as e:
print("Exception: ", e)
if menu.debug.get() == 1: