예제 #1
0
 def move_humanly_mouse_random_location_in_box(box):
     hc = HumanClicker()
     box = Box(box)
     delta_x = randint(0, box.width())
     delta_y = randint(0, box.height())
     to_location = (int(box.x() + delta_x), int(box.y() + delta_y))
     hc.move(to_location, 0.5)
예제 #2
0
 def __init__(self, hwnd, x, y, w, h):
     self.hc = HumanClicker()
     self.hwnd = hwnd
     self.x = x
     self.y = y
     self.w = w
     self.h = h
     self.range = hand_pick_range()
예제 #3
0
class PokerWatcher:
    def __init__(self, hwnd, x, y, w, h):
        self.hc = HumanClicker()
        self.hwnd = hwnd
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.range = hand_pick_range()

    def start(self):
        loop = asyncio.get_event_loop()
        loop.create_task(self.async_start())
        loop.run_forever()

    async def move_and_click(self, x, y):
        self.hc.move((x + self.x + randint(0, 3), y + self.y + randint(0, 3)),
                     2)
        self.hc.click()
        await asyncio.sleep(2)

    async def async_start(self):
        while True:
            await asyncio.sleep(0.2)
            screen_image = capture_screen(self.hwnd, self.w, self.h)

            if count_community_cards(screen_image) > 0:
                print('count_community_cards continue')
                continue

            action_index = find_action_index(screen_image)
            if action_index != 0:
                print('wait for player action')
                continue

            hole_cards = retrieve_hole_cards(screen_image)
            if not hole_cards:
                print("Failed to retrieve hole cards")
                continue

            (a, b) = hole_cards
            if (a, b) in self.range or (b, a) in self.range:
                mixer.music.play()
            else:
                x, y = FOLD_BUTTON_LOCATION
                r, g, b = screen_image.getpixel((x - 3, y - 3))
                if b > 150:
                    await self.move_and_click(x, y)
                else:
                    mixer.music.play()
                    x, y = CALL_BUTTON_LOCATION
                    await self.move_and_click(x, y)
예제 #4
0
class FindItem:
	def __init__(self, title_img):
		self.__title_img = title_img
		self.move = HumanClicker()


	def get_box_dimention(self):
		if pyautogui.locateOnScreen(self.__title_img):
			box_dimention = pyautogui.locateOnScreen(self.__title_img)
			x = box_dimention[0] + 10
			x2 = x + 119
			y = box_dimention[1] + box_dimention[3] + 20
			y2 = y + 443
			return (x,y,x2,y2)
	def find(self,item_to_find,expected_y):
			dimention = self.get_box_dimention()

			if expected_y:
				print("expected_y = ", expected_y)
				self.move.move((randint(dimention[0],dimention[2]),randint(expected_y-2,expected_y+2)),2  )
				cp = pyautogui.position()
				if item_to_find in readbox.read(cp[0]+5,cp[1]+20,cp[0]+150,cp[1]+30):
					print(pyautogui.position()[1])
					print('poszlo z pamieci')
					return pyautogui.position()[1]

						
			y_switch = dimention[1]
			direction = 0
			while True:

				if direction==0:
					y_switch += randint(5,15)
					if y_switch >= dimention[3]:
						print("1")
						direction = 1
				else:
					y_switch -= randint(5,15)
					if y_switch <= dimention[1]:
						print("0")
						direction = 0
				#self.move.move(,5))				
				pyautogui.moveTo(randint(dimention[0],dimention[2]),y_switch, 0.001, pyautogui.easeInQuad)
				cp = pyautogui.position()
				if item_to_find in readbox.read(cp[0]+5,cp[1]+20,cp[0]+150,cp[1]+30):
					print(cp[1])
					return cp[1]
예제 #5
0
def run_recovery(logger):
    # base_map_file_path = r"C:\temp\test\ca8b7525-9399-42f7-9eee-c0fdf0431b06.png"
    # client_map_file_path = r"C:\temp\templates\seer_village_bank.png"
    # match_coordinates = match_images(base_map_file_path, client_map_file_path,show_box=True)
    # if match_coordinates is None:
    #     pass
    # print "YES", match_coordinates

    hc = HumanClicker()

    game_window = RunescapeWindow(logger=logger)
    game_window.set_main_client_data()

    pprint(game_window.get_client_main_data())
    base_client_info = game_window.get_client_main_data()

    # base_map_file_path = r"C:\temp\test\ca8b7525-9399-42f7-9eee-c0fdf0431b06.png"
    # base_map_file_path = base_client_info.get("MapFile")

    # for client_name, client_info in base_client_info.iteritems():
    for client_name, client_info in base_client_info.items():
        logger.info("run recovery on {0}".format(client_name))
        base_info = base_client_info.get(client_name)
        base_map_file_path = base_info.get("MapFile")
        # base_map_file_path = "C:/temp/test/edaeac32-edf2-42af-ac74-ac6db88b5ec3.png"
        bank_anchor_file = r"C:\temp\templates\seer_village_bank.png"
        match_coordinates = match_images(base_map_file_path,
                                         bank_anchor_file,
                                         show_box=True)
        if match_coordinates is None:
            logger.info("Recovery has failed. Ending Script")
            continue
        else:
            click_loc = tuple(
                map(operator.add, base_info.get("ClientLoc"),
                    base_info.get("GamePlayLocByClient")))
            click_loc = tuple(
                map(operator.add, click_loc,
                    base_info.get("MapLocByGamePlay")))
            click_loc = tuple(map(operator.add, click_loc, match_coordinates))
            click_loc = tuple(map(operator.add, click_loc, (6, 16, 7, 16)))

            hc.move((click_loc[0], click_loc[1]), 2)
예제 #6
0
파일: window.py 프로젝트: Murtrag/game_bot
from pyclick import HumanClicker
import pyautogui
from random import randint

mouse = HumanClicker()


