forked from GloXFX/wizAPI
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwizAPI.py
More file actions
2059 lines (1752 loc) · 79.5 KB
/
wizAPI.py
File metadata and controls
2059 lines (1752 loc) · 79.5 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 win32gui
import os
import pyautogui
import cv2
import time
import numpy
import ctypes
# import only system from os
from os import system, name
class wizAPI:
def __init__(self, handle=None):
self._handle = handle
self._spell_memory = {}
self._friends_area = (625, 65, 20, 240)
self._spell_area = (245, 290, 370, 70)
self._enemy_area = (68, 26, 650, 35)
self._friendly_area = (136, 536, 650, 70)
self._login_area = (307,553+36,187,44)
region_offset = (5,5,0,0)
def wait(self, s):
""" Alias for time.sleep() that return self for function chaining """
time.sleep(s)
return self
# define our clear function
def clear_console(self):
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
def register_window(self, name="Wizard101", nth=0):
""" Assigns the instance to a wizard101 window (Required before using any other API functions) """
def win_enum_callback(handle, param):
if name == str(win32gui.GetWindowText(handle)):
param.append(handle)
handles = []
# Get all windows with the name "Wizard101"
win32gui.EnumWindows(win_enum_callback, handles)
handles.sort()
# Assigns the one at index nth
self._handle = handles[nth]
return self
def is_active(self):
""" Returns true if the window is focused """
return self._handle == win32gui.GetForegroundWindow()
def set_active(self):
""" Sets the window to active if it isn't already """
if not self.is_active():
""" Press alt before and after to prevent a nasty bug """
pyautogui.press('alt')
win32gui.SetForegroundWindow(self._handle)
pyautogui.press('alt')
return self
def is_teamup_at(self,pos=0):
""" Returns true if there is a teamup option available in window n (0-5)"""
self.set_active()
if (0 <= pos <=5):
#check if pixel value of line is a shade of red
#if yes, return true
#if no, return false
#32pixles * pos should give correct offset
return self.pixel_matches_color(coords=(500,262+32*pos),rgb=(135, 36, 64),threshold=10)
else:
return False
def select_teamup_at(self,pos=0):
self.set_active()
if (0 <= pos <=6):
#check if pixel value of line is a shade of red
#if yes, return true
#if no, return false
#32pixles * pos should give correct offset
return self.click(500,262+32*pos)
else:
#Do nothing
return self
""" DRIVER FOR TEAMUP BOT"""
successful_teamups = 0
def join_teamup(self,world=0,page=0,school="Fire"):
self.successful_teamups +=1
#quicksell after N rounds
if(self.successful_teamups % 10 == 0):
self.quick_sell(False, False)
self.wait(1)
#Wait for kiosk to prompt user to press x
self.reset_teamup_kiosk()
while not self.is_on_kiosk():
self.wait(.1)
#boot-up teamup kiosk
#print("Pressing x on terminal")
self.press_key('x').wait(1)
# Navigate and load up desired world for teamup
self.select_world_teamup(pos=world,page=0)
#move mouse out of the way of CV
self.move_mouse(535,492,speed=.1)
#load the list of displayed dungeons
teamup_availability = self.give_teamup_available()
#refresh page until team availability contains at least 1 true
while (not any(teamup_availability)):
self.wait(1)
self.teamup_refresh()
teamup_availability = self.give_teamup_available()
#try to join first available non-long team
# finding first True value
# using next() and enumerate()
teamup_index = next((i for i, j in enumerate(teamup_availability) if j), None)
self.select_teamup_at(teamup_index)
#checks if teamup icon is showing (in queue) or pet icon is missing (already loading in)
if(self.is_teamup_icon_showing() or (self.is_pet_icon_visible() is not False)):
#Great we are in
#wait for a lag in displaying the icon
self.wait(.5)
#wait until icon disappears (indicating loading screen into dungeon)
self.wait_for_teamup_queue()
self.wait(.1)
#print("Loading...")
if (self.is_teamup_canceled()):
#print("Teamup was canceled, restarting")
self.remove_queue_error_teamup().wait(1)
self.reset_teamup_kiosk()
return
if (self.is_refresh_showing()):
#refresh btn is showing so something errored out, restart program
#logout to reset kiosk 'x' prompt
self.reset_teamup_kiosk()
return
self.wait_pet_loading()
#print("In Dungeon")
self.clear_dialog()
self.move_mouse(717,40)
#wait for slow computer noobs to get in fight/load
#otherwise no credit
self.wait(.25)
#Walk forward until fight starts
while not self.is_turn_to_play():
self.hold_key('w', 1)
#print("In Fight")
#print("Next turn found")
inFight = True
battle_round = 0
while inFight:
self.mass_feint_attack_teamup(wizard_type = "hitter",boss_pos=0,hitter=school)
self.wait_for_end_of_round_dialog()
if self.is_idle():
inFight = False
if self.find_button('done'):
inFight = False
if self.find_button('more'):
inFight = False
#print("Battle 1 has ended")
self.wait(.5)
#remove any post-battle dialog (happens in few instances)
self.clear_dialog()
#potion managemant & use before teleporting home
if( not self.use_potion_if_needed_tp_house()):
#if no potion needed, just tp home
self.teleport_home()
self.wait_pet_loading()
return
else:
#Teamup no longer available, remove error & try again
#print("Team no longer joinable, restarting")
self.remove_queue_error_teamup().wait(1)
self.reset_teamup_kiosk()
#self.join_teamup(world=world,page=0)
return
def is_refresh_showing(self):
x, y = (523,474)#563,394
self.set_active()
large = self.screenshotRAM((x,y,19,24))
result = self.match_image(largeImg=large, smallImg='buttons/refresh.png',threshold=.1)
if result is not False:
return True
else:
return False
def give_teamup_available(self):
""" Assumes Kiosk is already opened"""
#Click world we care about
#pages are saved in cache so no switching pages here, only selecting worlds
#see how many active teamups are available on this world
teamup_availability = [False,False,False,False,False,False] #6 slots
for i in range(6):
if self.is_teamup_at(i) is not False:
#print("Found teamup at location "+str(i))
teamup_availability[i] = True
#filter out long instances
for i in range(6):
if self.is_teamup_long(i) == True:
#print("Found LONG at location "+str(i))
teamup_availability[i] = False
return teamup_availability
def is_teamup_long(self,pos=0):
""" Returns true if there is a timer icon on teamup (indicates long instance)"""
self.set_active()
if (0 <= pos <=5):
x, y = (560,244)
self.set_active()
large = self.screenshotRAM((x,y+32*pos,30,30))
result = self.match_image(largeImg=large, smallImg='icons/timer.png',threshold=.1)
if result is not False:
return True
else:
return False
else:
return False
def close_teamup_kiosk(self):
""" Refreshes availabel teamups """
self.set_active()
x, y = (565,492)
self.click(x,y)
return self
def reset_teamup_kiosk(self):
"""Closes out of kiosk & resets 'x' prompt"""
self.close_teamup_kiosk()
#wiggle back & forth to reset 'x' prompt
self.hold_key('w',.5)
self.hold_key('s', .1)
self.hold_key('w', .5)
def is_teamup_canceled(self):
x, y = (464,393)#563,394
self.set_active()
large = self.screenshotRAM((x,y,103,27))
result = self.match_image(largeImg=large, smallImg='buttons/ok.png',threshold=.1)
if result is not False:
return True
else:
return False
def is_teamup_icon_showing(self):
self.set_active()
x, y = (717,40)#563,394
# # self.move_mouse(x, y)
large = self.screenshotRAM((x,y,15,15))
result = self.match_image(largeImg=large, smallImg='icons/teamup_btn.png',threshold=.1)
if result is not False:
return True
else:
return False
def select_world_teamup(self,pos=0,page=0):
self.set_active()
if(0<=pos<=5):
#scroll until at desired page
for i in range(page):
#x,y pos of the yellow page-arrow
x, y = (570,212)
self.click(x,y)
#click on desired world pos
x, y = (250,212)
x = x+55*pos
self.click(x,y)
return self
else:
return self
def teamup_refresh(self):
""" Refreshes availabel teamups """
self.set_active()
x, y = (535,492)
self.click(x,y)
return self
def is_queued_teamup(self):
""" Returns true if wizard is queued on teamup"""
self.set_active()
x, y = (338,400)
large = self.screenshotRAM((x,y,130,26))
result = self.match_image(largeImg=large, smallImg='buttons/cancel_teamup.png',threshold=.1)
if result is not False:
return True
else:
return False
def wait_for_teamup_queue(self):
#waits until the teamup queue goes away
self.set_active()
x, y = (717,40)#563,394
result = True
while result is not False:
large = self.screenshotRAM((x,y,15,15))
result = self.match_image(largeImg=large, smallImg='icons/teamup_btn.png',threshold=.17)
self.wait(.5)
return self
def cancel_queue_teamup(self):
#clicks through buttons to cancel teamup queue
#useful if queue is taking too long
self.click(403,413)
self.click(403,383)
return self
def teleport_home(self):
self.press_key('home')
return self
def is_on_kiosk(self):
""" Checks if there is 'x' to interract dialogue for teamup """
self.set_active()
x, y = (386,541)
large = self.screenshotRAM((x,y,26,24))
result = self.match_image(largeImg=large, smallImg='icons/x_btn.png',threshold=.1)
if result is not False:
return True
else:
return False
def remove_queue_error_teamup(self):
#if team is no longer avaiable, an error will display on screen
#if wizard tries to click kiosk while already in a queue, same error will popup
#clicks ok
self.click(533,383).wait(.1)
self.click(533,400).wait(.1)
self.click(563,395).wait(.1)
return self
def get_window_rect(self):
"""Get the bounding rectangle of the window """
rect = win32gui.GetWindowRect(self._handle)
return [rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]]
def match_image(self, largeImg, smallImg, threshold=0.1, debug=False):
""" Finds smallImg in largeImg using template matching """
""" Adjust threshold for the precision of the match (between 0 and 1, the lowest being more precise """
""" Returns false if no match was found with the given threshold """
method = cv2.TM_SQDIFF_NORMED
# Read the images from the file
# print(type(smallImg))
# print(type(largeImg))
if(type(smallImg) is str):
small_image = cv2.imread(smallImg)
else:
small_image = cv2.cvtColor(numpy.array(smallImg), cv2.COLOR_RGB2BGR)
if(type(largeImg) is str):
large_image = cv2.imread(largeImg)
else:
large_image = cv2.cvtColor(numpy.array(largeImg), cv2.COLOR_RGB2BGR)
w, h = small_image.shape[:-1]
result = cv2.matchTemplate(small_image, large_image, method)
# We want the minimum squared difference
mn, _, mnLoc, _ = cv2.minMaxLoc(result)
if (mn >= threshold):
return False
# Extract the coordinates of our best match
x, y = mnLoc
if debug:
# Draw the rectangle:
# Get the size of the template. This is the same size as the match.
trows, tcols = small_image.shape[:2]
# Draw the rectangle on large_image
cv2.rectangle(large_image, (x, y),
(x+tcols, y+trows), (0, 0, 255), 2)
# Display the original image with the rectangle around the match.
cv2.imshow('output', large_image)
# The image is only displayed if we call this
cv2.waitKey(0)
# Return coordinates to center of match
return (x + (w * 0.5), y + (h * 0.5))
def pixel_matches_color(self, coords, rgb, threshold=0):
""" Matches the color of a pixel relative to the window's position """
wx, wy = self.get_window_rect()[:2]
x, y = coords
x+=self.region_offset[0]
y+=self.region_offset[1]
#print(pyautogui.pixel(x+wx,y+wy))
#print(rgb)
return pyautogui.pixelMatchesColor(x + wx, y + wy, rgb, tolerance=threshold)
def move_mouse(self, x, y, speed=.5):
""" Moves to mouse to the position (x, y) relative to the window's position """
wx, wy = self.get_window_rect()[:2]
pyautogui.moveTo(wx + x, wy + y, speed)
return self
def click(self, x, y, delay=.1, speed=.5, button='left'):
""" Moves the mouse to (x, y) relative to the window and presses the mouse button """
(self.set_active()
.move_mouse(x, y, speed=speed)
.wait(delay))
pyautogui.click(button=button)
return self
def screenshot(self, name, region=False):
"""
- Captures a screenshot of the window and saves it to 'name'
- Can also be used the capture specific parts of the window by passing in the region arg. (x, y, width, height) (Relative to the window position)
"""
self.set_active()
# region should be a tuple
# Example: (x, y, width, height)
window = self.get_window_rect()
if not region:
# Set the default region to the area of the window
region = window
else:
# Adjust the region so that it is relative to the window
wx, wy = window[:2]
region = list(region)
region[0] += wx
region[0] += self.region_offset[0]
region[1] += wy
region[1] += self.region_offset[1]
pyautogui.screenshot(name, region=region)
def screenshotRAM(self, region=False):
"""
- Captures a screenshot of the window and saves it to 'name'
- Can also be used the capture specific parts of the window by passing in the region arg. (x, y, width, height) (Relative to the window position)
"""
self.set_active()
# region should be a tuple
# Example: (x, y, width, height)
window = self.get_window_rect()
if not region:
# Set the default region to the area of the window
region = window
else:
# Adjust the region so that it is relative to the window
wx, wy = window[:2]
region = list(region)
region[0] += wx
region[0] += self.region_offset[0]
region[1] += wy
region[1] += self.region_offset[1]
return pyautogui.screenshot(region=region)
def teleport_to_friend(self, match_img):
"""
Completes a set of actions to teleport to a friend.
The friend must have the proper symbol next to it
symbol must match the image passed as 'match_img'
"""
self.set_active()
# Check if friends already opened (and close it)
while self.pixel_matches_color((780, 364), (230, 0, 0), 40):
self.click(780, 364).wait(0.2)
# Open friend menu
self.click(780, 50)
# Find friend that matches friend match_img
friend_area = self.screenshotRAM(region=self._friends_area)
found = self.match_image(
friend_area, 'icons/friends/' + match_img)
if found is not False:
x, y = found
offset_x, offset_y = self._friends_area[:2]
(self.click(offset_x + x + 50, offset_y + y) # Select friend
.click(450, 115) # Select port
.click(415, 395) # Select yes
)
self.wait_pet_loading()
return self
else:
#print('Friend cound not be found')
return False
def enter_dungeon_dialog(self):
""" Detects if the 'Enter Dungeon' dialog is present """
self.set_active()
return (self.pixel_matches_color((253, 550), (4, 195, 4), 5) and
self.pixel_matches_color((284, 550), (20, 218, 11), 5))
def is_pet_icon_visible(self):
self.set_active()
x,y = (126,535)
roi_image = self.screenshotRAM(region=(x,y,26,17))
found = self.match_image(roi_image,'pet_icon.png') or self.find_button('done') or self.find_button('more')
return found
def is_logo_bottom_left_loading(self):
self.set_active()
return self.pixel_matches_color((108, 551), (252, 127, 5), 30)
def is_logo_bottom_right_loading(self):
self.set_active()
return self.pixel_matches_color((623, 490+36), (255, 130, 16), 30)
def is_logo_bottom_left_or_right_loading(self):
self.set_active()
return self.pixel_matches_color((170, 532), (252, 127, 5), 30) or self.pixel_matches_color((108, 551), (252, 127, 5), 30)
def logout(self,isDungeon=False):
self.set_active()
self.press_key('esc')
#move mouse to quit button & click
self.click(265,482+36,delay=.2)
#if in dungeon, acknowledge the prompt
if(isDungeon==True):
self.wait(.5)
self.click(411,386+36,delay=.2)
#wait until loading is done
play_btn = self.screenshotRAM(region=self._login_area)
found = self.match_image(play_btn, 'buttons/play.png' , threshold=.2)
while (found == False):
self.wait(1)
play_btn = self.screenshotRAM(region=self._login_area)
found = self.match_image(play_btn, 'buttons/play.png' , threshold=.2)
#press play button
self.click(405,573+36,delay=.2)
def accurate_delay(self, delay):
''' Function to provide accurate time delay in millisecond
'''
_ = time.perf_counter() + delay
while time.perf_counter() < _:
pass
def hold_key(self, key, holdtime=0.0):
"""
Holds a key for a specific amount of time, usefull for moving with the W A S D keys
"""
self.set_active()
start = time.time()
pyautogui.keyDown(key)
"""
while time.time() - start < holdtime:
pass
"""
time.sleep(holdtime)
pyautogui.keyUp(key)
return self
# if(waittime > 0):
# self.accurate_delay(waittime)
# pyautogui.keyDown(key)
# self.accurate_delay(holdtime)
# pyautogui.keyUp(key)
def navigate_keys(self, keys, holdtimes, waittimes):
#keys []
#holdtimes []
#waittimes []
#assume they are in order
curr_time = 0.0
for i in range(len(keys)):
#wait until key needs to be pressed
delay_time = waittimes[i]-curr_time
"""start = time.time()
while time.time() - start < delay_time:
pass
"""
time.sleep(delay_time)
#hold key down for specified time
pyautogui.keyDown(keys[i])
start = time.time()
"""
while time.time() - start < holdtimes[i]:
pass
"""
time.sleep(holdtimes[i]-.15)
pyautogui.keyUp(keys[i])
curr_time = waittimes[i]+holdtimes[i]
return self
def press_key(self, key):
"""
Presses a key, useful for pressing 'x' to enter a dungeon
"""
self.set_active()
pyautogui.press(key)
return self
def is_health_low(self, health_percent):
self.set_active()
time.sleep(.3)
# Matches a pixel in the lower third of the health globe
if(health_percent==33):
POSITION = (23, 563)
COLOR = (126, 41, 3)
elif(health_percent==60):
POSITION = (26,541)
COLOR = (220, 43, 60)
elif(health_percent==80):
POSITION = (26,531)
COLOR = (242, 52, 81)
THRESHOLD = 15
#Prints out color of pixel that triggers health low
#used to see how much you need to change threshold
# if not self.pixel_matches_color(POSITION, COLOR, threshold=THRESHOLD):
# wx, wy = self.get_window_rect()[:2]
# print(pyautogui.pixel(26+wx,531+wy))
return not self.pixel_matches_color(POSITION, COLOR, threshold=THRESHOLD)
def is_mana_low(self):
self.set_active()
# Matches a pixel in the lower third of the mana globe
POSITION = (79, 591)
COLOR = (66, 13, 82)
THRESHOLD = 12
return not self.pixel_matches_color(POSITION, COLOR, threshold=THRESHOLD)
def use_potion_if_needed_tp_house(self,health_percent=33):
self.set_active()
mana_low = self.is_mana_low()
health_low = self.is_health_low(health_percent)
# print("Mana low? :"+str(mana_low))
# print("Health low? :" +str(health_low))
if mana_low or health_low:
#print('Clicking Potion')
self.click(160, 590, delay=.2)
self.wait(1)
if(self.is_mana_low() or self.is_health_low(health_percent)):
#kingsisle has a dumb bug where you cant tp mark location from instance
#so teleport home, THEN to potion lady
self.teleport_home()
self.wait_pet_loading()
self.wait(.1)
self.recall_location()
self.wait_pet_loading()
#Waits for hilda confirmation to pop
time.sleep(1)
#Begin Potion Buy
if(self.is_mana_low): # Buys potion before marking location
# Opens Dialog
self.press_key('x')
self.wait(.5)
#Potion Clicks
self.click(555, 300)
self.click(261, 491)
self.click(515, 470)
self.click(410, 390)
self.click(555, 300)
self.click(261, 491)
self.click(685, 540)
self.wait(.5)
# Get back to Dungeon
self.mark_location()
self.wait(16)
self.teleport_home()
self.wait_pet_loading()
else: # Marks location to waste mana before buying potions
self.mark_location()
self.wait(.5)
self.press_key('x')
self.wait(.5)
#Potion Clicks
self.click(555, 300)
self.click(261, 491)
self.click(515, 470)
self.click(410, 390)
self.click(555, 300)
self.click(261, 491)
self.click(685, 540)
self.wait(16)
#Gets back to dungeon
self.teleport_home()
self.wait_pet_loading()
return True
return False
def use_potion_if_needed(self, refill=False, teleport_to_wizard="", health_percent=33, teleport=False, teleport_friend_img="",greedy_tp=False): #Health Position defaults to 1/3
self.set_active()
mana_low = self.is_mana_low()
health_low = self.is_health_low(health_percent)
# if mana_low:
# print('Mana is low, using potion')
# if health_low:
# print('Health is low, using potion')
if mana_low or health_low:
#print('Clicking Potion')
self.click(160, 590, delay=.2)
self.wait(1)
if(self.is_mana_low() or self.is_health_low(health_percent) and refill): #IF Refill == true, all wiz must have HILDA marked in commons
#print('Refilling')
if(teleport):
self.teleport_to_friend(teleport_friend_img)
else:
self.recall_location()
self.wait_pet_loading()
print("Loaded into fairgrounds")
#Waits for hilda confirmation to pop
time.sleep(1)
#Begin Potion Buy
if(self.is_mana_low): # Buys potion before marking location
print("Mana is low; buying potion before marking location")
# Opens Dialog
self.press_key('x')
self.wait(.5)
#Potion Clicks
self.click(555, 300)
self.click(261, 491)
self.click(515, 470)
self.click(410, 390)
self.click(555, 300)
self.click(261, 491)
self.click(685, 540)
self.wait(.5)
# Get back to Dungeon
if(teleport == False):
self.mark_location()
self.wait(.5)
self.teleport_to_friend(teleport_to_wizard)
else: # Marks location to waste mana before buying potions
print("Only health is low; marking location and buying potions")
if(teleport == False):
self.mark_location()
self.wait(.5)
self.press_key('x')
self.wait(.5)
#Potion Clicks
self.click(555, 300)
self.click(261, 491)
self.click(515, 470)
self.click(410, 390)
self.click(555, 300)
self.click(261, 491)
self.click(685, 540)
self.wait(.5)
#Gets back to dungeon
self.teleport_to_friend(teleport_to_wizard)
def pass_turn(self):
self.click(254, 398, delay=.5).move_mouse(200, 400)
return self
def wait_pet_loading(self):
#wait for pet icon to disappear
while self.is_pet_icon_visible():
#print("pet icon is visible")
time.sleep(.2)
#wait for pept icon to reappear
while ((not self.is_pet_icon_visible()) and (not self.find_button('more')) and (not self.find_button('done'))):
time.sleep(.2)
def is_turn_to_play(self):
""" matches a yellow pixel in the 'pass' button """
#return self.pixel_matches_color((238, 398), (255, 255, 0), 20)
return self.is_turn_to_play_pass()
def is_turn_to_play_pass(self):
roi = (190, 385, 440, 40)
#roi = (roi[0]+self.region_offset[0],roi[1]+self.region_offset[1],roi[2]+self.region_offset[2],roi[3]+self.region_offset[3])
pic = self.screenshotRAM(region=roi)
found = self.match_image(pic, 'buttons/pass.png', threshold=.1)
if found is not False:
return True
else:
return False
def wait_for_next_turn(self):
""" Wait for spell round to begin """
while self.is_turn_to_play():
self.wait(1)
#print('Spell round begins')
""" Start detecting if it's our turn to play again """
while not self.is_turn_to_play():
self.wait(1)
#print('Our turn to play')
return self
def wait_for_turn_to_play(self):
while not self.is_turn_to_play():
self.wait(.5)
def wait_for_end_of_round_dialog(self):
""" Similar to wait_for_next_turn, but also detects if its the end of the battle """
""" Wait for spell round to begin """
while self.is_turn_to_play():
self.wait(1)
""" Start detecting if it's our turn to play again """
""" Or if it's the end of the battle """
while not (self.is_turn_to_play_pass() or self.is_idle() or self.find_button('done') or self.find_button('more')):
self.wait(1)
return self
def wait_for_end_of_round(self):
""" Similar to wait_for_next_turn, but also detects if its the end of the battle """
""" Wait for spell round to begin """
while self.is_turn_to_play_pass():
self.wait(1)
""" Start detecting if it's our turn to play again """
""" Or if it's the end of the battle """
while not (self.is_turn_to_play_pass() or self.is_idle()):
self.wait(1)
return self
def is_idle(self):
""" Matches a pink pixel in the pet icon (only visible when not in battle) """
#return self.pixel_matches_color((140, 554), (252, 146, 206), 2)
return self.is_pet_icon_visible()
def find_spell(self, spell_type, spell_name, threshold=0.10, max_tries=2, recapture=True):
"""
Attempts the find the spell passed is 'spell_name'
returns False if not found with the given threshold
Use recapture=False to not re-take the screenshot of the spell_area
Adds spell position to memory for later use
"""
self.set_active()
tries = 0
res = False
spell_area = self.screenshotRAM(region=self._spell_area)
while not res and tries < max_tries:
tries += 1
if tries > 1:
# Wait 1 second before re-trying
self.wait(1)
recapture = True
if recapture:
self.mouse_out_of_area(self._spell_area)
spell_area = self.screenshotRAM(region=self._spell_area)
res = self.match_image(
spell_area, ('spells/' + spell_type + '/' + spell_name + '.png'), threshold)
if res is not False:
x, y = res
offset_x, offset_y = self._spell_area[:2]
spell_pos = (offset_x + x, offset_y + y)
# Remember location
self._spell_memory[spell_name] = spell_pos
return spell_pos
else:
return False
def find_unusable_spells(self, limit=-1):
""" Returns an array of the positions of unusable spells (grayed out) """
""" Useful for farming Loremaster, it prevents getting a crowded deck if you learn a new spell """
self.set_active()
self.mouse_out_of_area(self._spell_area)
spell_area = self.screenshotRAM(region=self._spell_area)
w, h = (28, 38) # The size of the gray area we're looking for
#img = cv2.imread('spell_area.png')
img = cv2.cvtColor(numpy.array(spell_area), cv2.COLOR_RGB2BGR)
rows, cols = img.shape[:2]
pts = []
# Determine if a pixel is gray enough
def isGray(pixel, threshold):
return abs(int(min(*pixel)) - int(max(*pixel))) <= threshold
i = 2
j = 0
while j < (cols - w):
""" find a rectangle with no color """
grayScale = True
for y in range(h):
for x in range(w):
pixel = img[i + y, j + x]
if not isGray(pixel, threshold=30):
grayScale = False
if not grayScale:
break
if not grayScale:
break
if grayScale:
offset_x, offset_y = self._spell_area[:2]
spell_pos = (offset_x + j + w/2, offset_y + i+h/2)
pts.append(spell_pos)
j += w
# Break if we've reached the limit in requested areas
if limit > 0 and len(pts) >= limit:
break
j += 1
self._spell_memory["unusable"] = pts
return pts
def grab_spell_pngs(self, spell_name="default", spell_loc=""):
""" Saves png images of all spells in current hand """
""" """
self.set_active()
self.mouse_out_of_area(self._spell_area)
sa_x, sa_y, sa_w, sa_h = self._spell_area
sa_x += 0
sa_h += 2
my_spell_area = (sa_x,sa_y,sa_w,sa_h)
print(my_spell_area)
spell_area = self.screenshotRAM(region=my_spell_area)
#spell_area.save("currHand/{}.png".format(time.time()),format="PNG")
print(type(spell_area))
print(my_spell_area)
if not os.path.exists('currHand/{}{}'.format(spell_name,spell_loc)):
os.makedirs('currHand/{}{}'.format(spell_name,spell_loc))
for i in range(7):
print(i)
my_x, my_y = ((48*i)+(5.5*i)), 0
my_width, my_height = 48, sa_h
cropped_image = spell_area.crop((my_x,my_y,my_x+my_width,my_y+my_height))
cropped_image.save("currHand/{}{}/{}.png".format(spell_name,spell_loc,i),format="PNG")
return
def discard_unusable_spells(self, limit=-1):
count = 0
while True:
count += 1
#print(count)
try:
# Try accessing from memory
card_pos = self._spell_memory["unusable"][0]
except (KeyError, IndexError):
result = self.find_unusable_spells(limit=1)
if len(result) is not 0:
card_pos = result[0]
else:
break
#print(card_pos)
# Right click the card position
self.click(*card_pos, button='right', delay=.2)
# Flush card memory
self.flush_spell_memory()
def flush_spell_memory(self):