This repository was archived by the owner on Dec 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbot.py
More file actions
470 lines (376 loc) · 13.7 KB
/
bot.py
File metadata and controls
470 lines (376 loc) · 13.7 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
import os
import random
import time
import datetime
import math
import sys
import numpy
import cv2
import keyboard
import pyautogui
import shutil
from PIL import ImageGrab
from MTM import matchTemplates
from threading import Thread
#while True:
## print(pyautogui.position())
# time.sleep(0.3)
GAME_NUM = 0
START_TIME = datetime.datetime.now()
def notInList(results, thresholdDist, newObject):
for result in results:
if isinstance(result[1], tuple):
tupleObject = result[1]
if math.hypot(newObject[0] - tupleObject[0], newObject[1] - tupleObject[1]) < thresholdDist:
return False
else:
if math.hypot(newObject[0] - result[0], newObject[1] - result[1]) < thresholdDist:
return False
return True
def isInList(count, coin_item):
for counter in count:
if counter[0] == coin_item:
return True
return False
def countItemValue(count):
valuecount = 0
for counter in count:
valuecount += counter[1]
return valuecount
def matchTemplate(screen, template, templateName):
matches = []
thresholdDist = 30
match = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
locations = numpy.where(match >= .7)
for location in zip(*locations[::-1]):
if len(matches) == 0 or notInList(matches, thresholdDist, location):
matches.append((templateName, location))
return matches
def mouse_click(x, y, wait=0.2):
pyautogui.click(x, y)
time.sleep(wait)
def screen_grab():
im = ImageGrab.grab()
img_name = os.getcwd() + "\\imgs\\full_snap__" + str(int(time.time())) + ".png"
im.save(img_name, "PNG")
return img_name
def find_image(image_path, root_image_path):
matches = matchTemplates(
[("img", cv2.imread(image_path))],
cv2.imread(root_image_path),
N_object=10,
score_threshold=0.9,
# maxOverlap=0.25,
searchBox=None)
if len(matches["BBox"]) == 0:
return None, None
else:
box = matches["BBox"][0]
return box[0], box[1]
def check_image(img, thread=False, self=None):
if thread:
while self.game_status == "running":
b, _ = find_image(img, screen_grab())
if not b is None:
self.game_status = "ended"
else:
b, _ = find_image(img, screen_grab())
return True if b is not None else False
def click_image(img):
time.sleep(0.1)
x, y = find_image(img, screen_grab())
if x is None or y is None:
return
im = cv2.imread(img)
t_cols, t_rows, _ = im.shape
mouse_click(x + t_rows * (3 / 5), y + t_cols * (2 / 3))
def setup():
try:
os.mkdir('imgs')
except FileExistsError:
print("Program was not correctly closed last time. Make sure to exit the game with CTRL+C")
def start_game(self, start_img_path):
self.game_status = "starting"
click_image(start_img_path)
time.sleep(3)
retries = 0
while not check_image("rc_items/start_game.png"):
retries += 1
if check_image("rc_items/captcha_error.png") or retries >= 50:
print('captcha_error')
keyboard.press_and_release('F5')
break
time.sleep(1)
if not check_image("rc_items/start_game.png"):
pyautogui.moveTo(100, 100)
return True
sx, sy = find_image("rc_items/start_game.png", screen_grab())
if sx and sy:
mouse_click(sx + 2, sy + 2, wait=0.1)
else:
return True
return False
def start_game_msg(name):
global GAME_NUM
print("Starting Game #{!s}: '{}'@{!s}".format(GAME_NUM, name, datetime.datetime.now().time()))
GAME_NUM += 1
def end_game(self, fail=False):
if not fail:
self.game_status = "idle"
keyboard.press_and_release("page up")
keyboard.press_and_release("down")
while not check_image("rc_items/gain_power.png"):
if check_image("rc_items/gain_power_error.png"):
click_image("rc_items/gain_power_error.png")
break
time.sleep(1)
click_image("rc_items/gain_power.png")
click_image("rc_items/gain_power_error.png")
time.sleep(15)
if check_image("rc_items/collect_pc.png"):
click_image("rc_items/collect_pc.png")
keyboard.press_and_release("page up")
time.sleep(2)
click_image("rc_items/goto_games.png")
time.sleep(2)
if check_image("rc_items/collect_pc.png"):
click_image("rc_items/collect_pc.png")
else:
keyboard.press_and_release("page up")
time.sleep(2)
click_image("rc_items/goto_games.png")
os.execv(sys.executable, ['python'] + sys.argv) # restart script
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs)
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args,
**self._kwargs)
def join(self, *args):
Thread.join(self, *args)
return self._return
class Bot2048:
def __init__(self):
self.start_img_path = "rc_items/2048_gameimg.png"
self.available_moves = ["right", "left", "up", "down"]
self.game = "2048"
self.game_status = "idle"
def can_start(self):
return check_image(self.start_img_path)
def play(self):
err = start_game(self, self.start_img_path)
if err:
return not err
start_game_msg(self.game)
self.run_game()
end_game(self)
def run_game(self):
self.game_status = "running"
try:
thread = ThreadWithReturnValue(target=check_image,
args=("rc_items/gain_power.png", True, self,))
thread.start()
except:
print("Unable to start thread for checking image")
end_game(self, fail=True)
while self.game_status == "running":
for i in range(8):
keyboard.press_and_release(random.choice(self.available_moves))
time.sleep(0.15)
keyboard.press_and_release("page up") # to prevent errors for the thread with check image
class BotCoinFlip:
def __init__(self):
self.start_img_path = "rc_items/coinflip_gameimg.png"
self.game = "CoinFlip"
self.game_status = "idle"
self.coin_pos = []
self.coin_items = {
"binance": [],
"btc": [],
"eth": [],
"litecoin": [],
"monero": [],
"eos": [],
"rlt": [],
"xrp": [],
"xml": [],
"tether": [],
}
self.coin_images = [
("binance", cv2.imread("rc_items/coinflip_item_binance.png")),
("btc", cv2.imread("rc_items/coinflip_item_btc.png")),
("eth", cv2.imread("rc_items/coinflip_item_eth.png")),
("litecoin", cv2.imread("rc_items/coinflip_item_litecoin.png")),
("monero", cv2.imread("rc_items/coinflip_item_monero.png")),
("eos", cv2.imread("rc_items/coinflip_item_eos.png")),
("rlt", cv2.imread("rc_items/coinflip_item_rlt.png")),
("xrp", cv2.imread("rc_items/coinflip_item_xrp.png")),
("xml", cv2.imread("rc_items/coinflip_item_xml.png")),
("tether", cv2.imread("rc_items/coinflip_item_tether.png")),
]
self.card_image = [("card", cv2.imread("rc_items/coinflip_back.png"))]
def can_start(self):
return check_image(self.start_img_path)
def play(self):
err = start_game(self, self.start_img_path)
if err:
return False
start_game_msg(self.game)
pyautogui.moveTo(100, 100)
keyboard.press_and_release("down")
time.sleep(4)
self.get_coin_fields()
self.check_coins()
self.match_coins()
end_game(self)
return True
def get_coin_fields(self):
self.game_status = "running"
screen = cv2.imread(screen_grab())
matches = cv2.matchTemplate(screen, cv2.imread("rc_items/coinflip_back.png"), cv2.TM_CCOEFF_NORMED)
locations = numpy.where(matches >= .7)
append = self.coin_pos.append
thresholdDist = 30
for pt in zip(*locations[::-1]):
if len(self.coin_pos) == 0 or notInList(self.coin_pos, thresholdDist, pt):
append(pt)
def check_coins(self):
ind = 0
max_index = len(self.coin_pos)
while ind < max_index:
coin1_pos = self.coin_pos[ind]
coin2_pos = self.coin_pos[ind + 1]
mouse_click(coin1_pos[0] + 10, coin1_pos[1] + 10, wait=0.4)
mouse_click(coin2_pos[0] + 10, coin2_pos[1] + 10, wait=0.5)
# pyautogui.moveTo(100, 100)
screen = cv2.imread(screen_grab())
matches = []
threads = []
i = 1
for template in self.coin_images:
try:
thread = ThreadWithReturnValue(target=matchTemplate,
args=(screen, template[1], template[0],))
thread.start()
threads.append(thread)
# print("starting thread " + str(i) + " for matching " + template[0])
i += 1
except:
print("Couldn't start thread " + str(i) + " for matching " + template[0])
end_game(self, fail=True)
for thread in threads:
result = thread.join()
if len(result) > 0:
matches.append(result)
if len(matches) == 2:
coin1 = (matches[0][0][0], matches[0][0][1])
coin2 = (matches[1][0][0], matches[1][0][1])
if coin1[0] == coin2[0]:
self.coin_items.pop(coin1[0])
else:
self.coin_items[coin1[0]].append(coin1[1])
self.coin_items[coin2[0]].append(coin2[1])
else:
if len(matches) == 1:
coin = (matches[0][0][0], matches[0][0][1])
self.coin_items.pop(coin[0])
else:
end_game(self, fail=True)
ind += 2
def match_coins(self):
for coin in self.coin_items.values():
if len(coin) == 2:
c1 = coin[0]
mouse_click(c1[0] + 10, c1[1] + 10, wait=0.05)
c2 = coin[1]
mouse_click(c2[0] + 10, c2[1] + 10, wait=0.05)
time.sleep(2)
keyboard.press_and_release("esc")
class BotCoinClick:
def __init__(self):
self.start_img_path = "rc_items/coinclick_gameimg.png"
self.game = "CoinClick"
self.game_status = "idle"
def can_start(self):
return check_image(self.start_img_path)
def play(self):
err = start_game(self, self.start_img_path)
if err:
return not err
start_game_msg(self.game)
self.run_game()
end_game(self)
def run_game(self):
self.game_status = "running"
try:
thread = ThreadWithReturnValue(target=check_image,
args=("rc_items/gain_power.png", True, self,))
thread.start()
except:
print("Unable to start thread for checking image")
end_game(self, fail=True)
while self.game_status == "running":
if pyautogui.locateOnScreen("rc_items/gain_power_error.png", confidence=0.9):
self.game_status = "ended"
break
pic = pyautogui.screenshot(region=(530, 370, 828, 417,))
width, height = pic.size
clicked = False
for x in range(0, width, 5):
if clicked:
break
for y in range(0, height, 5):
r, g, b = pic.getpixel((x, y))
# blue coin
if b == 183 and r == 0:
mouse_click(x + 530, y + 380, wait=0)
clicked = True
break
# yellow coin
elif b == 64 and r == 200:
clicked = True
mouse_click(x + 530, y + 380, wait=0)
break
# orange coin
elif b == 33 and r == 231:
clicked = True
mouse_click(x + 530, y + 380, wait=0)
break
# grey coin
elif b == 230 and r == 230:
clicked = True
mouse_click(x + 535, y + 380, wait=0)
break
if self.game_status == "ended":
break
if self.game_status == "ended":
break
def main():
Bots = [
Bot2048,
BotCoinFlip,
BotCoinClick
]
global GAME_NUM
while True:
for bot in Bots:
if bot().can_start():
bot().play()
if __name__ == "__main__":
# pyautogui.displayMousePosition()
if os.path.exists("imgs"):
shutil.rmtree('imgs')
setup()
try:
main()
except KeyboardInterrupt:
print("Program closed by User!")
finally:
print("\nStatistics:\n",
"Time running: {!s}\n".format(datetime.datetime.now() - START_TIME),
"Played Games: {!s}\n".format(GAME_NUM)
)
shutil.rmtree('imgs')