class Window:
    def __init__(self, title):
        self._title = title

    def _get_title_dimension(self):
        return pyautogui.locateOnScreen(self._title, confidence=.8)

    def _get_window_image(self):
        title = self._get_title_dimension()
        return pyautogui.screenshot(region=(title.left - 10, title.top, 300,
                                            500))

    def find_item(self, item):
        title = self._get_title_dimension()

        title_x, title_y = pyautogui.center(title)
        mouse.move((randint(
            title_x - 30, title_x + 30), randint(title_y - 4, title_y + 4)), 2)
        pyautogui.click()

        return [(randint(title.left + x.left, title.left + x.left + 15),
                 randint(title.top + x.top + 3, title.top + x.top + 7))
                for x in pyautogui.locateAll(
                    item, self._get_window_image(), confidence=.9)]
예제 #7
0
from pyclick import HumanClicker
import pyautogui
import random

# initialize HumanClicker object
hc = HumanClicker()
iterations = 600  # how many times the script should loop and produce molten glass

for i in range(iterations):
    # establish random coordinates to avoid bot detection
    pos = random.randrange(-10, 10, 1)
    seaweedhor = random.randrange(-37, 37, 1)
    seaweedver = random.randrange(-26, 26, 1)
    deposithor = random.randrange(-44, 44, 1)
    depositver = random.randrange(-36, 36, 1)

    # establish random times to avoid bot detection
    spelltime = random.randrange(0, 2, 1)
    banktime = random.randrange(0, 1, 1)
    allothertime = random.randrange(0, 2, 1)

    # banking
    hc.move((929 + pos, 459 + pos), 3 + spelltime)
    hc.click()
    hc.move((1115 + deposithor, 659 + depositver), 1 + banktime)
    hc.click()

    # withdraw 18 buckets of sand
    hc.move((219 + pos, 222 + pos), 1 + allothertime)
    pyautogui.click(button='right')
    hc.move((203 + pos, 366 + pos), 1 + allothertime)
예제 #8
0
import numpy as np
from matplotlib import pyplot as plt
import pyautogui
import pyscreenshot as ImageGrab
import time
import pyaudio
import wave
from array import array
import keyboard
import mouse
import time
import random
from pyclick import HumanClicker

time.sleep(2)
hc = HumanClicker()


def bobberfish():
    b = 0
    for c in range(300, 850, 70):
        b += 1
        #Grabs the whole screen to search for 'Fishing Bobber' Tooltip
        im = ImageGrab.grab(bbox=(0, 0, 2560, 1440))
        im.save('im' + str(b) + '.png')
        # Image we want to search
        img_rgb = cv.imread('im' + str(b) + '.png')
        # Make image grey to remove some variation
        img_grey = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
        # Image we want to find
        template = cv.imread('cog2.png', 0)
예제 #9
0
def main_run():
    # loop while waiting on emey to die
    def wait_loop():
        health_counter = 1
        enemy = Enemy()
        #waits until enemy health is 0
        start_time = time.time()
        while health_counter != 50:
            enemy.getHealth()
            cv2.imshow('health-hsv', enemy.health_img)
            cv2.imshow('mask', enemy.mask)
            cv2.waitKey(1)
            if enemy.health == 0:
                #time.sleep(random())
                print(
                    f'Fight took:{time.time()-start_time:.2f} secs\nHealth Counter={health_counter}'
                )
                health_counter = 1
                return
            health_counter += 1
            #time.sleep(1+random())

    # initialize HumanClicker object
    hc = HumanClicker()

    #dark_wizard = [ [27,70,22], [28,107,64] ]
    #hill giant
    dark_wizard = [[20, 46, 34], [33, 106, 72]]
    green_tile = [[61, 113, 105], [68, 255, 255]]
    # low high hsv values
    player_tile = [[87, 232, 190], [90, 255, 255]]
    #gree_health_bar = [ [54,108,120],[62,255,255]]
    #red_health_bar = [ [0,254,254],[1,255,255] ]
    secs_wait = 1
    while 1:
        playScreen = Screenshot.shoot(0, 0, 520, 360, 'hsv')

        low = np.array(green_tile[0])
        high = np.array(green_tile[1])
        mask = cv2.inRange(playScreen, low, high)

        #kernel = np.ones((3,3), np.uint8)
        #closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        contours, _ = cv2.findContours(mask, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)

        areas = {}
        # gathers areas with center coords
        for con in (contours):
            area = cv2.contourArea(con)
            if area > 50:
                M = cv2.moments(con)
                #print(area)
                cx = int(M['m10'] / M['m00'])
                cy = int(M['m01'] / M['m00'])
                areas[area] = (cx, cy)
        # restarts loop if no emenies around
        if len(areas.keys()) == 0:
            print(f'No enemy detected...waiting {secs_wait} secs...')
            time.sleep(secs_wait)
            secs_wait += secs_wait * .20
            continue
        # find distance to 260,180 coords.  which is center of playing screen
        distances = {}
        for ele_set in areas.items():
            x = ele_set[1][0]
            y = ele_set[1][1]
            dist = int(sqrt(((260 - x)**2) + ((180 - y)**2)))
            distances[dist] = areas[ele_set[0]]
        # select point with min distance to center of play screen
        min_distance = min([i for i in distances.keys()])
        #print(f'minimum distance:{min_distance}')
        #print(f'coords:{distances[min_distance]}')

        # unpacks coords of tile closest to center of screen
        cx, cy = distances[min_distance]

        # move the mouse to position (100,100) on the screen in approximately 2 seconds
        hc.click(x=cx, y=cy)
        #autopy.mouse.move(cx,cy)
        #Mouse.moveTo(cx,cy)
        # wait after clicking to be able to see health box on top top of playscreen
        # time.sleep(2)
        # wait_loop()
        time.sleep(triangular(14, 29) / 1.5)
        # resets time to wait
        secs_wait = 1
예제 #10
0
from pyclick import HumanClicker
import pyautogui
import random
import time
import decimal

