grantygames

Untitled

Dec 24th, 2021
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.12 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from cv2 import cv2
  3.  
  4. from captcha.solveCaptcha import solveCaptcha
  5.  
  6. from os import listdir
  7. from src.logger import logger, loggerMapClicked
  8. from ahk import AHK
  9. from random import randint
  10. from random import random
  11. import pygetwindow
  12. import numpy as np
  13. import mss
  14. import time
  15. import sys
  16.  
  17. import yaml
  18.  
  19.  
  20. cat = """
  21. _
  22.  
  23. >>---> Press ctrl + c to kill the bot.
  24.  
  25. >>---> ta rodando krl."""
  26.  
  27.  
  28. print(cat)
  29. time.sleep(2)
  30.  
  31.  
  32. if __name__ == '__main__':
  33. stream = open("config.yaml", 'r')
  34. c = yaml.safe_load(stream)
  35.  
  36. ct = c['threshold']
  37. ch = c['home']
  38.  
  39. if not ch['enable']:
  40. print('>>---> o pobre nao tem casa ')
  41. print('\n')
  42.  
  43. pause = c['time_intervals']['interval_between_moviments']
  44. pyautogui.PAUSE = pause
  45.  
  46. pyautogui.FAILSAFE = False
  47. hero_clicks = 0
  48. login_attempts = 0
  49. last_log_is_progress = False
  50.  
  51.  
  52.  
  53. def addRandomness(n, randomn_factor_size=None):
  54. if randomn_factor_size is None:
  55. randomness_percentage = 0.1
  56. randomn_factor_size = randomness_percentage * n
  57.  
  58. random_factor = 2 * random() * randomn_factor_size
  59. if random_factor > 5:
  60. random_factor = 5
  61. without_average_random_factor = n - randomn_factor_size
  62. randomized_n = int(without_average_random_factor + random_factor)
  63. # logger('{} with randomness -> {}'.format(int(n), randomized_n))
  64. return int(randomized_n)
  65.  
  66. def moveToWithRandomness(x,y,t):
  67. pyautogui.moveTo(addRandomness(x,10),addRandomness(y,10),t+random()/2)
  68.  
  69.  
  70. def remove_suffix(input_string, suffix):
  71. if suffix and input_string.endswith(suffix):
  72. return input_string[:-len(suffix)]
  73. return input_string
  74.  
  75. def load_images():
  76. file_names = listdir('./targets/')
  77. targets = {}
  78. for file in file_names:
  79. path = 'targets/' + file
  80. targets[remove_suffix(file, '.png')] = cv2.imread(path)
  81.  
  82. return targets
  83.  
  84. images = load_images()
  85.  
  86. def loadHeroesToSendHome():
  87. file_names = listdir('./targets/heroes-to-send-home')
  88. heroes = []
  89. for file in file_names:
  90. path = './targets/heroes-to-send-home/' + file
  91. heroes.append(cv2.imread(path))
  92.  
  93. print('>>---> %d heroes that should be sent home loaded' % len(heroes))
  94. return heroes
  95.  
  96. if ch['enable']:
  97. home_heroes = loadHeroesToSendHome()
  98.  
  99. # go_work_img = cv2.imread('targets/go-work.png')
  100. # commom_img = cv2.imread('targets/commom-text.png')
  101. # arrow_img = cv2.imread('targets/go-back-arrow.png')
  102. # hero_img = cv2.imread('targets/hero-icon.png')
  103. # x_button_img = cv2.imread('targets/x.png')
  104. # teasureHunt_icon_img = cv2.imread('targets/treasure-hunt-icon.png')
  105. # ok_btn_img = cv2.imread('targets/ok.png')
  106. # connect_wallet_btn_img = cv2.imread('targets/connect-wallet.png')
  107. # select_wallet_hover_img = cv2.imread('targets/select-wallet-1-hover.png')
  108. # select_metamask_no_hover_img = cv2.imread('targets/select-wallet-1-no-hover.png')
  109. # sign_btn_img = cv2.imread('targets/select-wallet-2.png')
  110. # new_map_btn_img = cv2.imread('targets/new-map.png')
  111. # green_bar = cv2.imread('targets/green-bar.png')
  112. full_stamina = cv2.imread('targets/full-stamina.png')
  113.  
  114. robot = cv2.imread('targets/robot.png')
  115. # puzzle_img = cv2.imread('targets/puzzle.png')
  116. # piece = cv2.imread('targets/piece.png')
  117. slider = cv2.imread('targets/slider.png')
  118.  
  119.  
  120.  
  121. def show(rectangles, img = None):
  122.  
  123. if img is None:
  124. with mss.mss() as sct:
  125. monitor = sct.monitors[0]
  126. img = np.array(sct.grab(monitor))
  127.  
  128. for (x, y, w, h) in rectangles:
  129. cv2.rectangle(img, (x, y), (x + w, y + h), (255,255,255,255), 2)
  130.  
  131. # cv2.rectangle(img, (result[0], result[1]), (result[0] + result[2], result[1] + result[3]), (255,50,255), 2)
  132. cv2.imshow('img',img)
  133. cv2.waitKey(0)
  134.  
  135.  
  136.  
  137.  
  138.  
  139. def clickBtn(img,name=None, timeout=3, threshold = ct['default']):
  140. logger(None, progress_indicator=True)
  141. if not name is None:
  142. pass
  143. # print('waiting for "{}" button, timeout of {}s'.format(name, timeout))
  144. start = time.time()
  145. while(True):
  146. matches = positions(img, threshold=threshold)
  147. if(len(matches)==0):
  148. hast_timed_out = time.time()-start > timeout
  149. if(hast_timed_out):
  150. if not name is None:
  151. pass
  152. # print('timed out')
  153. return False
  154. # print('button not found yet')
  155. continue
  156.  
  157. x,y,w,h = matches[0]
  158. pos_click_x = x+w/2
  159. pos_click_y = y+h/2
  160. # mudar moveto pra w randomness
  161. moveToWithRandomness(pos_click_x,pos_click_y,1)
  162. pyautogui.click()
  163. return True
  164. print("THIS SHOULD NOT PRINT")
  165.  
  166.  
  167. def printSreen():
  168. with mss.mss() as sct:
  169. monitor = sct.monitors[0]
  170. sct_img = np.array(sct.grab(monitor))
  171. # The screen part to capture
  172. # monitor = {"top": 160, "left": 160, "width": 1000, "height": 135}
  173.  
  174. # Grab the data
  175. return sct_img[:,:,:3]
  176.  
  177. def positions(target, threshold=ct['default'],img = None):
  178. if img is None:
  179. img = printSreen()
  180. result = cv2.matchTemplate(img,target,cv2.TM_CCOEFF_NORMED)
  181. w = target.shape[1]
  182. h = target.shape[0]
  183.  
  184. yloc, xloc = np.where(result >= threshold)
  185.  
  186.  
  187. rectangles = []
  188. for (x, y) in zip(xloc, yloc):
  189. rectangles.append([int(x), int(y), int(w), int(h)])
  190. rectangles.append([int(x), int(y), int(w), int(h)])
  191.  
  192. rectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)
  193. return rectangles
  194.  
  195. def scroll():
  196.  
  197. commoms = positions(images['commom-text'], threshold = ct['commom'])
  198. if (len(commoms) == 0):
  199. return
  200. x,y,w,h = commoms[len(commoms)-1]
  201. #
  202. moveToWithRandomness(x,y,1)
  203.  
  204. if not c['use_click_and_drag_instead_of_scroll']:
  205. pyautogui.scroll(-c['scroll_size'])
  206. else:
  207. pyautogui.dragRel(0,-c['click_and_drag_amount'],duration=1, button='left')
  208.  
  209.  
  210. def clickButtons():
  211. buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
  212. # print('buttons: {}'.format(len(buttons)))
  213. for (x, y, w, h) in buttons:
  214. moveToWithRandomness(x+(w/2),y+(h/2),1)
  215. pyautogui.click()
  216. global hero_clicks
  217. hero_clicks = hero_clicks + 1
  218. #cv2.rectangle(sct_img, (x, y) , (x + w, y + h), (0,255,255),2)
  219. if hero_clicks > 20:
  220. logger('too many hero clicks, try to increase the go_to_work_btn threshold')
  221. return
  222. return len(buttons)
  223.  
  224. def isHome(hero, buttons):
  225. y = hero[1]
  226.  
  227. for (_,button_y,_,button_h) in buttons:
  228. isBelow = y < (button_y + button_h)
  229. isAbove = y > (button_y - button_h)
  230. if isBelow and isAbove:
  231. # if send-home button exists, the hero is not home
  232. return False
  233. return True
  234.  
  235. def isWorking(bar, buttons):
  236. y = bar[1]
  237.  
  238. for (_,button_y,_,button_h) in buttons:
  239. isBelow = y < (button_y + button_h)
  240. isAbove = y > (button_y - button_h)
  241. if isBelow and isAbove:
  242. return False
  243. return True
  244.  
  245. def clickGreenBarButtons():
  246. # ele clicka nos q tao trabaiano mas axo q n importa
  247. offset = 130
  248.  
  249. green_bars = positions(images['green-bar'], threshold=ct['green_bar'])
  250. logger('🟩 %d green bars detected' % len(green_bars))
  251. buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
  252. logger('πŸ†— %d buttons detected' % len(buttons))
  253.  
  254.  
  255. not_working_green_bars = []
  256. for bar in green_bars:
  257. if not isWorking(bar, buttons):
  258. not_working_green_bars.append(bar)
  259. if len(not_working_green_bars) > 0:
  260. logger('πŸ†— %d buttons with green bar detected' % len(not_working_green_bars))
  261. logger('πŸ‘† Clicking in %d heroes' % len(not_working_green_bars))
  262.  
  263. # se tiver botao com y maior que bar y-10 e menor que y+10
  264. for (x, y, w, h) in not_working_green_bars:
  265. # isWorking(y, buttons)
  266. moveToWithRandomness(x+offset+(w/2),y+(h/2),1)
  267. pyautogui.click()
  268. global hero_clicks
  269. hero_clicks = hero_clicks + 1
  270. if hero_clicks > 20:
  271. logger('⚠️ Too many hero clicks, try to increase the go_to_work_btn threshold')
  272. return
  273. #cv2.rectangle(sct_img, (x, y) , (x + w, y + h), (0,255,255),2)
  274. return len(not_working_green_bars)
  275.  
  276. def clickFullBarButtons():
  277. offset = 100
  278. full_bars = positions(images['full-stamina'], threshold=ct['default'])
  279. buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
  280.  
  281. not_working_full_bars = []
  282. for bar in full_bars:
  283. if not isWorking(bar, buttons):
  284. not_working_full_bars.append(bar)
  285.  
  286. if len(not_working_full_bars) > 0:
  287. logger('πŸ‘† Clicking in %d heroes' % len(not_working_full_bars))
  288.  
  289. for (x, y, w, h) in not_working_full_bars:
  290. moveToWithRandomness(x+offset+(w/2),y+(h/2),1)
  291. pyautogui.click()
  292. global hero_clicks
  293. hero_clicks = hero_clicks + 1
  294.  
  295. return len(not_working_full_bars)
  296.  
  297. def goToHeroes():
  298. if clickBtn(images['go-back-arrow']):
  299. global login_attempts
  300. login_attempts = 0
  301.  
  302. solveCaptcha(pause)
  303. #TODO tirar o sleep quando colocar o pulling
  304. time.sleep(1)
  305. clickBtn(images['hero-icon'])
  306. time.sleep(1)
  307. solveCaptcha(pause)
  308.  
  309. def goToGame():
  310. # in case of server overload popup
  311. clickBtn(images['x'])
  312. # time.sleep(3)
  313. clickBtn(images['x'])
  314.  
  315. clickBtn(images['treasure-hunt-icon'])
  316.  
  317. def refreshHeroesPositions():
  318.  
  319. logger('πŸ”ƒ Refreshing Heroes Positions')
  320. clickBtn(images['go-back-arrow'])
  321. clickBtn(images['treasure-hunt-icon'])
  322.  
  323. # time.sleep(3)
  324. clickBtn(images['treasure-hunt-icon'])
  325.  
  326. def login():
  327. global login_attempts
  328. logger('😿 Checking if game has disconnected')
  329.  
  330. if login_attempts > 3:
  331. logger('πŸ”ƒ Too many login attempts, refreshing')
  332. login_attempts = 0
  333. pyautogui.hotkey('ctrl','f5')
  334. return
  335.  
  336. if clickBtn(images['connect-wallet'], name='connectWalletBtn', timeout = 10):
  337. logger('πŸŽ‰ Connect wallet button detected, logging in!')
  338. solveCaptcha(pause)
  339. login_attempts = login_attempts + 1
  340. #TODO mto ele da erro e poco o botao n abre
  341. # time.sleep(10)
  342.  
  343. if clickBtn(images['select-wallet-2'], name='sign button', timeout=8):
  344. # sometimes the sign popup appears imediately
  345. login_attempts = login_attempts + 1
  346. # print('sign button clicked')
  347. # print('{} login attempt'.format(login_attempts))
  348. if clickBtn(images['treasure-hunt-icon'], name='teasureHunt', timeout = 15):
  349. # print('sucessfully login, treasure hunt btn clicked')
  350. login_attempts = 0
  351. return
  352. # click ok button
  353.  
  354. if not clickBtn(images['select-wallet-1-no-hover'], name='selectMetamaskBtn'):
  355. if clickBtn(images['select-wallet-1-hover'], name='selectMetamaskHoverBtn', threshold = ct['select_wallet_buttons'] ):
  356. pass
  357. # o ideal era que ele alternasse entre checar cada um dos 2 por um tempo
  358. # print('sleep in case there is no metamask text removed')
  359. # time.sleep(20)
  360. else:
  361. pass
  362. # print('sleep in case there is no metamask text removed')
  363. # time.sleep(20)
  364.  
  365. if clickBtn(images['select-wallet-2'], name='signBtn', timeout = 20):
  366. login_attempts = login_attempts + 1
  367. # print('sign button clicked')
  368. # print('{} login attempt'.format(login_attempts))
  369. # time.sleep(25)
  370. if clickBtn(images['treasure-hunt-icon'], name='teasureHunt', timeout=25):
  371. # print('sucessfully login, treasure hunt btn clicked')
  372. login_attempts = 0
  373. # time.sleep(15)
  374.  
  375. if clickBtn(images['ok'], name='okBtn', timeout=5):
  376. pass
  377. # time.sleep(15)
  378. # print('ok button clicked')
  379.  
  380.  
  381.  
  382. def sendHeroesHome():
  383. if not ch['enable']:
  384. return
  385. heroes_positions = []
  386. for hero in home_heroes:
  387. hero_positions = positions(hero, threshold=ch['hero_threshold'])
  388. if not len (hero_positions) == 0:
  389. #TODO maybe pick up match with most wheight instead of first
  390. hero_position = hero_positions[0]
  391. heroes_positions.append(hero_position)
  392.  
  393. n = len(heroes_positions)
  394. if n == 0:
  395. print('No heroes that should be sent home found.')
  396. return
  397. print(' %d heroes that should be sent home found' % n)
  398. # if send-home button exists, the hero is not home
  399. go_home_buttons = positions(images['send-home'], threshold=ch['home_button_threshold'])
  400. # TODO pass it as an argument for both this and the other function that uses it
  401. go_work_buttons = positions(images['go-work'], threshold=ct['go_to_work_btn'])
  402.  
  403. for position in heroes_positions:
  404. if not isHome(position,go_home_buttons):
  405. print(isWorking(position, go_work_buttons))
  406. if(not isWorking(position, go_work_buttons)):
  407. print ('hero not working, sending him home')
  408. moveToWithRandomness(go_home_buttons[0][0]+go_home_buttons[0][2]/2,position[1]+position[3]/2,1)
  409. pyautogui.click()
  410. else:
  411. print ('hero working, not sending him home(no dark work button)')
  412. else:
  413. print('hero already home, or home full(no dark home button)')
  414.  
  415.  
  416.  
  417.  
  418.  
  419. def refreshHeroes():
  420. logger('🏒 Search for heroes to work')
  421.  
  422. goToHeroes()
  423.  
  424. if c['select_heroes_mode'] == "full":
  425. logger('βš’οΈ Sending heroes with full stamina bar to work', 'green')
  426. elif c['select_heroes_mode'] == "green":
  427. logger('βš’οΈ Sending heroes with green stamina bar to work', 'green')
  428. else:
  429. logger('βš’οΈ Sending all heroes to work', 'green')
  430.  
  431. buttonsClicked = 1
  432. empty_scrolls_attempts = c['scroll_attemps']
  433.  
  434. while(empty_scrolls_attempts >0):
  435. if c['select_heroes_mode'] == 'full':
  436. buttonsClicked = clickFullBarButtons()
  437. elif c['select_heroes_mode'] == 'green':
  438. buttonsClicked = clickGreenBarButtons()
  439. else:
  440. buttonsClicked = clickButtons()
  441.  
  442. sendHeroesHome()
  443.  
  444. if buttonsClicked == 0:
  445. empty_scrolls_attempts = empty_scrolls_attempts - 1
  446. scroll()
  447. time.sleep(2)
  448. logger('πŸ’ͺ {} heroes sent to work'.format(hero_clicks))
  449. goToGame()
  450.  
  451.  
  452. def main():
  453. time.sleep(5)
  454. t = c['time_intervals']
  455.  
  456.  
  457. windows = []
  458.  
  459. for w in pygetwindow.getWindowsWithTitle('bombcrypto'):
  460. windows.append({
  461. "window": w,
  462. "login" : 0,
  463. "heroes" : 0,
  464. "new_map" : 0,
  465. "check_for_captcha" : 0,
  466. "refresh_heroes" : 0
  467. })
  468.  
  469. while True:
  470. now = time.time()
  471.  
  472. for last in windows:
  473. last["window"].activate()
  474. time.sleep(2)
  475.  
  476. if now - last["check_for_captcha"] > addRandomness(t['check_for_captcha'] * 60):
  477. last["check_for_captcha"] = now
  478. solveCaptcha(pause)
  479.  
  480. if now - last["heroes"] > addRandomness(t['send_heroes_for_work'] * 60):
  481. last["heroes"] = now
  482. refreshHeroes()
  483.  
  484. if now - last["login"] > addRandomness(t['check_for_login'] * 60):
  485. sys.stdout.flush()
  486. last["login"] = now
  487. login()
  488.  
  489. if now - last["new_map"] > t['check_for_new_map_button']:
  490. last["new_map"] = now
  491.  
  492. if clickBtn(images['new-map']):
  493. loggerMapClicked()
  494.  
  495.  
  496. if now - last["refresh_heroes"] > addRandomness( t['refresh_heroes_positions'] * 60):
  497. solveCaptcha(pause)
  498. last["refresh_heroes"] = now
  499. refreshHeroesPositions()
  500.  
  501. #clickBtn(teasureHunt)
  502. logger(None, progress_indicator=True)
  503.  
  504. sys.stdout.flush()
  505.  
  506. time.sleep(1)
  507.  
  508. main()
  509.  
  510.  
  511. #cv2.imshow('img',sct_img)
  512. #cv2.waitKey()
  513.  
  514. # colocar o botao em pt
  515. # soh resetar posiΓ§oes se n tiver clickado em newmap em x segundos
  516.  
  517.  
  518.  
Advertisement
Add Comment
Please, Sign In to add comment