-
Notifications
You must be signed in to change notification settings - Fork 535
/
index.py
536 lines (410 loc) · 16.6 KB
/
index.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
# -*- coding: utf-8 -*-
from src.logger import logger, loggerMapClicked
from cv2 import cv2
from os import listdir
from random import randint
from random import random
import numpy as np
import mss
import pyautogui
import time
import sys
import yaml
# Load config file.
stream = open("config.yaml", 'r')
c = yaml.safe_load(stream)
ct = c['threshold']
ch = c['home']
pause = c['time_intervals']['interval_between_moviments']
pyautogui.PAUSE = pause
cat = """
_
\`*-.
) _`-.
. : `. .
: _ ' \\
; *` _. `*-._
`-.-' `-.
; ` `.
:. . \\
. \ . : .-' .
' `+.; ; ' :
: ' | ; ;-.
; ' : :`-: _.`* ;
.*' / .*' ; .*`- +' `*'
`*-* `*-* `*-*'
=========================================================================
========== 💰 Have I helped you in any way? All I ask is a tip! 🧾 ======
========== ✨ Faça sua boa ação de hoje, manda aquela gorjeta! 😊 =======
=========================================================================
======================== vvv BCOIN BUSD BNB vvv =========================
============== 0xbd06182D8360FB7AC1B05e871e56c76372510dDf ===============
=========================================================================
===== https://www.paypal.com/donate?hosted_button_id=JVYSC6ZYCNQQQ ======
=========================================================================
>>---> Press ctrl + c to kill the bot.
>>---> Some configs can be found in the config.yaml file."""
def addRandomness(n, randomn_factor_size=None):
"""Returns n with randomness
Parameters:
n (int): A decimal integer
randomn_factor_size (int): The maximum value+- of randomness that will be
added to n
Returns:
int: n with randomness
"""
if randomn_factor_size is None:
randomness_percentage = 0.1
randomn_factor_size = randomness_percentage * n
random_factor = 2 * random() * randomn_factor_size
if random_factor > 5:
random_factor = 5
without_average_random_factor = n - randomn_factor_size
randomized_n = int(without_average_random_factor + random_factor)
# logger('{} with randomness -> {}'.format(int(n), randomized_n))
return int(randomized_n)
def moveToWithRandomness(x,y,t):
pyautogui.moveTo(addRandomness(x,10),addRandomness(y,10),t+random()/2)
def remove_suffix(input_string, suffix):
"""Returns the input_string without the suffix"""
if suffix and input_string.endswith(suffix):
return input_string[:-len(suffix)]
return input_string
def load_images(dir_path='./targets/'):
""" Programatically loads all images of dir_path as a key:value where the
key is the file name without the .png suffix
Returns:
dict: dictionary containing the loaded images as key:value pairs.
"""
file_names = listdir(dir_path)
targets = {}
for file in file_names:
path = 'targets/' + file
targets[remove_suffix(file, '.png')] = cv2.imread(path)
return targets
def loadHeroesToSendHome():
"""Loads the images in the path and saves them as a list"""
file_names = listdir('./targets/heroes-to-send-home')
heroes = []
for file in file_names:
path = './targets/heroes-to-send-home/' + file
heroes.append(cv2.imread(path))
print('>>---> %d heroes that should be sent home loaded' % len(heroes))
return heroes
def show(rectangles, img = None):
""" Show an popup with rectangles showing the rectangles[(x, y, w, h),...]
over img or a printSreen if no img provided. Useful for debugging"""
if img is None:
with mss.mss() as sct:
monitor = sct.monitors[0]
img = np.array(sct.grab(monitor))
for (x, y, w, h) in rectangles:
cv2.rectangle(img, (x, y), (x + w, y + h), (255,255,255,255), 2)
# cv2.rectangle(img, (result[0], result[1]), (result[0] + result[2], result[1] + result[3]), (255,50,255), 2)
cv2.imshow('img',img)
cv2.waitKey(0)
def clickBtn(img, timeout=3, threshold = ct['default']):
"""Search for img in the scree, if found moves the cursor over it and clicks.
Parameters:
img: The image that will be used as an template to find where to click.
timeout (int): Time in seconds that it will keep looking for the img before returning with fail
threshold(float): How confident the bot needs to be to click the buttons (values from 0 to 1)
"""
logger(None, progress_indicator=True)
start = time.time()
has_timed_out = False
while(not has_timed_out):
matches = positions(img, threshold=threshold)
if(len(matches)==0):
has_timed_out = time.time()-start > timeout
continue
x,y,w,h = matches[0]
pos_click_x = x+w/2
pos_click_y = y+h/2
moveToWithRandomness(pos_click_x,pos_click_y,1)
pyautogui.click()
return True
return False
def printSreen():
with mss.mss() as sct:
monitor = sct.monitors[0]
sct_img = np.array(sct.grab(monitor))
# The screen part to capture
# monitor = {"top": 160, "left": 160, "width": 1000, "height": 135}
# Grab the data
return sct_img[:,:,:3]
def positions(target, threshold=ct['default'],img = None):
if img is None:
img = printSreen()
result = cv2.matchTemplate(img,target,cv2.TM_CCOEFF_NORMED)
w = target.shape[1]
h = target.shape[0]
yloc, xloc = np.where(result >= threshold)
rectangles = []
for (x, y) in zip(xloc, yloc):
rectangles.append([int(x), int(y), int(w), int(h)])
rectangles.append([int(x), int(y), int(w), int(h)])
rectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)
return rectangles
def scroll():
commoms = positions(images['commom-text'], threshold = ct['commom'])
if (len(commoms) == 0):
return
x,y,w,h = commoms[len(commoms)-1]
#
moveToWithRandomness(x,y,1)
if not c['use_click_and_drag_instead_of_scroll']:
pyautogui.scroll(-c['scroll_size'])
else:
pyautogui.dragRel(0,-c['click_and_drag_amount'],duration=1, button='left')
def clickButtons():
buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
# print('buttons: {}'.format(len(buttons)))
for (x, y, w, h) in buttons:
moveToWithRandomness(x+(w/2),y+(h/2),1)
pyautogui.click()
global hero_clicks
hero_clicks = hero_clicks + 1
#cv2.rectangle(sct_img, (x, y) , (x + w, y + h), (0,255,255),2)
if hero_clicks > 20:
logger('too many hero clicks, try to increase the go_to_work_btn threshold')
return
return len(buttons)
def isHome(hero, buttons):
y = hero[1]
for (_,button_y,_,button_h) in buttons:
isBelow = y < (button_y + button_h)
isAbove = y > (button_y - button_h)
if isBelow and isAbove:
# if send-home button exists, the hero is not home
return False
return True
def isWorking(bar, buttons):
y = bar[1]
for (_,button_y,_,button_h) in buttons:
isBelow = y < (button_y + button_h)
isAbove = y > (button_y - button_h)
if isBelow and isAbove:
return False
return True
def clickGreenBarButtons():
# ele clicka nos q tao trabaiano mas axo q n importa
offset = 140
green_bars = positions(images['green-bar'], threshold=ct['green_bar'])
logger('🟩 %d green bars detected' % len(green_bars))
buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
logger('🆗 %d buttons detected' % len(buttons))
not_working_green_bars = []
for bar in green_bars:
if not isWorking(bar, buttons):
not_working_green_bars.append(bar)
if len(not_working_green_bars) > 0:
logger('🆗 %d buttons with green bar detected' % len(not_working_green_bars))
logger('👆 Clicking in %d heroes' % len(not_working_green_bars))
# se tiver botao com y maior que bar y-10 e menor que y+10
hero_clicks_cnt = 0
for (x, y, w, h) in not_working_green_bars:
# isWorking(y, buttons)
moveToWithRandomness(x+offset+(w/2),y+(h/2),1)
pyautogui.click()
global hero_clicks
hero_clicks = hero_clicks + 1
hero_clicks_cnt = hero_clicks_cnt + 1
if hero_clicks_cnt > 20:
logger('⚠️ Too many hero clicks, try to increase the go_to_work_btn threshold')
return
#cv2.rectangle(sct_img, (x, y) , (x + w, y + h), (0,255,255),2)
return len(not_working_green_bars)
def clickFullBarButtons():
offset = 100
full_bars = positions(images['full-stamina'], threshold=ct['default'])
buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
not_working_full_bars = []
for bar in full_bars:
if not isWorking(bar, buttons):
not_working_full_bars.append(bar)
if len(not_working_full_bars) > 0:
logger('👆 Clicking in %d heroes' % len(not_working_full_bars))
for (x, y, w, h) in not_working_full_bars:
moveToWithRandomness(x+offset+(w/2),y+(h/2),1)
pyautogui.click()
global hero_clicks
hero_clicks = hero_clicks + 1
return len(not_working_full_bars)
def goToHeroes():
if clickBtn(images['go-back-arrow']):
global login_attempts
login_attempts = 0
#TODO tirar o sleep quando colocar o pulling
time.sleep(1)
clickBtn(images['hero-icon'])
time.sleep(randint(1,3))
def goToGame():
# in case of server overload popup
clickBtn(images['x'])
# time.sleep(3)
clickBtn(images['x'])
clickBtn(images['treasure-hunt-icon'])
def refreshHeroesPositions():
logger('🔃 Refreshing Heroes Positions')
clickBtn(images['go-back-arrow'])
clickBtn(images['treasure-hunt-icon'])
# time.sleep(3)
clickBtn(images['treasure-hunt-icon'])
def login():
global login_attempts
logger('😿 Checking if game has disconnected')
if login_attempts > 3:
logger('🔃 Too many login attempts, refreshing')
login_attempts = 0
pyautogui.hotkey('ctrl','f5')
return
if clickBtn(images['connect-wallet'], timeout = 10):
logger('🎉 Connect wallet button detected, logging in!')
login_attempts = login_attempts + 1
#TODO mto ele da erro e poco o botao n abre
# time.sleep(10)
if clickBtn(images['select-wallet-2'], timeout=8):
# sometimes the sign popup appears imediately
login_attempts = login_attempts + 1
# print('sign button clicked')
# print('{} login attempt'.format(login_attempts))
if clickBtn(images['treasure-hunt-icon'], timeout = 15):
# print('sucessfully login, treasure hunt btn clicked')
login_attempts = 0
return
# click ok button
if not clickBtn(images['select-wallet-1-no-hover'], ):
if clickBtn(images['select-wallet-1-hover'], threshold = ct['select_wallet_buttons'] ):
pass
# o ideal era que ele alternasse entre checar cada um dos 2 por um tempo
# print('sleep in case there is no metamask text removed')
# time.sleep(20)
else:
pass
# print('sleep in case there is no metamask text removed')
# time.sleep(20)
if clickBtn(images['select-wallet-2'], timeout = 20):
login_attempts = login_attempts + 1
# print('sign button clicked')
# print('{} login attempt'.format(login_attempts))
# time.sleep(25)
if clickBtn(images['treasure-hunt-icon'], timeout=25):
# print('sucessfully login, treasure hunt btn clicked')
login_attempts = 0
# time.sleep(15)
if clickBtn(images['ok'], timeout=5):
pass
# time.sleep(15)
# print('ok button clicked')
def sendHeroesHome():
if not ch['enable']:
return
heroes_positions = []
for hero in home_heroes:
hero_positions = positions(hero, threshold=ch['hero_threshold'])
if not len (hero_positions) == 0:
#TODO maybe pick up match with most wheight instead of first
hero_position = hero_positions[0]
heroes_positions.append(hero_position)
n = len(heroes_positions)
if n == 0:
print('No heroes that should be sent home found.')
return
print(' %d heroes that should be sent home found' % n)
# if send-home button exists, the hero is not home
go_home_buttons = positions(images['send-home'], threshold=ch['home_button_threshold'])
# TODO pass it as an argument for both this and the other function that uses it
go_work_buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
for position in heroes_positions:
if not isHome(position,go_home_buttons):
print(isWorking(position, go_work_buttons))
if(not isWorking(position, go_work_buttons)):
print ('hero not working, sending him home')
moveToWithRandomness(go_home_buttons[0][0]+go_home_buttons[0][2]/2,position[1]+position[3]/2,1)
pyautogui.click()
else:
print ('hero working, not sending him home(no dark work button)')
else:
print('hero already home, or home full(no dark home button)')
def refreshHeroes():
logger('🏢 Search for heroes to work')
goToHeroes()
if c['select_heroes_mode'] == "full":
logger('⚒️ Sending heroes with full stamina bar to work', 'green')
elif c['select_heroes_mode'] == "green":
logger('⚒️ Sending heroes with green stamina bar to work', 'green')
else:
logger('⚒️ Sending all heroes to work', 'green')
buttonsClicked = 1
empty_scrolls_attempts = c['scroll_attemps']
while(empty_scrolls_attempts >0):
if c['select_heroes_mode'] == 'full':
buttonsClicked = clickFullBarButtons()
elif c['select_heroes_mode'] == 'green':
buttonsClicked = clickGreenBarButtons()
else:
buttonsClicked = clickButtons()
sendHeroesHome()
if buttonsClicked == 0:
empty_scrolls_attempts = empty_scrolls_attempts - 1
scroll()
time.sleep(2)
logger('💪 {} heroes sent to work'.format(hero_clicks))
goToGame()
def main():
"""Main execution setup and loop"""
# ==Setup==
global hero_clicks
global login_attempts
global last_log_is_progress
hero_clicks = 0
login_attempts = 0
last_log_is_progress = False
global images
images = load_images()
if ch['enable']:
global home_heroes
home_heroes = loadHeroesToSendHome()
else:
print('>>---> Home feature not enabled')
print('\n')
print(cat)
time.sleep(7)
t = c['time_intervals']
last = {
"login" : 0,
"heroes" : 0,
"new_map" : 0,
"check_for_captcha" : 0,
"refresh_heroes" : 0
}
# =========
while True:
now = time.time()
if now - last["check_for_captcha"] > addRandomness(t['check_for_captcha'] * 60):
last["check_for_captcha"] = now
if now - last["heroes"] > addRandomness(t['send_heroes_for_work'] * 60):
last["heroes"] = now
refreshHeroes()
if now - last["login"] > addRandomness(t['check_for_login'] * 60):
sys.stdout.flush()
last["login"] = now
login()
if now - last["new_map"] > t['check_for_new_map_button']:
last["new_map"] = now
if clickBtn(images['new-map']):
loggerMapClicked()
if now - last["refresh_heroes"] > addRandomness( t['refresh_heroes_positions'] * 60):
last["refresh_heroes"] = now
refreshHeroesPositions()
#clickBtn(teasureHunt)
logger(None, progress_indicator=True)
sys.stdout.flush()
time.sleep(1)
if __name__ == '__main__':
main()
#cv2.imshow('img',sct_img)
#cv2.waitKey()
# colocar o botao em pt
# soh resetar posiçoes se n tiver clickado em newmap em x segundos