# initialize HumanClicker object
hc = HumanClicker()
iterations = 100 # how many times the script should loop and cast make leather
pos = random.randrange(-20,20,1)

for i in range(iterations):

    hc.move((1454+random.randrange(-20,20,1),487+random.randrange(-20,20,1)), 0.6)
    hc.click()
    hc.move((1454+random.randrange(-20,20,1),562+random.randrange(-20,20,1)), 0.6)
    hc.click()
    
    hc.move((954+random.randrange(-20,20,1),482+random.randrange(-20,20,1)), 0.4)
    hc.click()

    pyautogui.keyDown('shift')
    time.sleep(.6)
    hc.move((1454+random.randrange(-20,20,1),637+random.randrange(-20,20,1)), 0.6)
    hc.click()
    hc.move((1454+random.randrange(-20,20,1),712+random.randrange(-20,20,1)), 0.6)
    hc.click()
    time.sleep(.5)
    pyautogui.keyUp('shift')
    time.sleep(.5)
예제 #11
0
from status import Status_Bar
from pyclick import HumanClicker  # super symulacja ruchu myszki
import pyautogui
import time
from random import randint, random
from lib.craft import Crafting
from lib.window import Window
mouse = HumanClicker()
status = Status_Bar()

t = Crafting(button='media/box-titles/create.png')
source = Window(title='media/box-titles/source.png')
inventory = Window(title='media/box-titles/inventory.png')
target = Window(title='media/box-titles/target.png')

while True:
    if status.stamin:
        t.continue_()
        # Get resources
        s_s = source.find_item(item="media/items/stone_shards.png")
        mouse.move((s_s[0][0], s_s[0][1]), 2)
        pyautogui.mouseDown()
        inventory_workspace = inventory.get_workspace()
        mouse.move(
            (inventory_workspace['left'],
             inventory_workspace["top"] + inventory_workspace["height"]), 2)
        pyautogui.mouseUp()
        time.sleep(random() * 2.5)
        pyautogui.press('enter')

        # Add resources to Crafting window and combine it
