def resolver_recompensas(self): mouse.move(981, 767, True, 1) while (self.color == (0, 1, 6)): mouse.move(667, 804, True, 1) mouse.click() mouse.move(981, 767, True, 0) sleep(5)
def click_start_button(): raid_screenshot = get_screen() height, width, _ = raid_screenshot.shape template_pixel = raid_screenshot[height - 2, width - 2] template_pixel_tuple = uint8(template_pixel) top_rect_collection = 0 for y in range(height - 2, 0, -1): if (raid_screenshot[y, width - 2] != template_pixel).any(): top_rect_collection = y break cropped = raid_screenshot[top_rect_collection:height, :] mask = cv2.inRange(cropped, template_pixel_tuple, template_pixel_tuple) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) mask = cv2.morphologyEx(mask, cv2.RETR_TREE, kernel) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) boxes = [cv2.boundingRect(cnt) for cnt in contours] boxes.sort(key=lambda box: box[0], reverse=True) if boxes[0][1] > boxes[1][1]: start_point = Point(boxes[0][0], boxes[0][1] + top_rect_collection, boxes[0][2], boxes[0][3]) else: start_point = Point(boxes[1][0], boxes[1][1] + top_rect_collection, boxes[1][2], boxes[1][3]) __mouse_move(start_point.center()[0], start_point.center()[1]) mouse.click()
def volver_a_jugar(self): sleep(10) self.resolver_recompensas() sleep(5) mouse.move(self.dict["OTRA"][0], self.dict["OTRA"][1], True, 1) mouse.click() sleep(5)
def go_campaign_location(): global count_scroll go_scroll_location(count_scroll) # raid_screenshot = get_screen() # temp_pos = search_module.get_object_position(raid_screenshot, location_template) __mouse_move(location_position.center()[0], location_position.center()[1]) mouse.click()
def clickrelativetopanel(self, relativevalue, corner='topleft', click='single'): """ Clicks on a relative position in a panel. eg: effect.controls.clickrelativetopanel(10,30) Will click 10 pixels to the right and 30 pixels to the bottom of the panel Effect Controls. Useful for UI mouse automation, even if you change the panel sizes. :param relativevalue: a tuple containing (x, y) coordinates of the relative value to move or click :param corner: which corner to start the relative move from options: default is 'topleft', 'topright', 'bottomleft', 'bottomright' :param click: default 'single, option to 'double' click """ x, y = self.abspos_from_rel(relativevalue, corner) mouse.move(x, y) if click == 'single': mouse.click() elif click == 'double': mouse.double_click() else: return
def waitSwitched(self, art_center_x, art_center_y, min_wait=0.1, max_wait=3, condition=lambda pix: sum(pix) / 3 > 200): start = time.time() total_wait = 0 while True: mouse.move(self.game_info.left + art_center_x, self.game_info.top + art_center_y) mouse.click() pix = captureWindow( self.game_info.hwnd, (art_center_x - self.game_info.art_width / 2 - self.game_info.art_expand, art_center_y, art_center_x - self.game_info.art_width / 2 - self.game_info.art_expand + 1.5, art_center_y + 1.5)) if condition(pix.getpixel((0, 0))): self.avg_response_time = 0.5 * self.avg_response_time + 0.5 * ( time.time() - start) return True else: time.sleep(min_wait) total_wait += min_wait if total_wait > max_wait: return False
def _on_key_press(self, click, key): x_key = not self.selection and key.name in self._xiterable y_key = self.selection and key.name in self._yiterable is_backspace = key.name == 'backspace' is_escape = key.name == 'esc' do_keypress = not (x_key or y_key or is_backspace or is_escape) if do_keypress: if key.event_type == 'down': keyboard.send(key.scan_code, do_press=True, do_release=False) else: keyboard.send(key.scan_code, do_press=False, do_release=True) elif key.event_type == 'up': if x_key: self.overlay(row=key.name, click=click, xiterable=self._xiterable, yiterable=self._yiterable) self.selection += key.name elif y_key: x, y = self.centers[f'{self.selection}{key.name}'] mouse.move(x, y) if click: mouse.click() self.empty() elif is_backspace: self.overlay(click=click) elif is_escape: self.empty()
def place(self, coordinates: Tuple[int, int]): # raise MonkeyPlaced if the monkey has already been placed. if self.placed: raise MonkeyPlaced # raise CoordinateError if invalid type or tuple length. if (type(coordinates) != list) and (type(coordinates) != tuple): raise CoordinateError if len(coordinates) != 2: raise CoordinateError # activate Bloons TD 6 window. focus_window("BloonsTD6") # move to the monkey's position # send the hotkey for the monkey # left click to place the monkey # time.sleep required for the monkey to be placed in time. mouse.move(coordinates[0], coordinates[1]) time.sleep(self.delay) keyboard.send(hotkeys["Monkeys"]["Heroes"]) time.sleep(self.delay) mouse.click() time.sleep(self.delay) # record the coordinates of the monkey. self.coordinates = coordinates # record that the monkey has been placed. self.placed = True self.level = 1
def kite_minion(areas, object_, attack_speed): ''' Kite from a coordinate ''' mouse.move(*object_['center']) mouse.click() time.sleep(.5 / attack_speed) evade_relative(object_['center'], areas) time.sleep(.3 / attack_speed)
def grid_onoff_togle(): current_xy = mouse.get_position() print("grid_onoff_togle is running") icon_name = "view_menu.png" pic_xy = find_pic_in_screen(icon_name) try: mouse.move(pic_xy[0], pic_xy[1], absolute=True) mouse.click() except: pass time.sleep(float(config.appSettings["sleep_normal"])) icon_name = "snap_grid_menu.png" pic_xy = find_pic_in_screen(icon_name) try: mouse.move(pic_xy[0], pic_xy[1], absolute=True) mouse.click() except: pass time.sleep(float(config.appSettings["sleep_normal"])) mouse.move(current_xy[0], current_xy[1], absolute=True) if config.appSettings["disable_gridSnap"] == "1": config.appSettings["disable_gridSnap"] = "0" else: config.appSettings["disable_gridSnap"] = "1" return
def login(): import mouse username = "******" password = "******" browser.get(url) browser.maximize_window() #很重要!! username_ele = browser.find_element_by_xpath( "//input[@id='login-username']") password_ele = browser.find_element_by_xpath("//input[@id='login-passwd']") username_ele.send_keys(username) password_ele.send_keys(password) #点击登录显示出验证码 login_btn = browser.find_element_by_xpath("//a[@class='btn btn-login']") login_btn.click() # 1. 鼠标移动到正确的元素上,显示出没有缺口的图片并下载 time.sleep(2) #截取图片,并获验证码图片的坐标 img_element = crop_image("captcha1.png") img_location = img_element.location ele_x = img_location["x"] ele_y = img_location["y"] + 114 #这里114是因为浏览器顶部的区域并没有被selenium识别 # mouse.click() time.sleep(2) # action.click() # time.sleep(2) #通过超级鹰获取各文字的位置 #超级鹰参考 http://www.chaojiying.com/ #多次尝试识别,最大尝试3次 #注意一下,超级鹰接口验证不一定每次都是正确的,多试几次就可以了 chaojiying = Chaojiying_Client('超级鹰的用户名', '超级鹰的密码', '96001') # 用户中心>>软件ID 生成一个替换 96001 for i in range(3): print("第{}次尝试识别".format(i)) im = open('captcha1.png', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要// print("验证码坐标:") json_data = chaojiying.PostPic(im, 9004) location_list = [] print(json_data) if json_data["err_no"] == 0: print("识别成功!") for location_info in json_data["pic_str"].split("|"): location_list.append( (location_info.split(",")[0], location_info.split(",")[1])) print(location_list) for x, y in location_list: mouse.move(ele_x + int(x), ele_y + int(y)) time.sleep(2) mouse.click() #点击确认按钮 browser.find_element_by_xpath( "//div[@class='geetest_commit_tip']").click() time.sleep(5) break else: print("识别失败,继续尝试!")
def mouse_lefts(hold='ctrl', on_off_key=62): # key_code for continuously pressing, 42 for shift, 29 for control if hold == 'ctrl': key_code = 29 elif hold == 'shift': key_code = 42 while 1: # scroll lock(70) or F4(62), F5(63) for starting the process keyboard.wait(on_off_key) frequency = 2000 # Set Frequency To 2000 Hertz duration = 50 # Set Duration, 1000 ms == 1 second for i in range(2): winsound.Beep(frequency, duration) keyboard.press(key_code) while 1: if keyboard.is_pressed(on_off_key): break time.sleep(0.05) mouse.click() frequency = 2000 duration = 100 winsound.Beep(frequency, duration) keyboard.release(key_code)
def run_cmd(commands): global sounds # This function will take a list of commands and tasks to execute # It does not do much at the moment. # Maybe use threading to do this in background? for cmd in commands: # The commands will be performed in this loop cmd2 = cmd.split("=") print(cmd2) if cmd2[0] == "wait": # Will take a integer and wait that amount of time time.sleep(int(cmd2[1])) elif cmd2[0] == "keypress_release": # Will take a key, which will be pressed and released keyboard.press_and_release(cmd2[1]) elif cmd2[0] == "play": # Will take a sound file, and play it snd.playsound(sounds + cmd2[1]) elif cmd2[0] == "disable-cat": # Will disable category. disable_cat(cmd2[1]) elif cmd2[0] == "enable-cat": # Enables a category enable_cat(cmd2[1]) elif cmd2[0] == "mouse_click": # Clicks a given mouse button mouse.click(button=cmd2[1])
def ppt(): kb.press_and_release('win+d') time.sleep(0.2) def windowEnumerationHandler(hwnd, top_windows): top_windows.append((hwnd, win32gui.GetWindowText(hwnd))) if __name__ == "__main__": results = [] top_windows = [] win32gui.EnumWindows(windowEnumerationHandler, top_windows) for i in top_windows: if "creo parametric" in i[1].lower(): print(i) win32gui.ShowWindow(i[0], 5) win32gui.SetForegroundWindow(i[0]) break kb.press_and_release('alt+space,x') time.sleep(1) kb.press_and_release('win+PrtScn') kb.press_and_release('win+r') time.sleep(.1) kb.write(path) kb.press_and_release('enter') time.sleep(5) kb.press_and_release('end') kb.press_and_release('alt+H,y') kb.press_and_release('ctrl+v') kb.press_and_release('ctrl+s') mo.move(700, 500, absolute=True, duration=0) mo.click(button='left') mo.click(button='right') kb.press_and_release('k,k')
def solve(self): self.start = time.time() while not self.complete: placed = False pair = self.pair if pair: for i in range(7): if self.pattern[i] == pair[0] and self.pattern[ i + 1] == pair[1]: self.place((i, i + 1)) placed = True if not placed: self.swap() else: self.times.append(time.time() - self.start) print("--------------------------------------------------") print("Round {} - {}".format(len(self.times), self.times[-1])) print("Running Average - {}".format( sum(self.times) / len(self.times))) print("Total Run Time - {}".format(sum(self.times))) mouse.move(1236, 687) mouse.click() time.sleep(.1) mouse.release() time.sleep(.5)
def click_loop(): global clicking, delay, cb_marked, repeat while running: if cb_marked == False and clicking == True: sleep(0.05) while repeat != 1 and clicking == True and running == True: mouse.click(click_but) repeat = int(repeat) - 1 clicking = True sleep(float(delay)) if repeat == 1: clicking = False if clicking == False: sleep(0.24) pass if clicking == True: mouse.click(click_but) sleep(float(delay))
def get_data(args): """gets the key to repeat and trigger :args: argument 1 is the name of key to press and argument two is the name of the trigger :returns: key press function and trigger key """ # sys.argv[1] is the key to be repeated and # sys.argv[2] is the key that triggers it start_stop_key = 'ctrl+shift' if len(sys.argv) > 1: if sys.argv[1] == '-l': press = lambda: mouse.click() print(Fore.CYAN + "left click" + Fore.RESET + " selected") elif sys.argv[1] == '-r': press = lambda: mouse.right_click() print(Fore.CYAN + "right click" + Fore.RESET + " selected") else: press = lambda: keyboard.send(sys.argv[1]) print(Fore.CYAN + sys.argv[1] + Fore.RESET + " selected") if len(sys.argv) > 2: start_stop_key = sys.argv[2] else: press = lambda: mouse.click() print(Fore.CYAN + "left click" + Fore.RESET + " selected") print("Press " + Fore.CYAN + start_stop_key + Fore.RESET + " to toggle clicker") return press, start_stop_key
def start_requests(self): """ 1. 启动 Chrome, 确保所有的 Chrome 实例都已经关闭 2. 手动启动 chromedriver, 虚拟出 Chrome 启动环境 """ ###### Method 1 ###### from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys chrome_option = Options() chrome_option.add_argument("--disable-extensions") chrome_option.add_experimental_option('debuggerAddress', '127.0.0.1:9222') browser = webdriver.Chrome(executable_path='C:/Users/ace01/Downloads/chromedriver.exe', chrome_options=chrome_option) # browser = webdriver.Chrome(executable_path='C:/Users/ace01/Downloads/chromedriver.exe') browser.get('https://www.zhihu.com/signin') # browser.find_element_by_css_selector('.SignFlow-tabs div:nth-child(2)').click() browser.find_elements_by_css_selector(".SignFlow-tab")[1].click() browser.find_element_by_css_selector('.SignFlow-accountInput.Input-wrapper .Input').send_keys(Keys.CONTROL+'a') browser.find_element_by_css_selector('.SignFlow-accountInput.Input-wrapper .Input').send_keys('17764534723') browser.find_element_by_css_selector('.SignFlow-password input').send_keys(Keys.CONTROL+'a') browser.find_element_by_css_selector('.SignFlow-password input').send_keys('hanser1998') move(534, 630) time.sleep(3) click() browser.find_element_by_css_selector('.Button.SignFlow-submitButton').click() time.sleep(60)
def jugar2(self): if keyboard.is_pressed("z"): box = (self.window.topleft[0] + int(self.window.width * 0.45), self.window.topleft[1] + int(self.window.height * 0.45), self.window.topleft[0] + int(self.window.width * 0.45), self.window.bottomright[1]) while True: #Busco el cartel de buscar partida self.buscar_partida2() sleep(1) #En este punto tengo ver si encontre partida self.log_entrada() #En este punto deberia estar en partida print("durmiendo") sleep(720) print("Despierto") while not self.window.isActive: self.rendirse() sleep(8) #resolver recompensas self.resolver_recompensas() self.jugadas += 1 pos = self.buscar_2(CELESTE, box) mouse.move(pos[0], pos[1]) sleep(0.3) mouse.click()
def addloop(): print("addloop is running") current_xy = mouse.get_position() mouse.move(2400, 450, absolute=True) mouse.click() time.sleep(float(config.appSettings["sleep_normal"])) mouse.move(2540, 450, absolute=True) mouse.click() time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("%") keyboard.send(pyperclip.paste()) keyboard.send("enter") time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("tab") time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("down") time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("tab, tab") time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("tab, tab") time.sleep(float(config.appSettings["sleep_long"])) keyboard.send("enter") time.sleep(float(config.appSettings["sleep_long"])) mouse.move(current_xy[0], current_xy[1], absolute=True) time.sleep(float(config.appSettings["sleep_normal"])) return
def _prepare(win, conf, click_x, click_y, location): # 图片二值化步长值 pg = tg = None _pg = conf.get('pg') _tg = conf.get('tg') while True: logger.info('等待 %s...' % _pg['text']) _img = screen.capture(win, location) for i in range(_pg['threshold'], 256): if ocr.recognize_text(_img, _pg['text'], i): _r, _g, _b = ocr._rgb_mean_value(_img) pg = { 'threshold': i, 'r': _r, 'g': _g, 'b': _b } _img.save('./images/pg.jpg') #TODO sum logger.info('识别%s'% _pg['text']) mouse.click(click_x, click_y) break if pg is None: continue _times = 0 while True: # 记录次数,超出 1分钟,约 600 次,跳出循环 if _times > 100: break _times += 1 _img2 = screen.capture(win, location) if ocr.recognize_color(_img2, _tg['color']) == False: _wait(0.1) continue logger.info('等待 %s...' % _tg['text']) _img2.save('./images/tg.jpg') for j in range(_tg['threshold'], 256): if ocr.recognize_text(_img2, _tg['text'], j): _r, _g, _b = ocr._rgb_mean_value(_img2) tg = { 'threshold': j, 'r': _r, 'g': _g, 'b': _b } logger.info('识别%s'%_tg['text']) break if tg is not None: break if pg is not None and tg is not None: break return pg, tg
def execute_instructions(instructions, row, x_coords, y_coords, game_board): y = y_coords[row] for instruction in instructions: x = x_coords[row][instruction] mouse.move(x, y, absolute=True, duration=0.25) game_board = move(game_board, row, instruction) mouse.click() return game_board
def select_marksman_three(win): time.sleep(.2) mouse.move(*Point(x=1157, y=840)) mouse.click() if win.pixel(1156, 493) == (255, 255, 255): time.sleep(.5) mouse.move(1208, 574) mouse.click()
def resolver_recompensas(self): pos = (0, 0) box = () pos = self.buscar_2(DORADO, box) if pos != (0, 0): mouse.move(pos[0], pos[1]) mouse.click() sleep(3)
def select(self): #self.scroll() # Disable if t1 #time.sleep(.2) # Disable if t1 mouse.move(*self.selection) mouse.click() time.sleep(.5) mouse.move(1208, 574) mouse.click()
def execute_action_mouse(x, y, action): mouse.move(x, y, duration=.02) if action == 0: pass elif action == 1: mouse.click(button='left') elif action == 2: mouse.click(button='right')
def upgradeFarm(farm): time.sleep(0.2) mousego(farm) time.sleep(0.1) mouse.click("left") time.sleep(0.1) firstpath(1) time.sleep(0.5)
def clickAssembling(): print('assembling') mouse.move(pos[0] + 20, pos[1] + 280) sleep(.1) mouse.click() sleep(.1) mouse.move(pos[0] + 200, pos[1] + 280) sleep(.1) mouse.click()
def main(): print('When we start, you will have 5 seconds to switch to Minecraft.') input('Press Enter to start..') print('Press Ctrl+C to stop.') sleep(5) print('Clicking...') while True: sleep(5) mouse.click()
def pixelsearch(self, pixel, offset=(0, 0, 0, 0), click=''): """ Searches first pixel and if click = '', return its absolute (x, y) position. :param pixel: a tuple (R, G, B) of int values corresponding to the pixel values. :param offset: a tuple (left, top, right, bottom) for how much to offset the search area. offset crops the panel search area so you can control better where you want to find the pixel, in case it finds pixels before that are not intended. :param click: whether to 'click', 'double' click, 'move', or if default '', return the position. """ p = self if DRAW_OUTLINES: p.draw_outline() #Lets set our haystack bounding box to be searched hx1, hy1 = p.rectangle().left + offset[0], p.rectangle( ).top + offset[1] hx2, hy2 = p.rectangle().right - offset[2], p.rectangle( ).bottom - offset[3] #save that haystack as a PIL RGB image and then as a numpy array im = getRectAsImage((hx1, hy1, hx2, hy2)) image = np.array(im) #image is RGB, but cv2 uses BGR for searching, so we need to invert it image = image[:, :, ::-1].copy() #we're not doing an upper or lower boundary because we want exactly the pixel that we specified lower = np.array([pixel[2], pixel[1], pixel[0]]) # BGR-code upper = np.array([pixel[2], pixel[1], pixel[0]]) # BGR-code mask = cv2.inRange(image, lower, upper) coord = cv2.findNonZero(mask) try: #foundcoord = first pixel found, we could implement a way to get the next pixels too. # we're not limited to the first one. foundcoord = (coord[0][0][0], coord[0][0][1]) #get the absolute position absx, absy = self.abspos_from_rel(foundcoord, offset=offset) print(f'Pixel found at {absx}, {absy}') if click == '': return (absx, absy) else: mouse.move(absx, absy) if click == 'single': mouse.click() elif click == 'double': mouse.double_click() elif click == 'move': return except TypeError: print('Pixel not found!')
def movePiece(self, move): print 'moving ', move.src, ' to ', move.des offset = self.tile_w / 2 srcXpos = self.x + ( move.src['x'] * self.tile_w) + offset srcYpos = self.y + ( move.src['y'] * self.tile_h) + offset desXpos = self.x + ( move.des['x'] * self.tile_w) + offset desYpos = self.y + ( move.des['y'] * self.tile_h) + offset mouse.click(srcXpos, srcYpos) mouse.click(desXpos, desYpos) mouse.move(self.x - 100, self.y)
def home(): mouse.click(164,371) time.sleep(wait)
def automateDis(model, numberOfImages=24, n=0, rotationOffset=None, initialRotation=None, initialTranslation=None, verticalOffset=None, disableXRotation=False, paint=False, teamColours=False, itemName='', REDVMTFile=None, BLUVMTFile=None, wikiUsername=None, wikiPassword=None): """ Method to automize process of taking images for 3D model views. Parameters: model -> An instance of a HLMVModelRegistryKey object for the model. Required. numberOfImages -> Number of images to take for one full rotation. Optional, default is 24. n -> Which nth step of rotation to start at. Optional, default is 0. rotationOffset -> The distance from the default centre of rotation to the new one (in HLMV units). Optional, default is none. initialRotation -> The initial model rotation as a tuple. Optional, default is (0 0 0). initialTranslation -> The initial model translation as a tuple. Optional, default is (0 0 0). verticalOffset -> The vertical offset for models that are centered in both other planes but not vertically. Optional, default is none. disableXRotation -> Boolean that disables tilting. Default is False. paint -> Boolean to indicate whether model is paintable. Optional, default is False. teamColours -> Boolean to indicate whether model is team coloured. Optional, default is False. itemName -> The name of the item. Optional, default is blank. REDVMTFile -> The RED vmt file location. Optional, default is none. BLUVMTFile -> The BLU vmt file location. Optional, default is none. wikiUsername -> wiki.tf2.com username. Optional, default is none. wikiPassword -> wiki.tf2.com password. Optional, default is none. """ folder = raw_input('Folder name for created images: ') outputFolder = outputImagesDir + os.sep + folder try: os.makedirs(outputFolder) except: answer = raw_input('Folder already exists, overwrite files? y\\n? ') if answer == 'yes' or answer == 'y': pass elif answer == 'no' or answer == 'n': sys.exit(1) if initialTranslation is None: initialTranslation = [model.returnTranslation()['x'], model.returnTranslation()['y'], model.returnTranslation()['z']] if initialRotation is None: initialRotation = [model.returnRotation()['x'], model.returnRotation()['y'], model.returnRotation()['z']] # Time for user to cancel script start mouse.sleep(3) try: subprocess.Popen(['taskkill', '/f', '/t' ,'/im', 'hlmv.exe'], stdout=PIPE, stderr=PIPE) mouse.sleep(2) except: pass print 'initialTranslation =', initialTranslation print 'initialRotation =', initialRotation model.setTranslation(x = initialTranslation[0], y = initialTranslation[1], z = initialTranslation[2]) model.setNormalMapping(True) model.setBGColour(255, 255, 255, 255) SDKLauncherCoords = None for yrotation in range((-180 + (360/numberOfImages * n)), 180, 360/numberOfImages): print 'n =', str(n) for xrotation in range(-15, 30, 15): if (disableXRotation and xrotation == 0) or not disableXRotation: # Set rotation mouse.sleep(0.5) model.setRotation(x = xrotation + float(initialRotation[0]), y = yrotation + float(initialRotation[1]), z = initialRotation[2]) print 'xRot = %s, yRot = %s' % (xrotation, yrotation) if rotationOffset is not None: # Set translation to account for off centre rotation result = rotateAboutNewCentre(initialTranslation[0], initialTranslation[1], initialTranslation[2], rotationOffset, yrotation, xrotation) print 'translation =', result model.setTranslation(x = result[0], y = result[1], z = result[2]) # Set translation to account for off centre horizontal rotation elif verticalOffset is not None: result = offsetVertically(initialTranslation[0], initialTranslation[1], initialTranslation[2], verticalOffset, yrotation, xrotation) print 'translation =', result model.setTranslation(x = result[0], y = result[1], z = result[2]) # Open HLMV if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmv.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmvunhighlighted.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmvinactive.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: print 'Couldn\'t find source SDK launcher to click on' break mouse.doubleclick(SDKLauncherCoords) mouse.sleep(2) # Maximise HLMV SendKeys(r'*{UP}') # Open recent model mouse.click(x=fileButtonCoordindates[0],y=fileButtonCoordindates[1]) SendKeys(r'{DOWN 8}{RIGHT}{ENTER}') mouse.sleep(1) # Item painting method def paintcycle(dict, whiteBackgroundImages, blackBackgroundImages): # Take whiteBG screenshots and crop for colour in dict: paintHat(dict[colour], REDVMTFile) SendKeys(r'{F5}') mouse.sleep(0.1) imgWhiteBG = screenshot() imgWhiteBG = imgWhiteBG.crop(imgCropBoundaries) whiteBackgroundImages[colour] = imgWhiteBG # Change BG colour to black SendKeys(r'^b') # Take blackBG screenshots and crop for colour in dict: paintHat(dict[colour], REDVMTFile) SendKeys(r'{F5}') mouse.sleep(0.1) imgBlackBG = screenshot() imgBlackBG = imgBlackBG.crop(imgCropBoundaries) blackBackgroundImages[colour] = imgBlackBG SendKeys(r'^b') SendKeys(r'{F5}') return whiteBackgroundImages, blackBackgroundImages if paint: whiteBackgroundImages = {} blackBackgroundImages = {} whiteBackgroundImages, blackBackgroundImages = paintcycle(paintDict, whiteBackgroundImages, blackBackgroundImages) if teamColours: # Change RED hat to BLU redVMTContents = open(REDVMTFile, 'rb').read() bluVMTContents = open(BLUVMTFile, 'rb').read() f = open(REDVMTFile, 'wb') f.write(bluVMTContents) f.close() whiteBackgroundImages, blackBackgroundImages = paintcycle(BLUPaintDict, whiteBackgroundImages, blackBackgroundImages) g = open(REDVMTFile, 'wb') g.write(redVMTContents) g.close() else: whiteBackgroundImages, blackBackgroundImages = paintcycle(BLUPaintDict, whiteBackgroundImages, blackBackgroundImages) else: if teamColours: # Take whiteBG screenshot and crop imgWhiteBGRED = screenshot() imgWhiteBGRED = imgWhiteBGRED.crop(imgCropBoundaries) # Change BG colour to black SendKeys(r'^b') # Take blackBG screenshot and crop imgBlackBGRED = screenshot() imgBlackBGRED = imgBlackBGRED.crop(imgCropBoundaries) # Change BG colour to white SendKeys(r'^b') # Change weapon colour to BLU redVMTContents = open(REDVMTFile, 'rb').read() bluVMTContents = open(BLUVMTFile, 'rb').read() f = open(REDVMTFile, 'wb') f.write(bluVMTContents) f.close() SendKeys(r'{F5}') mouse.sleep(0.1) # Take whiteBG screenshot and crop imgWhiteBGBLU = screenshot() imgWhiteBGBLU = imgWhiteBGBLU.crop(imgCropBoundaries) # Change BG colour to black SendKeys(r'^b') # Take blackBG screenshot and crop imgBlackBGBLU = screenshot() imgBlackBGBLU = imgBlackBGBLU.crop(imgCropBoundaries) # Return VMT back to RED g = open(REDVMTFile, 'wb') g.write(redVMTContents) g.close() else: # Take whiteBG screenshot and crop imgWhiteBG = screenshot() imgWhiteBG = imgWhiteBG.crop(imgCropBoundaries) # Change BG colour to black SendKeys(r'^b') # Take blackBG screenshot and crop imgBlackBG = screenshot() imgBlackBG = imgBlackBG.crop(imgCropBoundaries) # Remove background from images if paint: blendingMachine(xrotation, n, blackBackgroundImages, whiteBackgroundImages, outputFolder, True, True) else: if teamColours: blendingMachine(xrotation, n, {'RED':imgBlackBGRED,'BLU':imgBlackBGBLU}, {'RED':imgWhiteBGRED,'BLU':imgWhiteBGBLU}, outputFolder, False, True) else: blendingMachine(xrotation, n, imgBlackBG, imgWhiteBG, outputFolder, False, False) # Close HLMV subprocess.Popen(['taskkill', '/f', '/t' ,'/im', 'hlmv.exe'], stdout=PIPE, stderr=PIPE) # Check for kill switch killKeyState = GetKeyState(VK_CAPITAL) if killKeyState in [1, -127]: print '\nSuccessfully terminated' sys.exit(0) n += 1 blendingMachine() # Wait for threads to finish, if any # Stitch images together print 'Stitching images together...' stitchPool = threadpool(numThreads=2, defaultTarget=stitch) if paint: for colour in paintHexDict: if colour == 'Stock': if teamColours: finalImageName = itemName + ' RED ' + '3D.jpg' else: finalImageName = itemName + ' 3D.jpg' elif colour == 'Stock (BLU)': if teamColours: finalImageName = itemName + ' BLU ' + '3D.jpg' else: pass else: finalImageName = itemName + ' ' + paintHexDict[colour] + ' 3D.jpg' ##### Need to thread this ##### if colour == 'Stock (BLU)' and not teamColours: pass else: stitchPool(outputFolder, paintHexDict[colour], finalImageName, numberOfImages) else: if teamColours: finalREDImageName = itemName + ' RED 3D.jpg' finalBLUImageName = itemName + ' BLU 3D.jpg' stitchPool(outputFolder, ' RED', finalREDImageName, numberOfImages) stitchPool(outputFolder, ' BLU', finalBLUImageName, numberOfImages) else: finalImageName = itemName + ' 3D.jpg' stitchPool(outputFolder, None, finalImageName, numberOfImages) stitchPool.shutdown() # Upload images to wiki if paint: for colour in paintHexDict: if colour == 'Stock': if teamColours: fileName = itemName + ' RED ' + '3D.jpg' else: fileName = itemName + ' 3D.jpg' elif colour == 'Stock (BLU)': if teamColours: fileName = itemName + ' BLU ' + '3D.jpg' else: pass else: fileName = itemName + ' ' + paintHexDict[colour] + ' 3D.jpg' url = fileURL(fileName) description = open(outputFolder + os.sep + fileName + ' offsetmap.txt', 'rb').read() description = description.replace('url = <nowiki></nowiki>','url = <nowiki>' + url + '</nowiki>') if colour == 'Stock (BLU)' and not TeamColours: pass else: uploadFile(outputFolder + os.sep + fileName, fileName, description, wikiUsername, wikiPassword, category='', overwrite=False) else: if teamColours: finalREDImageName = itemName + ' RED 3D.jpg' finalBLUImageName = itemName + ' BLU 3D.jpg' url = fileURL(finalREDImageName) url2 = fileURL(finalBLUImageName) description = open(outputFolder + os.sep + finalREDImageName + ' offsetmap.txt', 'rb').read() description = description.replace('url = <nowiki></nowiki>','url = <nowiki>' + url + '</nowiki>') description2 = open(outputFolder + os.sep + finalBLUImageName + ' offsetmap.txt', 'rb').read() description2 = description2.replace('url = <nowiki></nowiki>','url = <nowiki>' + url2 + '</nowiki>') uploadFile(outputFolder + os.sep + finalREDImageName, finalREDImageName, description, wikiUsername, wikiPassword, category='', overwrite=False) uploadFile(outputFolder + os.sep + finalBLUImageName, finalBLUImageName, description2, wikiUsername, wikiPassword, category='', overwrite=False) else: finalImageName = itemName + ' 3D.jpg' url = fileURL(finalImageName) description = open(outputFolder + os.sep + finalImageName + ' offsetmap.txt', 'rb').read() description = description.replace('url = <nowiki></nowiki>','url = <nowiki>' + url + '</nowiki>') uploadFile(outputFolder + os.sep + finalImageName, finalImageName, description, wikiUsername, wikiPassword, category='', overwrite=False) # All done yay print '\nAll done'
doSend(logTh, screenTh, sendTh, recTh) elif "stop" in action: print("force quit") stop = True elif "capture" in action: screenTh.queue.put("capture") elif "move" in action: a, xS, yS = action.split() x = int(xS) y = int(yS) mouse.moveMouse(x,y) elif "click" in action: a, xS, yS = action.split() x = int(xS) y = int(yS) mouse.click(x,y) elif "update" in action: sendTh.inQueue.put("quit") screenTh.queue.put("quit") logTh.queue.put("quit") recTh.inQueue.put("quit") doUpdate() break #zip #send #repeat #??? #profit
def automateDis(model, numberOfImages=24, n=0, rotationOffset=None, initialRotation=None, initialTranslation=None, verticalOffset=None, disableXRotation=False, REDVMTFile=None, BLUVMTFile=None): """ Method to automize process of taking images for 3D model views. Parameters: model -> An instance of a HLMVModelRegistryKey object for the model. Required. numberOfImages -> Number of images to take for one full rotation. Optional, default is 24. n -> Which nth step of rotation to start at. Optional, default is 0. rotationOffset -> The distance from the default centre of rotation to the new one (in HLMV units). Optional, default is none. initialRotation -> The initial model rotation as a tuple. Optional, default is (0 0 0). initialTranslation -> The initial model translation as a tuple. Optional, default is (0 0 0). verticalOffset -> The vertical offset for models that are centered in both other planes but not vertically. Optional, default is none. disableXRotation -> Boolean that disables tilting. Default is False. """ folder = raw_input('Folder name for created images: ') outputFolder = outputImagesDir + os.sep + folder try: os.mkdir(outputFolder) except: answer = raw_input('Folder already exists, overwrite files? y\\n? ') if answer == 'yes' or answer == 'y': pass elif answer == 'no' or answer == 'n': sys.exit(1) if initialTranslation is None: initialTranslation = [model.returnTranslation()['x'], model.returnTranslation()['y'], model.returnTranslation()['z']] if initialRotation is None: initialRotation = [model.returnRotation()['x'], model.returnRotation()['y'], model.returnRotation()['z']] # Time for user to cancel script start mouse.sleep(3) try: subprocess.Popen(['taskkill', '/f', '/t' ,'/im', 'hlmv.exe'], stdout=PIPE, stderr=PIPE) mouse.sleep(2) except: pass print 'initialTranslation =', initialTranslation print 'initialRotation =', initialRotation model.setTranslation(x = initialTranslation[0], y = initialTranslation[1], z = initialTranslation[2]) model.setNormalMapping(True) SDKLauncherCoords = None whiteBackgroundImages = {} blackBackgroundImages = {} for yrotation in range((-180 + (360/24 * n)), 180, 360/numberOfImages): print 'n =', str(n) for xrotation in range(-15, 30, 15): if (disableXRotation and xrotation == 0) or not disableXRotation: # Set rotation mouse.sleep(0.5) model.setRotation(x = xrotation + float(initialRotation[0]), y = yrotation + float(initialRotation[1]), z = initialRotation[2]) print 'xRot = %s, yRot = %s' % (xrotation, yrotation) if rotationOffset is not None: # Set translation to account for off centre rotation result = rotateAboutNewCentre(initialTranslation[0], initialTranslation[1], initialTranslation[2], rotationOffset, yrotation, xrotation) print 'translation =', result model.setTranslation(x = result[0], y = result[1], z = result[2]) # Set translation to account for off centre horizontal rotation elif verticalOffset is not None: result = offsetVertically(initialTranslation[0], initialTranslation[1], initialTranslation[2], verticalOffset, yrotation, xrotation) print 'translation =', result model.setTranslation(x = result[0], y = result[1], z = result[2]) # Set white colour model.setBGColour(255, 255, 255, 255) # Open HLMV mouse.sleep(1) if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmv.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmvunhighlighted.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: SDKLauncherCoords = mouse.find({targetImagesDir + os.sep + 'openhlmvinactive.png': (0, 0)}, startingPoint=SDKLauncherStartingPoint) if SDKLauncherCoords is None: print 'Couldn\'t find source SDK launcher to click on' break mouse.doubleclick(SDKLauncherCoords) # Maximise HLMV mouse.sleep(2) SendKeys("""*{UP}""") # Open recent model mouse.click(x=fileButtonCoordindates[0],y=fileButtonCoordindates[1]) SendKeys("""{DOWN 8}{RIGHT}{ENTER}""") # Take whiteBG screenshots and crop mouse.sleep(2) def paintcycle(dict): for colour in dict: paintHat(dict[colour], REDVMTFile) SendKeys("""{F5}""") mouse.sleep(0.1) imgWhiteBG = ImageGrab.grab() imgWhiteBG = imgWhiteBG.crop(imgCropBoundaries) whiteBackgroundImages[colour] = imgWhiteBG # Change BG colour to black SendKeys("""^b""") # Take blackBG screenshots and crop for colour in dict: paintHat(dict[colour], REDVMTFile) SendKeys("""{F5}""") mouse.sleep(0.1) imgBlackBG = ImageGrab.grab() imgBlackBG = imgBlackBG.crop(imgCropBoundaries) blackBackgroundImages[colour] = imgBlackBG SendKeys("""^b""") paintcycle(paintDict) # Change RED hat to BLU redVMTContents = open(REDVMTFile, 'rb').read() bluVMTContents = open(BLUVMTFile, 'rb').read() f = open(REDVMTFile, 'wb') f.write(bluVMTContents) f.close() paintcycle(BLUPaintDict) g = open(REDVMTFile, 'wb') g.write(redVMTContents) g.close() # Remove background from images """for colour in whiteBackgroundImages: print 'processing ' + colour img = toAlphaBlackWhite(blackBackgroundImages[colour], whiteBackgroundImages[colour]) # Save screenshot if xrotation == -15: imgname = str(n) + 'up' + colour + '.png' elif xrotation == 15: imgname = str(n) + 'down' + colour + '.png' else: imgname = str(n) + '' + colour + '.png' img.save(outputFolder + os.sep + imgname, "PNG")""" BlendingThread(xrotation, n, blackBackgroundImages, whiteBackgroundImages, outputFolder) # Close HLMV subprocess.Popen(['taskkill', '/f', '/t' ,'/im', 'hlmv.exe'], stdout=PIPE, stderr=PIPE) n += 1 BlendingThread.waitForAll() # Stitch images together print 'Stitching images together...' stitch(outputFolder, finalImageName) # All done yay print '\nAll done'
def click(): mouse.click()
def shapes(): insert() mouse.click(303,135) time.sleep(wait)
def show(): mouse.click(1254,716) time.sleep(wait)
def back(): mouse.click(151,101) time.sleep(wait)
def insert(): mouse.click(306,148) time.sleep(wait)
def zoomin(): mouse.click(164,446) time.sleep(wait)