예제 #12
0
    square_mar_he = board_height / 8

    if who == "b":
        x_square1 = 9 - (ord(str(move)[0]) - 96)
        y_square1 = int(str(move)[1])
        x_square2 = 9 - (ord(str(move)[2]) - 96)
        y_square2 = int(str(move)[3])
    else:
        x_square1 = ord(str(move)[0]) - 96
        y_square1 = 9 - int(str(move)[1])
        x_square2 = ord(str(move)[2]) - 96
        y_square2 = 9 - int(str(move)[3])

    if legit == "y":
        time.sleep(random.randint(1, 35) / 10)
        hc = HumanClicker()
        curve = HumanCurve(
            pyautogui.position(),
            (round(board_pos[0] +
                   (square_mar_wi * x_square1) - square_mar_wi / 2) -
             random.randint(-13, 13),
             round(board_pos[1] +
                   (square_mar_he * y_square1) - square_mar_he / 2) -
             random.randint(-13, 13)),
            distortionFrequency=0,
            tweening=pytweening.easeInOutQuad,
            offsetBoundaryY=8,
            offsetBoundaryX=8,
            targetPoints=random.randint(30, 40))
        hc.move((round(board_pos[0] +
                       (square_mar_wi * x_square1) - square_mar_wi / 2),
예제 #13
0
class Frame():
    def __init__(self, setupwindow=True):
        # object contains window ID and x,y positions
        self.rs_window = setup.Window(setupwindow=setupwindow)
        self.rsx, self.rsy = self.rs_window.position
        self.hc = HumanClicker()

    def closeBank(self):
        """ Keybinding 'esc' should be enabled """
        press('esc', interval=triangular(0.05, 0.3))

    def depositAll(self):
        x = self.rsx + int(triangular(432, 453))
        y = self.rsy + int(triangular(324, 350))
        self.hc.click(x=x, y=y)

    def invCount(self, *args):
        """Counts the number of slots being used in inventory"""
        """pass a func to do something with each slot's ROI, then upper and lower """
        # makes sure inventory button is selected
        # if not self.is_button_selected('inventory'):
        #     self.press_button('inventory')

        bag, bagx, bagy = self.get_bag('bag and coords', 'hsv')
        # HSV range passed in args
        if args:
            low = np.array(args[1])
            high = np.array(args[2])
        # HSV range of Empy Inventory
        else:
            low = np.array([10, 46, 58])
            high = np.array([21, 92, 82])
        # applies mask
        mask = cv2.inRange(bag, low, high)

        # only applies to empty inventory
        if not args:
            # removes any noise
            kernel = np.ones((3, 3), np.uint8)
            closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

            #inverts mask
            closing = cv2.bitwise_not(closing)
        count = 0
        for row in range(7):
            for cols in range(4):
                # 1st Slot ROI
                if row == 0 and cols == 0:
                    #print(row,cols)
                    slot_x = 0
                    slot_x2 = 36

                    slot_y = 0
                    slot_y2 = 43
                # rest of slots ROI
                else:
                    slot_x = row * 36 + 1
                    slot_x2 = (row * 36) + 36 - 1

                    slot_y = cols * 43 + 1
                    slot_y2 = 43 + (cols * 43) - 1

                if args:
                    slot_roi = mask[slot_x:slot_x2, slot_y:slot_y2]
                else:
                    # Selected ROI
                    slot_roi = closing[slot_x:slot_x2, slot_y:slot_y2]

                # Do fucntion with slot_roi else  add to count
                if args:
                    passed_func = args[0]
                    #x,y,_,_ = cv2.boundingRect(slot_roi)
                    #_, psx, psy = getPlayingScreen()
                    slot_x += int(bagx + triangular(1, 30))
                    slot_y += int(bagy + triangular(5, 25))
                    passed_func(slot_x, slot_y)
                    return

                # just count
                else:
                    # check pixel value == 255
                    if 255 in slot_roi:
                        count += 1

        # returns the N of items in inv
        return count

    def invSlotIter(self):
        # loads database of items to drop
        item_database = {}
        # makes sure inventory button is selected
        if not self.is_button_selected('inventory'):
            self.press_button('inventory')

        bag, bagx, bagy = self.get_bag('bag and coords', 'hsv')
        bag_grey = self.get_bag('only')
        # debug
        #cv2.imshow('bag', bag)
        #cv2.waitKey(0)
        #cv2.imshow('bag_grey', bag_grey)
        #cv2.waitKey(0)

        # HSV range of Empy Inventory
        low = np.array([10, 46, 58])
        high = np.array([21, 92, 82])
        # applies mask
        mask = cv2.inRange(bag, low, high)
        #cv2.imshow('mask', mask)
        #cv2.waitKey(0)

        # removes any noise
        kernel = np.ones((3, 3), np.uint8)
        closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        #inverts mask
        closing = cv2.bitwise_not(closing)
        #cv2.imshow('closing', closing)
        #cv2.waitKey(0)

        # finds contours
        #_,contours,_ = cv2.findContours(closing.copy(), 1, 2)

        ### draws white rectangle on found itmes ###
        #for cnt in contours:
        #    # creates a white rectangle around items
        #    x,y,w,h = cv2.boundingRect(cnt)
        #    cv2.rectangle(closing,(x,y),(x+w,y+h),(255,255,255),-1)
        ############################################

        ### Draws division lines ###
        # draws row lines
        #sloth = closing.shape[0] / 7
        #slotw = closing.shape[1] / 4
        #for i,rows in enumerate(xrange(6)):
        #    cv2.line(closing,(0, sloth*(i+1)),(173,sloth*(i+1)),(255,255,255),1)
        # draws col lines
        #for i,cols in enumerate(xrange(3)):
        #    cv2.line(closing,(slotw*(i+1),0),(slotw*(i+1),253),(255,255,255),1)
        ############################

        # checks each slot for white pixels
        count = 0
        for row in range(7):
            for cols in range(4):
                # 1st Slot ROI
                if row == 0 and cols == 0:
                    #print(row,cols)
                    slot_x = 0
                    slot_x2 = 36

                    slot_y = 0
                    slot_y2 = 43
                # rest of slots ROI
                else:
                    slot_x = row * 36 + 1
                    slot_x2 = (row * 36) + 36 - 1

                    slot_y = cols * 43 + 1
                    slot_y2 = 43 + (cols * 43) - 1

                # Selected ROI
                slot_roi = closing[slot_x:slot_x2, slot_y:slot_y2]

                # check pixel value == 255
                if 255 in slot_roi:
                    # getting ROI from original screenshot
                    # bag_roi = bag_grey[slot_x:slot_x2, slot_y:slot_y2]

                    item_database[count] = (slot_x, slot_x2, slot_y, slot_y2)

                    #cv2.imshow('image',bag_roi)
                    #cv2.waitKey(0)
                    count += 1
                else:
                    item_database[count] = 0
                    count += 1

        for img_in_db in item_database:
            print(img_in_db)
            if img_in_db != 0:
                x, x2, y, y2 = img_in_db
                img_in_db = bag_grey[x:x2, y:y2]
                # cv2.imshow('img', img_in_db)
                # cv2.waitKey(0)

        return count

    def open_cw_bank(self):
        """Finds the visiblest square of the chest in castle wars bank, wors better when viewing from above at shortest distance."""

        # Takes screenshot, as Hue-saturated-value image
        play_window, psx, psy = self.getPlayingScreen('hsv')
        lower_gray = np.array([0, 0, 0])
        upper_gray = np.array([255, 255, 1])

        # Makes a black/white mask
        mask = cv2.inRange(play_window, lower_gray, upper_gray)
        # inverts selection
        #res = cv2.bitwise_and(play_window, play_window, mask=mask)
        kernel = np.ones((2, 2), np.uint8)
        dilation = cv2.dilate(mask, kernel, iterations=1)

        # cv2.imshow('img', dilation)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()

        # Finds contours
        contours, _ = cv2.findContours(dilation.copy(), cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)

        try:
            # looks for center of grey color with biggest area, > 3000
            for con in contours:
                # print(cv2.contourArea(con))
                if cv2.contourArea(con) > 10000:
                    #print(f"big area found {cv2.contourArea(con)}")

                    M = cv2.moments(con)
                    # finds centroid
                    cx, cy = (int(M["m10"] / M["m00"]),
                              int(M["m01"] / M["m00"]))
                    psx += cx
                    psy += cy
                    # adds randomness to coords
                    psx += int(triangular(-17, 17))
                    psy += int(triangular(-17, 17))
                    self.hc.click(x=psx, y=psy)
                    break
        except Exception as e:
            print(f"Bank NOT found!\nMove camera around!\n{e}")

    def find_bank_booth(self):
        """Finds bank booth and clicks it.  Returns True if found, else False"""

        bank_booth_glass_window = ([0, 72, 149], [179, 82, 163])
        # take screenshot of playing area
        play_area_screen, psx, psy = self.getPlayingScreen()

        # find glasswindow for bankbooth
        mask = cv2.inRange(play_area_screen,
                           np.array(bank_booth_glass_window[0]),
                           np.array(bank_booth_glass_window[1]))

        # gets osr window's position
        #rsx,rsy = position()

        psx += self.rsx
        psy += self.rsy

        kernel = np.ones((3, 3), np.uint8)
        closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        #cv2.imshow('img', closing)
        #cv2.waitKey(0)

        # Finds contours
        _, contours, _ = cv2.findContours(closing.copy(), cv2.RETR_TREE,
                                          cv2.CHAIN_APPROX_SIMPLE)

        try:
            for con in contours:
                if cv2.contourArea(con) > 10:
                    #print(cv2.contourArea(con))
                    M = cv2.moments(con)
                    # finds centroid
                    cx, cy = (int(M["m10"] / M["m00"]),
                              int(M["m01"] / M["m00"]))
                    psx += cx
                    psy += cy
                    # adds randomness to coords
                    psx += triangular(-7, 7)
                    psy += triangular(-7, 7)

                    self.hc.click(x=psx, y=psy)
                    sleep(triangular(.1, .5))
                    return 1
        except Exception as e:
            print(f"Bank NOT found!\nMove camera around!\n{e}")
        # returns False if bank not found
        return 0

    def antiban(self, skill):
        #rsx,rsy = position()
        rn = randint(0, 99)
        if rn == 0:
            print("Starting antiban")
            # Tuples of locations
            stats_btn = Mouse.genCoords(567, 194, 589, 215)

            #Clicks the skills button
            Mouse.moveClick(stats_btn[0] + self.rsx, stats_btn[1] + self.rsy,
                            1)

            #hovers over a certain skill
            self.skillHover(skill)
            self.moveback(skill)
            return True

            #returns true if antiban ran, to let me know if it acutally did ran

        elif rn == 1:
            print("Starting antiban")
            self.skillsHover(self.rsx, self.rsy)
            self.moveback(skill)
            return True

    def moveback(self, skill):
        if skill == 'magic':
            self.press_button('magic')
        else:
            #moves back to bag
            self.press_button('inventory')
        print("Antiban end")

    def greetings(self, skill):
        n = randint(0, 10)
        if randint(0, 10):
            if n == 0:
                Keyboard.type_this("What's going on guys?")
            elif n == 1:
                Keyboard.type_this("whats up ppl!?")
            elif n == 2:
                Keyboard.type_this("what you all doing?")
            elif n == 3:
                Keyboard.type_this("hiiiii guys!")
            elif n == 4:
                Keyboard.type_this("what's your guys highest skill lv??")
            elif n == 5:
                Keyboard.type_this("flash1:what!?")
            elif n == 6:
                Keyboard.type_this("what are you talking about?")
            elif n == 7:
                Keyboard.type_this("i dont need to be hearing this")
            elif n == 8:
                Keyboard.type_this("chilling...")
            elif n == 9:
                Keyboard.type_this("skilling, what about you all?")
            elif n == 10:
                Keyboard.type_this(
                    "right now im working on {}, what about you guys??".format(
                        skill))

            Keyboard.press('enter')
        sleep(triangular(.1, .5))

    def skillsHover(self, rsx, rsy):
        """Hovers over n skills by n times"""
        n = randint(0, 2)
        if n > 0:
            # Tuples of locations
            stats_btn = Mouse.genCoords(567, 194, 589, 215)
            #Clicks the skills button
            Mouse.moveClick(stats_btn[0] + rsx, stats_btn[1] + rsy, 1)
            for i in range(n):
                #                              x1  y1  x2  y2
                stats_window = Mouse.genCoords(557, 234, 729, 470)
                # Randomly hovers over a random skill
                Mouse.moveTo(stats_window[0] + rsx, stats_window[1] + rsy)
                sleep(triangular(.1, .5))

    def skillHover(self, skill):
        """Hovers over passed skill from 1-5 secs"""
        #Coordinates of skill's button
        skills = {
            'attack': 0,
            'hitpoints': 0,
            'mining': 0,
            'strength': 0,
            'agility': 0,
            'smithing': 0,
            'defence': 0,
            'herblore': (620, 295, 662, 311),
            'fishing': 0,
            'ranged': 0,
            'thieving': 0,
            'cooking': 0,
            'prayer': 0,
            'crafting': (621, 358, 664, 373),
            'firemaking': 0,
            'magic': (557, 388, 602, 402),
            'fletching': (620, 389, 666, 406),
            'woodcutting': 0,
            'runecraft': 0,
            'slayer': 0,
            'farming': 0,
            'construction': 0,
            'hunter': 0
        }

        x1, y1, x2, y2 = skills[skill]
        x, y = Mouse.genCoords(x1, y1, x2, y2)
        # Mouse.moveTo(x,y)
        randS = triangular(.1, .5)
        self.hc.move((x, y), randS)

    def logout(self):
        #  Door Button
        x, y = Mouse.genCoords(636, 495, 650, 515)
        x += self.rsx
        y += self.rsy
        Mouse.moveClick(x, y, 1)

        # Log out Button
        x, y = Mouse.genCoords(581, 428, 707, 450)
        x += self.rsx
        y += self.rsy
        Mouse.moveClick(x, y, 1)

    def press_button(self, button, *args):
        """Presses button on random coordinates stored in the buttons dictionary.  Returns button coords if 'coors' passed as argument"""
        buttons = {
            'combat': 0,
            'stats': (570, 197, 586, 214),
            'quest': 0,
            'inventory': (631, 194, 658, 221),
            'equipment': (666, 196, 687, 216),
            'prayer': (700, 198, 720, 214),
            'magic': (733, 195, 751, 214),
            'clan': 0,
            'friend': 0,
            'enemy': 0,
            'logout': 0,
            'options': 0,
            'emotes': 0,
            'music': 0,
            'quick-prayer': 0,
            'run': 0
        }

        #unpacks the tuple
        x1, y1, x2, y2 = buttons[button]

        try:
            if args[0] == 'coords':
                return x1, y1, x2, y2
        except:
            pass

        #generates random coords
        x, y = Mouse.genCoords(x1, y1, x2, y2)
        #moves to those coords
        Mouse.moveClick(x, y, 1)

    def findOptionClick(self, x, y, option_name):
        #Mouse.moveClick(x, y, 3)
        print(f"Right-Clicking:x{x} y:{y}")
        self.hc.click(x=x, y=y)
        sleep(triangular(.5, 1))
        """Option name of in Image database only needs to be passed, x,y are obsoleate"""
        from modules import Imgdb
        # Image DB
        idb = Imgdb.ImgDb()
        #name of option loaded from image db
        template = idb.pickled_dict[option_name]
        # turning template to graysacle if RBG
        if len(template.shape) == 3:
            template = cv2.cvtColor(template, cv2.COLOR_RGB2GRAY)
        # getting w and h for generating random coords in range
        template_w, template_h = template.shape[::-1]

        rs_window, x, y = self.getPlayingScreen('gray')

        res = cv2.matchTemplate(rs_window, template, cv2.TM_CCOEFF_NORMED)
        threshold = 1
        # Store the coordinates of matched area in a numpy array
        loc = np.where(res >= threshold)

        # clicks on option here when found in pattern
        for pt in zip(*loc[::-1]):  #goes through each found image
            # Draw a rectangle around the matched region.
            # cv2.rectangle(rs_window, pt, (pt[0] + template_w, pt[1] + template_h), (0,255,255), 2)

            # creates list of possible coords
            ptx = [i for i in range(pt[0] + 5, pt[0] + template_w)]
            pty = [i for i in range(pt[1] + 5, pt[1] + template_h)]
            # chooses a single coords from the list
            ptx = choice(ptx)
            pty = choice(pty)
            print(f"ptx{ptx} pty{pty}")

            # debug ###
            #cv2.imshow('img', rs_window)
            #cv2.waitKey(5000)
            #cv2.destroyAllWindows()

            # range of x and y to click on.
            # in the options
            #Mouse.randMove(x,y1,x+(w/2),y2, 1)
            #ptx, pty = Mouse.randCoord(pt, template_w, template_h)
            #Mouse.moveClick(ptx,pty, 1)
            self.hc.click(x=ptx, y=pty)
            sleep(triangular(1, 2))
            break

    def position(self, windowID=''):
        """ Returns top left position of Runescape window"""
        return self.rsx, self.rsy

    def getPlayingScreen(self, color):
        """ Returns play screen area as an HSV image,
            and the first point of the image """

        #playScreen = Screenshot.shoot(self.rsx, self.rsy,517,362,color)
        playScreen = Screenshot.shoot(self.rsx, self.rsy, 760, 520, color)

        return playScreen, self.rsx, self.rsy

    def getMinimap(self):
        """ INCOMPLETE Returns minimap area as an HSV image,
            and the first point of the image """
        # bag postions, x1,y1-x2,y2
        x1 = self.rsx + 570
        y1 = self.rsy + 30
        x2 = self.rsx + 720
        y2 = self.rsy + 170
        minimap = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
        return minimap, x1, y1

    def get_bag(self, return_coords=False, *args):
        #x1, y1 = position() #Get runescapes top-left coords

        # bag postions, x1,y1-x2,y2
        x1 = self.rsx + 565
        y1 = self.rsy + 239
        x2 = self.rsx + 721
        y2 = self.rsy + 485

        try:  # block to allow this func to also get 'hsv' img objects
            for arg in args:
                if arg == 'hsv':
                    rs_bag = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
                    return rs_bag, x1, y1
                if arg == 'gray':
                    rs_bag = Screenshot.shoot(x1, y1, x2, y2)
                    return rs_bag, x1, y1
        except:
            pass

        rs_bag = Screenshot.shoot(x1, y1, x2, y2)

        if return_coords:
            return rs_bag, x1, y1
        else:
            return rs_bag

    def getBankWindow(self, *args):
        """ window only includes the items in bank, to tabs or buttons"""
        #creates bank window boundaries
        x1 = self.rsx + 70
        y1 = self.rsy + 105
        x2 = self.rsx + 440
        y2 = self.rsy + 319
        # passing 'hsv' to this function returns hsv image
        try:
            if args[0] == 'hsv':
                #gets screenshot object
                bankWindow = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
                ##### DEBUG
                #cv2.imshow('bankwindow', bankWindow)
                #cv2.waitKey(0)
                ####
                return bankWindow, x1, y1
        except:
            #gets screenshot object
            bankWindow = Screenshot.shoot(x1, y1, x2, y2)
            return bankWindow, x1, y1

    def isBankOpen(self):
        """checks to see if bank is open, returns True, else False"""
        # black X button hsv values
        buttonx_hsv = (np.array([0, 254, 0]), np.array([179, 255, 255]))
        # gets current game's position
        #self.rsx,rsy = self.position()
        #button X on bank window coords
        x1 = self.rsx + 484
        y1 = self.rsy + 44
        x2 = self.rsx + 497
        y2 = self.rsy + 59

        # Screenshot X button
        img = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
        # cv2.imshow('img', img)
        # cv2.waitKey(2000)
        # cv2.destroyAllWindows()
        # Apply hsv ranges
        mask = cv2.inRange(img, buttonx_hsv[0], buttonx_hsv[1])

        # counts white pixels in X
        counter = 0
        for colors in mask:
            for color_value in colors:
                if color_value == 255:
                    counter += 1
        #print(counter)
        #cv2.imshow('img', mask)
        #cv2.waitKey(0)
        # 54 = Bank is open
        if counter == 54:
            return True
        return False

    def isCraftWinOpen(self):
        """checks to see if bank is open, returns True, else False"""
        # black X button hsv values
        buttonx_hsv = (np.array([0, 254, 0]), np.array([179, 255, 255]))
        # gets current game's position
        #self.rsx,rsy = self.position()
        #button X on bank window coords
        x1 = self.rsx + 480
        y1 = self.rsy + 53
        x2 = self.rsx + 497
        y2 = self.rsy + 70

        # Screenshot X button
        img = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
        # Apply hsv ranges
        mask = cv2.inRange(img, buttonx_hsv[0], buttonx_hsv[1])
        # cv2.imshow('img', img)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        # cv2.imshow('mask', mask)
        # cv2.waitKey(00)
        # cv2.destroyAllWindows()

        # counts white pixels in X
        counter = 0
        for colors in mask:
            for color_value in colors:
                if color_value == 255:
                    counter += 1
        #cv2.imshow('img', mask)
        #cv2.waitKey(0)
        # 54 = Bank is open
        # uncomment to see the number to set it to
        # print(counter) # uncomment to show what number should be on next line
        if counter == 54:
            return True
        return False

    def isRunActive(self):
        """checks to see if run is active, returns True, else False"""
        # checking color yellow on boot
        run_icon = (np.array([25, 135, 236]), np.array([26, 145, 237]))
        x1 = self.rsx + 564
        y1 = self.rsy + 152
        x2 = self.rsx + 578
        y2 = self.rsy + 160

        img = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
        # Apply hsv ranges
        mask = cv2.inRange(img, run_icon[0], run_icon[1])
        # if true run is off
        if mask.any():
            return True
        else:
            return False

    def isInvEmpty(self, bagimg=0):
        bag, bagx, bagy = self.get_bag('bag and coords', 'hsv')
        # looks for color of empty inv
        low = np.array([10, 46, 58])
        high = np.array([21, 92, 82])
        # applies mask
        mask = cv2.inRange(bag, low, high)
        # removes any noise
        kernel = np.ones((5, 5), np.uint8)
        closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
        # cv2.imshow('img', closing)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        if bagimg == 0:
            # looks to see if the inv is all white pixels
            # returns true, else False
            if (closing.view() == 255).all():
                # print("Inventory is Empty")
                return True
            # print("Inventory is Full")
            return False
        if bagimg == 1:
            # looks to see if the inv is all white pixels
            # returns true, else False
            if (closing.view() == 255).all():
                # print("Inventory is Empty")
                return True, (bag, bagx, bagy)
            # print("Inventory is Full")
            return False, (bag, bagx, bagy)

    def is_button_selected(self, button_name):
        """Returns true if button is selected, else False"""
        x1, y1, x2, y2 = self.press_button(button_name, 'coords')
        button_img = Screenshot.shoot(x1, y1, x2, y2, 'hsv')
        lower_red = np.array([0, 179, 0])
        upper_red = np.array([4, 193, 255])

        mask = cv2.inRange(button_img, lower_red, upper_red)

        for colors in mask:
            for value in colors:
                if value == 255:
                    #print('{} is selected'.format(button_name))
                    return 1
        # print('{} is NOT selected'.format(button_name))
        return 0
예제 #14
0
# This program is intended to create a myth cape mount, remove it, and repeat
# 8 times before calling the butler to fetch more planks.

from pyclick import HumanClicker
import pyautogui
import time
import pyperclip
import random
import decimal

# initialize HumanClicker object
hc = HumanClicker()
iterations = 93  # how many times the script should loop and make 8 cape mounts
for i in range(iterations):
    for i in range(8):
        xpos = random.randrange(-50, 20, 1)
        ypos = random.randrange(
            -3, 3,
            1)  # two ypos values so avoid one discrete value applied to all
        ypos2 = random.randrange(-3, 3, 1)
        xSettings = random.randrange(
            -10, 5,
            1)  # x and y settings to simulate randomness and avoid detection
        ySettings = random.randrange(-2, 2, 1)

        hc.move((1000 + xpos, 290 + ypos), 1)
        pyautogui.click(button='right')
        pyautogui.moveTo(1000 + xpos, 340 + ypos, duration=0.5)
        hc.click()
        time.sleep(1)
        for i in range(3):  # random press interval to evade bot detection
예제 #15
0
 def move_humanly_mouse_to_location(x, y):
     hc = HumanClicker()
     hc.move((int(x), int(y)), 0.5)
예제 #16
0
파일: main.py 프로젝트: 27bslash/osrs-bot
     output_dict['detection_boxes'],
     output_dict['detection_classes'],
     output_dict['detection_scores'],
     category_index,
     instance_masks=output_dict.get('detection_masks'),
     use_normalized_coordinates=True,
     line_thickness=8)
 boxes = output_dict['detection_boxes']
 # get all boxes from an array
 max_boxes_to_draw = boxes.shape[0]
 # get scores to get a threshold
 scores = output_dict['detection_scores']
 # this is set as a default but feel free to adjust it to your needs
 min_score_thresh = 0.75
 # iterate over all objects found
 hc = HumanClicker()
 for i in range(min(max_boxes_to_draw, boxes.shape[0])):
     #
     if scores is None or scores[i] > min_score_thresh:
         # boxes[i] is the box which will be drawn
         class_name = category_index[
             output_dict['detection_classes'][i]]['name']
         xmax = boxes[i][3] * 1920
         xmin = boxes[i][1] * 1920
         ymax = boxes[i][2] * 1080
         ymin = boxes[i][0] * 1080
         x_center = (xmax + xmin) / 2
         y_center = (ymax + ymin) / 2
         temp = []
         temp.append(class_name)
         temp.append(x_center)
예제 #17
0
from pyclick import HumanClicker
import pyautogui
import random
import time
import decimal

# initialize HumanClicker object
hc = HumanClicker()
iterations = 600 # how many times the script should loop and cast make leather

# initialize function to generate random time dleay

for i in range(iterations):
    # establish random coordinates to avoid bot detection
    pos = random.randrange(-50,50,1)
    dhidehor = random.randrange(-30,30,1)
    dhidever = random.randrange(-25,30,1)
    spellhor = random.randrange(-23,23,1)
    spellver = random.randrange(-23,23,1)
    deposithor = random.randrange(-40,40,1)
    depositver = random.randrange(-30,30,1)

    # establish random times to avoid bot detection
    spellTime = random.randrange(0,1,1)
    bankTime = random.randrange(0,1,1)
    allOtherTime = random.randrange(0,2,1)
   # movementTime = 

    # banking
    hc.move((929+pos,459+pos),3+spellTime)
    hc.click()
예제 #18
0
	def __init__(self, title_img):
		self.__title_img = title_img
		self.move = HumanClicker()
예제 #19
0
파일: miner.py 프로젝트: Murtrag/game_bot
from status import Status_Bar
from pyclick import HumanClicker  # super symulacja ruchu myszki
import pyautogui
import time
import random
import find_in_box
from lib.window import Window

mouse = HumanClicker()
status = Status_Bar()
mode = input("What kind of mining are you planing to do? w(wall)/v((vein)")

count = 0
while True:
    if mode == "v" or pyautogui.locateOnScreen(
            'media/title-window/cave_wall.png', confidence=.8):
        if status.stamin:

            pyautogui.typewrite('l')
            count += 1
            time.sleep(random.random() * 2)

            if mode == "v" and count >= random.randint(10, 50):
                pyautogui.typewrite('l')
                time.sleep(random.random())
                pyautogui.typewrite('l')
                time.sleep(random.random())
                pyautogui.typewrite('l')

                pile_of_items = Window(
                    title='media/box-titles/pile-of-items.png')
예제 #20
0
def run():
    hc = HumanClicker()
    # While there's no 'execution stop' command passed
    while exec_stop is False:
        # If the script is in autoclicker mode
        if mode == "autoclicker":
            try:
                # Configure positions based on your screen
                hc.move((840, 710), 1)
                hc.click()
                time.sleep(5)
                hc.move((841, 583), 1)
                hc.click()
                time.sleep(5)
                hc.move((693, 667), 1)
                hc.click()
                time.sleep(5)
            except:
                # If an error occurred
                print("An error occurred: ", sys.exc_info()[0])
                sys.exit(0)
        # If the script is in position logger mode
        else:
            try:
                # Print position to console every second
                print(pyautogui.position())
                time.sleep(1)
            except:
                # If an error occurred
                print("An error occurred: ", sys.exc_info()[0])
예제 #21
0
from pyclick import HumanClicker
import pyautogui
import random
import time
import decimal
import math

# initialize HumanClicker object
hc = HumanClicker()
barCount = 2000  # input how many bars you would like to process
iterations = math.floor(barCount / 81)  # 81 coal per loop iteration


def withdrawCoal():
    checkStamina()
    hc.move(((random.randrange(842, 868, 1)), (random.randrange(343, 367, 1))),
            (float(random.randrange(60, 100)) / 400))
    hc.click()
    time.sleep(float(random.randrange(52, 100)) / 100)
    pyautogui.press('esc')
    hc.move(
        ((random.randrange(1722, 1743, 1)), (random.randrange(752, 775, 1))),
        (float(random.randrange(50, 100)) / 400))
    hc.click()
    hc.move(((random.randrange(951, 970, 1)), (random.randrange(555, 571, 1))),
            (float(random.randrange(50, 100)) / 400))
    hc.click()
    hc.move(((random.randrange(842, 868, 1)), (random.randrange(343, 367, 1))),
            (float(random.randrange(60, 100)) / 400))
    hc.click()
    time.sleep(float(random.randrange(52, 100)) / 100)
예제 #22
0
 def __init__(self, setupwindow=True):
     # object contains window ID and x,y positions
     self.rs_window = setup.Window(setupwindow=setupwindow)
     self.rsx, self.rsy = self.rs_window.position
     self.hc = HumanClicker()
예제 #23
0
from pynput.keyboard import Key
from pynput.keyboard import Controller
import pynput.keyboard
import random
#new - добавил я 26 числа. Не тестил 2 добавления.
'''
Буду стараться по максимуму фиксить баги, чтобы быстрее закончить разработку.
'''
'''
Код красивый. Хочу так же научиться)
'''
path = 'img\\'
print('Starting TLM_digger...')
exec_stop = False
mode = 'autoclicker'
hc = HumanClicker()
keyboard = Controller()
#mode = "pos_logger":
debug = True

btn = {'mine': (),
       'close_d': (),
        }



def see(image):
    position = imgsearch.imagesearch(path + image + '.png')
    if position[0] != -1:
        if debug:
            print(f'SEE:    {image} {str(position)}')
예제 #24
0
파일: mixer.py 프로젝트: Murtrag/game_bot
from status import Status_Bar
from pyclick import HumanClicker  # super symulacja ruchu myszki
import pyautogui
import time
from random import randint, random
import find_in_box
mouse = HumanClicker()

while True:
    try:
        inventory = find_in_box.FindItem('media/box-titles/backpack.png')
        inv_cord = inventory.get_box_dimention()
        print('1')
        x, y = (randint(inv_cord[0] + 34, inv_cord[0] + 124),
                randint(inv_cord[1] + 20, inv_cord[1] + 48))
        mouse.move((x, y), 2)
        pyautogui.doubleClick()  #dbl click first herb

        mouse.move((x + randint(1, 4), y + randint(30, 100)), 1)
        pyautogui.rightClick()  #open menu with mixing option
        print('2')
        time.sleep(randint(1, 2))
        print('3')
        alchemy_raw = pyautogui.locateOnScreen(
            'media/menu/alchemy.png', confidence=.8)  #find alchemy option
        alchemy_x, alchemy_y = pyautogui.center(alchemy_raw)
        print('4')

        mouse.move((randint(alchemy_x - 3, alchemy_x + 3),
                    randint(alchemy_y - 3, alchemy_y + 3)),
                   2)  #mouse on alchemy position
예제 #25
0
 def init(cls):
     cls.hc = HumanClicker()
예제 #26
0
파일: crafter.py 프로젝트: Murtrag/game_bot
from status import Status_Bar
from pyclick import HumanClicker  # super symulacja ruchu myszki
import pyautogui
import time
from random import randint, random

mouse = HumanClicker()
status = Status_Bar()
while True:
    if status.stamin:
        button = pyautogui.locateOnScreen('media/box-titles/continue.png',
                                          confidence=.8)
        button_x, button_y = pyautogui.center(button)
        mouse.move(
            (randint(button_x - 30,
                     button_x + 30), randint(button_y - 3, button_y + 3)), 2)
        pyautogui.click()
        time.sleep(random() * 2)